diff --git a/.gitattributes b/.gitattributes index 243105aee962393f0be0cae2d4a93e5f30edb968..1dcff8d2f490217d163cef238c2216dd95c818bf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -555,3 +555,10 @@ loan-advisor-agent/.venv/Lib/site-packages/regex/__pycache__/_regex_core.cpython loan-advisor-agent/.venv/Lib/site-packages/regex/_regex.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text loan-advisor-agent/.venv/Lib/site-packages/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text loan-advisor-agent/.venv/Lib/site-packages/rpds/rpds.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/__config__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7f00791e7428870027765ac355854a2ff77cbc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__config__.py @@ -0,0 +1,173 @@ +# This file is generated by SciPy's build process +# It contains system_info results at the time of building this package. +from enum import Enum + +__all__ = ["show"] +_built_with_meson = True + + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + + +def _cleanup(d): + """ + Removes empty values in a `dict` recursively + This ensures we remove values that Meson could not provide to CONFIG + """ + if isinstance(d, dict): + return { k: _cleanup(v) for k, v in d.items() if v != '' and _cleanup(v) != '' } + else: + return d + + +CONFIG = _cleanup( + { + "Compilers": { + "c": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.3.0", + "commands": r"C:\Strawberry\c\bin\ccache.EXE, cc", + "args": r"", + "linker args": r"", + }, + "cython": { + "name": r"cython", + "linker": r"cython", + "version": r"3.2.4", + "commands": r"cython", + "args": r"", + "linker args": r"", + }, + "c++": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.3.0", + "commands": r"C:\Strawberry\c\bin\ccache.EXE, c++", + "args": r"", + "linker args": r"", + }, + "fortran": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.3.0", + "commands": r"gfortran", + "args": r"", + "linker args": r"", + }, + "pythran": { + "version": r"0.18.1", + "include directory": r"C:\Users\runneradmin\AppData\Local\Temp\build-env-jfo4tcpw\Lib\site-packages/pythran" + }, + }, + "Machine Information": { + "host": { + "cpu": r"x86_64", + "family": r"x86_64", + "endian": r"little", + "system": r"windows", + }, + "build": { + "cpu": r"x86_64", + "family": r"x86_64", + "endian": r"little", + "system": r"windows", + }, + "cross-compiled": bool("False".lower().replace('false', '')), + }, + "Build Dependencies": { + "blas": { + "name": "scipy-openblas", + "found": bool("True".lower().replace('false', '')), + "version": "0.3.30", + "detection method": "pkgconfig", + "include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/include", + "lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/lib", + "openblas configuration": r"OpenBLAS 0.3.30 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24", + "pc file directory": r"D:/a/scipy/scipy", + "has ilp64": bool(r"False".lower().replace('false', '')), + }, + "lapack": { + "name": "scipy-openblas", + "found": bool("True".lower().replace('false', '')), + "version": "0.3.30", + "detection method": "pkgconfig", + "include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/include", + "lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/lib", + "openblas configuration": r"OpenBLAS 0.3.30 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24", + "pc file directory": r"D:/a/scipy/scipy", + "has ilp64": bool(r"False".lower().replace('false', '')), + }, + "pybind11": { + "name": "pybind11", + "version": "3.0.2", + "detection method": "config-tool", + "include directory": r"unknown", + }, + }, + "Python Information": { + "path": r"C:\Users\runneradmin\AppData\Local\Temp\build-env-jfo4tcpw\Scripts\python.exe", + "version": "3.12", + }, + } +) + + +def _check_pyyaml(): + import yaml + + return yaml + + +def show(mode=DisplayModes.stdout.value): + """ + Show libraries and system information on which SciPy was built + and is being used + + Parameters + ---------- + mode : {`'stdout'`, `'dicts'`}, optional. + Indicates how to display the config information. + `'stdout'` prints to console, `'dicts'` returns a dictionary + of the configuration. + + Returns + ------- + out : {`dict`, `None`} + If mode is `'dicts'`, a dict is returned, else None + + Examples + -------- + >>> import scipy + >>> scipy.show_config() + ... # formatted output is printed to the console + + >>> config_dict = scipy.show_config(mode='dicts') + >>> list(config_dict.keys()) + ['Compilers', 'Machine Information', 'Build Dependencies', 'Python Information'] + + Notes + ----- + 1. The `'stdout'` mode will give more readable + output if ``pyyaml`` is installed + + """ + if mode == DisplayModes.stdout.value: + try: # Non-standard library, check import + yaml = _check_pyyaml() + + print(yaml.dump(CONFIG)) + except ModuleNotFoundError: + import warnings + import json + + warnings.warn("Install `pyyaml` for better output", stacklevel=1) + print(json.dumps(CONFIG, indent=2)) + elif mode == DisplayModes.dicts.value: + return CONFIG + else: + raise AttributeError( + f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}" + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..013c8c0eeee15097dba4d8cf14cc26857fbd5731 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__init__.py @@ -0,0 +1,150 @@ +""" +SciPy: A scientific computing package for Python +================================================ + +Documentation is available in the docstrings and +online at https://docs.scipy.org/doc/scipy/ + +Subpackages +----------- +:: + + cluster --- Vector Quantization / Kmeans + constants --- Physical and mathematical constants and units + datasets --- Dataset methods + differentiate --- Finite difference differentiation tools + fft --- Discrete Fourier transforms + fftpack --- Legacy discrete Fourier transforms + integrate --- Integration routines + interpolate --- Interpolation Tools + io --- Data input and output + linalg --- Linear algebra routines + ndimage --- N-D image package + odr --- Orthogonal Distance Regression + optimize --- Optimization Tools + signal --- Signal Processing Tools + sparse --- Sparse Matrices + spatial --- Spatial data structures and algorithms + special --- Special functions + stats --- Statistical Functions + +Public API in the main SciPy namespace +-------------------------------------- +:: + + __version__ --- SciPy version string + LowLevelCallable --- Low-level callback function + show_config --- Show scipy build configuration + test --- Run scipy unittests + +""" + + +# start delvewheel patch +def _delvewheel_patch_1_12_0(): + import os + if os.path.isdir(libs_dir := os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'scipy.libs'))): + os.add_dll_directory(libs_dir) + + +_delvewheel_patch_1_12_0() +del _delvewheel_patch_1_12_0 +# end delvewheel patch + +import importlib as _importlib + +from numpy import __version__ as __numpy_version__ + + +try: + from scipy.__config__ import show as show_config +except ImportError as e: + msg = """Error importing SciPy: you cannot import SciPy while + being in scipy source directory; please exit the SciPy source + tree first and relaunch your Python interpreter.""" + raise ImportError(msg) from e + + +from scipy.version import version as __version__ + + +# Allow distributors to run custom init code +from . import _distributor_init +del _distributor_init + + +from scipy._lib import _pep440 +# In maintenance branch, change to np_maxversion N+3 if numpy is at N +np_minversion = '1.26.4' +np_maxversion = '2.7.0' +if (_pep440.parse(__numpy_version__) < _pep440.Version(np_minversion) or + _pep440.parse(__numpy_version__) >= _pep440.Version(np_maxversion)): + import warnings + warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}" + f" is required for this version of SciPy (detected " + f"version {__numpy_version__})", + UserWarning, stacklevel=2) +del _pep440 + + +# This is the first import of an extension module within SciPy. If there's +# a general issue with the install, such that extension modules are missing +# or cannot be imported, this is where we'll get a failure - so give an +# informative error message. +try: + from scipy._lib._ccallback import LowLevelCallable +except ImportError as e: + msg = "The `scipy` install you are using seems to be broken, " + \ + "(extension modules cannot be imported), " + \ + "please try reinstalling." + raise ImportError(msg) from e + + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester + + +submodules = [ + 'cluster', + 'constants', + 'datasets', + 'differentiate', + 'fft', + 'fftpack', + 'integrate', + 'interpolate', + 'io', + 'linalg', + 'ndimage', + 'odr', + 'optimize', + 'signal', + 'sparse', + 'spatial', + 'special', + 'stats' +] + +__all__ = submodules + [ + 'LowLevelCallable', + 'test', + 'show_config', + '__version__', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + if name in submodules: + return _importlib.import_module(f'scipy.{name}') + else: + try: + return globals()[name] + except KeyError: + raise AttributeError( + f"Module 'scipy' has no attribute '{name}'" + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__config__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__config__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77733ecf4b5872ecf82e39c23ec050cb06f84f3a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__config__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa642cbf8f75c584c891531d82d776ca6f401ecf Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6655e3743cd629bd032c90545cb9c213308759f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/version.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b051040d5e7166763278cb6dabf4cd0eb0967a1f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/version.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..3c12443b7ac104609ce4b95ed7d24598215490ce Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.dll.a differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b03a5ffd00d07623f0765ad20fdf56b7bb95b508 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1990a1fbef9f2f75556db35b81d7180c903fc54db3f8fd08c14ac2cbc805c61b +size 186368 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_distributor_init.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_distributor_init.py new file mode 100644 index 0000000000000000000000000000000000000000..0c3acda987d79141950e75e4ffe7927d392c0882 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_distributor_init.py @@ -0,0 +1,18 @@ +""" Distributor init file + +Distributors: you can replace the contents of this file with your own custom +code to support particular distributions of SciPy. + +For example, this is a good place to put any checks for hardware requirements +or BLAS/LAPACK library initialization. + +The SciPy standard source distribution will not put code in this file beyond +the try-except import of `_distributor_init_local` (which is not part of a +standard source distribution), so you can safely replace this file with your +own version. +""" + +try: + from . import _distributor_init_local # noqa: F401 +except ImportError: + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0e84889f1b1b1bde4778558a9dd88ddd9cb477 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a939a4ccea57b441b7f6ee0413f7f32395ee11bd Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67d153dd0199cdbf7b04b23336a300c93e79be9e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ada82d716e4685f9ba89a1e3a31ea868178164c6 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b14510fc405b359e4f69f3194c15fe5c52867319 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10dd96fa98c204a7a9b59184ec55f659339822aa Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e86d9b9f7e5095d823538f0d2b6fc99d67f71b3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95c737e8c2ee9ef415c5699333dcfff8e7b07e7a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcc265c751f952568f0b8f7564c0f4f2504ae05e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57889961a1501b6a1531734a9f66e061bf1dacd7 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..471f696503f7417269d3b47310bc6f532ec38ae2 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79e5851c1045236931c5294300442bd920d3515d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..196088bb29ec140217428af8f83c240118e5a678 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0acc36482e43f0ff34d1dfabe0d64ae9d43d2d86 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8abc251eafae1071762593ced7ca35fdc4202a1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3a8bf1a5d52adfeb705262706d85ea834cc2757 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..b427b9a5d3c95d983fc161bf52ea279cccdc7b01 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api.py @@ -0,0 +1,1036 @@ +"""Utility functions to use Python Array API compatible libraries. + +For the context about the Array API see: +https://data-apis.org/array-api/latest/purpose_and_scope.html + +The SciPy use case of the Array API is described on the following page: +https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy +""" +import operator +import dataclasses +import functools +import textwrap + +from collections.abc import Generator +from contextlib import contextmanager +from contextvars import ContextVar +from types import ModuleType +from typing import Any, Literal, TypeAlias +from collections.abc import Iterable + +import numpy as np +import numpy.typing as npt + +from scipy._lib.array_api_compat import ( + is_array_api_obj, + is_lazy_array, + is_numpy_array, + is_cupy_array, + is_torch_array, + is_jax_array, + is_dask_array, + size as xp_size, + numpy as np_compat, + device as xp_device, + is_numpy_namespace as is_numpy, + is_cupy_namespace as is_cupy, + is_torch_namespace as is_torch, + is_jax_namespace as is_jax, + is_dask_namespace as is_dask, + is_array_api_strict_namespace as is_array_api_strict, +) +from scipy._lib.array_api_compat.common._helpers import _compat_module_name +from scipy._lib.array_api_extra.testing import lazy_xp_function +from scipy._lib._array_api_override import ( + array_namespace, SCIPY_ARRAY_API, SCIPY_DEVICE +) +from scipy._lib._docscrape import FunctionDoc +from scipy._lib import array_api_extra as xpx + + +__all__ = [ + '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal', + 'default_xp', 'eager_warns', 'is_lazy_array', 'is_marray', + 'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch', + 'np_compat', 'get_native_namespace_name', + 'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for', + 'xp_assert_close', 'xp_assert_equal', 'xp_assert_less', + 'xp_copy', 'xp_device', 'xp_ravel', 'xp_size', + 'xp_unsupported_param_msg', 'xp_vector_norm', 'xp_capabilities', + 'xp_result_type', 'xp_promote', + 'make_xp_test_case', 'make_xp_pytest_marks', 'make_xp_pytest_param', +] + + +Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589) +ArrayLike: TypeAlias = Array | npt.ArrayLike + + +def _check_finite(array: Array, xp: ModuleType) -> None: + """Check for NaNs or Infs.""" + if not xp.all(xp.isfinite(array)): + msg = "array must not contain infs or NaNs" + raise ValueError(msg) + +def _asarray( + array: ArrayLike, + dtype: Any = None, + order: Literal['K', 'A', 'C', 'F'] | None = None, + copy: bool | None = None, + *, + xp: ModuleType | None = None, + check_finite: bool = False, + subok: bool = False, + ) -> Array: + """SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and + `subok`. + + Memory layout parameter `order` is not exposed in the Array API standard. + `order` is only enforced if the input array implementation + is NumPy based, otherwise `order` is just silently ignored. + + `check_finite` is also not a keyword in the array API standard; included + here for convenience rather than that having to be a separate function + call inside SciPy functions. + + `subok` is included to allow this function to preserve the behaviour of + `np.asanyarray` for NumPy based inputs. + """ + if xp is None: + xp = array_namespace(array) + if is_numpy(xp): + # Use NumPy API to support order + if copy is True: + array = np.array(array, order=order, dtype=dtype, subok=subok) + elif subok: + array = np.asanyarray(array, order=order, dtype=dtype) + else: + array = np.asarray(array, order=order, dtype=dtype) + else: + try: + array = xp.asarray(array, dtype=dtype, copy=copy) + except TypeError: + coerced_xp = array_namespace(xp.asarray(3)) + array = coerced_xp.asarray(array, dtype=dtype, copy=copy) + + if check_finite: + _check_finite(array, xp) + + return array + + +def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array: + """ + Copies an array. + + Parameters + ---------- + x : array + + xp : array_namespace + + Returns + ------- + copy : array + Copied array + + Notes + ----- + This copy function does not offer all the semantics of `np.copy`, i.e. the + `subok` and `order` keywords are not used. + """ + # Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg, + # so this uses our other helper `_asarray`. + if xp is None: + xp = array_namespace(x) + + return _asarray(x, copy=True, xp=xp) + + +def _xp_copy_to_numpy(x: Array) -> np.ndarray: + """Copies a possibly on device array to a NumPy array. + + This function is intended only for converting alternative backend + arrays to numpy arrays within test code, to make it easier for use + of the alternative backend to be isolated only to the function being + tested. `_xp_copy_to_numpy` should NEVER be used except in test code + for the specific purpose mentioned above. In production code, attempts + to copy device arrays to NumPy arrays should fail, or else functions + may appear to be working on the GPU when they actually aren't. + + Parameters + ---------- + x : array + + Returns + ------- + ndarray + """ + xp = array_namespace(x) + if is_numpy(xp): + return x.copy() + if is_cupy(xp): + return x.get() + if is_torch(xp): + return x.cpu().numpy() + if is_array_api_strict(xp): + # array api strict supports multiple devices, so need to + # ensure x is on the cpu before copying to NumPy. + return np.asarray( + xp.asarray(x, device=xp.Device("CPU_DEVICE")), copy=True + ) + # Fall back to np.asarray. This works for dask.array. It + # currently works for jax.numpy, but hopefully JAX will make + # the transfer guard workable enough for use in scipy tests, in + # which case, JAX will have to be handled explicitly. + # If new backends are added, they may require explicit handling as + # well. + return np.asarray(x, copy=True) + + +_default_xp_ctxvar: ContextVar[ModuleType] = ContextVar("_default_xp") + +@contextmanager +def default_xp(xp: ModuleType) -> Generator[None, None, None]: + """In all ``xp_assert_*`` and ``assert_*`` function calls executed within this + context manager, test by default that the array namespace is + the provided across all arrays, unless one explicitly passes the ``xp=`` + parameter or ``check_namespace=False``. + + Without this context manager, the default value for `xp` is the namespace + for the desired array (the second parameter of the tests). + """ + token = _default_xp_ctxvar.set(xp) + try: + yield + finally: + _default_xp_ctxvar.reset(token) + + +def eager_warns(warning_type, *, match=None, xp): + """pytest.warns context manager if arrays of specified namespace are always eager. + + Otherwise, context manager that *ignores* specified warning. + """ + import pytest + from scipy._lib._util import ignore_warns + if is_numpy(xp) or is_array_api_strict(xp) or is_cupy(xp): + return pytest.warns(warning_type, match=match) + return ignore_warns(warning_type, match='' if match is None else match) + + +def _strict_check(actual, desired, xp, *, + check_namespace=True, check_dtype=True, check_shape=True, + check_0d=True): + __tracebackhide__ = True # Hide traceback for py.test + + if xp is None: + try: + xp = _default_xp_ctxvar.get() + except LookupError: + xp = array_namespace(desired) + + if check_namespace: + _assert_matching_namespace(actual, desired, xp) + + # only NumPy distinguishes between scalars and arrays; we do if check_0d=True. + # do this first so we can then cast to array (and thus use the array API) below. + if is_numpy(xp) and check_0d: + _msg = ("Array-ness does not match:\n Actual: " + f"{type(actual)}\n Desired: {type(desired)}") + assert ((xp.isscalar(actual) and xp.isscalar(desired)) + or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg + + actual = xp.asarray(actual) + desired = xp.asarray(desired) + + if check_dtype: + _msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}" + assert actual.dtype == desired.dtype, _msg + + if check_shape: + if is_dask(xp): + actual.compute_chunk_sizes() + desired.compute_chunk_sizes() + _msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}" + assert actual.shape == desired.shape, _msg + + desired = xp.broadcast_to(desired, actual.shape) + return actual, desired, xp + + +def _assert_matching_namespace(actual, desired, xp): + __tracebackhide__ = True # Hide traceback for py.test + + desired_arr_space = array_namespace(desired) + _msg = ("Namespace of desired array does not match expectations " + "set by the `default_xp` context manager or by the `xp`" + "pytest fixture.\n" + f"Desired array's space: {desired_arr_space.__name__}\n" + f"Expected namespace: {xp.__name__}") + assert desired_arr_space == xp, _msg + + actual_arr_space = array_namespace(actual) + _msg = ("Namespace of actual and desired arrays do not match.\n" + f"Actual: {actual_arr_space.__name__}\n" + f"Desired: {xp.__name__}") + assert actual_arr_space == xp, _msg + + +def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + + actual, desired, xp = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + if is_cupy(xp): + return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg) + elif is_torch(xp): + # PyTorch recommends using `rtol=0, atol=0` like this + # to test for exact equality + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True, + check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_array_equal(actual, desired, err_msg=err_msg) + + +def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True, + check_dtype=True, check_shape=True, check_0d=True, + err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + + actual, desired, xp = _strict_check( + actual, desired, xp, + check_namespace=check_namespace, check_dtype=check_dtype, + check_shape=check_shape, check_0d=check_0d + ) + + floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating')) + if rtol is None and floating: + # multiplier of 4 is used as for `np.float64` this puts the default `rtol` + # roughly half way between sqrt(eps) and the default for + # `numpy.testing.assert_allclose`, 1e-7 + rtol = xp.finfo(actual.dtype).eps**0.5 * 4 + elif rtol is None: + rtol = 1e-7 + + if is_cupy(xp): + return xp.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + elif is_torch(xp): + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol, + equal_nan=True, check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + + +def xp_assert_close_nulp(actual, desired, *, nulp=1, check_namespace=True, + check_dtype=True, check_shape=True, check_0d=True, + err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + + actual, desired, xp = _strict_check( + actual, desired, xp, + check_namespace=check_namespace, check_dtype=check_dtype, + check_shape=check_shape, check_0d=check_0d + ) + + actual, desired = map(_xp_copy_to_numpy, (actual, desired)) + return np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=nulp) + + +def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None): + __tracebackhide__ = True # Hide traceback for py.test + + actual, desired, xp = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + 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_native_namespace_name(xp: ModuleType) -> str: + """Return name for native namespace (without array_api_compat prefix).""" + name = xp.__name__ + return name.removeprefix(f"{_compat_module_name()}.") + + +def scipy_namespace_for(xp: ModuleType) -> ModuleType | None: + """Return the `scipy`-like namespace of a non-NumPy backend + + That is, return the namespace corresponding with backend `xp` that contains + `scipy` sub-namespaces like `linalg` and `special`. If no such namespace + exists, return ``None``. Useful for dispatching. + """ + + if is_cupy(xp): + import cupyx # type: ignore[import-not-found,import-untyped] + return cupyx.scipy + + if is_jax(xp): + import jax # type: ignore[import-not-found] + return jax.scipy + + if is_torch(xp): + return xp + + return None + + +# maybe use `scipy.linalg` if/when array API support is added +def xp_vector_norm(x: Array, /, *, + axis: int | tuple[int] | None = None, + keepdims: bool = False, + ord: int | float = 2, + xp: ModuleType | None = None) -> Array: + xp = array_namespace(x) if xp is None else xp + + if SCIPY_ARRAY_API: + # check for optional `linalg` extension + if hasattr(xp, 'linalg'): + return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord) + else: + if ord != 2: + raise ValueError( + "only the Euclidean norm (`ord=2`) is currently supported in " + "`xp_vector_norm` for backends not implementing the `linalg` " + "extension." + ) + # return (x @ x)**0.5 + # or to get the right behavior with nd, complex arrays + return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5 + else: + # to maintain backwards compatibility + return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims) + + +def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array: + # Equivalent of np.ravel written in terms of array API + # Even though it's one line, it comes up so often that it's worth having + # this function for readability + xp = array_namespace(x) if xp is None else xp + return xp.reshape(x, (-1,)) + + +def xp_swapaxes(a, axis1, axis2, xp=None): + # Equivalent of np.swapaxes written in terms of array API + xp = array_namespace(a) if xp is None else xp + axes = list(range(a.ndim)) + axes[axis1], axes[axis2] = axes[axis2], axes[axis1] + a = xp.permute_dims(a, axes) + return a + + +# utility to find common dtype with option to force floating +def xp_result_type(*args, force_floating=False, xp): + """ + Returns the dtype that results from applying type promotion rules + (see Array API Standard Type Promotion Rules) to the arguments. Augments + standard `result_type` in a few ways: + + - There is a `force_floating` argument that ensures that the result type + is floating point, even when all args are integer. + - When a TypeError is raised (e.g. due to an unsupported promotion) + and `force_floating=True`, we define a custom rule: use the result type + of the default float and any other floats passed. See + https://github.com/scipy/scipy/pull/22695/files#r1997905891 + for rationale. + - This function accepts array-like iterables, which are immediately converted + to the namespace's arrays before result type calculation. Consequently, the + result dtype may be different when an argument is `1.` vs `[1.]`. + + Typically, this function will be called shortly after `array_namespace` + on a subset of the arguments passed to `array_namespace`. + """ + # prevent double conversion of iterable to array + # avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334 + # don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars + args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg) + else arg) for arg in args] + args_not_none = [arg for arg in args if arg is not None] + if force_floating: + args_not_none.append(1.0) + + if is_numpy(xp) and xp.__version__ < '2.0': + # Follow NEP 50 promotion rules anyway + args_not_none = [arg.dtype if getattr(arg, 'size', 0) == 1 else arg + for arg in args_not_none] + return xp.result_type(*args_not_none) + + try: # follow library's preferred promotion rules + return xp.result_type(*args_not_none) + except TypeError: # mixed type promotion isn't defined + if not force_floating: + raise + # use `result_type` of default floating point type and any floats present + # This can be revisited, but right now, the only backends that get here + # are array-api-strict (which is not for production use) and PyTorch + # (due to data-apis/array-api-compat#279). + float_args = [] + for arg in args_not_none: + arg_array = xp.asarray(arg) if np.isscalar(arg) else arg + dtype = getattr(arg_array, 'dtype', arg) + if xp.isdtype(dtype, ('real floating', 'complex floating')): + float_args.append(arg) + return xp.result_type(*float_args, xp_default_dtype(xp)) + + +def xp_promote(*args, broadcast=False, force_floating=False, xp): + """ + Promotes elements of *args to result dtype, ignoring `None`s. + Includes options for forcing promotion to floating point and + broadcasting the arrays, again ignoring `None`s. + Type promotion rules follow `xp_result_type` instead of `xp.result_type`. + + Typically, this function will be called shortly after `array_namespace` + on a subset of the arguments passed to `array_namespace`. + + This function accepts array-like iterables, which are immediately converted + to the namespace's arrays before result type calculation. Consequently, the + result dtype may be different when an argument is `1.` vs `[1.]`. + + See Also + -------- + xp_result_type + """ + if not args: + return args + + # prevent double conversion of iterable to array + # avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334 + # don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars + args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg) + else arg) for arg in args] + + dtype = xp_result_type(*args, force_floating=force_floating, xp=xp) + + args = [(_asarray(arg, dtype=dtype, subok=True, xp=xp) if arg is not None else arg) + for arg in args] + + if not broadcast: + return args[0] if len(args)==1 else tuple(args) + + args_not_none = [arg for arg in args if arg is not None] + + # determine result shape + shapes = {arg.shape for arg in args_not_none} + try: + shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1 + else args_not_none[0].shape) + except ValueError as e: + message = "Array shapes are incompatible for broadcasting." + raise ValueError(message) from e + + out = [] + for arg in args: + if arg is None: + out.append(arg) + continue + + # broadcast only if needed + # Even if two arguments need broadcasting, this is faster than + # `broadcast_arrays`, especially since we've already determined `shape` + if arg.shape != shape: + kwargs = {'subok': True} if is_numpy(xp) else {} + arg = xp.broadcast_to(arg, shape, **kwargs) + + # This is much faster than xp.astype(arg, dtype, copy=False) + if arg.dtype != dtype: + arg = xp.astype(arg, dtype) + + out.append(arg) + + return out[0] if len(out)==1 else tuple(out) + + +def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array: + xp = array_namespace(arr) if xp is None else xp + arr_dtype = arr.dtype + # The standard float dtypes are float32 and float64. + # Convert float32 to complex64, + # and float64 (and non-standard real dtypes) to complex128 + if xp.isdtype(arr_dtype, xp.float32): + arr = xp.astype(arr, xp.complex64) + elif xp.isdtype(arr_dtype, 'real floating'): + arr = xp.astype(arr, xp.complex128) + + return arr + + +def xp_default_dtype(xp): + """Query the namespace-dependent default floating-point dtype. + """ + if is_torch(xp): + # historically, we allow pytorch to keep its default of float32 + return xp.get_default_dtype() + else: + # we default to float64 + return xp.float64 + + +### MArray Helpers ### +def xp_result_device(*args): + """Return the device of an array in `args`, for the purpose of + input-output device propagation. + If there are multiple devices, return an arbitrary one. + If there are no arrays, return None (this typically happens only on NumPy). + """ + for arg in args: + # Do not do a duck-type test for the .device attribute, as many backends today + # don't have it yet. See workarouunds in array_api_compat.device(). + if is_array_api_obj(arg): + return xp_device(arg) + return None + + +# np.r_ replacement +def concat_1d(xp: ModuleType | None, *arrays: Iterable[ArrayLike]) -> Array: + """A replacement for `np.r_` as `xp.concat` does not accept python scalars + or 0-D arrays. + """ + arys = [xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp) for a in arrays] + return xp.concat(arys) + + +def is_marray(xp): + """Returns True if `xp` is an MArray namespace; False otherwise.""" + return "marray" in xp.__name__ + + +def _length_nonmasked(x, axis, keepdims=False, xp=None): + xp = array_namespace(x) if xp is None else xp + if is_marray(xp): + if np.iterable(axis): + message = '`axis` must be an integer or None for use with `MArray`.' + raise NotImplementedError(message) + return xp.astype(xp.count(x, axis=axis, keepdims=keepdims), x.dtype) + return (xp_size(x) if axis is None else + # compact way to deal with axis tuples or ints + int(np.prod(np.asarray(x.shape)[np.asarray(axis)]))) + + +def _share_masks(*args, xp): + if is_marray(xp): + mask = functools.reduce(operator.or_, (arg.mask for arg in args)) + args = [xp.asarray(arg.data, mask=mask) for arg in args] + return args[0] if len(args) == 1 else args + +### End MArray Helpers ### + + +@dataclasses.dataclass(repr=False) +class _XPSphinxCapability: + cpu: bool | None # None if not applicable + gpu: bool | None + warnings: list[str] = dataclasses.field(default_factory=list) + + def _render(self, value): + if value is None: + return "n/a" + if not value: + return "⛔" + if self.warnings: + res = "⚠️ " + '; '.join(self.warnings) + assert len(res) <= 20, "Warnings too long" + return res + return "✅" + + def __str__(self): + cpu = self._render(self.cpu) + gpu = self._render(self.gpu) + return f"{cpu:20} {gpu:20}" + + +def _make_sphinx_capabilities( + # lists of tuples [(module name, reason), ...] + skip_backends=(), xfail_backends=(), + # @pytest.mark.skip/xfail_xp_backends kwargs + cpu_only=False, np_only=False, out_of_scope=False, exceptions=(), + # xpx.lazy_xp_backends kwargs + allow_dask_compute=False, jax_jit=True, + # list of tuples [(module name, reason), ...] + warnings = (), + # unused in documentation + reason=None, +): + if out_of_scope: + return {"out_of_scope": True} + + exceptions = set(exceptions) + + # Default capabilities + capabilities = { + "numpy": _XPSphinxCapability(cpu=True, gpu=None), + "array_api_strict": _XPSphinxCapability(cpu=True, gpu=None), + "cupy": _XPSphinxCapability(cpu=None, gpu=True), + "torch": _XPSphinxCapability(cpu=True, gpu=True), + "jax.numpy": _XPSphinxCapability(cpu=True, gpu=True, + warnings=[] if jax_jit else ["no JIT"]), + # Note: Dask+CuPy is currently untested and unsupported + "dask.array": _XPSphinxCapability(cpu=True, gpu=None, + warnings=["computes graph"] if allow_dask_compute else []), + } + + # documentation doesn't display the reason + for module, _ in list(skip_backends) + list(xfail_backends): + backend = capabilities[module] + if backend.cpu is not None: + backend.cpu = False + if backend.gpu is not None: + backend.gpu = False + + for module, backend in capabilities.items(): + if np_only and module not in exceptions | {"numpy"}: + if backend.cpu is not None: + backend.cpu = False + if backend.gpu is not None: + backend.gpu = False + elif cpu_only and module not in exceptions and backend.gpu is not None: + backend.gpu = False + + for module, warning in warnings: + backend = capabilities[module] + backend.warnings.append(warning) + + return capabilities + + +def _make_capabilities_note(fun_name, capabilities, extra_note=None): + if "out_of_scope" in capabilities: + # It will be better to link to a section of the dev-arrayapi docs + # that explains what is and isn't in-scope, but such a section + # doesn't exist yet. Using :ref:`dev-arrayapi` as a placeholder. + note = f""" + **Array API Standard Support** + + `{fun_name}` is not in-scope for support of Python Array API Standard compatible + backends other than NumPy. + + See :ref:`dev-arrayapi` for more information. + """ + return textwrap.dedent(note) + + # Note: deliberately not documenting array-api-strict + note = f""" + **Array API Standard Support** + + `{fun_name}` has experimental support for Python Array API Standard compatible + backends in addition to NumPy. Please consider testing these features + by setting an environment variable ``SCIPY_ARRAY_API=1`` and providing + CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following + combinations of backend and device (or other capability) are supported. + + ==================== ==================== ==================== + Library CPU GPU + ==================== ==================== ==================== + NumPy {capabilities['numpy'] } + CuPy {capabilities['cupy'] } + PyTorch {capabilities['torch'] } + JAX {capabilities['jax.numpy'] } + Dask {capabilities['dask.array'] } + ==================== ==================== ==================== + + """ + (extra_note or "") + " See :ref:`dev-arrayapi` for more information." + + return textwrap.dedent(note) + + +def xp_capabilities( + *, + # Alternative capabilities table. + # Used only for testing this decorator. + capabilities_table=None, + # Generate pytest.mark.skip/xfail_xp_backends. + # See documentation in conftest.py. + # lists of tuples [(module name, reason), ...] + skip_backends=(), xfail_backends=(), + cpu_only=False, np_only=False, reason=None, + out_of_scope=False, exceptions=(), + # lists of tuples [(module name, reason), ...] + warnings=(), + # xpx.testing.lazy_xp_function kwargs. + # Refer to array-api-extra documentation. + allow_dask_compute=False, jax_jit=True, + # Extra note to inject into the docstring + extra_note=None, +): + """Decorator for a function that states its support among various + Array API compatible backends. + + This decorator has two effects: + 1. It allows tagging tests with ``@make_xp_test_case`` or + ``make_xp_pytest_param`` (see below) to automatically generate + SKIP/XFAIL markers and perform additional backend-specific + testing, such as extra validation for Dask and JAX; + 2. It automatically adds a note to the function's docstring, containing + a table matching what has been tested. + + See Also + -------- + make_xp_test_case + make_xp_pytest_param + array_api_extra.testing.lazy_xp_function + """ + capabilities_table = (xp_capabilities_table if capabilities_table is None + else capabilities_table) + + if out_of_scope: + np_only = True + + capabilities = dict( + skip_backends=skip_backends, + xfail_backends=xfail_backends, + cpu_only=cpu_only, + np_only=np_only, + out_of_scope=out_of_scope, + reason=reason, + exceptions=exceptions, + allow_dask_compute=allow_dask_compute, + jax_jit=jax_jit, + warnings=warnings, + ) + sphinx_capabilities = _make_sphinx_capabilities(**capabilities) + + def decorator(f): + # Don't use a wrapper, as in some cases @xp_capabilities is + # applied to a ufunc + capabilities_table[f] = capabilities + note = _make_capabilities_note(f.__name__, sphinx_capabilities, extra_note) + doc = FunctionDoc(f) + doc['Notes'].append(note) + doc = str(doc).split("\n", 1)[1].lstrip(" \n") # remove signature + try: + f.__doc__ = doc + except AttributeError: + # Can't update __doc__ on ufuncs if SciPy + # was compiled against NumPy < 2.2. + pass + + return f + return decorator + + +def make_xp_test_case(*funcs, capabilities_table=None): + capabilities_table = (xp_capabilities_table if capabilities_table is None + else capabilities_table) + """Generate pytest decorator for a test function that tests functionality + of one or more Array API compatible functions. + + Read the parameters of the ``@xp_capabilities`` decorator applied to the + listed functions and: + + - Generate the ``@pytest.mark.skip_xp_backends`` and + ``@pytest.mark.xfail_xp_backends`` decorators + for the decorated test function + - Tag the function with `xpx.testing.lazy_xp_function` + + Example:: + + @make_xp_test_case(f1) + def test_f1(xp): + ... + + @make_xp_test_case(f2) + def test_f2(xp): + ... + + @make_xp_test_case(f1, f2) + def test_f1_and_f2(xp): + ... + + The above is equivalent to:: + @pytest.mark.skip_xp_backends(...) + @pytest.mark.skip_xp_backends(...) + @pytest.mark.xfail_xp_backends(...) + @pytest.mark.xfail_xp_backends(...) + def test_f1(xp): + ... + + etc., where the arguments of ``skip_xp_backends`` and ``xfail_xp_backends`` are + determined by the ``@xp_capabilities`` decorator applied to the functions. + + See Also + -------- + xp_capabilities + make_xp_pytest_marks + make_xp_pytest_param + array_api_extra.testing.lazy_xp_function + """ + marks = make_xp_pytest_marks(*funcs, capabilities_table=capabilities_table) + return lambda func: functools.reduce(lambda f, g: g(f), marks, func) + + +def make_xp_pytest_param(func, *args, capabilities_table=None): + """Variant of ``make_xp_test_case`` that returns a pytest.param for a function, + with all necessary skip_xp_backends and xfail_xp_backends marks applied:: + + @pytest.mark.parametrize( + "func", [make_xp_pytest_param(f1), make_xp_pytest_param(f2)] + ) + def test(func, xp): + ... + + The above is equivalent to:: + + @pytest.mark.parametrize( + "func", [ + pytest.param(f1, marks=[ + pytest.mark.skip_xp_backends(...), + pytest.mark.xfail_xp_backends(...), ...]), + pytest.param(f2, marks=[ + pytest.mark.skip_xp_backends(...), + pytest.mark.xfail_xp_backends(...), ...]), + ) + def test(func, xp): + ... + + Parameters + ---------- + func : Callable + Function to be tested. It must be decorated with ``@xp_capabilities``. + *args : Any, optional + Extra pytest parameters for the use case, e.g.:: + + @pytest.mark.parametrize("func,verb", [ + make_xp_pytest_param(f1, "hello"), + make_xp_pytest_param(f2, "world")]) + def test(func, verb, xp): + # iterates on (func=f1, verb="hello") + # and (func=f2, verb="world") + + See Also + -------- + xp_capabilities + make_xp_test_case + make_xp_pytest_marks + array_api_extra.testing.lazy_xp_function + """ + import pytest + + marks = make_xp_pytest_marks(func, capabilities_table=capabilities_table) + return pytest.param(func, *args, marks=marks, id=func.__name__) + + +def make_xp_pytest_marks(*funcs, capabilities_table=None): + """Variant of ``make_xp_test_case`` that returns a list of pytest marks, + which can be used with the module-level `pytestmark = ...` variable:: + + pytestmark = make_xp_pytest_marks(f1, f2) + + def test(xp): + ... + + In this example, the whole test module is dedicated to testing `f1` or `f2`, + and the two functions have the same capabilities, so it's unnecessary to + cherry-pick which test tests which function. + The above is equivalent to:: + + pytestmark = [ + pytest.mark.skip_xp_backends(...), + pytest.mark.xfail_xp_backends(...), ...]), + ] + + def test(xp): + ... + + See Also + -------- + xp_capabilities + make_xp_test_case + make_xp_pytest_param + array_api_extra.testing.lazy_xp_function + """ + capabilities_table = (xp_capabilities_table if capabilities_table is None + else capabilities_table) + import pytest + + marks = [] + for func in funcs: + capabilities = capabilities_table[func] + exceptions = capabilities['exceptions'] + reason = capabilities['reason'] + + if capabilities['cpu_only']: + marks.append(pytest.mark.skip_xp_backends( + cpu_only=True, exceptions=exceptions, reason=reason)) + if capabilities['np_only']: + marks.append(pytest.mark.skip_xp_backends( + np_only=True, exceptions=exceptions, reason=reason)) + + for mod_name, reason in capabilities['skip_backends']: + marks.append(pytest.mark.skip_xp_backends(mod_name, reason=reason)) + for mod_name, reason in capabilities['xfail_backends']: + marks.append(pytest.mark.xfail_xp_backends(mod_name, reason=reason)) + + lazy_kwargs = {k: capabilities[k] + for k in ('allow_dask_compute', 'jax_jit')} + lazy_xp_function(func, **lazy_kwargs) + + return marks + + +# Is it OK to have a dictionary that is mutated (once upon import) in many places? +xp_capabilities_table = {} # type: ignore[var-annotated] + + +def xp_device_type(a: Array) -> Literal["cpu", "cuda", None]: + if is_numpy_array(a): + return "cpu" + if is_cupy_array(a): + return "cuda" + if is_torch_array(a): + # TODO this can return other backends e.g. tpu but they're unsupported in scipy + return a.device.type + if is_jax_array(a): + # TODO this can return other backends e.g. tpu but they're unsupported in scipy + return "cuda" if (p := a.device.platform) == "gpu" else p + if is_dask_array(a): + return xp_device_type(a._meta) + # array-api-strict is a stand-in for unknown libraries; don't special-case it + return None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_compat_vendor.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_compat_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd1eaeacc9776b489ffea6708a5261f90b115a2d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_compat_vendor.py @@ -0,0 +1,9 @@ +# DO NOT RENAME THIS FILE +# This is a hook for array_api_extra/src/array_api_extra/_lib/_compat.py +# to override functions of array_api_compat. + +from .array_api_compat import * # noqa: F403 +from ._array_api_override import array_namespace as scipy_array_namespace + +# overrides array_api_compat.array_namespace inside array-api-extra +array_namespace = scipy_array_namespace # type: ignore[assignment] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_docs_tables.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_docs_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..bad2fdd8b776bd262403fbf2dc80c63816ff9312 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_docs_tables.py @@ -0,0 +1,294 @@ +"""Generate flat tables showing Array API capabilities for use in docs. + +These tables are intended for presenting Array API capabilities across +a wide number of functions at once. Rows correspond to functions and +columns correspond to library/device/option combinations. +""" + +from collections import defaultdict +from enum import auto, Enum +from importlib import import_module +from types import ModuleType + +from scipy._lib._array_api import xp_capabilities_table +from scipy._lib._array_api import _make_sphinx_capabilities + +# For undocumented aliases of public functions which are kept around for +# backwards compatibility reasons. These should be excluded from the +# tables since they would be redundant. There are also no docs pages to +# link entries to. +ALIASES = { + "scipy.linalg": { + # Alias of scipy.linalg.solve_continuous_lyapunov + "solve_lyapunov", + }, + "scipy.ndimage": { + # Alias of scipy.ndimage.sum_labels + "sum", + }, + "scipy.special": { + # Alias of scipy.special.jv + "jn", + # Alias of scipy.special.roots_legendre + "p_roots", + # Alias of scipy.special.roots_chebyt + "t_roots", + # Alias of scipy.special.roots_chebyu + "u_roots", + # Alias of scipy.special.roots_chebyc + "c_roots", + # Alias of scipy.special.roots_chebys + "s_roots", + # Alias of scipy.special.roots_jacobi + "j_roots", + # Alias of scipy.special.roots_laguerre + "l_roots", + # Alias of scipy.special.roots_genlaguerre + "la_roots", + # Alias of scipy.special.roots_hermite + "h_roots", + # Alias of scipy.special.roots_hermitenorm + "he_roots", + # Alias of scipy.special.roots_gegenbauer + "cg_roots", + # Alias of scipy.special.roots_sh_legendre + "ps_roots", + # Alias of scipy.special.roots_sh_chebyt + "ts_roots", + # Alias of scipy.special.roots_chebyu + "us_roots", + # Alias of scipy.special.roots_sh_jacobi + "js_roots", + } +} + +# Shortened names for use in table. +BACKEND_NAMES_MAP = { + "jax.numpy": "jax", + "dask.array": "dask", +} + + +class BackendSupportStatus(Enum): + YES = auto() + NO = auto() + OUT_OF_SCOPE = auto() + UNKNOWN = auto() + + +def _process_capabilities_table_entry(entry: dict | None) -> dict[str, dict[str, bool]]: + """Returns dict showing alternative backend support in easy to consume form. + + Parameters + ---------- + entry : Optional[dict] + A dict with the structure of the values of the dict + scipy._lib._array_api.xp_capabilities_table. If None, it is + assumped that no alternative backends are supported. + Default: None. + + Returns + ------- + dict[str, dict[str, bool]] + The output dict currently has keys "cpu", "gpu", "jit" and "lazy". + The value associated to each key is itself a dict. The keys of + the inner dicts correspond to backends, with bool values stating + whether or not the backend is supported with a given device or + mode. Inapplicable backends do not appear in the inner dicts + (e.g. since cupy is gpu-only, it does not appear in the inner + dict keyed on "cpu"). Only alternative backends to NumPy are + included since NumPY support should be guaranteed. + + """ + # This is a template for the output format. If more backends and + # backend options are added, it will need to be updated manually. + # Entries start as boolean, but upon returning, will take values + # from the BackendSupportStatus Enum. + output = { + "cpu": {"torch": False, "jax": False, "dask": False}, + "gpu": {"cupy": False, "torch": False, "jax": False}, + "jit": {"jax": False}, + "lazy": {"dask": False}, + } + S = BackendSupportStatus + if entry is None: + # If there is no entry, assume no alternative backends are supported. + # If the list of supported backends will grows, this hard-coded dict + # will need to be updated. + return { + outer_key: {inner_key: S.UNKNOWN for inner_key in outer_value} + for outer_key, outer_value in output.items() + } + + if entry["out_of_scope"]: + # None is used to signify out-of-scope functions. + return { + outer_key: {inner_key: S.OUT_OF_SCOPE for inner_key in outer_value} + for outer_key, outer_value in output.items() + } + + # For now, use _make_sphinx_capabilities because that's where + # the relevant logic for determining what is and isn't + # supported based on xp_capabilities_table entries lives. + # Perhaps this logic should be decoupled from sphinx. + for backend, capabilities in _make_sphinx_capabilities(**entry).items(): + if backend in {"array_api_strict", "numpy"}: + continue + backend = BACKEND_NAMES_MAP.get(backend, backend) + cpu, gpu = capabilities.cpu, capabilities.gpu + if cpu is not None: + if backend not in output["cpu"]: + raise ValueError( + "Input capabilities table entry contains unhandled" + f" backend {backend} on cpu." + ) + output["cpu"][backend] = cpu + if gpu is not None: + if backend not in output["gpu"]: + raise ValueError( + "Input capabilities table entry contains unhandled" + f" backend {backend} on gpu." + ) + output["gpu"][backend] = gpu + if backend == "jax": + output["jit"]["jax"] = entry["jax_jit"] and output["cpu"]["jax"] + if backend == "dask.array": + support_lazy = not entry["allow_dask_compute"] and output["dask"] + output["lazy"]["dask"] = support_lazy + return { + outer_key: { + inner_key: S.YES if inner_value else S.NO + for inner_key, inner_value in outer_value.items() + } + for outer_key, outer_value in output.items() + } + + +def is_named_function_like_object(obj): + return ( + not isinstance(obj, ModuleType | type) + and callable(obj) and hasattr(obj, "__name__") + ) + + +def make_flat_capabilities_table( + modules: str | list[str], + backend_type: str, + /, + *, + capabilities_table: list[str] | None = None, +) -> list[dict[str, str]]: + """Generate full table of array api capabilities across public functions. + + Parameters + ---------- + modules : str | list[str] + A string containing single SciPy module, (e.g `scipy.stats`, `scipy.fft`) + or a list of such strings. + + backend_type : {'cpu', 'gpu', 'jit', 'lazy'} + + capabilities_table : Optional[list[str]] + Table in the form of `scipy._lib._array_api.xp_capabilities_table`. + If None, uses `scipy._lib._array_api.xp_capabilities_table`. + Default: None. + + Returns + ------- + output : list[dict[str, str]] + `output` is a table in dict format + (keys corresponding to column names). The first column is "module". + The other columns correspond to supported backends for the given + `backend_type`, e.g. jax.numpy, torch, and dask on cpu. + numpy is excluded because it should always be supported. + See the helper function + `_process_capabilities_table_entry` above). + + """ + if backend_type not in {"cpu", "gpu", "jit", "lazy"}: + raise ValueError(f"Received unhandled backend type {backend_type}") + + if isinstance(modules, str): + modules = [modules] + + if capabilities_table is None: + capabilities_table = xp_capabilities_table + + output = [] + + for module_name in modules: + module = import_module(module_name) + public_things = module.__all__ + for name in public_things: + if name in ALIASES.get(module_name, {}): + # Skip undocumented aliases that are kept + # for backwards compatibility reasons. + continue + thing = getattr(module, name) + if not is_named_function_like_object(thing): + continue + entry = xp_capabilities_table.get(thing, None) + capabilities = _process_capabilities_table_entry(entry)[backend_type] + row = {"module": module_name} + row.update({"function": name}) + row.update(capabilities) + output.append(row) + return output + + +def calculate_table_statistics( + flat_table: list[dict[str, str]] +) -> dict[str, tuple[dict[str, str], bool]]: + """Get counts of what is supported per module. + + Parameters + ---------- + flat_table : list[dict[str, str]] + A table as returned by `make_flat_capabilities_table` + + Returns + ------- + dict[str, tuple[dict[str, str], bool]] + dict mapping module names to 2-tuples containing an inner dict and a + bool. The inner dicts have a key "total" along with keys for each + backend column of the supplied flat capabilities table. The value + corresponding to total is the total count of functions in the given + module, and the value associated to the other keys is the count of + functions that support that particular backend. The bool is False if + the calculation may be innacurate due to missing xp_capabilities + decorators, and True if all functions for that particular module have + been decorated with xp_capabilities. + """ + if not flat_table: + return [] + + counter = defaultdict(lambda: defaultdict(int)) + + S = BackendSupportStatus + # Keep track of which modules have functions with missing xp_capabilities + # decorators so this information can be passed back to the caller. + missing_xp_capabilities = set() + for entry in flat_table: + entry = entry.copy() + entry.pop("function") + module = entry.pop("module") + current_counter = counter[module] + + # By design, all backends and options must be considered out-of-scope + # if one is, so just pick an arbitrary entry here to test if function is + # in-scope. + if next(iter(entry.values())) != S.OUT_OF_SCOPE: + current_counter["total"] += 1 + for key, value in entry.items(): + # Functions missing xp_capabilities will be tabulated as + # unsupported, but may actually be supported. There is a + # note about this in the documentation and this function is + # set up to return information needed to put asterisks next + # to percentages impacted by missing xp_capabilities decorators. + current_counter[key] += 1 if value == S.YES else 0 + if value == S.UNKNOWN: + missing_xp_capabilities.add(module) + return { + key: (dict(value), key not in missing_xp_capabilities) + for key, value in counter.items() + } diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_no_0d.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_no_0d.py new file mode 100644 index 0000000000000000000000000000000000000000..2d997be2644381142b6a5d14bcaf97228b5b330a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_override.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_override.py new file mode 100644 index 0000000000000000000000000000000000000000..9ee104db5cf1590ef6e3bd5ec12081f2b7b61aa4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_override.py @@ -0,0 +1,150 @@ +""" +Override functions from array_api_compat, for use by array-api-extra +and internally. + +See also _array_api_compat_vendor.py +""" +import enum +import os + +from functools import lru_cache +from types import ModuleType +from typing import Any, TypeAlias + +import numpy as np +import numpy.typing as npt + +from scipy._lib import array_api_compat +import scipy._lib.array_api_compat.numpy as np_compat +from scipy._lib.array_api_compat import is_array_api_obj, is_jax_array +from scipy._lib._sparse import SparseABC + + +Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589) +ArrayLike: TypeAlias = Array | npt.ArrayLike + +# To enable array API and strict array-like input validation +SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False) +# To control the default device - for use in the test suite only +SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu") + + +class _ArrayClsInfo(enum.Enum): + skip = 0 + numpy = 1 + array_like = 2 + unknown = 3 + + +@lru_cache(100) +def _validate_array_cls(cls: type) -> _ArrayClsInfo: + if issubclass(cls, (list, tuple)): + return _ArrayClsInfo.array_like + + # this comes from `_util._asarray_validated` + if issubclass(cls, SparseABC): + 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 issubclass(cls, np.ma.MaskedArray): + raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.") + + if issubclass(cls, np.matrix): + raise TypeError("Inputs of type `numpy.matrix` are not supported.") + + if issubclass(cls, (np.ndarray, np.generic)): + return _ArrayClsInfo.numpy + + # Note: this must happen after the test for np.generic, because + # np.float64 and np.complex128 are subclasses of float and complex respectively. + # This matches the behavior of array_api_compat. + if issubclass(cls, (int, float, complex, bool, type(None))): + return _ArrayClsInfo.skip + + return _ArrayClsInfo.unknown + + +def array_namespace(*arrays: Array) -> 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 + ----- + Wrapper around `array_api_compat.array_namespace`. + + 1. Check for the global switch `SCIPY_ARRAY_API`. If disabled, just + return array_api_compat.numpy namespace and skip all compliance checks. + + 2. Check for known-bad array classes. + The following subclasses are not supported and raise and error: + + - `numpy.ma.MaskedArray` + - `numpy.matrix` + - NumPy arrays which do not have a boolean or numerical dtype + - `scipy.sparse` arrays + + 3. Coerce array-likes to NumPy arrays and check their dtype. + Note that non-scalar array-likes can't be mixed with non-NumPy Array + API objects; e.g. + + - `array_namespace([1, 2])` returns NumPy namespace; + - `array_namespace(np.asarray([1, 2], [3, 4])` returns NumPy namespace; + - `array_namespace(cp.asarray([1, 2], [3, 4])` raises an error. + """ + if not SCIPY_ARRAY_API: + # here we could wrap the namespace if needed + return np_compat + + numpy_arrays = [] + api_arrays = [] + + for array in arrays: + arr_info = _validate_array_cls(type(array)) + if arr_info is _ArrayClsInfo.skip: + pass + + elif arr_info is _ArrayClsInfo.numpy: + if array.dtype.kind in 'iufcb': # Numeric or bool + numpy_arrays.append(array) + elif array.dtype.kind == 'V' and is_jax_array(array): + # Special case for JAX zero gradient arrays; + # see array_api_compat._common._helpers._is_jax_zero_gradient_array + api_arrays.append(array) # JAX zero gradient array + else: + raise TypeError(f"An argument has dtype `{array.dtype!r}`; " + "only boolean and numerical dtypes are supported.") + + elif arr_info is _ArrayClsInfo.unknown and is_array_api_obj(array): + api_arrays.append(array) + + else: + # list, tuple, or arbitrary object + try: + array = np.asanyarray(array) + except TypeError: + raise TypeError("An argument is neither array API compatible nor " + "coercible by NumPy.") + if array.dtype.kind not in 'iufcb': # Numeric or bool + raise TypeError(f"An argument has dtype `{array.dtype!r}`; " + "only boolean and numerical dtypes are supported.") + numpy_arrays.append(array) + + # When there are exclusively NumPy and ArrayLikes, skip calling + # array_api_compat.array_namespace for performance. + if not api_arrays: + return np_compat + + # In case of mix of NumPy/ArrayLike and non-NumPy Array API arrays, + # let array_api_compat.array_namespace raise an error. + return array_api_compat.array_namespace(*numpy_arrays, *api_arrays) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_bunch.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1b6157c4ec70dc746271401cf1bf5d0c53ae3b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_bunch.py @@ -0,0 +1,229 @@ +import sys as _sys +from keyword import iskeyword as _iskeyword + + +def _validate_names(typename, field_names, extra_field_names): + """ + Ensure that all the given names are valid Python identifiers that + do not start with '_'. Also check that there are no duplicates + among field_names + extra_field_names. + """ + for name in [typename] + field_names + extra_field_names: + if not isinstance(name, str): + raise TypeError('typename and all field names must be strings') + if not name.isidentifier(): + raise ValueError('typename and all field names must be valid ' + f'identifiers: {name!r}') + if _iskeyword(name): + raise ValueError('typename and all field names cannot be a ' + f'keyword: {name!r}') + + seen = set() + for name in field_names + extra_field_names: + if name.startswith('_'): + raise ValueError('Field names cannot start with an underscore: ' + f'{name!r}') + if name in seen: + raise ValueError(f'Duplicate field name: {name!r}') + seen.add(name) + + +# Note: This code is adapted from CPython:Lib/collections/__init__.py +def _make_tuple_bunch(typename, field_names, extra_field_names=None, + module=None): + """ + Create a namedtuple-like class with additional attributes. + + This function creates a subclass of tuple that acts like a namedtuple + and that has additional attributes. + + The additional attributes are listed in `extra_field_names`. The + values assigned to these attributes are not part of the tuple. + + The reason this function exists is to allow functions in SciPy + that currently return a tuple or a namedtuple to returned objects + that have additional attributes, while maintaining backwards + compatibility. + + This should only be used to enhance *existing* functions in SciPy. + New functions are free to create objects as return values without + having to maintain backwards compatibility with an old tuple or + namedtuple return value. + + Parameters + ---------- + typename : str + The name of the type. + field_names : list of str + List of names of the values to be stored in the tuple. These names + will also be attributes of instances, so the values in the tuple + can be accessed by indexing or as attributes. At least one name + is required. See the Notes for additional restrictions. + extra_field_names : list of str, optional + List of names of values that will be stored as attributes of the + object. See the notes for additional restrictions. + + Returns + ------- + cls : type + The new class. + + Notes + ----- + There are restrictions on the names that may be used in `field_names` + and `extra_field_names`: + + * The names must be unique--no duplicates allowed. + * The names must be valid Python identifiers, and must not begin with + an underscore. + * The names must not be Python keywords (e.g. 'def', 'and', etc., are + not allowed). + + Examples + -------- + >>> from scipy._lib._bunch import _make_tuple_bunch + + Create a class that acts like a namedtuple with length 2 (with field + names `x` and `y`) that will also have the attributes `w` and `beta`: + + >>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta']) + + `Result` is the new class. We call it with keyword arguments to create + a new instance with given values. + + >>> result1 = Result(x=1, y=2, w=99, beta=0.5) + >>> result1 + Result(x=1, y=2, w=99, beta=0.5) + + `result1` acts like a tuple of length 2: + + >>> len(result1) + 2 + >>> result1[:] + (1, 2) + + The values assigned when the instance was created are available as + attributes: + + >>> result1.y + 2 + >>> result1.beta + 0.5 + """ + if len(field_names) == 0: + raise ValueError('field_names must contain at least one name') + + if extra_field_names is None: + extra_field_names = [] + _validate_names(typename, field_names, extra_field_names) + + typename = _sys.intern(str(typename)) + field_names = tuple(map(_sys.intern, field_names)) + extra_field_names = tuple(map(_sys.intern, extra_field_names)) + + all_names = field_names + extra_field_names + arg_list = ', '.join(field_names) + full_list = ', '.join(all_names) + repr_fmt = ''.join(('(', + ', '.join(f'{name}=%({name})r' for name in all_names), + ')')) + tuple_new = tuple.__new__ + _dict, _tuple, _zip = dict, tuple, zip + + # Create all the named tuple methods to be added to the class namespace + + s = f"""\ +def __new__(_cls, {arg_list}, **extra_fields): + return _tuple_new(_cls, ({arg_list},)) + +def __init__(self, {arg_list}, **extra_fields): + for key in self._extra_fields: + if key not in extra_fields: + raise TypeError("missing keyword argument '%s'" % (key,)) + for key, val in extra_fields.items(): + if key not in self._extra_fields: + raise TypeError("unexpected keyword argument '%s'" % (key,)) + self.__dict__[key] = val + +def __setattr__(self, key, val): + if key in {repr(field_names)}: + raise AttributeError("can't set attribute %r of class %r" + % (key, self.__class__.__name__)) + else: + self.__dict__[key] = val +""" + del arg_list + namespace = {'_tuple_new': tuple_new, + '__builtins__': dict(TypeError=TypeError, + AttributeError=AttributeError), + '__name__': f'namedtuple_{typename}'} + exec(s, namespace) + __new__ = namespace['__new__'] + __new__.__doc__ = f'Create new instance of {typename}({full_list})' + __init__ = namespace['__init__'] + __init__.__doc__ = f'Instantiate instance of {typename}({full_list})' + __setattr__ = namespace['__setattr__'] + + def __repr__(self): + 'Return a nicely formatted representation string' + return self.__class__.__name__ + repr_fmt % self._asdict() + + def _asdict(self): + 'Return a new dict which maps field names to their values.' + out = _dict(_zip(self._fields, self)) + out.update(self.__dict__) + return out + + def __getnewargs_ex__(self): + 'Return self as a plain tuple. Used by copy and pickle.' + return _tuple(self), self.__dict__ + + # Modify function metadata to help with introspection and debugging + for method in (__new__, __repr__, _asdict, __getnewargs_ex__): + method.__qualname__ = f'{typename}.{method.__name__}' + + # Build-up the class namespace dictionary + # and use type() to build the result class + class_namespace = { + '__doc__': f'{typename}({full_list})', + '_fields': field_names, + '__new__': __new__, + '__init__': __init__, + '__repr__': __repr__, + '__setattr__': __setattr__, + '_asdict': _asdict, + '_extra_fields': extra_field_names, + '__getnewargs_ex__': __getnewargs_ex__, + # _field_defaults and _replace are added to get Polars to detect + # a bunch object as a namedtuple. See gh-22450 + '_field_defaults': {}, + '_replace': None, + } + for index, name in enumerate(field_names): + + def _get(self, index=index): + return self[index] + class_namespace[name] = property(_get) + for name in extra_field_names: + + def _get(self, name=name): + return self.__dict__[name] + class_namespace[name] = property(_get) + + result = type(typename, (tuple,), class_namespace) + + # For pickling to work, the __module__ variable needs to be set to the + # frame where the named tuple is created. Bypass this step in environments + # where sys._getframe is not defined (Jython for example) or sys._getframe + # is not defined for arguments greater than 0 (IronPython), or where the + # user has specified a particular module. + if module is None: + try: + module = _sys._getframe(1).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + if module is not None: + result.__module__ = module + __new__.__module__ = module + + return result diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..e2aaea3fbdf68c8c14d786b40ce4329f9f9e2126 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..a05463b754dce4d85452d592865fb828126ea322 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a96f18dcf1cf3ba7a0d12992ec79d67445a13c93 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:509d2e681897f4253263c063ad8a2aa0c2459b85ce3d86754b401d42ab26dc9a +size 105472 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_disjoint_set.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d4eecdecf8b2eb41230c93a246b4734779ee58 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_docscrape.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_docscrape.py new file mode 100644 index 0000000000000000000000000000000000000000..52e8a1727209b675ab4a8225654bf8ad75086af1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py new file mode 100644 index 0000000000000000000000000000000000000000..baa008e54b32a9bfd5bc42c939e6465493833d08 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py @@ -0,0 +1,346 @@ +# `_elementwise_iterative_method.py` includes tools for writing functions that +# - are vectorized to work elementwise on arrays, +# - implement non-trivial, iterative algorithms with a callback interface, and +# - return rich objects with iteration count, termination status, etc. +# +# Examples include: +# `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding, +# `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization, +# `scipy.optimize._differentiate._differentiate for numerical differentiation, +# `scipy.optimize._bracket._bracket_root for finding rootfinding brackets, +# `scipy.optimize._bracket._bracket_minimize for finding minimization brackets, +# `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature, +# `scipy.differentiate.derivative` for finite difference based differentiation. + +import math +import numpy as np +from ._util import _RichResult, _call_callback_maybe_halt +from ._array_api import array_namespace, xp_size, xp_result_type +import scipy._lib.array_api_extra as xpx + +_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. + xat = xp_result_type(*xs, force_floating=True, xp=xp) + xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename + xs, args = xas[:nx], xas[nx:] + xs = [xp.asarray(x, dtype=xat) for x in xs] # use copy=False when implemented + fs = [xp.asarray(func(x, *args)) for x in xs] + shape = xs[0].shape + fshape = fs[0].shape + + if preserve_shape: + # bind original shape/func now to avoid late-binding gotcha + def func(x, *args, shape=shape, func=func, **kwargs): + i = (0,)*(len(fshape) - len(shape)) + return func(x[i], *args, **kwargs) + shape = np.broadcast_shapes(fshape, shape) # just shapes; use of NumPy OK + xs = [xp.broadcast_to(x, shape) for x in xs] + args = [xp.broadcast_to(arg, shape) for arg in args] + + message = ("The shape of the array returned by `func` must be the same as " + "the broadcasted shape of `x` and all other `args`.") + if preserve_shape is not None: # only in tanhsinh for now + message = f"When `preserve_shape=False`, {message.lower()}" + shapes_equal = [f.shape == shape for f in fs] + if not all(shapes_equal): # use Python all to reduce overhead + raise ValueError(message) + + # These algorithms tend to mix the dtypes of the abscissae and function + # values, so figure out what the result will be and convert them all to + # that type from the outset. + xfat = xp.result_type(*([f.dtype for f in fs] + [xat])) + if not complex_ok and not xp.isdtype(xfat, "real floating"): + raise ValueError("Abscissae and function output must be real numbers.") + xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs] + fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs] + + # To ensure that we can do indexing, we'll work with at least 1d arrays, + # but remember the appropriate shape of the output. + xs = [xp.reshape(x, (-1,)) for x in xs] + fs = [xp.reshape(f, (-1,)) for f in fs] + args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args] + return func, xs, fs, args, shape, xfat, xp + + +def _loop(work, callback, shape, maxiter, func, args, dtype, pre_func_eval, + post_func_eval, check_termination, post_termination_check, + customize_result, res_work_pairs, xp, preserve_shape=False): + """Main loop of a vectorized scalar optimization algorithm + + Parameters + ---------- + work : _RichResult + All variables that need to be retained between iterations. Must + contain attributes `nit`, `nfev`, and `success`. All arrays are + subject to being "compressed" if `preserve_shape is False`; nest + arrays that should not be compressed inside another object (e.g. + `dict` or `_RichResult`). + callback : callable + User-specified callback function + shape : tuple of ints + The shape of all output arrays + maxiter : + Maximum number of iterations of the algorithm + func : callable + The user-specified callable that is being optimized or solved + args : tuple + Additional positional arguments to be passed to `func`. + dtype : NumPy dtype + The common dtype of all abscissae and function values + pre_func_eval : callable + A function that accepts `work` and returns `x`, the active elements + of `x` at which `func` will be evaluated. May modify attributes + of `work` with any algorithmic steps that need to happen + at the beginning of an iteration, before `func` is evaluated, + post_func_eval : callable + A function that accepts `x`, `func(x)`, and `work`. May modify + attributes of `work` with any algorithmic steps that need to happen + in the middle of an iteration, after `func` is evaluated but before + the termination check. + check_termination : callable + A function that accepts `work` and returns `stop`, a boolean array + indicating which of the active elements have met a termination + condition. + post_termination_check : callable + A function that accepts `work`. May modify `work` with any algorithmic + steps that need to happen after the termination check and before the + end of the iteration. + customize_result : callable + A function that accepts `res` and `shape` and returns `shape`. May + modify `res` (in-place) according to preferences (e.g. rearrange + elements between attributes) and modify `shape` if needed. + res_work_pairs : list of (str, str) + Identifies correspondence between attributes of `res` and attributes + of `work`; i.e., attributes of active elements of `work` will be + copied to the appropriate indices of `res` when appropriate. The order + determines the order in which _RichResult attributes will be + pretty-printed. + preserve_shape : bool, default: False + Whether to compress the attributes of `work` (to avoid unnecessary + computation on elements that have already converged). + + Returns + ------- + res : _RichResult + The final result object + + Notes + ----- + Besides providing structure, this framework provides several important + services for a vectorized optimization algorithm. + + - It handles common tasks involving iteration count, function evaluation + count, a user-specified callback, and associated termination conditions. + - It compresses the attributes of `work` to eliminate unnecessary + computation on elements that have already converged. + + """ + if xp is None: + raise NotImplementedError("Must provide xp.") + + cb_terminate = False + + # Initialize the result object and active element index array + n_elements = math.prod(shape) + active = xp.arange(n_elements) # in-progress element indices + res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs} + res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool) + res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32) + res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32) + res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32) + res = _RichResult(res_dict) + work.args = args + + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + + while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements: + x = pre_func_eval(work) + + if work.args and work.args[0].ndim != x.ndim: + # `x` always starts as 1D. If the SciPy function that uses + # _loop added dimensions to `x`, we need to + # add them to the elements of `args`. + args = [] + for arg in work.args: + n_new_dims = x.ndim - arg.ndim + new_shape = arg.shape + (1,)*n_new_dims + args.append(xp.reshape(arg, new_shape)) + work.args = args + + x_shape = x.shape + if preserve_shape: + x = xp.reshape(x, (shape + (-1,))) + f = func(x, *work.args) + f = xp.asarray(f, dtype=dtype) + if preserve_shape: + x = xp.reshape(x, x_shape) + f = xp.reshape(f, x_shape) + work.nfev += 1 if x.ndim == 1 else x.shape[-1] + + post_func_eval(x, f, work) + + work.nit += 1 + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + break + if xp_size(active) == 0: + break + + post_termination_check(work) + + work.status = xpx.at(work.status)[:].set(_ECALLBACK if cb_terminate else _ECONVERR) + return _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + + +def _check_termination(work, res, res_work_pairs, active, check_termination, + preserve_shape, xp): + # Checks termination conditions, updates elements of `res` with + # corresponding elements of `work`, and compresses `work`. + + stop = check_termination(work) + + if xp.any(stop): + # update the active elements of the result object with the active + # elements for which a termination condition has been met + _update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp) + + if preserve_shape: + stop = stop[active] + + proceed = ~stop + active = active[proceed] + + if not preserve_shape: + # compress the arrays to avoid unnecessary computation + for key, val in work.items(): + # `continued_fraction` hacks `n`; improve if this becomes a problem + if key in {'args', 'n'}: + continue + work[key] = val[proceed] if getattr(val, 'ndim', 0) > 0 else val + work.args = [arg[proceed] for arg in work.args] + + return active + + +def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp): + # Update `active` indices of the arrays in result object `res` with the + # contents of the scalars and arrays in `update_dict`. When provided, + # `mask` is a boolean array applied both to the arrays in `update_dict` + # that are to be used and to the arrays in `res` that are to be updated. + update_dict = {key1: work[key2] for key1, key2 in res_work_pairs} + update_dict['success'] = work.status == 0 + + if mask is not None: + if preserve_shape: + active_mask = xp.zeros_like(mask) + active_mask = xpx.at(active_mask)[active].set(True) + active_mask = active_mask & mask + for key, val in update_dict.items(): + val = val[active_mask] if getattr(val, 'ndim', 0) > 0 else val + res[key] = xpx.at(res[key])[active_mask].set(val) + else: + active_mask = active[mask] + for key, val in update_dict.items(): + val = val[mask] if getattr(val, 'ndim', 0) > 0 else val + res[key] = xpx.at(res[key])[active_mask].set(val) + else: + for key, val in update_dict.items(): + if preserve_shape and getattr(val, 'ndim', 0) > 0: + val = val[active] + res[key] = xpx.at(res[key])[active].set(val) + + +def _prepare_result(work, res, res_work_pairs, active, shape, customize_result, + preserve_shape, xp): + # Prepare the result object `res` by creating a copy, copying the latest + # data from work, running the provided result customization function, + # and reshaping the data to the original shapes. + res = res.copy() + _update_active(work, res, res_work_pairs, active, None, preserve_shape, xp) + + shape = customize_result(res, shape) + + for key, val in res.items(): + # this looks like it won't work for xp != np if val is not numeric + temp = xp.reshape(val, shape) + res[key] = temp[()] if temp.ndim == 0 else temp + + res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs] + return _RichResult(**res) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..d75afa0b5fbd2b0bd02828ec4fb22603ffd25eee Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..08c08ad1b6f5a6afc0b6a9a32392b460d7a9ba80 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.pyd differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_gcutils.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..c08d35c48985aced8c73c93d92e89616850e270a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_pep440.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_pep440.py new file mode 100644 index 0000000000000000000000000000000000000000..aee9f2757ce9cbd825a67a8a06a8f110b2a8b720 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_public_api.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_public_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ae370dd123a3320bd67430433a813fb302e778d
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_public_api.py
@@ -0,0 +1,56 @@
+"""PUBLIC_MODULES was once included in scipy._lib.tests.test_public_api.
+
+It has been separated into this file so that this list of public modules
+could be used when generating tables showing support for alternative
+array API backends across modules in
+scipy/doc/source/array_api_capabilities.py.
+"""
+
+# Historically SciPy has not used leading underscores for private submodules
+# much.  This has resulted in lots of things that look like public modules
+# (i.e. things that can be imported as `import scipy.somesubmodule.somefile`),
+# but were never intended to be public.  The PUBLIC_MODULES list contains
+# 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"
+]]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_sparse.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..914df4038740a36f848b348235de87e877b80f30
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_sparse.py
@@ -0,0 +1,41 @@
+from abc import ABC
+
+__all__ = ["SparseABC", "issparse"]
+
+
+class SparseABC(ABC):
+    pass
+
+
+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, SparseABC)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..9c26b029e0cd63b391b1eed50a2091199b62ae38
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..7f80f9ec417a7638faaae642c95d2395ec1aa916
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.pyd differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..e00f58b5328faf7fe7fed5c1a51f024f8f9843fe
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..ff8a69e53057d39e4dc6b775e7489a4633b4b7cd
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.pyd differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..699e4bb7fdd411bf0f106913d7ffb036f21c7f9b
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..adb9428b55a0abba57c57581890ff16c3dc0106d
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.pyd differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_testutils.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ff66215aaca3f44b39703896aed18b333f71c31
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_testutils.py
@@ -0,0 +1,373 @@
+"""
+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 is None:
+            extra_argv = []
+        pytest_args += extra_argv
+        if any(arg == "-m" or arg == "--markers" for arg in extra_argv):
+            # Likely conflict with default --mode=fast
+            raise ValueError("Must specify -m before --")
+
+        if verbose and int(verbose) > 1:
+            pytest_args += ["-" + "v"*(int(verbose)-1)]
+
+        if coverage:
+            pytest_args += ["--cov=" + module_path]
+
+        if label == "fast":
+            pytest_args += ["-m", "not slow"]
+        elif label != "full":
+            pytest_args += ["-m", label]
+
+        if tests is None:
+            tests = [self.module_name]
+
+        if parallel is not None and parallel > 1:
+            if _pytest_has_xdist():
+                pytest_args += ['-n', str(parallel)]
+            else:
+                import warnings
+                warnings.warn('Could not run tests in parallel because '
+                              'pytest-xdist plugin is not available.',
+                              stacklevel=2)
+
+        pytest_args += ['--pyargs'] + list(tests)
+
+        try:
+            code = pytest.main(pytest_args)
+        except SystemExit as exc:
+            code = exc.code
+
+        return (code == 0)
+
+
+class _TestPythranFunc:
+    '''
+    These are situations that can be tested in our pythran tests:
+    - A function with multiple array arguments and then
+      other positional and keyword arguments.
+    - A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
+    Note: list/tuple input is not yet tested!
+
+    `self.arguments`: A dictionary which key is the index of the argument,
+                      value is tuple(array value, all supported dtypes)
+    `self.partialfunc`: A function used to freeze some non-array argument
+                        that of no interests in the original function
+    '''
+    ALL_INTEGER = [np.int8, np.int16, np.int32, np.int64, np.intc, np.intp]
+    ALL_FLOAT = [np.float32, np.float64]
+    ALL_COMPLEX = [np.complex64, np.complex128]
+
+    def setup_method(self):
+        self.arguments = {}
+        self.partialfunc = None
+        self.expected = None
+
+    def get_optional_args(self, func):
+        # get optional arguments with its default value,
+        # used for testing keywords
+        signature = inspect.signature(func)
+        optional_args = {}
+        for k, v in signature.parameters.items():
+            if v.default is not inspect.Parameter.empty:
+                optional_args[k] = v.default
+        return optional_args
+
+    def get_max_dtype_list_length(self):
+        # get the max supported dtypes list length in all arguments
+        max_len = 0
+        for arg_idx in self.arguments:
+            cur_len = len(self.arguments[arg_idx][1])
+            if cur_len > max_len:
+                max_len = cur_len
+        return max_len
+
+    def get_dtype(self, dtype_list, dtype_idx):
+        # get the dtype from dtype_list via index
+        # if the index is out of range, then return the last dtype
+        if dtype_idx > len(dtype_list)-1:
+            return dtype_list[-1]
+        else:
+            return dtype_list[dtype_idx]
+
+    def test_all_dtypes(self):
+        for type_idx in range(self.get_max_dtype_list_length()):
+            args_array = []
+            for arg_idx in self.arguments:
+                new_dtype = self.get_dtype(self.arguments[arg_idx][1],
+                                           type_idx)
+                args_array.append(self.arguments[arg_idx][0].astype(new_dtype))
+            self.pythranfunc(*args_array)
+
+    def test_views(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(self.arguments[arg_idx][0][::-1][::-1])
+        self.pythranfunc(*args_array)
+
+    def test_strided(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(np.repeat(self.arguments[arg_idx][0],
+                                        2, axis=0)[::2])
+        self.pythranfunc(*args_array)
+
+
+def _pytest_has_xdist():
+    """
+    Check if the pytest-xdist plugin is installed, providing parallel tests
+    """
+    # Check xdist exists without importing, otherwise pytests emits warnings
+    from importlib.util import find_spec
+    return find_spec('xdist') is not None
+
+
+def check_free_memory(free_mb):
+    """
+    Check *free_mb* of memory is available, otherwise do pytest.skip
+    """
+    import pytest
+
+    try:
+        mem_free = _parse_size(os.environ['SCIPY_AVAILABLE_MEM'])
+        msg = '{} MB memory required, but environment SCIPY_AVAILABLE_MEM={}'.format(
+            free_mb, os.environ['SCIPY_AVAILABLE_MEM'])
+    except KeyError:
+        mem_free = _get_mem_available()
+        if mem_free is None:
+            pytest.skip("Could not determine available memory; set SCIPY_AVAILABLE_MEM "
+                        "variable to free memory in MB to run the test.")
+        msg = f'{free_mb} MB memory required, but {mem_free/1e6} MB available'
+
+    if mem_free < free_mb * 1e6:
+        pytest.skip(msg)
+
+
+def _parse_size(size_str):
+    suffixes = {'': 1e6,
+                'b': 1.0,
+                'k': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12,
+                'kb': 1e3, 'Mb': 1e6, 'Gb': 1e9, 'Tb': 1e12,
+                'kib': 1024.0, 'Mib': 1024.0**2, 'Gib': 1024.0**3, 'Tib': 1024.0**4}
+    m = re.match(r'^\s*(\d+)\s*({})\s*$'.format('|'.join(suffixes.keys())),
+                 size_str,
+                 re.I)
+    if not m or m.group(2) not in suffixes:
+        raise ValueError("Invalid size string")
+
+    return float(m.group(1)) * suffixes[m.group(2)]
+
+
+def _get_mem_available():
+    """
+    Get information about memory available, not counting swap.
+    """
+    try:
+        import psutil
+        return psutil.virtual_memory().available
+    except (ImportError, AttributeError):
+        pass
+
+    if sys.platform.startswith('linux'):
+        info = {}
+        with open('/proc/meminfo') as f:
+            for line in f:
+                p = line.split()
+                info[p[0].strip(':').lower()] = float(p[1]) * 1e3
+
+        if 'memavailable' in info:
+            # Linux >= 3.14
+            return info['memavailable']
+        else:
+            return info['memfree'] + info['cached']
+
+    return None
+
+def _test_cython_extension(tmp_path, srcdir):
+    """
+    Helper function to test building and importing Cython modules that
+    make use of the Cython APIs for BLAS, LAPACK, optimize, and special.
+    """
+    import pytest
+    try:
+        subprocess.check_call(["meson", "--version"])
+    except FileNotFoundError:
+        pytest.skip("No usable 'meson' found")
+
+    # Make safe for being called by multiple threads within one test
+    tmp_path = tmp_path / str(threading.get_ident())
+
+    # build the examples in a temporary directory
+    mod_name = os.path.split(srcdir)[1]
+    shutil.copytree(srcdir, tmp_path / mod_name)
+    build_dir = tmp_path / mod_name / 'tests' / '_cython_examples'
+    target_dir = build_dir / 'build'
+    os.makedirs(target_dir, exist_ok=True)
+
+    # Ensure we use the correct Python interpreter even when `meson` is
+    # installed in a different Python environment (see numpy#24956)
+    native_file = str(build_dir / 'interpreter-native-file.ini')
+    with open(native_file, 'w') as f:
+        f.write("[binaries]\n")
+        f.write(f"python = '{sys.executable}'")
+
+    if sys.platform == "win32":
+        subprocess.check_call(["meson", "setup",
+                               "--buildtype=release",
+                               "--native-file", native_file,
+                               "--vsenv", str(build_dir)],
+                              cwd=target_dir,
+                              )
+    else:
+        subprocess.check_call(["meson", "setup",
+                               "--native-file", native_file, str(build_dir)],
+                              cwd=target_dir
+                              )
+    subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
+
+    # import without adding the directory to sys.path
+    suffix = sysconfig.get_config_var('EXT_SUFFIX')
+
+    def load(modname):
+        so = (target_dir / modname).with_suffix(suffix)
+        spec = spec_from_file_location(modname, so)
+        mod = module_from_spec(spec)
+        spec.loader.exec_module(mod)
+        return mod
+
+    # test that the module can be imported
+    return load("extending"), load("extending_cpp")
+
+
+def _run_concurrent_barrier(n_workers, fn, *args, **kwargs):
+    """
+    Run a given function concurrently across a given number of threads.
+
+    This 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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_tmpdirs.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d863b78dfaf027e4729f3e782edaec81dcb3077
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/LICENSE b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..90e4b0a1e185e7073aae5d480af303b0ea992700
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2382b9a6c52e0e207dd37a268a6cab49f3dae591
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec898d63612a467d3f00f690ac76a94eac9f3fd8
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5e5771382155ee3eaf9ea6f4c89aaba1664fce4
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_backend.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c78dcb8f44a769529ca3a7570ce3162a564be0b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..9550e35665e2bc1fa3fbfde6d8909d15fdfb1880
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..643a6954efeae3a57360f9bfac05fecec1dea3a4
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.pyd
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2fa9cd0fca336b35fca629e2ceedde50fdeed9d6d6ea3575a2bc4889222bc2d6
+size 235008
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_util.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..81b574efdf33c4fead379617baedeef1b1d99aab
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_util.py
@@ -0,0 +1,1251 @@
+import re
+from contextlib import contextmanager
+import functools
+import operator
+import warnings
+import numbers
+from collections import namedtuple
+import inspect
+import math
+import os
+import sys
+import textwrap
+from types import ModuleType
+from typing import Literal, TypeAlias, TypeVar
+
+import numpy as np
+from scipy._lib._array_api import (Array, array_namespace, is_lazy_array, is_numpy,
+                                   is_marray, xp_size, xp_result_device, xp_result_type)
+from scipy._lib._docscrape import FunctionDoc, Parameter
+from scipy._lib._sparse import issparse
+
+from numpy.exceptions import AxisError
+
+
+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
+
+
+# Wrapped function for inspect.signature for compatibility with Python 3.14+
+# See gh-23913
+#
+# PEP 649/749 allows for underfined annotations at runtime, and added the
+# `annotation_format` parameter to handle these cases.
+# `annotationlib.Format.FORWARDREF` is the closest to previous behavior,
+# returning ForwardRef objects fornew undefined annotations cases.
+#
+# Consider dropping this wrapper when support for Python 3.13 is dropped.
+if sys.version_info >= (3, 14):
+    import annotationlib
+    def wrapped_inspect_signature(callable):
+        """Get a signature object for the passed callable."""
+        return inspect.signature(callable,
+                                 annotation_format=annotationlib.Format.FORWARDREF)
+else:
+    wrapped_inspect_signature = inspect.signature
+
+
+_RNG: TypeAlias = np.random.Generator | np.random.RandomState
+SeedType: TypeAlias = IntNumber | _RNG | None
+
+GeneratorType = TypeVar("GeneratorType", bound=_RNG)
+
+
+def _lazyselect(condlist, choicelist, arrays, default=0):
+    """
+    Mimic `np.select(condlist, choicelist)`.
+
+    Notice, it assumes that all `arrays` are of the same shape or can be
+    broadcasted together.
+
+    All functions in `choicelist` must accept array arguments in the order
+    given in `arrays` and must return an array of the same shape as broadcasted
+    `arrays`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> x = np.arange(6)
+    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
+    array([  0,   1,   4,   0,  64, 125])
+
+    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
+    array([   0.,    1.,    4.,   0.,   64.,  125.])
+
+    >>> a = -np.ones_like(x)
+    >>> _lazyselect([x < 3, x > 3],
+    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
+    ...             (x, a), default=np.nan)
+    array([   0.,    1.,    4.,   nan,  -64., -125.])
+
+    """
+    arrays = np.broadcast_arrays(*arrays)
+    tcode = np.mintypecode([a.dtype.char for a in arrays])
+    out = np.full(np.shape(arrays[0]), fill_value=default, dtype=tcode)
+    for func, cond in zip(choicelist, condlist):
+        if np.all(cond is False):
+            continue
+        cond, _ = np.broadcast_arrays(cond, arrays[0])
+        temp = tuple(np.extract(cond, arr) for arr in arrays)
+        np.place(out, cond, func(*temp))
+    return out
+
+
+def _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)
+
+        # Add the old parameter name to the function signature
+        wrapped_signature = inspect.signature(fun)
+        wrapper.__signature__ = wrapped_signature.replace(parameters=[
+            *wrapped_signature.parameters.values(),
+            inspect.Parameter(old_name, inspect.Parameter.KEYWORD_ONLY, default=None),
+        ])
+
+        if replace_doc:
+            doc = FunctionDoc(wrapper)
+            parameter_names = [param.name for param in doc['Parameters']]
+            if 'rng' in parameter_names:
+                _type = "{None, int, `numpy.random.Generator`}, optional"
+                _desc = _rng_desc.replace("{old_name}", old_name)
+                old_doc = doc['Parameters'][parameter_names.index('rng')].desc
+                old_doc_keep = old_doc[old_doc.index("") + 1:] if "" in old_doc else []
+                new_doc = [_desc] + old_doc_keep
+                _rng_parameter_doc = Parameter('rng', _type, new_doc)
+                doc['Parameters'][parameter_names.index('rng')] = _rng_parameter_doc
+                doc = str(doc).split("\n", 1)[1].lstrip(" \n")  # remove signature
+                wrapper.__doc__ = str(doc)
+        return wrapper
+
+    return decorator
+
+
+# copy-pasted from scikit-learn utils/validation.py
+def check_random_state(seed):
+    """Turn `seed` into a `np.random.RandomState` instance.
+
+    Parameters
+    ----------
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Returns
+    -------
+    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        Random number generator.
+
+    """
+    if seed is None or seed is np.random:
+        return np.random.mtrand._rand
+    if isinstance(seed, numbers.Integral | np.integer):
+        return np.random.RandomState(seed)
+    if isinstance(seed, np.random.RandomState | np.random.Generator):
+        return seed
+
+    raise ValueError(f"'{seed}' cannot be used to seed a numpy.random.RandomState"
+                     " instance")
+
+
+def _asarray_validated(a, check_finite=True,
+                       sparse_ok=False, objects_ok=False, mask_ok=False,
+                       as_inexact=False):
+    """
+    Helper function for SciPy argument validation.
+
+    Many SciPy linear algebra functions do support arbitrary array-like
+    input arguments. Examples of commonly unsupported inputs include
+    matrices containing inf/nan, sparse matrix representations, and
+    matrices with complicated elements.
+
+    Parameters
+    ----------
+    a : array_like
+        The array-like input.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    sparse_ok : bool, optional
+        True if scipy sparse matrices are allowed.
+    objects_ok : bool, optional
+        True if arrays with dype('O') are allowed.
+    mask_ok : bool, optional
+        True if masked arrays are allowed.
+    as_inexact : bool, optional
+        True to convert the input array to a np.inexact dtype.
+
+    Returns
+    -------
+    ret : ndarray
+        The converted validated array.
+
+    """
+    if not sparse_ok:
+        if issparse(a):
+            msg = ('Sparse arrays/matrices are not supported by this function. '
+                   'Perhaps one of the `scipy.sparse.linalg` functions '
+                   'would work instead.')
+            raise ValueError(msg)
+    if not mask_ok:
+        if np.ma.isMaskedArray(a):
+            raise ValueError('masked arrays are not supported')
+    toarray = np.asarray_chkfinite if check_finite else np.asarray
+    a = toarray(a)
+    if not objects_ok:
+        if a.dtype is np.dtype('O'):
+            raise ValueError('object arrays are not supported')
+    if as_inexact:
+        if not np.issubdtype(a.dtype, np.inexact):
+            a = toarray(a, dtype=np.float64)
+    return a
+
+
+def _validate_int(k, name, minimum=None):
+    """
+    Validate a scalar integer.
+
+    This function can be used to validate an argument to a function
+    that expects the value to be an integer.  It uses `operator.index`
+    to validate the value (so, for example, k=2.0 results in a
+    TypeError).
+
+    Parameters
+    ----------
+    k : int
+        The value to be validated.
+    name : str
+        The name of the parameter.
+    minimum : int, optional
+        An optional lower bound.
+    """
+    try:
+        k = operator.index(k)
+    except TypeError:
+        raise TypeError(f'{name} must be an integer.') from None
+    if minimum is not None and k < minimum:
+        raise ValueError(f'{name} must be an integer not less '
+                         f'than {minimum}') from None
+    return k
+
+
+# Add a replacement for inspect.getfullargspec()/
+# The version below is borrowed from Django,
+# https://github.com/django/django/pull/4846.
+
+# Note an inconsistency between inspect.getfullargspec(func) and
+# inspect.signature(func). If `func` is a bound method, the latter does *not*
+# list `self` as a first argument, while the former *does*.
+# Hence, cook up a common ground replacement: `getfullargspec_no_self` which
+# mimics `inspect.getfullargspec` but does not list `self`.
+#
+# This way, the caller code does not need to know whether it uses a legacy
+# .getfullargspec or a bright and shiny .signature.
+
+FullArgSpec = namedtuple('FullArgSpec',
+                         ['args', 'varargs', 'varkw', 'defaults',
+                          'kwonlyargs', 'kwonlydefaults', 'annotations'])
+
+
+def getfullargspec_no_self(func):
+    """inspect.getfullargspec replacement using inspect.signature.
+
+    If func is a bound method, do not list the 'self' parameter.
+
+    Parameters
+    ----------
+    func : callable
+        A callable to inspect
+
+    Returns
+    -------
+    fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                              kwonlydefaults, annotations)
+
+        NOTE: if the first argument of `func` is self, it is *not*, I repeat
+        *not*, included in fullargspec.args.
+        This is done for consistency between inspect.getargspec() under
+        Python 2.x, and inspect.signature() under Python 3.x.
+
+    """
+    sig = wrapped_inspect_signature(func)
+    args = [
+        p.name for p in sig.parameters.values()
+        if p.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD,
+                      inspect.Parameter.POSITIONAL_ONLY]
+    ]
+    varargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_POSITIONAL
+    ]
+    varargs = varargs[0] if varargs else None
+    varkw = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_KEYWORD
+    ]
+    varkw = varkw[0] if varkw else None
+    defaults = tuple(
+        p.default for p in sig.parameters.values()
+        if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and
+            p.default is not p.empty)
+    ) or None
+    kwonlyargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.KEYWORD_ONLY
+    ]
+    kwdefaults = {p.name: p.default for p in sig.parameters.values()
+                  if p.kind == inspect.Parameter.KEYWORD_ONLY and
+                  p.default is not p.empty}
+    annotations = {p.name: p.annotation for p in sig.parameters.values()
+                   if p.annotation is not p.empty}
+    return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                       kwdefaults or None, annotations)
+
+
+class _FunctionWrapper:
+    """
+    Object to wrap user's function, allowing picklability
+    """
+    def __init__(self, f, args):
+        self.f = f
+        self.args = [] if args is None else args
+
+    def __call__(self, x):
+        return self.f(x, *self.args)
+
+
+class _ScalarFunctionWrapper:
+    """
+    Object to wrap scalar user function, allowing picklability
+    """
+    def __init__(self, f, args=None):
+        self.f = f
+        self.args = [] if args is None else args
+        self.nfev = 0
+
+    def __call__(self, x):
+        # Send a copy because the user may overwrite it.
+        # The user of this class might want `x` to remain unchanged.
+        fx = self.f(np.copy(x), *self.args)
+        self.nfev += 1
+
+        # Make sure the function returns a true scalar
+        if not np.isscalar(fx):
+            try:
+                fx = np.asarray(fx).item()
+            except (TypeError, ValueError) as e:
+                raise ValueError(
+                    "The user-provided objective function "
+                    "must return a scalar value."
+                ) from e
+        return fx
+
+class MapWrapper:
+    """
+    Parallelisation wrapper for working with map-like callables, such as
+    `multiprocessing.Pool.map`.
+
+    Parameters
+    ----------
+    pool : int or map-like callable
+        If `pool` is an integer, then it specifies the number of threads to
+        use for parallelization. If ``int(pool) == 1``, then no parallel
+        processing is used and the map builtin is used.
+        If ``pool == -1``, then the pool will utilize all available CPUs.
+        If `pool` is a map-like callable that follows the same
+        calling sequence as the built-in map function, then this callable is
+        used for parallelization.
+    """
+    def __init__(self, pool=1):
+        self.pool = None
+        self._mapfunc = map
+        self._own_pool = False
+
+        if callable(pool):
+            self.pool = pool
+            self._mapfunc = self.pool
+        else:
+            from multiprocessing import get_context, get_start_method
+
+            method = get_start_method(allow_none=True)
+
+            if method is None and os.name=='posix' and sys.version_info < (3, 14):
+                # Python 3.13 and older used "fork" on posix, which can lead to
+                # deadlocks. This backports that fix to older Python versions.
+                method = 'forkserver'
+
+            # user supplies a number
+            if int(pool) == -1:
+                # use as many processors as possible
+                self.pool = get_context(method=method).Pool()
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            elif int(pool) == 1:
+                pass
+            elif int(pool) > 1:
+                # use the number of processors requested
+                self.pool = get_context(method=method).Pool(processes=int(pool))
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            else:
+                raise RuntimeError("Number of workers specified must be -1,"
+                                   " an int >= 1, or an object with a 'map' "
+                                   "method")
+
+    def __enter__(self):
+        return self
+
+    def terminate(self):
+        if self._own_pool:
+            self.pool.terminate()
+
+    def join(self):
+        if self._own_pool:
+            self.pool.join()
+
+    def close(self):
+        if self._own_pool:
+            self.pool.close()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        if self._own_pool:
+            self.pool.close()
+            self.pool.terminate()
+
+    def __call__(self, func, iterable):
+        # only accept one iterable because that's all Pool.map accepts
+        try:
+            return self._mapfunc(func, iterable)
+        except TypeError as e:
+            # wrong number of arguments
+            raise TypeError("The map-like callable must be of the"
+                            " form f(func, iterable)") from e
+
+
+def _workers_wrapper(func):
+    """
+    Wrapper to deal with setup-cleanup of workers outside a user function via a
+    ContextManager. It saves having to do the setup/tear down with within that
+    function, which can be messy.
+    """
+    @functools.wraps(func)
+    def inner(*args, **kwds):
+        kwargs = kwds.copy()
+        if 'workers' not in kwargs:
+            _workers = map
+        elif 'workers' in kwargs and kwargs['workers'] is None:
+            _workers = map
+        else:
+            _workers = kwargs['workers']
+
+        with MapWrapper(_workers) as mf:
+            kwargs['workers'] = mf
+            return func(*args, **kwargs)
+
+    return inner
+
+
+def rng_integers(gen, low, high=None, size=None, dtype='int64',
+                 endpoint=False):
+    """
+    Return random integers from low (inclusive) to high (exclusive), or if
+    endpoint=True, low (inclusive) to high (inclusive). Replaces
+    `RandomState.randint` (with endpoint=False) and
+    `RandomState.random_integers` (with endpoint=True).
+
+    Return random integers from the "discrete uniform" distribution of the
+    specified dtype. If high is None (the default), then results are from
+    0 to low.
+
+    Parameters
+    ----------
+    gen : {None, np.random.RandomState, np.random.Generator}
+        Random number generator. If None, then the np.random.RandomState
+        singleton is used.
+    low : int or array-like of ints
+        Lowest (signed) integers to be drawn from the distribution (unless
+        high=None, in which case this parameter is 0 and this value is used
+        for high).
+    high : int or array-like of ints
+        If provided, one above the largest (signed) integer to be drawn from
+        the distribution (see above for behavior if high=None). If array-like,
+        must contain integer values.
+    size : array-like of ints, optional
+        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
+        samples are drawn. Default is None, in which case a single value is
+        returned.
+    dtype : {str, dtype}, optional
+        Desired dtype of the result. All dtypes are determined by their name,
+        i.e., 'int64', 'int', etc, so byteorder is not available and a specific
+        precision may have different C types depending on the platform.
+        The default value is 'int64'.
+    endpoint : bool, optional
+        If True, sample from the interval [low, high] instead of the default
+        [low, high) Defaults to False.
+
+    Returns
+    -------
+    out: int or ndarray of ints
+        size-shaped array of random integers from the appropriate distribution,
+        or a single such random int if size not provided.
+    """
+    if isinstance(gen, np.random.Generator):
+        return gen.integers(low, high=high, size=size, dtype=dtype,
+                            endpoint=endpoint)
+    else:
+        if gen is None:
+            # default is RandomState singleton used by np.random.
+            gen = np.random.mtrand._rand
+        if endpoint:
+            # inclusive of endpoint
+            # remember that low and high can be arrays, so don't modify in
+            # place
+            if high is None:
+                return gen.randint(low + 1, size=size, dtype=dtype)
+            if high is not None:
+                return gen.randint(low, high=high + 1, size=size, dtype=dtype)
+
+        # exclusive
+        return gen.randint(low, high=high, size=size, dtype=dtype)
+
+
+@contextmanager
+def _fixed_default_rng(seed=1638083107694713882823079058616272161):
+    """Context with a fixed np.random.default_rng seed."""
+    orig_fun = np.random.default_rng
+    np.random.default_rng = lambda seed=seed: orig_fun(seed)
+    try:
+        yield
+    finally:
+        np.random.default_rng = orig_fun
+
+
+@contextmanager
+def ignore_warns(expected_warning, *, match=None):
+    with warnings.catch_warnings():
+        warnings.filterwarnings("ignore", match, expected_warning)
+        yield
+
+
+def _rng_html_rewrite(func):
+    """Rewrite the HTML rendering of ``np.random.default_rng``.
+
+    This is intended to decorate
+    ``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.
+
+    Examples are only run by Sphinx when there are plot involved. Even so,
+    it does not change the result values getting printed.
+    """
+    # hexadecimal or number seed, case-insensitive
+    pattern = re.compile(r'np.random.default_rng\((0x[0-9A-F]+|\d+)\)', re.I)
+
+    def _wrapped(*args, **kwargs):
+        res = func(*args, **kwargs)
+        lines = [
+            re.sub(pattern, 'np.random.default_rng()', line)
+            for line in res
+        ]
+        return lines
+
+    return _wrapped
+
+
+def _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 _contains_nan(
+    a: Array,
+    nan_policy: Literal["propagate", "raise", "omit"] = "propagate",
+    *,
+    xp_omit_okay: bool = False,
+    xp: ModuleType | None = None,
+) -> Array | bool:
+    # Regarding `xp_omit_okay`: Temporarily, while `_axis_nan_policy` does not
+    # handle non-NumPy arrays, most functions that call `_contains_nan` want
+    # it to raise an error if `nan_policy='omit'` and `xp` is not `np`.
+    # Some functions support `nan_policy='omit'` natively, so setting this to
+    # `True` prevents the error from being raised.
+    policies = {"propagate", "raise", "omit"}
+    if nan_policy not in policies:
+        msg = f"nan_policy must be one of {policies}."
+        raise ValueError(msg)
+
+    if xp_size(a) == 0:
+        return False
+
+    if xp is None:
+        xp = array_namespace(a)
+
+    if xp.isdtype(a.dtype, "real floating"):
+        # Faster and less memory-intensive than xp.any(xp.isnan(a)), and unlike other
+        # reductions, `max`/`min` won't return NaN unless there is a NaN in the data.
+        contains_nan = xp.isnan(xp.max(a))
+    elif xp.isdtype(a.dtype, "complex floating"):
+        # Typically `real` and `imag` produce views; otherwise, `xp.any(xp.isnan(a))`
+        # would be more efficient.
+        contains_nan = xp.isnan(xp.max(xp.real(a))) | xp.isnan(xp.max(xp.imag(a)))
+    elif is_numpy(xp) and np.issubdtype(a.dtype, object):
+        contains_nan = False
+        for el in a.ravel():
+            # isnan doesn't work on non-numeric elements
+            if np.issubdtype(type(el), np.number) and np.isnan(el):
+                contains_nan = True
+                break
+    else:
+        # Only `object` and `inexact` arrays can have NaNs
+        return False
+
+    # The implicit call to bool(contains_nan) must happen after testing
+    # nan_policy to prevent lazy and device-bound xps from raising in the
+    # default policy='propagate' case.
+    if nan_policy == 'raise':
+        if is_lazy_array(a):
+            msg = "nan_policy='raise' is not supported for lazy arrays."
+            raise TypeError(msg)
+        if contains_nan:
+            msg = "The input contains nan values"
+            raise ValueError(msg)
+    elif nan_policy == 'omit' and not xp_omit_okay and not is_numpy(xp):
+        if is_lazy_array(a):
+            msg = "nan_policy='omit' is not supported for lazy arrays."
+            raise TypeError(msg)
+
+    return contains_nan
+
+
+def _rename_parameter(old_name, new_name, dep_version=None):
+    """
+    Generate decorator for backward-compatible keyword renaming.
+
+    Apply the decorator generated by `_rename_parameter` to functions with a
+    recently renamed parameter to maintain backward-compatibility.
+
+    After decoration, the function behaves as follows:
+    If only the new parameter is passed into the function, behave as usual.
+    If only the old parameter is passed into the function (as a keyword), raise
+    a DeprecationWarning if `dep_version` is provided, and behave as usual
+    otherwise.
+    If both old and new parameters are passed into the function, raise a
+    DeprecationWarning if `dep_version` is provided, and raise the appropriate
+    TypeError (function got multiple values for argument).
+
+    Parameters
+    ----------
+    old_name : str
+        Old name of parameter
+    new_name : str
+        New name of parameter
+    dep_version : str, optional
+        Version of SciPy in which old parameter was deprecated in the format
+        'X.Y.Z'. If supplied, the deprecation message will indicate that
+        support for the old parameter will be removed in version 'X.Y+2.Z'
+
+    Notes
+    -----
+    Untested with functions that accept *args. Probably won't work as written.
+
+    """
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            if old_name in kwargs:
+                if dep_version:
+                    end_version = dep_version.split('.')
+                    end_version[1] = str(int(end_version[1]) + 2)
+                    end_version = '.'.join(end_version)
+                    message = (f"Use of keyword argument `{old_name}` is "
+                               f"deprecated and replaced by `{new_name}`.  "
+                               f"Support for `{old_name}` will be removed "
+                               f"in SciPy {end_version}.")
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+                if new_name in kwargs:
+                    message = (f"{fun.__name__}() got multiple values for "
+                               f"argument now known as `{new_name}`")
+                    raise TypeError(message)
+                kwargs[new_name] = kwargs.pop(old_name)
+            return fun(*args, **kwargs)
+        return wrapper
+    return decorator
+
+
+def _rng_spawn(rng, n_children):
+    # spawns independent RNGs from a parent RNG
+    bg = rng._bit_generator
+    ss = bg._seed_seq
+    child_rngs = [np.random.Generator(type(bg)(child_ss))
+                  for child_ss in ss.spawn(n_children)]
+    return child_rngs
+
+
+def _get_nan(*data, shape=(), xp=None):
+    xp = array_namespace(*data) if xp is None else xp
+    # Get NaN of appropriate dtype for data
+    dtype = xp_result_type(*data, force_floating=True, xp=xp)
+    device = xp_result_device(*data)
+    res = xp.full(shape, xp.nan, dtype=dtype, device=device)
+    if not shape:
+        res = res[()]
+    # whenever mdhaber/marray#89 is resolved, could just return `res`
+    return res.data if is_marray(xp) else res
+
+
+def normalize_axis_index(axis, ndim):
+    # Check if `axis` is in the correct range and normalize it
+    if axis < -ndim or axis >= ndim:
+        msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
+        raise AxisError(msg)
+
+    if axis < 0:
+        axis = axis + ndim
+    return axis
+
+
+def _call_callback_maybe_halt(callback, res):
+    """Call wrapped callback; return True if algorithm should stop.
+
+    Parameters
+    ----------
+    callback : callable or None
+        A user-provided callback wrapped with `_wrap_callback`
+    res : OptimizeResult
+        Information about the current iterate
+
+    Returns
+    -------
+    halt : bool
+        True if minimization should stop
+
+    """
+    if callback is None:
+        return False
+    try:
+        callback(res)
+        return False
+    except StopIteration:
+        callback.stop_iteration = True
+        return True
+
+
+class _RichResult(dict):
+    """ Container for multiple outputs with pretty-printing """
+    def __getattr__(self, name):
+        try:
+            return self[name]
+        except KeyError as e:
+            raise AttributeError(name) from e
+
+    __setattr__ = dict.__setitem__  # type: ignore[assignment]
+    __delattr__ = dict.__delitem__  # type: ignore[assignment]
+
+    def __repr__(self):
+        order_keys = ['message', 'success', 'status', 'fun', 'funl', 'x', 'xl',
+                      'col_ind', 'nit', 'lower', 'upper', 'eqlin', 'ineqlin',
+                      'converged', 'flag', 'function_calls', 'iterations',
+                      'root']
+        order_keys = getattr(self, '_order_keys', order_keys)
+        # 'slack', 'con' are redundant with residuals
+        # 'crossover_nit' is probably not interesting to most users
+        omit_keys = {'slack', 'con', 'crossover_nit', '_order_keys'}
+
+        def key(item):
+            try:
+                return order_keys.index(item[0].lower())
+            except ValueError:  # item not in list
+                return np.inf
+
+        def omit_redundant(items):
+            for item in items:
+                if item[0] in omit_keys:
+                    continue
+                yield item
+
+        def item_sorter(d):
+            return sorted(omit_redundant(d.items()), key=key)
+
+        if self.keys():
+            return _dict_formatter(self, sorter=item_sorter)
+        else:
+            return self.__class__.__name__ + "()"
+
+    def __dir__(self):
+        return list(self.keys())
+
+
+def _indenter(s, n=0):
+    """
+    Ensures that lines after the first are indented by the specified amount
+    """
+    split = s.split("\n")
+    indent = " "*n
+    return ("\n" + indent).join(split)
+
+
+def _float_formatter_10(x):
+    """
+    Returns a string representation of a float with exactly ten characters
+    """
+    if np.isposinf(x):
+        return "       inf"
+    elif np.isneginf(x):
+        return "      -inf"
+    elif np.isnan(x):
+        return "       nan"
+    return np.format_float_scientific(x, precision=3, pad_left=2, unique=False)
+
+
+def _dict_formatter(d, n=0, mplus=1, sorter=None):
+    """
+    Pretty printer for dictionaries
+
+    `n` keeps track of the starting indentation;
+    lines are indented by this much after a line break.
+    `mplus` is additional left padding applied to keys
+    """
+    if isinstance(d, dict):
+        m = max(map(len, list(d.keys()))) + mplus  # width to print keys
+        s = '\n'.join([k.rjust(m) + ': ' +  # right justified, width m
+                       _indenter(_dict_formatter(v, m+n+2, 0, sorter), m+2)
+                       for k, v in sorter(d)])  # +2 for ': '
+    else:
+        # By default, NumPy arrays print with linewidth=76. `n` is
+        # the indent at which a line begins printing, so it is subtracted
+        # from the default to avoid exceeding 76 characters total.
+        # `edgeitems` is the number of elements to include before and after
+        # ellipses when arrays are not shown in full.
+        # `threshold` is the maximum number of elements for which an
+        # array is shown in full.
+        # These values tend to work well for use with OptimizeResult.
+        with np.printoptions(linewidth=76-n, edgeitems=2, threshold=12,
+                             formatter={'float_kind': _float_formatter_10}):
+            s = str(d)
+    return s
+
+
+_batch_note = """
+The documentation is written assuming array arguments are of specified
+"core" shapes. However, array argument(s) of this function may have additional
+"batch" dimensions prepended to the core shape. In this case, the array is treated
+as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+Note that calls with zero-size batches are unsupported and will raise a ``ValueError``.
+"""
+
+
+def _apply_over_batch(*argdefs):
+    """
+    Factory for decorator that applies a function over batched arguments.
+
+    Array arguments may have any number of core dimensions (typically 0,
+    1, or 2) and any broadcastable batch shapes. There may be any
+    number of array outputs of any number of dimensions. Assumptions
+    right now - which are satisfied by all functions of interest in `linalg` -
+    are that all array inputs are consecutive keyword or positional arguments,
+    and that the wrapped function returns either a single array or a tuple of
+    arrays. It's only as general as it needs to be right now - it can be extended.
+
+    Parameters
+    ----------
+    *argdefs : tuple of (str, int)
+        Definitions of array arguments: the keyword name of the argument, and
+        the number of core dimensions.
+
+    Example:
+    --------
+    `linalg.eig` accepts two matrices as the first two arguments `a` and `b`, where
+    `b` is optional, and returns one array or a tuple of arrays, depending on the
+    values of other positional or keyword arguments. To generate a wrapper that applies
+    the function over batches of `a` and optionally `b` :
+
+    >>> _apply_over_batch(('a', 2), ('b', 2))
+    """
+    names, ndims = list(zip(*argdefs))
+    n_arrays = len(names)
+
+    def decorator(f):
+        @functools.wraps(f)
+        def wrapper(*args, **kwargs):
+            args = list(args)
+
+            # Ensure all arrays in `arrays`, other arguments in `other_args`/`kwargs`
+            arrays, other_args = args[:n_arrays], args[n_arrays:]
+            for i, name in enumerate(names):
+                if name in kwargs:
+                    if i + 1 <= len(args):
+                        raise ValueError(f'{f.__name__}() got multiple values '
+                                         f'for argument `{name}`.')
+                    else:
+                        arrays.append(kwargs.pop(name))
+
+            xp = array_namespace(*arrays)
+
+            # Determine core and batch shapes
+            batch_shapes = []
+            core_shapes = []
+            for i, (array, ndim) in enumerate(zip(arrays, ndims)):
+                array = None if array is None else xp.asarray(array)
+                shape = () if array is None else array.shape
+
+                if ndim == "1|2":  # special case for `solve`, etc.
+                    ndim = 2 if array.ndim >= 2 else 1
+
+                arrays[i] = array
+                batch_shapes.append(shape[:-ndim] if ndim > 0 else shape)
+                core_shapes.append(shape[-ndim:] if ndim > 0 else ())
+
+            # Early exit if call is not batched
+            if not any(batch_shapes):
+                return f(*arrays, *other_args, **kwargs)
+
+            # Determine broadcasted batch shape
+            batch_shape = np.broadcast_shapes(*batch_shapes)  # Gives OK error message
+
+            # We can't support zero-size batches right now because without data with
+            # which to call the function, the decorator doesn't even know the *number*
+            # of outputs, let alone their core shapes or dtypes.
+            if math.prod(batch_shape) == 0:
+                message = f'`{f.__name__}` does not support zero-size batches.'
+                raise ValueError(message)
+
+            # Broadcast arrays to appropriate shape
+            for i, (array, core_shape) in enumerate(zip(arrays, core_shapes)):
+                if array is None:
+                    continue
+                arrays[i] = xp.broadcast_to(array, batch_shape + core_shape)
+
+            # Main loop
+            results = []
+            for index in np.ndindex(batch_shape):
+                result = f(*((array[index] if array is not None else None)
+                             for array in arrays), *other_args, **kwargs)
+                # Assume `result` is either a tuple or single array. This is easily
+                # generalized by allowing the contributor to pass an `unpack_result`
+                # callable to the decorator factory.
+                result = (result,) if not isinstance(result, tuple) else result
+                results.append(result)
+            results = list(zip(*results))
+
+            # Reshape results
+            for i, result in enumerate(results):
+                result = xp.stack(result)
+                core_shape = result.shape[1:]
+                results[i] = xp.reshape(result, batch_shape + core_shape)
+
+            # Assume `result` should be a single array if there is only one element or
+            # a `tuple` otherwise. This is easily generalized by allowing the
+            # contributor to pass an `pack_result` callable to the decorator factory.
+            return results[0] if len(results) == 1 else results
+
+        doc = FunctionDoc(wrapper)
+        doc['Extended Summary'].append(_batch_note.rstrip())
+        wrapper.__doc__ = str(doc).split("\n", 1)[1].lstrip(" \n")  # remove signature
+
+        return wrapper
+    return decorator
+
+
+def np_vecdot(x1, x2, /, *, axis=-1):
+    # `np.vecdot` has advantages (e.g. see gh-22462), so let's use it when
+    # available. As functions are translated to Array API, `np_vecdot` can be
+    # replaced with `xp.vecdot`.
+    if np.__version__ > "2.0":
+        return np.vecdot(x1, x2, axis=axis)
+    else:
+        # of course there are other fancy ways of doing this (e.g. `einsum`)
+        # but let's keep it simple since it's temporary
+        return np.sum(x1 * x2, axis=axis)
+
+
+def _dedent_for_py313(s):
+    """Apply textwrap.dedent to s for Python versions 3.13 or later."""
+    return s if sys.version_info < (3, 13) else textwrap.dedent(s)
+
+
+def broadcastable(shape_a: tuple[int, ...], shape_b: tuple[int, ...]) -> bool:
+    """Check if two shapes are broadcastable."""
+    return all(
+        (m == n) or (m == 1) or (n == 1) for m, n in zip(shape_a[::-1], shape_b[::-1])
+    )
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..63696b08b03a3dfe5bc983839774b6967ab2fe93
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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, CuPy, JAX, sparse and others that are
+compatible with the Array API standard https://data-apis.org/array-api/latest/.
+See also NEP 47 https://numpy.org/neps/nep-0047-array-api-standard.html.
+
+Unlike array_api_strict, this is not a strict minimal implementation of the
+Array API, but rather just an extension of the main NumPy namespace with
+changes needed to be compliant with the Array API. See
+https://numpy.org/doc/stable/reference/array_api.html for a full list of
+changes. In particular, unlike array_api_strict, this package does not use a
+separate Array object, but rather just uses numpy.ndarray directly.
+
+Library authors using the Array API may wish to test against array_api_strict
+to ensure they are not using functionality outside of the standard, but prefer
+this implementation for the default when working with NumPy arrays.
+
+"""
+__version__ = '1.13.0'
+
+from .common import *  # noqa: F401, F403
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01618c5f7e46c6b6852f1ef5b06655c960bb12b3
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c7bd0c41d480323a08b81a50ca3a571ac15ffed6
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/_internal.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..566da6bb380a2debabc9e9ece115e4b2c9b893a7
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/_internal.py
@@ -0,0 +1,77 @@
+"""
+Internal helpers
+"""
+
+import importlib
+from collections.abc import Callable
+from functools import wraps
+from inspect import signature
+from types import ModuleType
+from typing import TypeVar
+
+_T = TypeVar("_T")
+
+
+def get_xp(xp: ModuleType) -> Callable[[Callable[..., _T]], Callable[..., _T]]:
+    """
+    Decorator to automatically replace xp with the corresponding array module.
+
+    Use like
+
+    import numpy as np
+
+    @get_xp(np)
+    def func(x, /, xp, kwarg=None):
+        return xp.func(x, kwarg=kwarg)
+
+    Note that xp must be a keyword argument and come after all non-keyword
+    arguments.
+
+    """
+
+    def inner(f: Callable[..., _T], /) -> Callable[..., _T]:
+        @wraps(f)
+        def wrapped_f(*args: object, **kwargs: object) -> object:
+            return f(*args, xp=xp, **kwargs)
+
+        sig = signature(f)
+        new_sig = sig.replace(
+            parameters=[par for i, par in sig.parameters.items() if i != "xp"]
+        )
+
+        if wrapped_f.__doc__ is None:
+            wrapped_f.__doc__ = f"""\
+Array API compatibility wrapper for {f.__name__}.
+
+See the corresponding documentation in NumPy/CuPy and/or the array API
+specification for more details.
+
+"""
+        wrapped_f.__signature__ = new_sig  # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]
+        return wrapped_f  # type: ignore[return-value] # pyright: ignore[reportReturnType]
+
+    return inner
+
+
+def clone_module(mod_name: str, globals_: dict[str, object]) -> list[str]:
+    """Import everything from module, updating globals().
+    Returns __all__.
+    """
+    mod = importlib.import_module(mod_name)
+    # Neither of these two methods is sufficient by itself,
+    # depending on various idiosyncrasies of the libraries we're wrapping.
+    objs = {}
+    exec(f"from {mod.__name__} import *", objs)
+
+    for n in dir(mod):
+        if not n.startswith("_") and hasattr(mod, n):
+            objs[n] = getattr(mod, n)
+
+    globals_.update(objs)
+    return list(objs)
+
+
+__all__ = ["get_xp", "clone_module"]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..abb3bc480b2ab6725632868f8323761f8c90279f
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__init__.py
@@ -0,0 +1 @@
+from ._helpers import *  # noqa: F403
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60a76e1c5ba83d63c882a88edacb84ba39a8ab59
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5378c5bc5aa9d92ac5618dbfd721be96dd0eb216
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39ede79dc3ecc37f04aedb0a20cdd334e3b104f7
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88a9ffbb8f0680e648b1e4783f90533ec7924b7f
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb41a8d3600bdd75ead65f1cf12cb0cf934c4a21
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_typing.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_typing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a294662f9f7acd317c95a5585183b4744715659
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_typing.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_aliases.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..31849b08985dce9d46cf0fc8ba733fe3a9f97f3e
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
@@ -0,0 +1,702 @@
+"""
+These are functions that are just aliases of existing functions in NumPy.
+"""
+
+from __future__ import annotations
+
+import inspect
+from collections.abc import Sequence
+from typing import TYPE_CHECKING, Any, NamedTuple, cast
+
+from ._helpers import _check_device, array_namespace
+from ._helpers import device as _get_device
+from ._helpers import is_cupy_namespace
+from ._typing import Array, Device, DType, Namespace
+
+if TYPE_CHECKING:
+    # TODO: import from typing (requires Python >=3.13)
+    from typing_extensions import TypeIs
+
+# These functions are modified from the NumPy versions.
+
+# Creation functions add the device keyword (which does nothing for NumPy and Dask)
+
+
+def arange(
+    start: float,
+    /,
+    stop: float | None = None,
+    step: float = 1,
+    *,
+    xp: Namespace,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.arange(start, stop=stop, step=step, dtype=dtype, **kwargs)
+
+
+def empty(
+    shape: int | tuple[int, ...],
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.empty(shape, dtype=dtype, **kwargs)
+
+
+def empty_like(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.empty_like(x, dtype=dtype, **kwargs)
+
+
+def eye(
+    n_rows: int,
+    n_cols: int | None = None,
+    /,
+    *,
+    xp: Namespace,
+    k: int = 0,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.eye(n_rows, M=n_cols, k=k, dtype=dtype, **kwargs)
+
+
+def full(
+    shape: int | tuple[int, ...],
+    fill_value: complex,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.full(shape, fill_value, dtype=dtype, **kwargs)
+
+
+def full_like(
+    x: Array,
+    /,
+    fill_value: complex,
+    *,
+    xp: Namespace,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.full_like(x, fill_value, dtype=dtype, **kwargs)
+
+
+def linspace(
+    start: float,
+    stop: float,
+    /,
+    num: int,
+    *,
+    xp: Namespace,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    endpoint: bool = True,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.linspace(start, stop, num, dtype=dtype, endpoint=endpoint, **kwargs)
+
+
+def ones(
+    shape: int | tuple[int, ...],
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.ones(shape, dtype=dtype, **kwargs)
+
+
+def ones_like(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.ones_like(x, dtype=dtype, **kwargs)
+
+
+def zeros(
+    shape: int | tuple[int, ...],
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.zeros(shape, dtype=dtype, **kwargs)
+
+
+def zeros_like(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.zeros_like(x, dtype=dtype, **kwargs)
+
+
+# np.unique() is split into four functions in the array API:
+# unique_all, unique_counts, unique_inverse, and unique_values (this is done
+# to remove polymorphic return types).
+
+# The functions here return namedtuples (np.unique() returns a normal
+# tuple).
+
+
+# Note that these named tuples aren't actually part of the standard namespace,
+# but I don't see any issue with exporting the names here regardless.
+class UniqueAllResult(NamedTuple):
+    values: Array
+    indices: Array
+    inverse_indices: Array
+    counts: Array
+
+
+class UniqueCountsResult(NamedTuple):
+    values: Array
+    counts: Array
+
+
+class UniqueInverseResult(NamedTuple):
+    values: Array
+    inverse_indices: Array
+
+
+def _unique_kwargs(xp: Namespace) -> dict[str, bool]:
+    # Older versions of NumPy and CuPy do not have equal_nan. Rather than
+    # trying to parse version numbers, just check if equal_nan is in the
+    # signature.
+    s = inspect.signature(xp.unique)
+    if "equal_nan" in s.parameters:
+        return {"equal_nan": False}
+    return {}
+
+
+def unique_all(x: Array, /, xp: Namespace) -> UniqueAllResult:
+    kwargs = _unique_kwargs(xp)
+    values, indices, inverse_indices, counts = xp.unique(
+        x,
+        return_counts=True,
+        return_index=True,
+        return_inverse=True,
+        **kwargs,
+    )
+    # np.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueAllResult(
+        values,
+        indices,
+        inverse_indices,
+        counts,
+    )
+
+
+def unique_counts(x: Array, /, xp: Namespace) -> UniqueCountsResult:
+    kwargs = _unique_kwargs(xp)
+    res = xp.unique(
+        x, return_counts=True, return_index=False, return_inverse=False, **kwargs
+    )
+
+    return UniqueCountsResult(*res)
+
+
+def unique_inverse(x: Array, /, xp: Namespace) -> UniqueInverseResult:
+    kwargs = _unique_kwargs(xp)
+    values, inverse_indices = xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=True,
+        **kwargs,
+    )
+    # xp.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueInverseResult(values, inverse_indices)
+
+
+def unique_values(x: Array, /, xp: Namespace) -> Array:
+    kwargs = _unique_kwargs(xp)
+    return xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=False,
+        **kwargs,
+    )
+
+
+# These functions have different keyword argument names
+
+
+def std(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    correction: float = 0.0,  # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs: object,
+) -> Array:
+    return xp.std(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+
+def var(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    correction: float = 0.0,  # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs: object,
+) -> Array:
+    return xp.var(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+
+# cumulative_sum is renamed from cumsum, and adds the include_initial keyword
+# argument
+
+
+def cumulative_sum(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | None = None,
+    dtype: DType | None = None,
+    include_initial: bool = False,
+    **kwargs: object,
+) -> Array:
+    wrapped_xp = array_namespace(x)
+
+    # TODO: The standard is not clear about what should happen when x.ndim == 0.
+    if axis is None:
+        if x.ndim > 1:
+            raise ValueError(
+                "axis must be specified in cumulative_sum for more than one dimension"
+            )
+        axis = 0
+
+    res = xp.cumsum(x, axis=axis, dtype=dtype, **kwargs)
+
+    # np.cumsum does not support include_initial
+    if include_initial:
+        initial_shape = list(x.shape)
+        initial_shape[axis] = 1
+        res = xp.concatenate(
+            [
+                wrapped_xp.zeros(
+                    shape=initial_shape, dtype=res.dtype, device=_get_device(res)
+                ),
+                res,
+            ],
+            axis=axis,
+        )
+    return res
+
+
+def cumulative_prod(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | None = None,
+    dtype: DType | None = None,
+    include_initial: bool = False,
+    **kwargs: object,
+) -> Array:
+    wrapped_xp = array_namespace(x)
+
+    if axis is None:
+        if x.ndim > 1:
+            raise ValueError(
+                "axis must be specified in cumulative_prod for more than one dimension"
+            )
+        axis = 0
+
+    res = xp.cumprod(x, axis=axis, dtype=dtype, **kwargs)
+
+    # np.cumprod does not support include_initial
+    if include_initial:
+        initial_shape = list(x.shape)
+        initial_shape[axis] = 1
+        res = xp.concatenate(
+            [
+                wrapped_xp.ones(
+                    shape=initial_shape, dtype=res.dtype, device=_get_device(res)
+                ),
+                res,
+            ],
+            axis=axis,
+        )
+    return res
+
+
+# The min and max argument names in clip are different and not optional in numpy, and type
+# promotion behavior is different.
+def clip(
+    x: Array,
+    /,
+    min: float | Array | None = None,
+    max: float | Array | None = None,
+    *,
+    xp: Namespace,
+    # TODO: np.clip has other ufunc kwargs
+    out: Array | None = None,
+) -> Array:
+    def _isscalar(a: object) -> TypeIs[float | None]:
+        return isinstance(a, int | float) or a is None
+
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    wrapped_xp = array_namespace(x)
+
+    result_shape = xp.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    # np.clip does type promotion but the array API clip requires that the
+    # output have the same dtype as x. We do this instead of just downcasting
+    # the result of xp.clip() to handle some corner cases better (e.g.,
+    # avoiding uint64 -> float64 promotion).
+
+    # Note: cases where min or max overflow (integer) or round (float) in the
+    # wrong direction when downcasting to x.dtype are unspecified. This code
+    # just does whatever NumPy does when it downcasts in the assignment, but
+    # other behavior could be preferred, especially for integers. For example,
+    # this code produces:
+
+    # >>> clip(asarray(0, dtype=int8), asarray(128, dtype=int16), None)
+    # -128
+
+    # but an answer of 0 might be preferred. See
+    # https://github.com/numpy/numpy/issues/24976 for more discussion on this issue.
+
+    # At least handle the case of Python integers correctly (see
+    # https://github.com/numpy/numpy/pull/26892).
+    if wrapped_xp.isdtype(x.dtype, "integral"):
+        if type(min) is int and min <= wrapped_xp.iinfo(x.dtype).min:
+            min = None
+        if type(max) is int and max >= wrapped_xp.iinfo(x.dtype).max:
+            max = None
+
+    dev = _get_device(x)
+    if out is None:
+        out = wrapped_xp.empty(result_shape, dtype=x.dtype, device=dev)
+    assert out is not None  # workaround for a type-narrowing issue in pyright
+    out[()] = x
+
+    if min is not None:
+        a = wrapped_xp.asarray(min, dtype=x.dtype, device=dev)
+        a = xp.broadcast_to(a, result_shape)
+        ia = (out < a) | xp.isnan(a)
+        out[ia] = a[ia]
+
+    if max is not None:
+        b = wrapped_xp.asarray(max, dtype=x.dtype, device=dev)
+        b = xp.broadcast_to(b, result_shape)
+        ib = (out > b) | xp.isnan(b)
+        out[ib] = b[ib]
+
+    # Return a scalar for 0-D
+    return out[()]
+
+
+# Unlike transpose(), the axes argument to permute_dims() is required.
+def permute_dims(x: Array, /, axes: tuple[int, ...], xp: Namespace) -> Array:
+    return xp.transpose(x, axes)
+
+
+# np.reshape calls the keyword argument 'newshape' instead of 'shape'
+def reshape(
+    x: Array,
+    /,
+    shape: tuple[int, ...],
+    xp: Namespace,
+    *,
+    copy: bool | None = None,
+    **kwargs: object,
+) -> Array:
+    if copy is True:
+        x = x.copy()
+    elif copy is False:
+        y = x.view()
+        y.shape = shape
+        return y
+    return xp.reshape(x, shape, **kwargs)
+
+
+# The descending keyword is new in sort and argsort, and 'kind' replaced with
+# 'stable'
+def argsort(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int = -1,
+    descending: bool = False,
+    stable: bool = True,
+    **kwargs: object,
+) -> Array:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs["kind"] = "stable"
+    if not descending:
+        res = xp.argsort(x, axis=axis, **kwargs)
+    else:
+        # As NumPy has no native descending sort, we imitate it here. Note that
+        # simply flipping the results of xp.argsort(x, ...) would not
+        # respect the relative order like it would in native descending sorts.
+        res = xp.flip(
+            xp.argsort(xp.flip(x, axis=axis), axis=axis, **kwargs),
+            axis=axis,
+        )
+        # Rely on flip()/argsort() to validate axis
+        normalised_axis = axis if axis >= 0 else x.ndim + axis
+        max_i = x.shape[normalised_axis] - 1
+        res = max_i - res
+    return res
+
+
+def sort(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int = -1,
+    descending: bool = False,
+    stable: bool = True,
+    **kwargs: object,
+) -> Array:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs["kind"] = "stable"
+    res = xp.sort(x, axis=axis, **kwargs)
+    if descending:
+        res = xp.flip(res, axis=axis)
+    return res
+
+
+# nonzero should error for zero-dimensional arrays
+def nonzero(x: Array, /, xp: Namespace, **kwargs: object) -> tuple[Array, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return xp.nonzero(x, **kwargs)
+
+
+# linear algebra functions
+
+
+def matmul(x1: Array, x2: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    return xp.matmul(x1, x2, **kwargs)
+
+
+# Unlike transpose, matrix_transpose only transposes the last two axes.
+def matrix_transpose(x: Array, /, xp: Namespace) -> Array:
+    if x.ndim < 2:
+        raise ValueError("x must be at least 2-dimensional for matrix_transpose")
+    return xp.swapaxes(x, -1, -2)
+
+
+def tensordot(
+    x1: Array,
+    x2: Array,
+    /,
+    xp: Namespace,
+    *,
+    axes: int | tuple[Sequence[int], Sequence[int]] = 2,
+    **kwargs: object,
+) -> Array:
+    return xp.tensordot(x1, x2, axes=axes, **kwargs)
+
+
+def vecdot(x1: Array, x2: Array, /, xp: Namespace, *, axis: int = -1) -> Array:
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    if hasattr(xp, "broadcast_tensors"):
+        _broadcast = xp.broadcast_tensors
+    else:
+        _broadcast = xp.broadcast_arrays
+
+    x1_ = xp.moveaxis(x1, axis, -1)
+    x2_ = xp.moveaxis(x2, axis, -1)
+    x1_, x2_ = _broadcast(x1_, x2_)
+
+    res = xp.conj(x1_[..., None, :]) @ x2_[..., None]
+    return res[..., 0, 0]
+
+
+# isdtype is a new function in the 2022.12 array API specification.
+
+
+def isdtype(
+    dtype: DType,
+    kind: DType | str | tuple[DType | str, ...],
+    xp: Namespace,
+    *,
+    _tuple: bool = True,  # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return any(
+            isdtype(dtype, k, xp, _tuple=False)
+            for k in cast("tuple[DType | str, ...]", kind)
+        )
+    elif isinstance(kind, str):
+        if kind == "bool":
+            return dtype == xp.bool_
+        elif kind == "signed integer":
+            return xp.issubdtype(dtype, xp.signedinteger)
+        elif kind == "unsigned integer":
+            return xp.issubdtype(dtype, xp.unsignedinteger)
+        elif kind == "integral":
+            return xp.issubdtype(dtype, xp.integer)
+        elif kind == "real floating":
+            return xp.issubdtype(dtype, xp.floating)
+        elif kind == "complex floating":
+            return xp.issubdtype(dtype, xp.complexfloating)
+        elif kind == "numeric":
+            return xp.issubdtype(dtype, xp.number)
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        # This will allow things that aren't required by the spec, like
+        # isdtype(np.float64, float) or isdtype(np.int64, 'l'). Should we be
+        # more strict here to match the type annotation? Note that the
+        # array_api_strict implementation will be very strict.
+        return dtype == kind
+
+
+# unstack is a new function in the 2023.12 array API standard
+def unstack(x: Array, /, xp: Namespace, *, axis: int = 0) -> tuple[Array, ...]:
+    if x.ndim == 0:
+        raise ValueError("Input array must be at least 1-d.")
+    return tuple(xp.moveaxis(x, axis, 0))
+
+
+# numpy 1.26 does not use the standard definition for sign on complex numbers
+
+
+def sign(x: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    if isdtype(x.dtype, "complex floating", xp=xp):
+        out = (x / xp.abs(x, **kwargs))[...]
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0j] = 0j
+    else:
+        out = xp.sign(x, **kwargs)
+    # CuPy sign() does not propagate nans. See
+    # https://github.com/data-apis/array-api-compat/issues/136
+    if is_cupy_namespace(xp) and isdtype(x.dtype, "real floating", xp=xp):
+        out[xp.isnan(x)] = xp.nan
+    return out[()]
+
+
+def finfo(type_: DType | Array, /, xp: Namespace) -> Any:
+    # It is surprisingly difficult to recognize a dtype apart from an array.
+    # np.int64 is not the same as np.asarray(1).dtype!
+    try:
+        return xp.finfo(type_)
+    except (ValueError, TypeError):
+        return xp.finfo(type_.dtype)
+
+
+def iinfo(type_: DType | Array, /, xp: Namespace) -> Any:
+    try:
+        return xp.iinfo(type_)
+    except (ValueError, TypeError):
+        return xp.iinfo(type_.dtype)
+
+
+__all__ = [
+    "arange",
+    "empty",
+    "empty_like",
+    "eye",
+    "full",
+    "full_like",
+    "linspace",
+    "ones",
+    "ones_like",
+    "zeros",
+    "zeros_like",
+    "UniqueAllResult",
+    "UniqueCountsResult",
+    "UniqueInverseResult",
+    "unique_all",
+    "unique_counts",
+    "unique_inverse",
+    "unique_values",
+    "std",
+    "var",
+    "cumulative_sum",
+    "cumulative_prod",
+    "clip",
+    "permute_dims",
+    "reshape",
+    "argsort",
+    "sort",
+    "nonzero",
+    "matmul",
+    "matrix_transpose",
+    "tensordot",
+    "vecdot",
+    "isdtype",
+    "unstack",
+    "sign",
+    "finfo",
+    "iinfo",
+]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_fft.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..8792f53cded6e4414c26548cf519f50efde9ca88
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_fft.py
@@ -0,0 +1,213 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Literal, TypeAlias
+
+from ._typing import Array, Device, DType, Namespace
+
+_Norm: TypeAlias = Literal["backward", "ortho", "forward"]
+
+# Note: NumPy fft functions improperly upcast float32 and complex64 to
+# complex128, which is why we require wrapping them all here.
+
+def fft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.fft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.ifft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.fftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.ifftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def rfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.rfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.irfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def rfftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.rfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.irfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def hfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.hfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.float32)
+    return res
+
+def ihfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.ihfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftfreq(
+    n: int,
+    /,
+    xp: Namespace,
+    *,
+    d: float = 1.0,
+    dtype: DType | None = None,
+    device: Device | None = None,
+) -> Array:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    res = xp.fft.fftfreq(n, d=d)
+    if dtype is not None:
+        return res.astype(dtype)
+    return res
+
+def rfftfreq(
+    n: int,
+    /,
+    xp: Namespace,
+    *,
+    d: float = 1.0,
+    dtype: DType | None = None,
+    device: Device | None = None,
+) -> Array:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    res = xp.fft.rfftfreq(n, d=d)
+    if dtype is not None:
+        return res.astype(dtype)
+    return res
+
+def fftshift(
+    x: Array, /, xp: Namespace, *, axes: int | Sequence[int] | None = None
+) -> Array:
+    return xp.fft.fftshift(x, axes=axes)
+
+def ifftshift(
+    x: Array, /, xp: Namespace, *, axes: int | Sequence[int] | None = None
+) -> Array:
+    return xp.fft.ifftshift(x, axes=axes)
+
+__all__ = [
+    "fft",
+    "ifft",
+    "fftn",
+    "ifftn",
+    "rfft",
+    "irfft",
+    "rfftn",
+    "irfftn",
+    "hfft",
+    "ihfft",
+    "fftfreq",
+    "rfftfreq",
+    "fftshift",
+    "ifftshift",
+]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..60e8d5667f36699daec849b770dbede5270eb0ec
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
@@ -0,0 +1,1079 @@
+"""
+Various helper functions which are not part of the spec.
+
+Functions which start with an underscore are for internal use only but helpers
+that are in __all__ are intended as additional helper functions for use by end
+users of the compat library.
+"""
+
+from __future__ import annotations
+
+import enum
+import inspect
+import math
+import sys
+import warnings
+from collections.abc import Collection, Hashable
+from functools import lru_cache
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    Final,
+    Literal,
+    SupportsIndex,
+    TypeAlias,
+    TypeGuard,
+    cast,
+    overload,
+)
+
+from ._typing import Array, Device, HasShape, Namespace, SupportsArrayNamespace
+
+if TYPE_CHECKING:
+    import cupy as cp
+    import dask.array as da
+    import jax
+    import ndonnx as ndx
+    import numpy as np
+    import numpy.typing as npt
+    import sparse
+    import torch
+
+    # TODO: import from typing (requires Python >=3.13)
+    from typing_extensions import TypeIs
+
+    _ZeroGradientArray: TypeAlias = npt.NDArray[np.void]
+
+    _ArrayApiObj: TypeAlias = (
+        npt.NDArray[Any]
+        | cp.ndarray
+        | da.Array
+        | jax.Array
+        | ndx.Array
+        | sparse.SparseArray
+        | torch.Tensor
+        | SupportsArrayNamespace[Any]
+    )
+
+_API_VERSIONS_OLD: Final = frozenset({"2021.12", "2022.12", "2023.12"})
+_API_VERSIONS: Final = _API_VERSIONS_OLD | frozenset({"2024.12"})
+
+
+@lru_cache(100)
+def _issubclass_fast(cls: type, modname: str, clsname: str) -> bool:
+    try:
+        mod = sys.modules[modname]
+    except KeyError:
+        return False
+    parent_cls = getattr(mod, clsname)
+    return issubclass(cls, parent_cls)
+
+
+def _is_jax_zero_gradient_array(x: object) -> TypeGuard[_ZeroGradientArray]:
+    """Return True if `x` is a zero-gradient array.
+
+    These arrays are a design quirk of Jax that may one day be removed.
+    See https://github.com/google/jax/issues/20620.
+    """
+    # Fast exit
+    try:
+        dtype = x.dtype  # type: ignore[attr-defined]
+    except AttributeError:
+        return False
+    cls = cast(Hashable, type(dtype))
+    if not _issubclass_fast(cls, "numpy.dtypes", "VoidDType"):
+        return False
+
+    if "jax" not in sys.modules:
+        return False
+
+    import jax
+    # jax.float0 is a np.dtype([('float0', 'V')])
+    return dtype == jax.float0
+
+
+def is_numpy_array(x: object) -> TypeIs[npt.NDArray[Any]]:
+    """
+    Return True if `x` is a NumPy array.
+
+    This function does not import NumPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `ndarray` subclasses and NumPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # TODO: Should we reject ndarray subclasses?
+    cls = cast(Hashable, type(x))
+    return (
+        _issubclass_fast(cls, "numpy", "ndarray") 
+        or _issubclass_fast(cls, "numpy", "generic")
+    ) and not _is_jax_zero_gradient_array(x)
+
+
+def is_cupy_array(x: object) -> bool:
+    """
+    Return True if `x` is a CuPy array.
+
+    This function does not import CuPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "cupy", "ndarray")
+
+
+def is_torch_array(x: object) -> TypeIs[torch.Tensor]:
+    """
+    Return True if `x` is a PyTorch tensor.
+
+    This function does not import PyTorch if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "torch", "Tensor")
+
+
+def is_ndonnx_array(x: object) -> TypeIs[ndx.Array]:
+    """
+    Return True if `x` is a ndonnx Array.
+
+    This function does not import ndonnx if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "ndonnx", "Array")
+
+
+def is_dask_array(x: object) -> TypeIs[da.Array]:
+    """
+    Return True if `x` is a dask.array Array.
+
+    This function does not import dask if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "dask.array", "Array")
+
+
+def is_jax_array(x: object) -> TypeIs[jax.Array]:
+    """
+    Return True if `x` is a JAX array.
+
+    This function does not import JAX if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    # We test for jax.core.Tracer here to identify jax arrays during jit tracing. From jax 0.8.2 on,
+    # tracers are not a subclass of jax.Array anymore. Note that tracers can also represent
+    # non-array values and a fully correct implementation would need to use isinstance checks. Since
+    # we use hash-based caching with type names as keys, we cannot use instance checks without
+    # losing performance here. For more information, see
+    # https://github.com/data-apis/array-api-compat/pull/369 and the corresponding issue.
+    return (
+        _issubclass_fast(cls, "jax", "Array")
+        or _issubclass_fast(cls, "jax.core", "Tracer")
+        or _is_jax_zero_gradient_array(x)
+    )
+
+
+def is_pydata_sparse_array(x: object) -> TypeIs[sparse.SparseArray]:
+    """
+    Return True if `x` is an array from the `sparse` package.
+
+    This function does not import `sparse` if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    # TODO: Account for other backends.
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "sparse", "SparseArray")
+
+
+def is_array_api_obj(x: object) -> TypeGuard[_ArrayApiObj]:
+    """
+    Return True if `x` is an array API compatible array object.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    return (
+        hasattr(x, '__array_namespace__') 
+        or _is_array_api_cls(cast(Hashable, type(x)))
+    )
+
+
+@lru_cache(100)
+def _is_array_api_cls(cls: type) -> bool:
+    return (
+        # TODO: drop support for numpy<2 which didn't have __array_namespace__
+        _issubclass_fast(cls, "numpy", "ndarray")
+        or _issubclass_fast(cls, "numpy", "generic")
+        or _issubclass_fast(cls, "cupy", "ndarray")
+        or _issubclass_fast(cls, "torch", "Tensor")
+        or _issubclass_fast(cls, "dask.array", "Array")
+        or _issubclass_fast(cls, "sparse", "SparseArray")
+        # TODO: drop support for jax<0.4.32 which didn't have __array_namespace__
+        or _issubclass_fast(cls, "jax", "Array")
+        or _issubclass_fast(cls, "jax.core", "Tracer")  # see is_jax_array for limitations
+    )
+
+
+def _compat_module_name() -> str:
+    assert __name__.endswith(".common._helpers")
+    return __name__.removesuffix(".common._helpers")
+
+
+@lru_cache(100)
+def is_numpy_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a NumPy namespace.
+
+    This includes both NumPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"numpy", _compat_module_name() + ".numpy"}
+
+
+@lru_cache(100)
+def is_cupy_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a CuPy namespace.
+
+    This includes both CuPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"cupy", _compat_module_name() + ".cupy"}
+
+
+@lru_cache(100)
+def is_torch_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a PyTorch namespace.
+
+    This includes both PyTorch itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"torch", _compat_module_name() + ".torch"}
+
+
+def is_ndonnx_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is an NDONNX namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == "ndonnx"
+
+
+@lru_cache(100)
+def is_dask_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a Dask namespace.
+
+    This includes both ``dask.array`` itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"dask.array", _compat_module_name() + ".dask.array"}
+
+
+def is_jax_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a JAX namespace.
+
+    This includes ``jax.numpy`` and ``jax.experimental.array_api`` which existed in
+    older versions of JAX.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"jax.numpy", "jax.experimental.array_api"}
+
+
+def is_pydata_sparse_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a pydata/sparse namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == "sparse"
+
+
+def is_array_api_strict_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is an array-api-strict namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    """
+    return xp.__name__ == "array_api_strict"
+
+
+def _check_api_version(api_version: str | None) -> None:
+    if api_version in _API_VERSIONS_OLD:
+        warnings.warn(
+            f"The {api_version} version of the array API specification was requested but the returned namespace is actually version 2024.12"
+        )
+    elif api_version is not None and api_version not in _API_VERSIONS:
+        raise ValueError(
+            "Only the 2024.12 version of the array API specification is currently supported"
+        )
+
+
+class _ClsToXPInfo(enum.Enum):
+    SCALAR = 0
+    MAYBE_JAX_ZERO_GRADIENT = 1
+
+
+@lru_cache(100)
+def _cls_to_namespace(
+    cls: type,
+    api_version: str | None,
+    use_compat: bool | None,
+) -> tuple[Namespace | None, _ClsToXPInfo | None]:
+    if use_compat not in (None, True, False):
+        raise ValueError("use_compat must be None, True, or False")
+    _use_compat = use_compat in (None, True)
+    cls_ = cast(Hashable, cls)  # Make mypy happy
+
+    if (
+        _issubclass_fast(cls_, "numpy", "ndarray") 
+        or _issubclass_fast(cls_, "numpy", "generic")
+    ):
+        if use_compat is True:
+            _check_api_version(api_version)
+            from .. import numpy as xp
+        elif use_compat is False:
+            import numpy as xp  # type: ignore[no-redef]
+        else:
+            # NumPy 2.0+ have __array_namespace__; however they are not
+            # yet fully array API compatible.
+            from .. import numpy as xp  # type: ignore[no-redef]
+        return xp, _ClsToXPInfo.MAYBE_JAX_ZERO_GRADIENT
+
+    # Note: this must happen _after_ the test for np.generic,
+    # because np.float64 and np.complex128 are subclasses of float and complex.
+    if issubclass(cls, int | float | complex | type(None)):
+        return None, _ClsToXPInfo.SCALAR
+
+    if _issubclass_fast(cls_, "cupy", "ndarray"):
+        if _use_compat:
+            _check_api_version(api_version)
+            from .. import cupy as xp  # type: ignore[no-redef]
+        else:
+            import cupy as xp  # type: ignore[no-redef]
+        return xp, None
+
+    if _issubclass_fast(cls_, "torch", "Tensor"):
+        if _use_compat:
+            _check_api_version(api_version)
+            from .. import torch as xp  # type: ignore[no-redef]
+        else:
+            import torch as xp  # type: ignore[no-redef]
+        return xp, None
+
+    if _issubclass_fast(cls_, "dask.array", "Array"):
+        if _use_compat:
+            _check_api_version(api_version)
+            from ..dask import array as xp  # type: ignore[no-redef]
+        else:
+            import dask.array as xp  # type: ignore[no-redef]
+        return xp, None
+
+    # Backwards compatibility for jax<0.4.32
+    if _issubclass_fast(cls_, "jax", "Array"):
+        return _jax_namespace(api_version, use_compat), None
+
+    return None, None
+
+
+def _jax_namespace(api_version: str | None, use_compat: bool | None) -> Namespace:
+    if use_compat:
+        raise ValueError("JAX does not have an array-api-compat wrapper")
+    import jax.numpy as jnp
+    if not hasattr(jnp, "__array_namespace_info__"):
+        # JAX v0.4.32 and newer implements the array API directly in jax.numpy.
+        # For older JAX versions, it is available via jax.experimental.array_api.
+        # jnp.Array objects gain the __array_namespace__ method.
+        import jax.experimental.array_api  # noqa: F401
+    # Test api_version
+    return jnp.empty(0).__array_namespace__(api_version=api_version)
+
+
+def array_namespace(
+    *xs: Array | complex | None,
+    api_version: str | None = None,
+    use_compat: bool | None = None,
+) -> Namespace:
+    """
+    Get the array API compatible namespace for the arrays `xs`.
+
+    Parameters
+    ----------
+    xs: arrays
+        one or more arrays. xs can also be Python scalars (bool, int, float,
+        complex, or None), which are ignored.
+
+    api_version: str
+        The newest version of the spec that you need support for (currently
+        the compat library wrapped APIs support v2024.12).
+
+    use_compat: bool or None
+        If None (the default), the native namespace will be returned if it is
+        already array API compatible, otherwise a compat wrapper is used. If
+        True, the compat library wrapped library will be returned. If False,
+        the native library namespace is returned.
+
+    Returns
+    -------
+
+    out: namespace
+        The array API compatible namespace corresponding to the arrays in `xs`.
+
+    Raises
+    ------
+    TypeError
+        If `xs` contains arrays from different array libraries or contains a
+        non-array.
+
+
+    Typical usage is to pass the arguments of a function to
+    `array_namespace()` at the top of a function to get the corresponding
+    array API namespace:
+
+    .. code:: python
+
+       def your_function(x, y):
+           xp = array_api_compat.array_namespace(x, y)
+           # Now use xp as the array library namespace
+           return xp.mean(x, axis=0) + 2*xp.std(y, axis=0)
+
+
+    Wrapped array namespaces can also be imported directly. For example,
+    `array_namespace(np.array(...))` will return `array_api_compat.numpy`.
+    This function will also work for any array library not wrapped by
+    array-api-compat if it explicitly defines `__array_namespace__
+    `__
+    (the wrapped namespace is always preferred if it exists).
+
+    See Also
+    --------
+
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+
+    """
+    namespaces: set[Namespace] = set()
+    for x in xs:
+        xp, info = _cls_to_namespace(cast(Hashable, type(x)), api_version, use_compat)
+        if info is _ClsToXPInfo.SCALAR:
+            continue
+
+        if (
+            info is _ClsToXPInfo.MAYBE_JAX_ZERO_GRADIENT
+            and _is_jax_zero_gradient_array(x)
+        ):
+            xp = _jax_namespace(api_version, use_compat)
+
+        if xp is None:
+            get_ns = getattr(x, "__array_namespace__", None)
+            if get_ns is None:
+                raise TypeError(f"{type(x).__name__} is not a supported array type")
+            if use_compat:
+                raise ValueError(
+                    "The given array does not have an array-api-compat wrapper"
+                )
+            xp = get_ns(api_version=api_version)
+
+        namespaces.add(xp)
+
+    try:
+        (xp,) = namespaces
+        return xp
+    except ValueError:
+        if not namespaces:
+            raise TypeError(
+                "array_namespace requires at least one non-scalar array input"
+            )
+        raise TypeError(f"Multiple namespaces for array inputs: {namespaces}")
+
+
+# backwards compatibility alias
+get_namespace = array_namespace
+
+
+def _check_device(bare_xp: Namespace, device: Device) -> None:  # pyright: ignore[reportUnusedFunction]
+    """
+    Validate dummy device on device-less array backends.
+
+    Notes
+    -----
+    This function is also invoked by CuPy, which does have multiple devices
+    if there are multiple GPUs available.
+    However, CuPy multi-device support is currently impossible
+    without using the global device or a context manager:
+
+    https://github.com/data-apis/array-api-compat/pull/293
+    """
+    if bare_xp is sys.modules.get("numpy"):
+        if device not in ("cpu", None):
+            raise ValueError(f"Unsupported device for NumPy: {device!r}")
+
+    elif bare_xp is sys.modules.get("dask.array"):
+        if device not in ("cpu", _DASK_DEVICE, None):
+            raise ValueError(f"Unsupported device for Dask: {device!r}")
+
+
+# Placeholder object to represent the dask device
+# when the array backend is not the CPU.
+# (since it is not easy to tell which device a dask array is on)
+class _dask_device:
+    def __repr__(self) -> Literal["DASK_DEVICE"]:
+        return "DASK_DEVICE"
+
+
+_DASK_DEVICE = _dask_device()
+
+
+# device() is not on numpy.ndarray or dask.array and to_device() is not on numpy.ndarray
+# or cupy.ndarray. They are not included in array objects of this library
+# because this library just reuses the respective ndarray classes without
+# wrapping or subclassing them. These helper functions can be used instead of
+# the wrapper functions for libraries that need to support both NumPy/CuPy and
+# other libraries that use devices.
+def device(x: _ArrayApiObj, /) -> Device:
+    """
+    Hardware device the array data resides on.
+
+    This is equivalent to `x.device` according to the `standard
+    `__.
+    This helper is included because some array libraries either do not have
+    the `device` attribute or include it with an incompatible API.
+
+    Parameters
+    ----------
+    x: array
+        array instance from an array API compatible library.
+
+    Returns
+    -------
+    out: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    Notes
+    -----
+
+    For NumPy the device is always `"cpu"`. For Dask, the device is always a
+    special `DASK_DEVICE` object.
+
+    See Also
+    --------
+
+    to_device : Move array data to a different device.
+
+    """
+    if is_numpy_array(x):
+        return "cpu"
+    elif is_dask_array(x):
+        # Peek at the metadata of the Dask array to determine type
+        if is_numpy_array(x._meta):
+            # Must be on CPU since backed by numpy
+            return "cpu"
+        return _DASK_DEVICE
+    elif is_jax_array(x):
+        # FIXME Jitted JAX arrays do not have a device attribute
+        #       https://github.com/jax-ml/jax/issues/26000
+        #       Return None in this case. Note that this workaround breaks
+        #       the standard and will result in new arrays being created on the
+        #       default device instead of the same device as the input array(s).
+        x_device = getattr(x, "device", None)
+        # Older JAX releases had .device() as a method, which has been replaced
+        # with a property in accordance with the standard.
+        if inspect.ismethod(x_device):
+            return x_device()
+        else:
+            return x_device
+    elif is_pydata_sparse_array(x):
+        # `sparse` will gain `.device`, so check for this first.
+        x_device = getattr(x, "device", None)
+        if x_device is not None:
+            return x_device
+        # Everything but DOK has this attr.
+        try:
+            inner = x.data  # pyright: ignore
+        except AttributeError:
+            return "cpu"
+        # Return the device of the constituent array
+        return device(inner)  # pyright: ignore
+    return x.device  # type: ignore  # pyright: ignore
+
+
+# Prevent shadowing, used below
+_device = device
+
+
+# Based on cupy.array_api.Array.to_device
+def _cupy_to_device(
+    x: cp.ndarray,
+    device: Device,
+    /,
+    stream: int | Any | None = None,
+) -> cp.ndarray:
+    import cupy as cp
+
+    if device == "cpu":
+        # allowing us to use `to_device(x, "cpu")`
+        # is useful for portable test swapping between
+        # host and device backends
+        return x.get()
+    if not isinstance(device, cp.cuda.Device):
+        raise TypeError(f"Unsupported device type {device!r}")
+
+    if stream is None:
+        with device:
+            return cp.asarray(x)
+
+    # stream can be an int as specified in __dlpack__, or a CuPy stream
+    if isinstance(stream, int):
+        stream = cp.cuda.ExternalStream(stream)
+    elif not isinstance(stream, cp.cuda.Stream):
+        raise TypeError(f"Unsupported stream type {stream!r}")
+
+    with device, stream:
+        return cp.asarray(x)
+
+
+def _torch_to_device(
+    x: torch.Tensor,
+    device: torch.device | str | int,
+    /,
+    stream: int | Any | None = None,
+) -> torch.Tensor:
+    if stream is not None:
+        raise NotImplementedError
+    return x.to(device)
+
+
+def to_device(x: Array, device: Device, /, *, stream: int | Any | None = None) -> Array:
+    """
+    Copy the array from the device on which it currently resides to the specified ``device``.
+
+    This is equivalent to `x.to_device(device, stream=stream)` according to
+    the `standard
+    `__.
+    This helper is included because some array libraries do not have the
+    `to_device` method.
+
+    Parameters
+    ----------
+
+    x: array
+        array instance from an array API compatible library.
+
+    device: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    stream: int | Any | None
+        stream object to use during copy. In addition to the types supported
+        in ``array.__dlpack__``, implementations may choose to support any
+        library-specific stream object with the caveat that any code using
+        such an object would not be portable.
+
+    Returns
+    -------
+
+    out: array
+        an array with the same data and data type as ``x`` and located on the
+        specified ``device``.
+
+    Notes
+    -----
+
+    For NumPy, this function effectively does nothing since the only supported
+    device is the CPU. For CuPy, this method supports CuPy CUDA
+    :external+cupy:class:`Device ` and
+    :external+cupy:class:`Stream ` objects. For PyTorch,
+    this is the same as :external+torch:meth:`x.to(device) `
+    (the ``stream`` argument is not supported in PyTorch).
+
+    See Also
+    --------
+
+    device : Hardware device the array data resides on.
+
+    """
+    if is_numpy_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        if device == "cpu":
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_cupy_array(x):
+        # cupy does not yet have to_device
+        return _cupy_to_device(x, device, stream=stream)
+    elif is_torch_array(x):
+        return _torch_to_device(x, device, stream=stream)
+    elif is_dask_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        # TODO: What if our array is on the GPU already?
+        if device == "cpu":
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_jax_array(x):
+        if not hasattr(x, "__array_namespace__"):
+            # In JAX v0.4.31 and older, this import adds to_device method to x...
+            import jax.experimental.array_api  # noqa: F401  # pyright: ignore
+
+            # ... but only on eager JAX. It won't work inside jax.jit.
+            if not hasattr(x, "to_device"):
+                return x
+        return x.to_device(device, stream=stream)
+    elif is_pydata_sparse_array(x) and device == _device(x):
+        # Perform trivial check to return the same array if
+        # device is same instead of err-ing.
+        return x
+    return x.to_device(device, stream=stream)  # pyright: ignore
+
+
+@overload
+def size(x: HasShape[Collection[SupportsIndex]]) -> int: ...
+@overload
+def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None: ...
+def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None:
+    """
+    Return the total number of elements of x.
+
+    This is equivalent to `x.size` according to the `standard
+    `__.
+
+    This helper is included because PyTorch defines `size` in an
+    :external+torch:meth:`incompatible way `.
+    It also fixes dask.array's behaviour which returns nan for unknown sizes, whereas
+    the standard requires None.
+    """
+    # Lazy API compliant arrays, such as ndonnx, can contain None in their shape
+    if None in x.shape:
+        return None
+    out = math.prod(cast("Collection[SupportsIndex]", x.shape))
+    # dask.array.Array.shape can contain NaN
+    return None if math.isnan(out) else out
+
+
+@lru_cache(100)
+def _is_writeable_cls(cls: type) -> bool | None:
+    if (
+        _issubclass_fast(cls, "numpy", "generic")
+        or _issubclass_fast(cls, "jax", "Array")
+        or _issubclass_fast(cls, "jax.core", "Tracer")  # see is_jax_array for limitations
+        or _issubclass_fast(cls, "sparse", "SparseArray")
+    ):
+        return False
+    if _is_array_api_cls(cls):
+        return True
+    return None
+
+
+def is_writeable_array(x: object) -> TypeGuard[_ArrayApiObj]:
+    """
+    Return False if ``x.__setitem__`` is expected to raise; True otherwise.
+    Return False if `x` is not an array API compatible object.
+
+    Warning
+    -------
+    As there is no standard way to check if an array is writeable without actually
+    writing to it, this function blindly returns True for all unknown array types.
+    """
+    cls = cast(Hashable, type(x))
+    if _issubclass_fast(cls, "numpy", "ndarray"):
+        return cast("npt.NDArray", x).flags.writeable
+    res = _is_writeable_cls(cls)
+    if res is not None:
+        return res
+    return hasattr(x, '__array_namespace__')
+
+
+@lru_cache(100)
+def _is_lazy_cls(cls: type) -> bool | None:
+    if (
+        _issubclass_fast(cls, "numpy", "ndarray")
+        or _issubclass_fast(cls, "numpy", "generic")
+        or _issubclass_fast(cls, "cupy", "ndarray")
+        or _issubclass_fast(cls, "torch", "Tensor")
+        or _issubclass_fast(cls, "sparse", "SparseArray")
+    ):
+        return False
+    if (
+        _issubclass_fast(cls, "jax", "Array")
+        or _issubclass_fast(cls, "jax.core", "Tracer")  # see is_jax_array for limitations
+        or _issubclass_fast(cls, "dask.array", "Array")
+        or _issubclass_fast(cls, "ndonnx", "Array")
+    ):
+        return True
+    return  None
+
+
+def is_lazy_array(x: object) -> TypeGuard[_ArrayApiObj]:
+    """Return True if x is potentially a future or it may be otherwise impossible or
+    expensive to eagerly read its contents, regardless of their size, e.g. by
+    calling ``bool(x)`` or ``float(x)``.
+
+    Return False otherwise; e.g. ``bool(x)`` etc. is guaranteed to succeed and to be
+    cheap as long as the array has the right dtype and size.
+
+    Note
+    ----
+    This function errs on the side of caution for array types that may or may not be
+    lazy, e.g. JAX arrays, by always returning True for them.
+    """
+    # **JAX note:** while it is possible to determine if you're inside or outside
+    # jax.jit by testing the subclass of a jax.Array object, as well as testing bool()
+    # as we do below for unknown arrays, this is not recommended by JAX best practices.
+
+    # **Dask note:** Dask eagerly computes the graph on __bool__, __float__, and so on.
+    # This behaviour, while impossible to change without breaking backwards
+    # compatibility, is highly detrimental to performance as the whole graph will end
+    # up being computed multiple times.
+
+    # Note: skipping reclassification of JAX zero gradient arrays, as one will
+    # exclusively get them once they leave a jax.grad JIT context.
+    cls = cast(Hashable, type(x))
+    res = _is_lazy_cls(cls)
+    if res is not None:
+        return res
+
+    if not hasattr(x, "__array_namespace__"):
+        return False
+
+    # Unknown Array API compatible object. Note that this test may have dire consequences
+    # in terms of performance, e.g. for a lazy object that eagerly computes the graph
+    # on __bool__ (dask is one such example, which however is special-cased above).
+
+    # Select a single point of the array
+    s = size(cast("HasShape[Collection[SupportsIndex | None]]", x))
+    if s is None:
+        return True
+    xp = array_namespace(x)
+    if s > 1:
+        x = xp.reshape(x, (-1,))[0]
+    # Cast to dtype=bool and deal with size 0 arrays
+    x = xp.any(x)
+
+    try:
+        bool(x)
+        return False
+    # The Array API standard dictactes that __bool__ should raise TypeError if the
+    # output cannot be defined.
+    # Here we allow for it to raise arbitrary exceptions, e.g. like Dask does.
+    except Exception:
+        return True
+
+
+__all__ = [
+    "array_namespace",
+    "device",
+    "get_namespace",
+    "is_array_api_obj",
+    "is_array_api_strict_namespace",
+    "is_cupy_array",
+    "is_cupy_namespace",
+    "is_dask_array",
+    "is_dask_namespace",
+    "is_jax_array",
+    "is_jax_namespace",
+    "is_numpy_array",
+    "is_numpy_namespace",
+    "is_torch_array",
+    "is_torch_namespace",
+    "is_ndonnx_array",
+    "is_ndonnx_namespace",
+    "is_pydata_sparse_array",
+    "is_pydata_sparse_namespace",
+    "is_writeable_array",
+    "is_lazy_array",
+    "size",
+    "to_device",
+]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_linalg.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ec28689b8de9baaa92160df5340894543a75c46
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
@@ -0,0 +1,230 @@
+from __future__ import annotations
+
+import math
+from typing import Literal, NamedTuple, cast
+
+import numpy as np
+
+if np.__version__[0] == "2":
+    from numpy.lib.array_utils import normalize_axis_tuple
+else:
+    from numpy.core.numeric import normalize_axis_tuple  # type: ignore[no-redef]
+
+from .._internal import get_xp
+from ._aliases import isdtype, matmul, matrix_transpose, tensordot, vecdot
+from ._typing import Array, DType, JustFloat, JustInt, Namespace
+
+
+# These are in the main NumPy namespace but not in numpy.linalg
+def cross(
+    x1: Array,
+    x2: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int = -1,
+    **kwargs: object,
+) -> Array:
+    return xp.cross(x1, x2, axis=axis, **kwargs)
+
+def outer(x1: Array, x2: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    return xp.outer(x1, x2, **kwargs)
+
+class EighResult(NamedTuple):
+    eigenvalues: Array
+    eigenvectors: Array
+
+class QRResult(NamedTuple):
+    Q: Array
+    R: Array
+
+class SlogdetResult(NamedTuple):
+    sign: Array
+    logabsdet: Array
+
+class SVDResult(NamedTuple):
+    U: Array
+    S: Array
+    Vh: Array
+
+# These functions are the same as their NumPy counterparts except they return
+# a namedtuple.
+def eigh(x: Array, /, xp: Namespace, **kwargs: object) -> EighResult:
+    return EighResult(*xp.linalg.eigh(x, **kwargs))
+
+def qr(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    mode: Literal["reduced", "complete"] = "reduced",
+    **kwargs: object,
+) -> QRResult:
+    return QRResult(*xp.linalg.qr(x, mode=mode, **kwargs))
+
+def slogdet(x: Array, /, xp: Namespace, **kwargs: object) -> SlogdetResult:
+    return SlogdetResult(*xp.linalg.slogdet(x, **kwargs))
+
+def svd(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    full_matrices: bool = True,
+    **kwargs: object,
+) -> SVDResult:
+    return SVDResult(*xp.linalg.svd(x, full_matrices=full_matrices, **kwargs))
+
+# These functions have additional keyword arguments
+
+# The upper keyword argument is new from NumPy
+def cholesky(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    upper: bool = False,
+    **kwargs: object,
+) -> Array:
+    L = xp.linalg.cholesky(x, **kwargs)
+    if upper:
+        U = get_xp(xp)(matrix_transpose)(L)
+        if get_xp(xp)(isdtype)(U.dtype, 'complex floating'):
+            U = xp.conj(U)  # pyright: ignore[reportConstantRedefinition]
+        return U
+    return L
+
+# The rtol keyword argument of matrix_rank() and pinv() is new from NumPy.
+# Note that it has a different semantic meaning from tol and rcond.
+def matrix_rank(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    rtol: float | Array | None = None,
+    **kwargs: object,
+) -> Array:
+    # this is different from xp.linalg.matrix_rank, which supports 1
+    # dimensional arrays.
+    if x.ndim < 2:
+        raise xp.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
+    S: Array = get_xp(xp)(svdvals)(x, **kwargs)
+    if rtol is None:
+        tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * xp.finfo(S.dtype).eps
+    else:
+        # this is different from xp.linalg.matrix_rank, which does not
+        # multiply the tolerance by the largest singular value.
+        tol = S.max(axis=-1, keepdims=True)*xp.asarray(rtol)[..., xp.newaxis]
+    return xp.count_nonzero(S > tol, axis=-1)
+
+def pinv(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    rtol: float | Array | None = None,
+    **kwargs: object,
+) -> Array:
+    # this is different from xp.linalg.pinv, which does not multiply the
+    # default tolerance by max(M, N).
+    if rtol is None:
+        rtol = max(x.shape[-2:]) * xp.finfo(x.dtype).eps
+    return xp.linalg.pinv(x, rcond=rtol, **kwargs)
+
+# These functions are new in the array API spec
+
+def matrix_norm(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    keepdims: bool = False,
+    ord: Literal[1, 2, -1, -2] | JustFloat | Literal["fro", "nuc"] | None = "fro",
+) -> Array:
+    return xp.linalg.norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord)
+
+# svdvals is not in NumPy (but it is in SciPy). It is equivalent to
+# xp.linalg.svd(compute_uv=False).
+def svdvals(x: Array, /, xp: Namespace) -> Array | tuple[Array, ...]:
+    return xp.linalg.svd(x, compute_uv=False)
+
+def vector_norm(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    ord: JustInt | JustFloat = 2,
+) -> Array:
+    # xp.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
+    # when axis=None and the input is 2-D, so to force a vector norm, we make
+    # it so the input is 1-D (for axis=None), or reshape so that norm is done
+    # on a single dimension.
+    if axis is None:
+        # Note: xp.linalg.norm() doesn't handle 0-D arrays
+        _x = x.ravel()
+        _axis = 0
+    elif isinstance(axis, tuple):
+        # Note: The axis argument supports any number of axes, whereas
+        # xp.linalg.norm() only supports a single axis for vector norm.
+        normalized_axis = cast(
+            "tuple[int, ...]",
+            normalize_axis_tuple(axis, x.ndim),  # pyright: ignore[reportCallIssue]
+        )
+        rest = tuple(i for i in range(x.ndim) if i not in normalized_axis)
+        newshape = axis + rest
+        _x = xp.transpose(x, newshape).reshape(
+            (math.prod([x.shape[i] for i in axis]), *[x.shape[i] for i in rest]))
+        _axis = 0
+    else:
+        _x = x
+        _axis = axis
+
+    res = xp.linalg.norm(_x, axis=_axis, ord=ord)
+
+    if keepdims:
+        # We can't reuse xp.linalg.norm(keepdims) because of the reshape hacks
+        # above to avoid matrix norm logic.
+        shape = list(x.shape)
+        axes = cast(
+            "tuple[int, ...]",
+            normalize_axis_tuple(  # pyright: ignore[reportCallIssue]
+                range(x.ndim) if axis is None else axis,
+                x.ndim,
+            ),
+        )
+        for i in axes:
+            shape[i] = 1
+        res = xp.reshape(res, tuple(shape))
+
+    return res
+
+# xp.diagonal and xp.trace operate on the first two axes whereas these
+# operates on the last two
+
+def diagonal(x: Array, /, xp: Namespace, *, offset: int = 0, **kwargs: object) -> Array:
+    return xp.diagonal(x, offset=offset, axis1=-2, axis2=-1, **kwargs)
+
+def trace(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    offset: int = 0,
+    dtype: DType | None = None,
+    **kwargs: object,
+) -> Array:
+    return xp.asarray(
+        xp.trace(x, offset=offset, dtype=dtype, axis1=-2, axis2=-1, **kwargs)
+    )
+
+__all__ = ['cross', 'matmul', 'outer', 'tensordot', 'EighResult',
+           'QRResult', 'SlogdetResult', 'SVDResult', 'eigh', 'qr', 'slogdet',
+           'svd', 'cholesky', 'matrix_rank', 'pinv', 'matrix_norm',
+           'matrix_transpose', 'svdvals', 'vecdot', 'vector_norm', 'diagonal',
+           'trace']
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_typing.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0018b69d624e37b49e28b35d7d6cdca103effe5
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/common/_typing.py
@@ -0,0 +1,189 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from types import ModuleType as Namespace
+from typing import (
+    TYPE_CHECKING,
+    Literal,
+    Protocol,
+    TypeAlias,
+    TypedDict,
+    TypeVar,
+    final,
+)
+
+if TYPE_CHECKING:
+    from _typeshed import Incomplete
+
+    SupportsBufferProtocol: TypeAlias = Incomplete
+    Array: TypeAlias = Incomplete
+    Device: TypeAlias = Incomplete
+    DType: TypeAlias = Incomplete
+else:
+    SupportsBufferProtocol = object
+    Array = object
+    Device = object
+    DType = object
+
+
+_T_co = TypeVar("_T_co", covariant=True)
+
+
+# These "Just" types are equivalent to the `Just` type from the `optype` library,
+# apart from them not being `@runtime_checkable`.
+# - docs: https://github.com/jorenham/optype/blob/master/README.md#just
+# - code: https://github.com/jorenham/optype/blob/master/optype/_core/_just.py
+@final
+class JustInt(Protocol):  # type: ignore[misc]
+    @property  # type: ignore[override]
+    def __class__(self, /) -> type[int]: ...
+    @__class__.setter
+    def __class__(self, value: type[int], /) -> None: ...  # pyright: ignore[reportIncompatibleMethodOverride]
+
+
+@final
+class JustFloat(Protocol):  # type: ignore[misc]
+    @property  # type: ignore[override]
+    def __class__(self, /) -> type[float]: ...
+    @__class__.setter
+    def __class__(self, value: type[float], /) -> None: ...  # pyright: ignore[reportIncompatibleMethodOverride]
+
+
+@final
+class JustComplex(Protocol):  # type: ignore[misc]
+    @property  # type: ignore[override]
+    def __class__(self, /) -> type[complex]: ...
+    @__class__.setter
+    def __class__(self, value: type[complex], /) -> None: ...  # pyright: ignore[reportIncompatibleMethodOverride]
+
+
+class NestedSequence(Protocol[_T_co]):
+    def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
+    def __len__(self, /) -> int: ...
+
+
+class SupportsArrayNamespace(Protocol[_T_co]):
+    def __array_namespace__(self, /, *, api_version: str | None) -> _T_co: ...
+
+
+class HasShape(Protocol[_T_co]):
+    @property
+    def shape(self, /) -> _T_co: ...
+
+
+# Return type of `__array_namespace_info__.default_dtypes`
+Capabilities = TypedDict(
+    "Capabilities",
+    {
+        "boolean indexing": bool,
+        "data-dependent shapes": bool,
+        "max dimensions": int,
+    },
+)
+
+# Return type of `__array_namespace_info__.default_dtypes`
+DefaultDTypes = TypedDict(
+    "DefaultDTypes",
+    {
+        "real floating": DType,
+        "complex floating": DType,
+        "integral": DType,
+        "indexing": DType,
+    },
+)
+
+
+_DTypeKind: TypeAlias = Literal[
+    "bool",
+    "signed integer",
+    "unsigned integer",
+    "integral",
+    "real floating",
+    "complex floating",
+    "numeric",
+]
+# Type of the `kind` parameter in `__array_namespace_info__.dtypes`
+DTypeKind: TypeAlias = _DTypeKind | tuple[_DTypeKind, ...]
+
+
+# `__array_namespace_info__.dtypes(kind="bool")`
+class DTypesBool(TypedDict):
+    bool: DType
+
+
+# `__array_namespace_info__.dtypes(kind="signed integer")`
+class DTypesSigned(TypedDict):
+    int8: DType
+    int16: DType
+    int32: DType
+    int64: DType
+
+
+# `__array_namespace_info__.dtypes(kind="unsigned integer")`
+class DTypesUnsigned(TypedDict):
+    uint8: DType
+    uint16: DType
+    uint32: DType
+    uint64: DType
+
+
+# `__array_namespace_info__.dtypes(kind="integral")`
+class DTypesIntegral(DTypesSigned, DTypesUnsigned):
+    pass
+
+
+# `__array_namespace_info__.dtypes(kind="real floating")`
+class DTypesReal(TypedDict):
+    float32: DType
+    float64: DType
+
+
+# `__array_namespace_info__.dtypes(kind="complex floating")`
+class DTypesComplex(TypedDict):
+    complex64: DType
+    complex128: DType
+
+
+# `__array_namespace_info__.dtypes(kind="numeric")`
+class DTypesNumeric(DTypesIntegral, DTypesReal, DTypesComplex):
+    pass
+
+
+# `__array_namespace_info__.dtypes(kind=None)` (default)
+class DTypesAll(DTypesBool, DTypesNumeric):
+    pass
+
+
+# `__array_namespace_info__.dtypes(kind=?)` (fallback)
+DTypesAny: TypeAlias = Mapping[str, DType]
+
+
+__all__ = [
+    "Array",
+    "Capabilities",
+    "DType",
+    "DTypeKind",
+    "DTypesAny",
+    "DTypesAll",
+    "DTypesBool",
+    "DTypesNumeric",
+    "DTypesIntegral",
+    "DTypesSigned",
+    "DTypesUnsigned",
+    "DTypesReal",
+    "DTypesComplex",
+    "DefaultDTypes",
+    "Device",
+    "HasShape",
+    "Namespace",
+    "JustInt",
+    "JustFloat",
+    "JustComplex",
+    "NestedSequence",
+    "SupportsArrayNamespace",
+    "SupportsBufferProtocol",
+]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..64890a4497bbb618840819bbf1ffb139ecdb91b3
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
@@ -0,0 +1,24 @@
+from typing import Final
+from cupy import * # noqa: F403
+
+# from cupy import * doesn't overwrite these builtin names
+from cupy import abs, max, min, round # noqa: F401
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+from ._info import __array_namespace_info__  # noqa: F401
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
+
+__array_api_version__: Final = '2024.12'
+
+__all__ = sorted(
+    {name for name in globals() if not name.startswith("__")}
+    - {"Final", "_aliases", "_info", "_typing"}
+    | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"}
+)
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..4de62acf67103495fcb475e8b0d4cf1af3655cb9
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
@@ -0,0 +1,168 @@
+from __future__ import annotations
+
+from builtins import bool as py_bool
+
+import cupy as cp
+
+from ..common import _aliases, _helpers
+from ..common._typing import NestedSequence, SupportsBufferProtocol
+from .._internal import get_xp
+from ._typing import Array, Device, DType
+
+bool = cp.bool_
+
+# Basic renames
+acos = cp.arccos
+acosh = cp.arccosh
+asin = cp.arcsin
+asinh = cp.arcsinh
+atan = cp.arctan
+atan2 = cp.arctan2
+atanh = cp.arctanh
+bitwise_left_shift = cp.left_shift
+bitwise_invert = cp.invert
+bitwise_right_shift = cp.right_shift
+concat = cp.concatenate
+pow = cp.power
+
+arange = get_xp(cp)(_aliases.arange)
+empty = get_xp(cp)(_aliases.empty)
+empty_like = get_xp(cp)(_aliases.empty_like)
+eye = get_xp(cp)(_aliases.eye)
+full = get_xp(cp)(_aliases.full)
+full_like = get_xp(cp)(_aliases.full_like)
+linspace = get_xp(cp)(_aliases.linspace)
+ones = get_xp(cp)(_aliases.ones)
+ones_like = get_xp(cp)(_aliases.ones_like)
+zeros = get_xp(cp)(_aliases.zeros)
+zeros_like = get_xp(cp)(_aliases.zeros_like)
+UniqueAllResult = get_xp(cp)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(cp)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(cp)(_aliases.UniqueInverseResult)
+unique_all = get_xp(cp)(_aliases.unique_all)
+unique_counts = get_xp(cp)(_aliases.unique_counts)
+unique_inverse = get_xp(cp)(_aliases.unique_inverse)
+unique_values = get_xp(cp)(_aliases.unique_values)
+std = get_xp(cp)(_aliases.std)
+var = get_xp(cp)(_aliases.var)
+cumulative_sum = get_xp(cp)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(cp)(_aliases.cumulative_prod)
+clip = get_xp(cp)(_aliases.clip)
+permute_dims = get_xp(cp)(_aliases.permute_dims)
+reshape = get_xp(cp)(_aliases.reshape)
+argsort = get_xp(cp)(_aliases.argsort)
+sort = get_xp(cp)(_aliases.sort)
+nonzero = get_xp(cp)(_aliases.nonzero)
+matmul = get_xp(cp)(_aliases.matmul)
+matrix_transpose = get_xp(cp)(_aliases.matrix_transpose)
+tensordot = get_xp(cp)(_aliases.tensordot)
+sign = get_xp(cp)(_aliases.sign)
+finfo = get_xp(cp)(_aliases.finfo)
+iinfo = get_xp(cp)(_aliases.iinfo)
+
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol,
+    /,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    copy: py_bool | None = None,
+    **kwargs: object,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    with cp.cuda.Device(device):
+        if copy is None:
+            return cp.asarray(obj, dtype=dtype, **kwargs)
+        else:
+            res = cp.array(obj, dtype=dtype, copy=copy, **kwargs)
+            if not copy and res is not obj:
+                raise ValueError("Unable to avoid copy while creating an array as requested")
+            return res
+
+
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: py_bool = True,
+    device: Device | None = None,
+) -> Array:
+    if device is None:
+        return x.astype(dtype=dtype, copy=copy)
+    out = _helpers.to_device(x.astype(dtype=dtype, copy=False), device)
+    return out.copy() if copy and out is x else out
+
+
+# cupy.count_nonzero does not have keepdims
+def count_nonzero(
+    x: Array,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: py_bool = False,
+) -> Array:
+   result = cp.count_nonzero(x, axis)
+   if keepdims:
+       if axis is None:
+            return cp.reshape(result, [1]*x.ndim)
+       return cp.expand_dims(result, axis)
+   return result
+
+# ceil, floor, and trunc return integers for integer inputs
+
+def ceil(x: Array, /) -> Array:
+    if cp.issubdtype(x.dtype, cp.integer):
+        return x.copy()
+    return cp.ceil(x)
+
+
+def floor(x: Array, /) -> Array:
+    if cp.issubdtype(x.dtype, cp.integer):
+        return x.copy()
+    return cp.floor(x)
+
+
+def trunc(x: Array, /) -> Array:
+    if cp.issubdtype(x.dtype, cp.integer):
+        return x.copy()
+    return cp.trunc(x)
+
+
+# take_along_axis: axis defaults to -1 but in cupy (and numpy) axis is a required arg
+def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1) -> Array:
+    return cp.take_along_axis(x, indices, axis=axis)
+
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(cp, 'vecdot'):
+    vecdot = cp.vecdot
+else:
+    vecdot = get_xp(cp)(_aliases.vecdot)
+
+if hasattr(cp, 'isdtype'):
+    isdtype = cp.isdtype
+else:
+    isdtype = get_xp(cp)(_aliases.isdtype)
+
+if hasattr(cp, 'unstack'):
+    unstack = cp.unstack
+else:
+    unstack = get_xp(cp)(_aliases.unstack)
+
+__all__ = _aliases.__all__ + ['asarray', 'astype',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'bool', 'concat', 'count_nonzero', 'pow', 'sign',
+                              'ceil', 'floor', 'trunc', 'take_along_axis']
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_info.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecfc3b446845f6c20cb1cd300410ca4c633b01c1
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
@@ -0,0 +1,336 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from cupy import (
+    dtype,
+    cuda,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for CuPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for CuPy.
+
+    Examples
+    --------
+    >>> info = xp.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': cupy.float64,
+     'complex floating': cupy.complex128,
+     'integral': cupy.int64,
+     'indexing': cupy.int64}
+
+    """
+
+    __module__ = 'cupy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for CuPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          CuPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new CuPy arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new CuPy arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        Device(0)
+
+        Notes
+        -----
+        This method returns the static default device when CuPy is initialized.
+        However, the *current* device used by creation functions (``empty`` etc.)
+        can be changed globally or with a context manager.
+
+        See Also
+        --------
+        https://github.com/data-apis/array-api/issues/835
+        """
+        return cuda.Device(0)
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new CuPy arrays.
+
+        For CuPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``cupy.float64``
+        - **"complex floating"**: ``cupy.complex128``
+        - **"integral"**: ``cupy.intp``
+        - **"indexing"**: ``cupy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new CuPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': cupy.float64,
+         'complex floating': cupy.complex128,
+         'integral': cupy.int64,
+         'indexing': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by CuPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            CuPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': cupy.int8,
+         'int16': cupy.int16,
+         'int32': cupy.int32,
+         'int64': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by CuPy.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by CuPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        """
+        return [cuda.Device(i) for i in range(cuda.runtime.getDeviceCount())]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7f57b46a52a1b7d0fcc888c100059465f7910e7
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+__all__ = ["Array", "DType", "Device"]
+
+from typing import TYPE_CHECKING
+
+import cupy as cp
+from cupy import ndarray as Array
+from cupy.cuda.device import Device
+
+if TYPE_CHECKING:
+    # NumPy 1.x on Python 3.10 fails to parse np.dtype[]
+    DType = cp.dtype[
+        cp.intp
+        | cp.int8
+        | cp.int16
+        | cp.int32
+        | cp.int64
+        | cp.uint8
+        | cp.uint16
+        | cp.uint32
+        | cp.uint64
+        | cp.float32
+        | cp.float64
+        | cp.complex64
+        | cp.complex128
+        | cp.bool_
+    ]
+else:
+    DType = cp.dtype
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/fft.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..66536fdd0308de94a6b1f9e47cc945cb9b5ba383
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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: dict[str, object] = {}
+exec("from cupy.fft import *", _n)
+del _n["__builtins__"]
+fft_all = list(_n)
+del _n
+
+from ..common import _fft
+from .._internal import get_xp
+
+import cupy as cp
+
+fft = get_xp(cp)(_fft.fft)
+ifft = get_xp(cp)(_fft.ifft)
+fftn = get_xp(cp)(_fft.fftn)
+ifftn = get_xp(cp)(_fft.ifftn)
+rfft = get_xp(cp)(_fft.rfft)
+irfft = get_xp(cp)(_fft.irfft)
+rfftn = get_xp(cp)(_fft.rfftn)
+irfftn = get_xp(cp)(_fft.irfftn)
+hfft = get_xp(cp)(_fft.hfft)
+ihfft = get_xp(cp)(_fft.ihfft)
+fftfreq = get_xp(cp)(_fft.fftfreq)
+rfftfreq = get_xp(cp)(_fft.rfftfreq)
+fftshift = get_xp(cp)(_fft.fftshift)
+ifftshift = get_xp(cp)(_fft.ifftshift)
+
+__all__ = fft_all + _fft.__all__
+
+def __dir__() -> list[str]:
+    return __all__
+
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ef6099f80299c49feea8e9e423e6749a144508a
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
@@ -0,0 +1,47 @@
+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: dict[str, object] = {}
+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__
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8299a45b1ddbdc2b35db65372a4542e09d64f6b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
@@ -0,0 +1,26 @@
+from typing import Final
+
+from ..._internal import clone_module
+
+__all__ = clone_module("dask.array", globals())
+
+# These imports may overwrite names from the import * above.
+from . import _aliases
+from ._aliases import *  # type: ignore[assignment] # noqa: F403
+from ._info import __array_namespace_info__  # noqa: F401
+
+__array_api_version__: Final = "2024.12"
+del Final
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
+
+__all__ = sorted(
+    set(__all__)
+    | set(_aliases.__all__)
+    | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"}
+)
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..d42b9b9a10f7fe20675774b546a6ff70e4dd5ce5
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
@@ -0,0 +1,369 @@
+# pyright: reportPrivateUsage=false
+# pyright: reportUnknownArgumentType=false
+# pyright: reportUnknownMemberType=false
+# pyright: reportUnknownVariableType=false
+
+from __future__ import annotations
+
+from builtins import bool as py_bool
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeIs
+
+import dask.array as da
+import numpy as np
+from numpy import bool_ as bool
+from numpy import (
+    can_cast,
+    complex64,
+    complex128,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    result_type,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+)
+
+from ..._internal import get_xp
+from ...common import _aliases, _helpers, array_namespace
+from ...common._typing import (
+    Array,
+    Device,
+    DType,
+    NestedSequence,
+    SupportsBufferProtocol,
+)
+
+isdtype = get_xp(np)(_aliases.isdtype)
+unstack = get_xp(da)(_aliases.unstack)
+
+
+# da.astype doesn't respect copy=True
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: py_bool = True,
+    device: Device | None = None,
+) -> Array:
+    """
+    Array API compatibility wrapper for astype().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    # TODO: respect device keyword?
+    _helpers._check_device(da, device)
+
+    if not copy and dtype == x.dtype:
+        return x
+    x = x.astype(dtype)
+    return x.copy() if copy else x
+
+
+# Common aliases
+
+
+# This arange func is modified from the common one to
+# not pass stop/step as keyword arguments, which will cause
+# an error with dask
+def arange(
+    start: float,
+    /,
+    stop: float | None = None,
+    step: float = 1,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    """
+    Array API compatibility wrapper for arange().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    # TODO: respect device keyword?
+    _helpers._check_device(da, device)
+
+    args: list[Any] = [start]
+    if stop is not None:
+        args.append(stop)
+    else:
+        # stop is None, so start is actually stop
+        # prepend the default value for start which is 0
+        args.insert(0, 0)
+    args.append(step)
+
+    return da.arange(*args, dtype=dtype, **kwargs)
+
+
+eye = get_xp(da)(_aliases.eye)
+linspace = get_xp(da)(_aliases.linspace)
+UniqueAllResult = get_xp(da)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(da)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(da)(_aliases.UniqueInverseResult)
+unique_all = get_xp(da)(_aliases.unique_all)
+unique_counts = get_xp(da)(_aliases.unique_counts)
+unique_inverse = get_xp(da)(_aliases.unique_inverse)
+unique_values = get_xp(da)(_aliases.unique_values)
+permute_dims = get_xp(da)(_aliases.permute_dims)
+std = get_xp(da)(_aliases.std)
+var = get_xp(da)(_aliases.var)
+cumulative_sum = get_xp(da)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(da)(_aliases.cumulative_prod)
+empty = get_xp(da)(_aliases.empty)
+empty_like = get_xp(da)(_aliases.empty_like)
+full = get_xp(da)(_aliases.full)
+full_like = get_xp(da)(_aliases.full_like)
+ones = get_xp(da)(_aliases.ones)
+ones_like = get_xp(da)(_aliases.ones_like)
+zeros = get_xp(da)(_aliases.zeros)
+zeros_like = get_xp(da)(_aliases.zeros_like)
+reshape = get_xp(da)(_aliases.reshape)
+matrix_transpose = get_xp(da)(_aliases.matrix_transpose)
+vecdot = get_xp(da)(_aliases.vecdot)
+nonzero = get_xp(da)(_aliases.nonzero)
+matmul = get_xp(np)(_aliases.matmul)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+finfo = get_xp(np)(_aliases.finfo)
+iinfo = get_xp(np)(_aliases.iinfo)
+
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol,
+    /,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    copy: py_bool | None = None,
+    **kwargs: object,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    # TODO: respect device keyword?
+    _helpers._check_device(da, device)
+
+    if isinstance(obj, da.Array):
+        if dtype is not None and dtype != obj.dtype:
+            if copy is False:
+                raise ValueError("Unable to avoid copy when changing dtype")
+            obj = obj.astype(dtype)
+        return obj.copy() if copy else obj  # pyright: ignore[reportAttributeAccessIssue]
+
+    if copy is False:
+        raise ValueError(
+            "Unable to avoid copy when converting a non-dask object to dask"
+        )
+
+    # copy=None to be uniform across dask < 2024.12 and >= 2024.12
+    # see https://github.com/dask/dask/pull/11524/
+    obj = np.array(obj, dtype=dtype, copy=True)
+    return da.from_array(obj)
+
+
+# Element wise aliases
+from dask.array import arccos as acos
+from dask.array import arccosh as acosh
+from dask.array import arcsin as asin
+from dask.array import arcsinh as asinh
+from dask.array import arctan as atan
+from dask.array import arctan2 as atan2
+from dask.array import arctanh as atanh
+
+# Other
+from dask.array import concatenate as concat
+from dask.array import invert as bitwise_invert
+from dask.array import left_shift as bitwise_left_shift
+from dask.array import power as pow
+from dask.array import right_shift as bitwise_right_shift
+
+
+# dask.array.clip does not work unless all three arguments are provided.
+# Furthermore, the masking workaround in common._aliases.clip cannot work with
+# dask (meaning uint64 promoting to float64 is going to just be unfixed for
+# now).
+def clip(
+    x: Array,
+    /,
+    min: float | Array | None = None,
+    max: float | Array | None = None,
+) -> Array:
+    """
+    Array API compatibility wrapper for clip().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+
+    def _isscalar(a: float | Array | None, /) -> TypeIs[float | None]:
+        return a is None or isinstance(a, (int, float))
+
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    # TODO: This won't handle dask unknown shapes
+    result_shape = np.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    if min is not None:
+        min = da.broadcast_to(da.asarray(min), result_shape)
+    if max is not None:
+        max = da.broadcast_to(da.asarray(max), result_shape)
+
+    if min is None and max is None:
+        return da.positive(x)
+
+    if min is None:
+        return astype(da.minimum(x, max), x.dtype)
+    if max is None:
+        return astype(da.maximum(x, min), x.dtype)
+
+    return astype(da.minimum(da.maximum(x, min), max), x.dtype)
+
+
+def _ensure_single_chunk(x: Array, axis: int) -> tuple[Array, Callable[[Array], Array]]:
+    """
+    Make sure that Array is not broken into multiple chunks along axis.
+
+    Returns
+    -------
+    x : Array
+        The input Array with a single chunk along axis.
+    restore : Callable[Array, Array]
+        function to apply to the output to rechunk it back into reasonable chunks
+    """
+    if axis < 0:
+        axis += x.ndim
+    if x.numblocks[axis] < 2:
+        return x, lambda x: x
+
+    # Break chunks on other axes in an attempt to keep chunk size low
+    x = x.rechunk({i: -1 if i == axis else "auto" for i in range(x.ndim)})
+
+    # Rather than reconstructing the original chunks, which can be a
+    # very expensive affair, just break down oversized chunks without
+    # incurring in any transfers over the network.
+    # This has the downside of a risk of overchunking if the array is
+    # then used in operations against other arrays that match the
+    # original chunking pattern.
+    return x, lambda x: x.rechunk()
+
+
+def sort(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    descending: py_bool = False,
+    stable: py_bool = True,
+) -> Array:
+    """
+    Array API compatibility layer around the lack of sort() in Dask.
+
+    Warnings
+    --------
+    This function temporarily rechunks the array along `axis` to a single chunk.
+    This can be extremely inefficient and can lead to out-of-memory errors.
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    x, restore = _ensure_single_chunk(x, axis)
+
+    meta_xp = array_namespace(x._meta)
+    x = da.map_blocks(
+        meta_xp.sort,
+        x,
+        axis=axis,
+        meta=x._meta,
+        dtype=x.dtype,
+        descending=descending,
+        stable=stable,
+    )
+
+    return restore(x)
+
+
+def argsort(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    descending: py_bool = False,
+    stable: py_bool = True,
+) -> Array:
+    """
+    Array API compatibility layer around the lack of argsort() in Dask.
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+
+    Warnings
+    --------
+    This function temporarily rechunks the array along `axis` into a single chunk.
+    This can be extremely inefficient and can lead to out-of-memory errors.
+    """
+    x, restore = _ensure_single_chunk(x, axis)
+
+    meta_xp = array_namespace(x._meta)
+    dtype = meta_xp.argsort(x._meta).dtype
+    meta = meta_xp.astype(x._meta, dtype)
+    x = da.map_blocks(
+        meta_xp.argsort,
+        x,
+        axis=axis,
+        meta=meta,
+        dtype=dtype,
+        descending=descending,
+        stable=stable,
+    )
+
+    return restore(x)
+
+
+# dask.array.count_nonzero does not have keepdims
+def count_nonzero(
+    x: Array,
+    axis: int | None = None,
+    keepdims: py_bool = False,
+) -> Array:
+    result = da.count_nonzero(x, axis)
+    if keepdims:
+        if axis is None:
+            return da.reshape(result, [1] * x.ndim)
+        return da.expand_dims(result, axis)
+    return result
+
+
+__all__ = [
+    "count_nonzero",
+    "bool",
+    "int8", "int16", "int32", "int64",
+    "uint8", "uint16", "uint32", "uint64",
+    "float32", "float64",
+    "complex64", "complex128",
+    "asarray", "astype", "can_cast", "result_type",
+    "pow",
+    "concat",
+    "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh",
+    "bitwise_left_shift", "bitwise_right_shift", "bitwise_invert",
+]  # fmt: skip
+__all__ += _aliases.__all__
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..2624c85284faefd5926d21005ed82d4ed74a2ef2
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
@@ -0,0 +1,407 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+
+# pyright: reportPrivateUsage=false
+
+from __future__ import annotations
+
+from typing import Literal, TypeAlias, overload
+
+import dask.array as da
+from numpy import bool_ as bool
+from numpy import (
+    complex64,
+    complex128,
+    dtype,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    intp,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+)
+
+from ...common._helpers import _DASK_DEVICE, _check_device, _dask_device
+from ...common._typing import (
+    Capabilities,
+    DefaultDTypes,
+    DType,
+    DTypeKind,
+    DTypesAll,
+    DTypesAny,
+    DTypesBool,
+    DTypesComplex,
+    DTypesIntegral,
+    DTypesNumeric,
+    DTypesReal,
+    DTypesSigned,
+    DTypesUnsigned,
+)
+Device: TypeAlias = Literal["cpu"] | _dask_device
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for Dask.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for Dask.
+
+    Examples
+    --------
+    >>> info = xp.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': dask.float64,
+     'complex floating': dask.complex128,
+     'integral': dask.int64,
+     'indexing': dask.int64}
+
+    """
+
+    __module__ = "dask.array"
+
+    def capabilities(self) -> Capabilities:
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing.
+
+          Dask support boolean indexing as long as both the index
+          and the indexed arrays have known shapes.
+          Note however that the output .shape and .size properties
+          will contain a non-compliant math.nan instead of None.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes.
+
+          Dask implements unique_values et.al.
+          Note however that the output .shape and .size properties
+          will contain a non-compliant math.nan instead of None.
+
+        - **"max dimensions"**: integer indicating the maximum number of
+          dimensions supported by the array library.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self) -> Device:
+        """
+        The default device used for new Dask arrays.
+
+        For Dask, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new Dask arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(self, /, *, device: Device | None = None) -> DefaultDTypes:
+        """
+        The default data types used for new Dask arrays.
+
+        For Dask, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new Dask
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': dask.float64,
+         'complex floating': dask.complex128,
+         'integral': dask.int64,
+         'indexing': dask.int64}
+
+        """
+        _check_device(da, device)
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: None = None
+    ) -> DTypesAll: ...
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: Literal["bool"]
+    ) -> DTypesBool: ...
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: Literal["signed integer"]
+    ) -> DTypesSigned: ...
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: Literal["unsigned integer"]
+    ) -> DTypesUnsigned: ...
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: Literal["integral"]
+    ) -> DTypesIntegral: ...
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: Literal["real floating"]
+    ) -> DTypesReal: ...
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: Literal["complex floating"]
+    ) -> DTypesComplex: ...
+    @overload
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: Literal["numeric"]
+    ) -> DTypesNumeric: ...
+    def dtypes(
+        self, /, *, device: Device | None = None, kind: DTypeKind | None = None
+    ) -> DTypesAny:
+        """
+        The array API data types supported by Dask.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            Dask data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': dask.int8,
+         'int16': dask.int16,
+         'int32': dask.int32,
+         'int64': dask.int64}
+
+        """
+        _check_device(da, device)
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res: dict[str, DType] = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self) -> list[Device]:
+        """
+        The devices supported by Dask.
+
+        For Dask, this always returns ``['cpu', DASK_DEVICE]``.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by Dask.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu', DASK_DEVICE]
+
+        """
+        return ["cpu", _DASK_DEVICE]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fecf6a57bcff3681dd0cd1791bedf73a3bdfc15
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
@@ -0,0 +1,16 @@
+from ..._internal import clone_module
+
+__all__ = clone_module("dask.array.fft", globals())
+
+from ...common import _fft
+from ..._internal import get_xp
+
+import dask.array as da
+
+fftfreq = get_xp(da)(_fft.fftfreq)
+rfftfreq = get_xp(da)(_fft.rfftfreq)
+
+__all__ += ["fftfreq", "rfftfreq"]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1f7505792dd9594b3e2fde5532910c0125acb00
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from typing import Literal
+
+import dask.array as da
+
+# The `matmul` and `tensordot` functions are in both the main and linalg namespaces
+from dask.array import matmul, outer, tensordot
+
+# Exports
+from ..._internal import clone_module, get_xp
+from ...common import _linalg
+from ...common._typing import Array
+
+__all__ = clone_module("dask.array.linalg", globals())
+
+from ._aliases import matrix_transpose, vecdot
+
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+# TODO: use the QR wrapper once dask
+# supports the mode keyword on QR
+# https://github.com/dask/dask/issues/10388
+#qr = get_xp(da)(_linalg.qr)
+def qr(  # type: ignore[no-redef]
+    x: Array,
+    mode: Literal["reduced", "complete"] = "reduced",
+    **kwargs: object,
+) -> QRResult:
+    if mode != "reduced":
+        raise ValueError("dask arrays only support using mode='reduced'")
+    return QRResult(*da.linalg.qr(x, **kwargs))
+trace = get_xp(da)(_linalg.trace)
+cholesky = get_xp(da)(_linalg.cholesky)
+matrix_rank = get_xp(da)(_linalg.matrix_rank)
+matrix_norm = get_xp(da)(_linalg.matrix_norm)
+
+
+# Wrap the svd functions to not pass full_matrices to dask
+# when full_matrices=False (as that is the default behavior for dask),
+# and dask doesn't have the full_matrices keyword
+def svd(x: Array, full_matrices: bool = True, **kwargs: object) -> SVDResult:  # type: ignore[no-redef]
+    if full_matrices:
+        raise ValueError("full_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__ += ["trace", "outer", "matmul", "tensordot",
+            "matrix_transpose", "vecdot", "EighResult",
+            "QRResult", "SlogdetResult", "SVDResult", "qr",
+            "cholesky", "matrix_rank", "matrix_norm", "svdvals",
+            "vector_norm", "diagonal"]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d44a07878bc33f41d962dc86dfaf333b0415753d
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
@@ -0,0 +1,38 @@
+# ruff: noqa: PLC0414
+from typing import Final
+
+from .._internal import clone_module
+
+# This needs to be loaded explicitly before cloning
+import numpy.typing  # noqa: F401
+
+__all__ = clone_module("numpy", globals())
+
+# These imports may overwrite names from the import * above.
+from . import _aliases
+from ._aliases import *  # type: ignore[assignment,no-redef] # noqa: F403
+from ._info import __array_namespace_info__  # noqa: F401
+
+# Don't know why, but we have to do an absolute import to import linalg. If we
+# instead do
+#
+# from . import linalg
+#
+# It doesn't overwrite np.linalg from above. The import is generated
+# dynamically so that the library can be vendored.
+__import__(__package__ + ".linalg")
+
+__import__(__package__ + ".fft")
+
+from .linalg import matrix_transpose, vecdot  # type: ignore[no-redef]  # noqa: F401
+
+__array_api_version__: Final = "2024.12"
+
+__all__ = sorted(
+    set(__all__) 
+    | set(_aliases.__all__) 
+    | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"}
+)
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6aedad162f4e3d8c761ccb9e8ebaf723cb8170a2
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd720b2dea633529780a227519aa146214e11093
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13cd58d9bbdefccf120b335675d0cb00b4fee6c9
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_typing.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_typing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b00f37aa0292392d3215d2552c4ce7574e115c0
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_typing.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c87d6892c375d92d1e67c5dc8d5e250df5541611
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..803f6028e650666ccc6d87c751e6a55685b40437
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae339abbdb0b0237bc1681a3370627f07761eee
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
@@ -0,0 +1,191 @@
+# pyright: reportPrivateUsage=false
+from __future__ import annotations
+
+from builtins import bool as py_bool
+from typing import Any, cast
+
+import numpy as np
+
+from .._internal import get_xp
+from ..common import _aliases, _helpers
+from ..common._typing import NestedSequence, SupportsBufferProtocol
+from ._typing import Array, Device, DType
+
+bool = np.bool_
+
+# Basic renames
+acos = np.arccos
+acosh = np.arccosh
+asin = np.arcsin
+asinh = np.arcsinh
+atan = np.arctan
+atan2 = np.arctan2
+atanh = np.arctanh
+bitwise_left_shift = np.left_shift
+bitwise_invert = np.invert
+bitwise_right_shift = np.right_shift
+concat = np.concatenate
+pow = np.power
+
+arange = get_xp(np)(_aliases.arange)
+empty = get_xp(np)(_aliases.empty)
+empty_like = get_xp(np)(_aliases.empty_like)
+eye = get_xp(np)(_aliases.eye)
+full = get_xp(np)(_aliases.full)
+full_like = get_xp(np)(_aliases.full_like)
+linspace = get_xp(np)(_aliases.linspace)
+ones = get_xp(np)(_aliases.ones)
+ones_like = get_xp(np)(_aliases.ones_like)
+zeros = get_xp(np)(_aliases.zeros)
+zeros_like = get_xp(np)(_aliases.zeros_like)
+UniqueAllResult = get_xp(np)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(np)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(np)(_aliases.UniqueInverseResult)
+unique_all = get_xp(np)(_aliases.unique_all)
+unique_counts = get_xp(np)(_aliases.unique_counts)
+unique_inverse = get_xp(np)(_aliases.unique_inverse)
+unique_values = get_xp(np)(_aliases.unique_values)
+std = get_xp(np)(_aliases.std)
+var = get_xp(np)(_aliases.var)
+cumulative_sum = get_xp(np)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(np)(_aliases.cumulative_prod)
+clip = get_xp(np)(_aliases.clip)
+permute_dims = get_xp(np)(_aliases.permute_dims)
+reshape = get_xp(np)(_aliases.reshape)
+argsort = get_xp(np)(_aliases.argsort)
+sort = get_xp(np)(_aliases.sort)
+nonzero = get_xp(np)(_aliases.nonzero)
+matmul = get_xp(np)(_aliases.matmul)
+matrix_transpose = get_xp(np)(_aliases.matrix_transpose)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+finfo = get_xp(np)(_aliases.finfo)
+iinfo = get_xp(np)(_aliases.iinfo)
+
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+# asarray() is different enough between numpy, cupy, and dask, the logic
+# complicated enough that it's easier to define it separately for each module
+# rather than trying to combine everything into one function in common/
+def asarray(
+    obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol,
+    /,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    copy: py_bool | None = None,
+    **kwargs: Any,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    _helpers._check_device(np, device)
+
+    # None is unsupported in NumPy 1.0, but we can use an internal enum
+    # False in NumPy 1.0 means None in NumPy 2.0 and in the Array API
+    if copy is None:
+        copy = np._CopyMode.IF_NEEDED  # type: ignore[assignment,attr-defined]
+    elif copy is False:
+        copy = np._CopyMode.NEVER  # type: ignore[assignment,attr-defined]
+
+    return np.array(obj, copy=copy, dtype=dtype, **kwargs)
+
+
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: py_bool = True,
+    device: Device | None = None,
+) -> Array:
+    _helpers._check_device(np, device)
+    return x.astype(dtype=dtype, copy=copy)
+
+
+# count_nonzero returns a python int for axis=None and keepdims=False
+# https://github.com/numpy/numpy/issues/17562
+def count_nonzero(
+    x: Array,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: py_bool = False,
+) -> Array:
+    # NOTE: this is currently incorrectly typed in numpy, but will be fixed in
+    # numpy 2.2.5 and 2.3.0: https://github.com/numpy/numpy/pull/28750
+    result = cast("Any", np.count_nonzero(x, axis=axis, keepdims=keepdims))  # pyright: ignore[reportArgumentType, reportCallIssue]
+    if axis is None and not keepdims:
+        return np.asarray(result)
+    return result
+
+
+# take_along_axis: axis defaults to -1 but in numpy axis is a required arg
+def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1) -> Array:
+    return np.take_along_axis(x, indices, axis=axis)
+
+
+# ceil, floor, and trunc return integers for integer inputs in NumPy < 2
+
+def ceil(x: Array, /) -> Array:
+    if np.__version__ < '2' and np.issubdtype(x.dtype, np.integer):
+        return x.copy()
+    return np.ceil(x)
+
+
+def floor(x: Array, /) -> Array:
+    if np.__version__ < '2' and np.issubdtype(x.dtype, np.integer):
+        return x.copy()
+    return np.floor(x)
+
+
+def trunc(x: Array, /) -> Array:
+    if np.__version__ < '2' and np.issubdtype(x.dtype, np.integer):
+        return x.copy()
+    return np.trunc(x)
+
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np, "vecdot"):
+    vecdot = np.vecdot
+else:
+    vecdot = get_xp(np)(_aliases.vecdot)  # type: ignore[assignment]
+
+if hasattr(np, "isdtype"):
+    isdtype = np.isdtype
+else:
+    isdtype = get_xp(np)(_aliases.isdtype)
+
+if hasattr(np, "unstack"):
+    unstack = np.unstack
+else:
+    unstack = get_xp(np)(_aliases.unstack)
+
+__all__ = _aliases.__all__ + [
+    "asarray",
+    "astype",
+    "acos",
+    "acosh",
+    "asin",
+    "asinh",
+    "atan",
+    "atan2",
+    "atanh",
+    "ceil",
+    "floor",
+    "trunc",
+    "bitwise_left_shift",
+    "bitwise_invert",
+    "bitwise_right_shift",
+    "bool",
+    "concat",
+    "count_nonzero",
+    "pow",
+    "take_along_axis"
+]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_info.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..e547ec989c519eee722384be99f9b4e45903dece
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
@@ -0,0 +1,367 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from __future__ import annotations
+
+from numpy import bool_ as bool
+from numpy import (
+    complex64,
+    complex128,
+    dtype,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    intp,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+)
+
+from ..common._typing import DefaultDTypes
+from ._typing import Device, DType
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for NumPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for NumPy.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'numpy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for NumPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          NumPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new NumPy arrays.
+
+        For NumPy, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new NumPy arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(
+        self,
+        *,
+        device: Device | None = None,
+    ) -> DefaultDTypes:
+        """
+        The default data types used for new NumPy arrays.
+
+        For NumPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for. For NumPy, only
+            ``'cpu'`` is allowed.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new NumPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': numpy.float64,
+         'complex floating': numpy.complex128,
+         'integral': numpy.int64,
+         'indexing': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(
+        self,
+        *,
+        device: Device | None = None,
+        kind: str | tuple[str, ...] | None = None,
+    ) -> dict[str, DType]:
+        """
+        The array API data types supported by NumPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for. For NumPy, only ``'cpu'`` is
+            allowed.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            NumPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": dtype(bool)}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res: dict[str, DType] = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self) -> list[Device]:
+        """
+        The devices supported by NumPy.
+
+        For NumPy, this always returns ``['cpu']``.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by NumPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu']
+
+        """
+        return ["cpu"]
+
+
+__all__ = ["__array_namespace_info__"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..a14832dfc2e6e12a5e3589c89633b33d68d76527
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
@@ -0,0 +1,29 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal, TypeAlias
+
+import numpy as np
+
+Device: TypeAlias = Literal["cpu"]
+
+if TYPE_CHECKING:
+
+    # NumPy 1.x on Python 3.10 fails to parse np.dtype[]
+    DType: TypeAlias = np.dtype[
+        np.bool_
+        | np.integer[Any]
+        | np.float32
+        | np.float64
+        | np.complex64
+        | np.complex128
+    ]
+    Array: TypeAlias = np.ndarray[Any, DType]
+else:
+    DType: TypeAlias = np.dtype
+    Array: TypeAlias = np.ndarray
+
+__all__ = ["Array", "DType", "Device"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/fft.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba8edbb605306d0887f0e3fb60b267e1c3bf864b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
@@ -0,0 +1,30 @@
+import numpy as np
+
+from .._internal import clone_module
+
+__all__ = clone_module("numpy.fft", globals())
+
+from .._internal import get_xp
+from ..common import _fft
+
+fft = get_xp(np)(_fft.fft)
+ifft = get_xp(np)(_fft.ifft)
+fftn = get_xp(np)(_fft.fftn)
+ifftn = get_xp(np)(_fft.ifftn)
+rfft = get_xp(np)(_fft.rfft)
+irfft = get_xp(np)(_fft.irfft)
+rfftn = get_xp(np)(_fft.rfftn)
+irfftn = get_xp(np)(_fft.irfftn)
+hfft = get_xp(np)(_fft.hfft)
+ihfft = get_xp(np)(_fft.ihfft)
+fftfreq = get_xp(np)(_fft.fftfreq)
+rfftfreq = get_xp(np)(_fft.rfftfreq)
+fftshift = get_xp(np)(_fft.fftshift)
+ifftshift = get_xp(np)(_fft.ifftshift)
+
+
+__all__ = sorted(set(__all__) | set(_fft.__all__))
+
+def __dir__() -> list[str]:
+    return __all__
+
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcd9f0081ba5b59a17417c4d937cc103832f8c00
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
@@ -0,0 +1,128 @@
+# pyright: reportAttributeAccessIssue=false
+# pyright: reportUnknownArgumentType=false
+# pyright: reportUnknownMemberType=false
+# pyright: reportUnknownVariableType=false
+
+from __future__ import annotations
+
+import numpy as np
+
+from .._internal import clone_module, get_xp
+from ..common import _linalg
+
+__all__ = clone_module("numpy.linalg", globals())
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot  # noqa: F401
+from ._typing import Array
+
+cross = get_xp(np)(_linalg.cross)
+outer = get_xp(np)(_linalg.outer)
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+eigh = get_xp(np)(_linalg.eigh)
+qr = get_xp(np)(_linalg.qr)
+slogdet = get_xp(np)(_linalg.slogdet)
+svd = get_xp(np)(_linalg.svd)
+cholesky = get_xp(np)(_linalg.cholesky)
+matrix_rank = get_xp(np)(_linalg.matrix_rank)
+pinv = get_xp(np)(_linalg.pinv)
+matrix_norm = get_xp(np)(_linalg.matrix_norm)
+svdvals = get_xp(np)(_linalg.svdvals)
+diagonal = get_xp(np)(_linalg.diagonal)
+trace = get_xp(np)(_linalg.trace)
+
+# Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a
+# vector when it is exactly 1-dimensional. All other cases treat x2 as a stack
+# of matrices. The np.linalg.solve behavior of allowing stacks of both
+# matrices and vectors is ambiguous c.f.
+# https://github.com/numpy/numpy/issues/15349 and
+# https://github.com/data-apis/array-api/issues/285.
+
+# To workaround this, the below is the code from np.linalg.solve except
+# only calling solve1 in the exactly 1D case.
+
+
+# This code is here instead of in common because it is numpy specific. Also
+# note that CuPy's solve() does not currently support broadcasting (see
+# https://github.com/cupy/cupy/blob/main/cupy/cublas.py#L43).
+def solve(x1: Array, x2: Array, /) -> Array:
+    try:
+        from numpy.linalg._linalg import (  # type: ignore[attr-defined]
+            _assert_stacked_2d,
+            _assert_stacked_square,
+            _commonType,
+            _makearray,
+            _raise_linalgerror_singular,
+            isComplexType,
+        )
+    except ImportError:
+        from numpy.linalg.linalg import (  # type: ignore[attr-defined]
+            _assert_stacked_2d,
+            _assert_stacked_square,
+            _commonType,
+            _makearray,
+            _raise_linalgerror_singular,
+            isComplexType,
+        )
+    from numpy.linalg import _umath_linalg
+
+    x1, _ = _makearray(x1)
+    _assert_stacked_2d(x1)
+    _assert_stacked_square(x1)
+    x2, wrap = _makearray(x2)
+    t, result_t = _commonType(x1, x2)
+
+    # This part is different from np.linalg.solve
+    gufunc: np.ufunc
+    if x2.ndim == 1:
+        gufunc = _umath_linalg.solve1
+    else:
+        gufunc = _umath_linalg.solve
+
+    # This does nothing currently but is left in because it will be relevant
+    # when complex dtype support is added to the spec in 2022.
+    signature = "DD->D" if isComplexType(t) else "dd->d"
+    with np.errstate(
+        call=_raise_linalgerror_singular,
+        invalid="call",
+        over="ignore",
+        divide="ignore",
+        under="ignore",
+    ):
+        r: Array = gufunc(x1, x2, signature=signature)
+
+    return wrap(r.astype(result_t, copy=False))
+
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np.linalg, "vector_norm"):
+    vector_norm = np.linalg.vector_norm
+else:
+    vector_norm = get_xp(np)(_linalg.vector_norm)
+
+
+_all = [
+    "LinAlgError",
+    "cond",
+    "det",
+    "eig",
+    "eigvals",
+    "eigvalsh",
+    "inv",
+    "lstsq",
+    "matrix_power",
+    "multi_dot",
+    "norm",
+    "solve", 
+    "tensorinv",
+    "tensorsolve",
+    "vector_norm",
+]
+__all__ = sorted(set(__all__) | set(_linalg.__all__) | set(_all))
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a647bb73b0a1a819e861965c6130748228b3230
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
@@ -0,0 +1,25 @@
+from typing import Final
+
+from .._internal import clone_module
+
+__all__ = clone_module("torch", globals())
+
+# These imports may overwrite names from the import * above.
+from . import _aliases
+from ._aliases import * # noqa: F403
+from ._info import __array_namespace_info__  # noqa: F401
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
+
+__array_api_version__: Final = '2024.12'
+
+__all__ = sorted(
+    set(__all__)
+    | set(_aliases.__all__)
+    | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"}
+)
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dcb08443878f14d0deb3e36cdf6aedabd370d0b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
@@ -0,0 +1,875 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from functools import reduce as _reduce, wraps as _wraps
+from builtins import all as _builtin_all, any as _builtin_any
+from typing import Any, Literal
+
+import torch
+
+from .._internal import get_xp
+from ..common import _aliases
+from ..common._typing import NestedSequence, SupportsBufferProtocol
+from ._typing import Array, Device, DType
+
+_int_dtypes = {
+    torch.uint8,
+    torch.int8,
+    torch.int16,
+    torch.int32,
+    torch.int64,
+}
+try:
+    # torch >=2.3
+    _int_dtypes |= {torch.uint16, torch.uint32, torch.uint64}
+except AttributeError:
+    pass
+
+
+_array_api_dtypes = {
+    torch.bool,
+    *_int_dtypes,
+    torch.float32,
+    torch.float64,
+    torch.complex64,
+    torch.complex128,
+}
+
+_promotion_table = {
+    # ints
+    (torch.int8, torch.int16): torch.int16,
+    (torch.int8, torch.int32): torch.int32,
+    (torch.int8, torch.int64): torch.int64,
+    (torch.int16, torch.int32): torch.int32,
+    (torch.int16, torch.int64): torch.int64,
+    (torch.int32, torch.int64): torch.int64,
+    # ints and uints (mixed sign)
+    (torch.uint8, torch.int8): torch.int16,
+    (torch.uint8, torch.int16): torch.int16,
+    (torch.uint8, torch.int32): torch.int32,
+    (torch.uint8, torch.int64): torch.int64,
+    # floats
+    (torch.float32, torch.float64): torch.float64,
+    # complexes
+    (torch.complex64, torch.complex128): torch.complex128,
+    # Mixed float and complex
+    (torch.float32, torch.complex64): torch.complex64,
+    (torch.float32, torch.complex128): torch.complex128,
+    (torch.float64, torch.complex64): torch.complex128,
+    (torch.float64, torch.complex128): torch.complex128,
+}
+
+_promotion_table.update({(b, a): c for (a, b), c in _promotion_table.items()})
+_promotion_table.update({(a, a): a for a in _array_api_dtypes})
+
+
+def _two_arg(f):
+    @_wraps(f)
+    def _f(x1, x2, /, **kwargs):
+        x1, x2 = _fix_promotion(x1, x2)
+        return f(x1, x2, **kwargs)
+    if _f.__doc__ is None:
+        _f.__doc__ = f"""\
+Array API compatibility wrapper for torch.{f.__name__}.
+
+See the corresponding PyTorch documentation and/or the array API specification
+for more details.
+
+"""
+    return _f
+
+def _fix_promotion(x1, x2, only_scalar=True):
+    if not isinstance(x1, torch.Tensor) or not isinstance(x2, torch.Tensor):
+        return x1, x2
+    if x1.dtype not in _array_api_dtypes or x2.dtype not in _array_api_dtypes:
+        return x1, x2
+    # If an argument is 0-D pytorch downcasts the other argument
+    if not only_scalar or x1.shape == ():
+        dtype = result_type(x1, x2)
+        x2 = x2.to(dtype)
+    if not only_scalar or x2.shape == ():
+        dtype = result_type(x1, x2)
+        x1 = x1.to(dtype)
+    return x1, x2
+
+
+_py_scalars = (bool, int, float, complex)
+
+
+def result_type(*arrays_and_dtypes: Array | DType | complex) -> DType:
+    num = len(arrays_and_dtypes)
+
+    if num == 0:
+        raise ValueError("At least one array or dtype must be provided")
+
+    elif num == 1:
+        x = arrays_and_dtypes[0]
+        if isinstance(x, torch.dtype):
+            return x
+        return x.dtype
+
+    if num == 2:
+        x, y = arrays_and_dtypes
+        return _result_type(x, y)
+
+    else:
+        # sort scalars so that they are treated last
+        scalars, others = [], []
+        for x in arrays_and_dtypes:
+            if isinstance(x, _py_scalars):
+                scalars.append(x)
+            else:
+                others.append(x)
+        if not others:
+            raise ValueError("At least one array or dtype must be provided")
+
+        # combine left-to-right
+        return _reduce(_result_type, others + scalars)
+
+
+def _result_type(x: Array | DType | complex, y: Array | DType | complex) -> DType:
+    if not (isinstance(x, _py_scalars) or isinstance(y, _py_scalars)):
+        xdt = x if isinstance(x, torch.dtype) else x.dtype
+        ydt = y if isinstance(y, torch.dtype) else y.dtype
+
+        try:
+            return _promotion_table[xdt, ydt]
+        except KeyError:
+            pass
+
+    # This doesn't result_type(dtype, dtype) for non-array API dtypes
+    # because torch.result_type only accepts tensors. This does however, allow
+    # cross-kind promotion.
+    x = torch.tensor([], dtype=x) if isinstance(x, torch.dtype) else x
+    y = torch.tensor([], dtype=y) if isinstance(y, torch.dtype) else y
+    return torch.result_type(x, y)
+
+
+def can_cast(from_: DType | Array, to: DType, /) -> bool:
+    if not isinstance(from_, torch.dtype):
+        from_ = from_.dtype
+    return torch.can_cast(from_, to)
+
+# Basic renames
+bitwise_invert = torch.bitwise_not
+newaxis = None
+# torch.conj sets the conjugation bit, which breaks conversion to other
+# libraries. See https://github.com/data-apis/array-api-compat/issues/173
+conj = torch.conj_physical
+
+# Two-arg elementwise functions
+# These require a wrapper to do the correct type promotion on 0-D tensors
+add = _two_arg(torch.add)
+atan2 = _two_arg(torch.atan2)
+bitwise_and = _two_arg(torch.bitwise_and)
+bitwise_left_shift = _two_arg(torch.bitwise_left_shift)
+bitwise_or = _two_arg(torch.bitwise_or)
+bitwise_right_shift = _two_arg(torch.bitwise_right_shift)
+bitwise_xor = _two_arg(torch.bitwise_xor)
+copysign = _two_arg(torch.copysign)
+divide = _two_arg(torch.divide)
+# Also a rename. torch.equal does not broadcast
+equal = _two_arg(torch.eq)
+floor_divide = _two_arg(torch.floor_divide)
+greater = _two_arg(torch.greater)
+greater_equal = _two_arg(torch.greater_equal)
+hypot = _two_arg(torch.hypot)
+less = _two_arg(torch.less)
+less_equal = _two_arg(torch.less_equal)
+logaddexp = _two_arg(torch.logaddexp)
+# logical functions are not included here because they only accept bool in the
+# spec, so type promotion is irrelevant.
+maximum = _two_arg(torch.maximum)
+minimum = _two_arg(torch.minimum)
+multiply = _two_arg(torch.multiply)
+not_equal = _two_arg(torch.not_equal)
+pow = _two_arg(torch.pow)
+remainder = _two_arg(torch.remainder)
+subtract = _two_arg(torch.subtract)
+
+
+def asarray(
+    obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol,
+    /,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    copy: bool | None = None,
+    **kwargs: Any,
+) -> Array:
+    # torch.asarray does not respect input->output device propagation
+    # https://github.com/pytorch/pytorch/issues/150199
+    if device is None and isinstance(obj, torch.Tensor):
+        device = obj.device
+    return torch.asarray(obj, dtype=dtype, device=device, copy=copy, **kwargs)
+
+
+# These wrappers are mostly based on the fact that pytorch uses 'dim' instead
+# of 'axis'.
+
+# torch.min and torch.max return a tuple and don't support multiple axes https://github.com/pytorch/pytorch/issues/58745
+def max(x: Array, /, *, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amax(x, axis, keepdims=keepdims)
+
+def min(x: Array, /, *, axis: int | tuple[int, ...] |None = None, keepdims: bool = False) -> Array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amin(x, axis, keepdims=keepdims)
+
+clip = get_xp(torch)(_aliases.clip)
+unstack = get_xp(torch)(_aliases.unstack)
+cumulative_sum = get_xp(torch)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(torch)(_aliases.cumulative_prod)
+finfo = get_xp(torch)(_aliases.finfo)
+iinfo = get_xp(torch)(_aliases.iinfo)
+
+
+# torch.sort also returns a tuple
+# https://github.com/pytorch/pytorch/issues/70921
+def sort(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    descending: bool = False,
+    stable: bool = True,
+    **kwargs: object,
+) -> Array:
+    return torch.sort(x, dim=axis, descending=descending, stable=stable, **kwargs).values
+
+
+# Wrap torch.argsort to set stable=True by default
+def argsort(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    descending: bool = False,
+    stable: bool = True,
+    **kwargs: object,
+) -> Array:
+    return torch.argsort(x, dim=axis, descending=descending, stable=stable, **kwargs)
+
+
+def _normalize_axes(axis, ndim):
+    axes = []
+    if ndim == 0 and axis:
+        # Better error message in this case
+        raise IndexError(f"Dimension out of range: {axis[0]}")
+    lower, upper = -ndim, ndim - 1
+    for a in axis:
+        if a < lower or a > upper:
+            # Match torch error message (e.g., from sum())
+            raise IndexError(f"Dimension out of range (expected to be in range of [{lower}, {upper}], but got {a}")
+        if a < 0:
+            a = a + ndim
+        if a in axes:
+            # Use IndexError instead of RuntimeError, and "axis" instead of "dim"
+            raise IndexError(f"Axis {a} appears multiple times in the list of axes")
+        axes.append(a)
+    return sorted(axes)
+
+def _axis_none_keepdims(x, ndim, keepdims):
+    # Apply keepdims when axis=None
+    # (https://github.com/pytorch/pytorch/issues/71209)
+    # Note that this is only valid for the axis=None case.
+    if keepdims:
+        for i in range(ndim):
+            x = torch.unsqueeze(x, 0)
+    return x
+
+def _reduce_multiple_axes(f, x, axis, keepdims=False, **kwargs):
+    # Some reductions don't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    axes = _normalize_axes(axis, x.ndim)
+    for a in reversed(axes):
+        x = torch.movedim(x, a, -1)
+    x = torch.flatten(x, -len(axes))
+
+    out = f(x, -1, **kwargs)
+
+    if keepdims:
+        for a in axes:
+            out = torch.unsqueeze(out, a)
+    return out
+
+
+def _sum_prod_no_axis(x: Array, dtype: DType | None) -> Array:
+    """
+    Implements `sum(..., axis=())` and `prod(..., axis=())`.
+    
+    Works around https://github.com/pytorch/pytorch/issues/29137
+    """
+    if dtype is not None:
+        return x.clone() if dtype == x.dtype else x.to(dtype)
+
+    # We can't upcast uint8 according to the spec because there is no
+    # torch.uint64, so at least upcast to int64 which is what prod does
+    # when axis=None.
+    if x.dtype in (torch.uint8, torch.int8, torch.int16, torch.int32):
+        return x.to(torch.int64)
+
+    return x.clone()
+
+
+def prod(x: Array,
+         /,
+         *,
+         axis: int | tuple[int, ...] | None = None,
+         dtype: DType | None = None,
+         keepdims: bool = False,
+         **kwargs: object) -> Array:
+
+    if axis == ():
+        return _sum_prod_no_axis(x, dtype)
+    # torch.prod doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        return _reduce_multiple_axes(torch.prod, x, axis, keepdims=keepdims, dtype=dtype, **kwargs)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.prod(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+
+    return torch.prod(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+
+def sum(x: Array,
+         /,
+         *,
+         axis: int | tuple[int, ...] | None = None,
+         dtype: DType | None = None,
+         keepdims: bool = False,
+         **kwargs: object) -> Array:
+
+    if axis == ():
+        return _sum_prod_no_axis(x, dtype)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.sum(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+
+    return torch.sum(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+def any(x: Array,
+        /,
+        *,
+        axis: int | tuple[int, ...] | None = None,
+        keepdims: bool = False,
+        **kwargs: object) -> Array:
+
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.any doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.any, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.any(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.any doesn't return bool for uint8
+    return torch.any(x, axis, keepdims=keepdims).to(torch.bool)
+
+def all(x: Array,
+        /,
+        *,
+        axis: int | tuple[int, ...] | None = None,
+        keepdims: bool = False,
+        **kwargs: object) -> Array:
+
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.all doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.all, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.all(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.all doesn't return bool for uint8
+    return torch.all(x, axis, keepdims=keepdims).to(torch.bool)
+
+def mean(x: Array,
+         /,
+         *,
+         axis: int | tuple[int, ...] | None = None,
+         keepdims: bool = False,
+         **kwargs: object) -> Array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.mean(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.mean(x, axis, keepdims=keepdims, **kwargs)
+
+def std(x: Array,
+        /,
+        *,
+        axis: int | tuple[int, ...] | None = None,
+        correction: float = 0.0,
+        keepdims: bool = False,
+        **kwargs: object) -> Array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    if isinstance(correction, float):
+        _correction = int(correction)
+        if correction != _correction:
+            raise NotImplementedError("float correction in torch std() is not yet supported")
+    else:
+        _correction = correction
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.std(x, tuple(range(x.ndim)), correction=_correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.std(x, axis, correction=_correction, keepdims=keepdims, **kwargs)
+
+def var(x: Array,
+        /,
+        *,
+        axis: int | tuple[int, ...] | None = None,
+        correction: float = 0.0,
+        keepdims: bool = False,
+        **kwargs: object) -> Array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    # if isinstance(correction, float):
+    #     correction = int(correction)
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.var(x, tuple(range(x.ndim)), correction=correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.var(x, axis, correction=correction, keepdims=keepdims, **kwargs)
+
+# torch.concat doesn't support dim=None
+# https://github.com/pytorch/pytorch/issues/70925
+def concat(arrays: tuple[Array, ...] | list[Array],
+           /,
+           *,
+           axis: int | None = 0,
+           **kwargs: object) -> Array:
+    if axis is None:
+        arrays = tuple(ar.flatten() for ar in arrays)
+        axis = 0
+    return torch.concat(arrays, axis, **kwargs)
+
+# torch.squeeze only accepts int dim and doesn't require it
+# https://github.com/pytorch/pytorch/issues/70924. Support for tuple dim was
+# added at https://github.com/pytorch/pytorch/pull/89017.
+def squeeze(x: Array, /, axis: int | tuple[int, ...]) -> Array:
+    if isinstance(axis, int):
+        axis = (axis,)
+    for a in axis:
+        if x.shape[a] != 1:
+            raise ValueError("squeezed dimensions must be equal to 1")
+    axes = _normalize_axes(axis, x.ndim)
+    # Remove this once pytorch 1.14 is released with the above PR #89017.
+    sequence = [a - i for i, a in enumerate(axes)]
+    for a in sequence:
+        x = torch.squeeze(x, a)
+    return x
+
+# torch.broadcast_to uses size instead of shape
+def broadcast_to(x: Array, /, shape: tuple[int, ...], **kwargs: object) -> Array:
+    return torch.broadcast_to(x, shape, **kwargs)
+
+# torch.permute uses dims instead of axes
+def permute_dims(x: Array, /, axes: tuple[int, ...]) -> Array:
+    return torch.permute(x, axes)
+
+# The axis parameter doesn't work for flip() and roll()
+# https://github.com/pytorch/pytorch/issues/71210. Also torch.flip() doesn't
+# accept axis=None
+def flip(x: Array, /, *, axis: int | tuple[int, ...] | None = None, **kwargs: object) -> Array:
+    if axis is None:
+        axis = tuple(range(x.ndim))
+    # torch.flip doesn't accept dim as an int but the method does
+    # https://github.com/pytorch/pytorch/issues/18095
+    return x.flip(axis, **kwargs)
+
+def roll(x: Array, /, shift: int | tuple[int, ...], *, axis: int | tuple[int, ...] | None = None, **kwargs: object) -> Array:
+    return torch.roll(x, shift, axis, **kwargs)
+
+def nonzero(x: Array, /, **kwargs: object) -> tuple[Array, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return torch.nonzero(x, as_tuple=True, **kwargs)
+
+
+# torch uses `dim` instead of `axis`
+def diff(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    n: int = 1,
+    prepend: Array | None = None,
+    append: Array | None = None,
+) -> Array:
+    return torch.diff(x, dim=axis, n=n, prepend=prepend, append=append)
+
+
+# torch uses `dim` instead of `axis`, does not have keepdims
+def count_nonzero(
+    x: Array,
+    /,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+) -> Array:
+    result = torch.count_nonzero(x, dim=axis)
+    if keepdims:
+        if isinstance(axis, int):
+            return result.unsqueeze(axis)
+        elif isinstance(axis, tuple):
+            n_axis = [x.ndim + ax if ax < 0 else ax for ax in axis]
+            sh = [1 if i in n_axis else x.shape[i] for i in range(x.ndim)]
+            return torch.reshape(result, sh)
+        return _axis_none_keepdims(result, x.ndim, keepdims)
+    else:
+        return result
+
+
+# "repeat" is torch.repeat_interleave;  also the dim argument
+def repeat(x: Array, repeats: int | Array, /, *, axis: int | None = None) -> Array:
+    return torch.repeat_interleave(x, repeats, axis)
+
+
+def where(condition: Array, x1: Array | complex, x2: Array | complex, /) -> Array:
+    x1, x2 = _fix_promotion(x1, x2)
+    return torch.where(condition, x1, x2)
+
+
+# torch.reshape doesn't have the copy keyword
+def reshape(x: Array,
+            /,
+            shape: tuple[int, ...],
+            *,
+            copy: bool | None = None,
+            **kwargs: object) -> Array:
+    if copy is not None:
+        raise NotImplementedError("torch.reshape doesn't yet support the copy keyword")
+    return torch.reshape(x, shape, **kwargs)
+
+# torch.arange doesn't support returning empty arrays
+# (https://github.com/pytorch/pytorch/issues/70915), and doesn't support some
+# keyword argument combinations
+# (https://github.com/pytorch/pytorch/issues/70914)
+def arange(start: float,
+           /,
+           stop: float | None = None,
+           step: float = 1,
+           *,
+           dtype: DType | None = None,
+           device: Device | None = None,
+           **kwargs: object) -> Array:
+    if stop is None:
+        start, stop = 0, start
+    if step > 0 and stop <= start or step < 0 and stop >= start:
+        if dtype is None:
+            if _builtin_all(isinstance(i, int) for i in [start, stop, step]):
+                dtype = torch.int64
+            else:
+                dtype = torch.float32
+        return torch.empty(0, dtype=dtype, device=device, **kwargs)
+    return torch.arange(start, stop, step, dtype=dtype, device=device, **kwargs)
+
+# torch.eye does not accept None as a default for the second argument and
+# doesn't support off-diagonals (https://github.com/pytorch/pytorch/issues/70910)
+def eye(n_rows: int,
+        n_cols: int | None = None,
+        /,
+        *,
+        k: int = 0,
+        dtype: DType | None = None,
+        device: Device | None = None,
+        **kwargs: object) -> Array:
+    if n_cols is None:
+        n_cols = n_rows
+    z = torch.zeros(n_rows, n_cols, dtype=dtype, device=device, **kwargs)
+    if abs(k) <= n_rows + n_cols:
+        z.diagonal(k).fill_(1)
+    return z
+
+# torch.linspace doesn't have the endpoint parameter
+def linspace(start: float,
+             stop: float,
+             /,
+             num: int,
+             *,
+             dtype: DType | None = None,
+             device: Device | None = None,
+             endpoint: bool = True,
+             **kwargs: object) -> Array:
+    if not endpoint:
+        return torch.linspace(start, stop, num+1, dtype=dtype, device=device, **kwargs)[:-1]
+    return torch.linspace(start, stop, num, dtype=dtype, device=device, **kwargs)
+
+# torch.full does not accept an int size
+# https://github.com/pytorch/pytorch/issues/70906
+def full(shape: int | tuple[int, ...],
+         fill_value: complex,
+         *,
+         dtype: DType | None = None,
+         device: Device | None = None,
+         **kwargs: object) -> Array:
+    if isinstance(shape, int):
+        shape = (shape,)
+
+    return torch.full(shape, fill_value, dtype=dtype, device=device, **kwargs)
+
+# ones, zeros, and empty do not accept shape as a keyword argument
+def ones(shape: int | tuple[int, ...],
+         *,
+         dtype: DType | None = None,
+         device: Device | None = None,
+         **kwargs: object) -> Array:
+    return torch.ones(shape, dtype=dtype, device=device, **kwargs)
+
+def zeros(shape: int | tuple[int, ...],
+         *,
+         dtype: DType | None = None,
+         device: Device | None = None,
+         **kwargs: object) -> Array:
+    return torch.zeros(shape, dtype=dtype, device=device, **kwargs)
+
+def empty(shape: int | tuple[int, ...],
+         *,
+         dtype: DType | None = None,
+         device: Device | None = None,
+         **kwargs: object) -> Array:
+    return torch.empty(shape, dtype=dtype, device=device, **kwargs)
+
+# tril and triu do not call the keyword argument k
+
+def tril(x: Array, /, *, k: int = 0) -> Array:
+    return torch.tril(x, k)
+
+def triu(x: Array, /, *, k: int = 0) -> Array:
+    return torch.triu(x, k)
+
+# Functions that aren't in torch https://github.com/pytorch/pytorch/issues/58742
+def expand_dims(x: Array, /, *, axis: int = 0) -> Array:
+    return torch.unsqueeze(x, axis)
+
+
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: bool = True,
+    device: Device | None = None,
+) -> Array:
+    if device is not None:
+        return x.to(device, dtype=dtype, copy=copy)
+    return x.to(dtype=dtype, copy=copy)
+
+
+def broadcast_arrays(*arrays: Array) -> 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: object) -> Array:
+    # torch.matmul doesn't type promote (but differently from _fix_promotion)
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.matmul(x1, x2, **kwargs)
+
+matrix_transpose = get_xp(torch)(_aliases.matrix_transpose)
+_vecdot = get_xp(torch)(_aliases.vecdot)
+
+def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return _vecdot(x1, x2, axis=axis)
+
+# torch.tensordot uses dims instead of axes
+def tensordot(
+    x1: Array,
+    x2: Array,
+    /,
+    *, 
+    axes: int | tuple[Sequence[int], Sequence[int]] = 2, 
+    **kwargs: object,
+) -> Array:
+    # Note: torch.tensordot fails with integer dtypes when there is only 1
+    # element in the axis (https://github.com/pytorch/pytorch/issues/84530).
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.tensordot(x1, x2, dims=axes, **kwargs)
+
+
+def isdtype(
+    dtype: DType, 
+    kind: DType | str | tuple[DType | str, ...],
+    *,
+    _tuple: bool = True, # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return _builtin_any(isdtype(dtype, k, _tuple=False) for k in kind)
+    elif isinstance(kind, str):
+        if kind == 'bool':
+            return dtype == torch.bool
+        elif kind == 'signed integer':
+            return dtype in _int_dtypes and dtype.is_signed
+        elif kind == 'unsigned integer':
+            return dtype in _int_dtypes and not dtype.is_signed
+        elif kind == 'integral':
+            return dtype in _int_dtypes
+        elif kind == 'real floating':
+            return dtype.is_floating_point
+        elif kind == 'complex floating':
+            return dtype.is_complex
+        elif kind == 'numeric':
+            return isdtype(dtype, ('integral', 'real floating', 'complex floating'))
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        return dtype == kind
+
+def take(x: Array, indices: Array, /, *, axis: int | None = None, **kwargs: object) -> Array:
+    if axis is None:
+        if x.ndim != 1:
+            raise ValueError("axis must be specified when ndim > 1")
+        axis = 0
+    # torch does not support negative indices,
+    # see https://github.com/pytorch/pytorch/issues/146211
+    return torch.index_select(
+        x,
+        axis,
+        torch.where(indices < 0, indices + x.shape[axis], indices),
+        **kwargs
+    )
+
+
+def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1) -> Array:
+    # torch does not support negative indices,
+    # see https://github.com/pytorch/pytorch/issues/146211
+    return torch.take_along_dim(
+        x,
+        torch.where(indices < 0, indices + x.shape[axis], indices),
+        dim=axis
+    )
+
+
+def sign(x: Array, /) -> Array:
+    # torch sign() does not support complex numbers and does not propagate
+    # nans. See https://github.com/data-apis/array-api-compat/issues/136
+    if x.dtype.is_complex:
+        out = x/torch.abs(x)
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0+0j] = 0+0j
+        return out
+    else:
+        out = torch.sign(x)
+        if x.dtype.is_floating_point:
+            out[torch.isnan(x)] = torch.nan
+        return out
+
+
+def meshgrid(*arrays: Array, indexing: Literal['xy', 'ij'] = 'xy') -> list[Array]:
+    # enforce the default of 'xy'
+    # TODO: is the return type a list or a tuple
+    return list(torch.meshgrid(*arrays, indexing=indexing))
+
+
+__all__ = ['asarray', 'result_type', 'can_cast',
+           'permute_dims', 'bitwise_invert', 'newaxis', 'conj', 'add',
+           'atan2', 'bitwise_and', 'bitwise_left_shift', 'bitwise_or',
+           'bitwise_right_shift', 'bitwise_xor', 'copysign', 'count_nonzero',
+           'diff', 'divide',
+           'equal', 'floor_divide', 'greater', 'greater_equal', 'hypot',
+           'less', 'less_equal', 'logaddexp', 'maximum', 'minimum',
+           'multiply', 'not_equal', 'pow', 'remainder', 'subtract', 'max',
+           'min', 'clip', 'unstack', 'cumulative_sum', 'cumulative_prod', 'sort',
+           'argsort', 'prod', 'sum', 'any', 'all', 'mean', 'std', 'var', 'concat',
+           'squeeze', 'broadcast_to', 'flip', 'roll', 'nonzero', 'where', 'reshape',
+           'arange', 'eye', 'linspace', 'full', 'ones', 'zeros', 'empty',
+           'tril', 'triu', 'expand_dims', 'astype', 'broadcast_arrays',
+           'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult',
+           'unique_all', 'unique_counts', 'unique_inverse', 'unique_values',
+           'matmul', 'matrix_transpose', 'vecdot', 'tensordot', 'isdtype',
+           'take', 'take_along_axis', 'sign', 'finfo', 'iinfo', 'repeat', 'meshgrid']
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_info.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..167dcf477adece2b49446061b2a67e0bdb6cd67c
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_info.py
@@ -0,0 +1,369 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+import torch
+
+from functools import cache
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for PyTorch.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for PyTorch.
+
+    Examples
+    --------
+    >>> info = xp.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'torch'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for PyTorch.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          PyTorch.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new PyTorch arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new PyTorch arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        device(type='cpu')
+
+        Notes
+        -----
+        This method returns the static default device when PyTorch is initialized.
+        However, the *current* device used by creation functions (``empty`` etc.)
+        can be changed at runtime.
+
+        See Also
+        --------
+        https://github.com/data-apis/array-api/issues/835
+        """
+        return torch.device("cpu")
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new PyTorch arrays.
+
+        Parameters
+        ----------
+        device : Device, optional
+            The device to get the default data types for.
+            Unused for PyTorch, as all devices use the same default dtypes.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new PyTorch
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': torch.float32,
+         'complex floating': torch.complex64,
+         'integral': torch.int64,
+         'indexing': torch.int64}
+
+        """
+        # Note: if the default is set to float64, the devices like MPS that
+        # don't support float64 will error. We still return the default_dtype
+        # value here because this error doesn't represent a different default
+        # per-device.
+        default_floating = torch.get_default_dtype()
+        default_complex = torch.complex64 if default_floating == torch.float32 else torch.complex128
+        default_integral = torch.int64
+        return {
+            "real floating": default_floating,
+            "complex floating": default_complex,
+            "integral": default_integral,
+            "indexing": default_integral,
+        }
+
+
+    def _dtypes(self, kind):
+        bool = torch.bool
+        int8 = torch.int8
+        int16 = torch.int16
+        int32 = torch.int32
+        int64 = torch.int64
+        uint8 = torch.uint8
+        # uint16, uint32, and uint64 are present in newer versions of pytorch,
+        # but they aren't generally supported by the array API functions, so
+        # we omit them from this function.
+        float32 = torch.float32
+        float64 = torch.float64
+        complex64 = torch.complex64
+        complex128 = torch.complex128
+
+        if kind is None:
+            return {
+                "bool": bool,
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": uint8,
+            }
+        if kind == "integral":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+            }
+        if kind == "real floating":
+            return {
+                "float32": float32,
+                "float64": float64,
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "numeric":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    @cache
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by PyTorch.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : Device, optional
+            The device to get the data types for.
+            Unused for PyTorch, as all devices use the same dtypes.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            PyTorch data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        res = self._dtypes(kind)
+        for k, v in res.copy().items():
+            try:
+                torch.empty((0,), dtype=v, device=device)
+            except:
+                del res[k]
+        return res
+
+    @cache
+    def devices(self):
+        """
+        The devices supported by PyTorch.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by PyTorch.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.devices()
+        [device(type='cpu'), device(type='mps', index=0), device(type='meta')]
+
+        """
+        # Torch doesn't have a straightforward way to get the list of all
+        # currently supported devices. To do this, we first parse the error
+        # message of torch.device to get the list of all possible types of
+        # device:
+        try:
+            torch.device('notadevice')
+            raise AssertionError("unreachable")  # pragma: nocover
+        except RuntimeError as e:
+            # The error message is something like:
+            # "Expected one of cpu, cuda, ipu, xpu, mkldnn, opengl, opencl, ideep, hip, ve, fpga, ort, xla, lazy, vulkan, mps, meta, hpu, mtia, privateuseone device type at start of device string: notadevice"
+            devices_names = e.args[0].split('Expected one of ')[1].split(' device type')[0].split(', ')
+
+        # Next we need to check for different indices for different devices.
+        # device(device_name, index=index) doesn't actually check if the
+        # device name or index is valid. We have to try to create a tensor
+        # with it (which is why this function is cached).
+        devices = []
+        for device_name in devices_names:
+            i = 0
+            while True:
+                try:
+                    a = torch.empty((0,), device=torch.device(device_name, index=i))
+                    if a.device in devices:
+                        break
+                    devices.append(a.device)
+                except:
+                    break
+                i += 1
+
+        return devices
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_typing.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2a7a1b11180dd087b662356b90ad7e7fa7a10b6
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/_typing.py
@@ -0,0 +1,3 @@
+__all__ = ["Array", "Device", "DType"]
+
+from torch import device as Device, dtype as DType, Tensor as Array
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/fft.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b0c536571c4902a29d0de97dafe670d85e6c409
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/fft.py
@@ -0,0 +1,82 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Literal
+
+import torch  # noqa: F401
+import torch.fft
+
+from ._typing import Array
+from .._internal import clone_module
+
+__all__ = clone_module("torch.fft", globals())
+
+# Several torch fft functions do not map axes to dim
+
+def fftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs: object,
+) -> Array:
+    return torch.fft.fftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def ifftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs: object,
+) -> Array:
+    return torch.fft.ifftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def rfftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs: object,
+) -> Array:
+    return torch.fft.rfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def irfftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs: object,
+) -> Array:
+    return torch.fft.irfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def fftshift(
+    x: Array,
+    /,
+    *,
+    axes: int | Sequence[int] = None,
+    **kwargs: object,
+) -> Array:
+    return torch.fft.fftshift(x, dim=axes, **kwargs)
+
+def ifftshift(
+    x: Array,
+    /,
+    *,
+    axes: int | Sequence[int] = None,
+    **kwargs: object,
+) -> Array:
+    return torch.fft.ifftshift(x, dim=axes, **kwargs)
+
+
+__all__ += ["fftn", "ifftn", "rfftn", "irfftn", "fftshift", "ifftshift"]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/linalg.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..16711247c6ad29ff0ba22b0444c02ee60f1f860e
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
@@ -0,0 +1,114 @@
+from __future__ import annotations
+
+import torch
+import torch.linalg
+
+from .._internal import clone_module
+
+__all__ = clone_module("torch.linalg", globals())
+
+# outer is implemented in torch but aren't in the linalg namespace
+from torch import outer
+from ._aliases import _fix_promotion, sum
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot
+from ._typing import Array, DType
+from ..common._typing import JustInt, JustFloat
+
+# Note: torch.linalg.cross does not default to axis=-1 (it defaults to the
+# first axis with size 3), see https://github.com/pytorch/pytorch/issues/58743
+
+# torch.cross also does not support broadcasting when it would add new
+# dimensions https://github.com/pytorch/pytorch/issues/39656
+def cross(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    if not (-min(x1.ndim, x2.ndim) <= axis < max(x1.ndim, x2.ndim)):
+        raise ValueError(f"axis {axis} out of bounds for cross product of arrays with shapes {x1.shape} and {x2.shape}")
+    if not (x1.shape[axis] == x2.shape[axis] == 3):
+        raise ValueError(f"cross product axis must have size 3, got {x1.shape[axis]} and {x2.shape[axis]}")
+    x1, x2 = torch.broadcast_tensors(x1, x2)
+    return torch.linalg.cross(x1, x2, dim=axis)
+
+def vecdot(x1: Array, x2: Array, /, *, axis: int = -1, **kwargs: object) -> Array:
+    from ._aliases import isdtype
+
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+
+    # torch.linalg.vecdot incorrectly allows broadcasting along the contracted dimension
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    # torch.linalg.vecdot doesn't support integer dtypes
+    if isdtype(x1.dtype, 'integral') or isdtype(x2.dtype, 'integral'):
+        if kwargs:
+            raise RuntimeError("vecdot kwargs not supported for integral dtypes")
+
+        x1_ = torch.moveaxis(x1, axis, -1)
+        x2_ = torch.moveaxis(x2, axis, -1)
+        x1_, x2_ = torch.broadcast_tensors(x1_, x2_)
+
+        res = x1_[..., None, :] @ x2_[..., None]
+        return res[..., 0, 0]
+    return torch.linalg.vecdot(x1, x2, dim=axis, **kwargs)
+
+def solve(x1: Array, x2: Array, /, **kwargs: object) -> Array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    # Torch tries to emulate NumPy 1 solve behavior by using batched 1-D solve
+    # whenever
+    # 1. x1.ndim - 1 == x2.ndim
+    # 2. x1.shape[:-1] == x2.shape
+    #
+    # See linalg_solve_is_vector_rhs in
+    # aten/src/ATen/native/LinearAlgebraUtils.h and
+    # TORCH_META_FUNC(_linalg_solve_ex) in
+    # aten/src/ATen/native/BatchLinearAlgebra.cpp in the PyTorch source code.
+    #
+    # The easiest way to work around this is to prepend a size 1 dimension to
+    # x2, since x2 is already one dimension less than x1.
+    #
+    # See https://github.com/pytorch/pytorch/issues/52915
+    if x2.ndim != 1 and x1.ndim - 1 == x2.ndim and x1.shape[:-1] == x2.shape:
+        x2 = x2[None]
+    return torch.linalg.solve(x1, x2, **kwargs)
+
+# torch.trace doesn't support the offset argument and doesn't support stacking
+def trace(x: Array, /, *, offset: int = 0, dtype: DType | None = None) -> Array:
+    # Use our wrapped sum to make sure it does upcasting correctly
+    return sum(torch.diagonal(x, offset=offset, dim1=-2, dim2=-1), axis=-1, dtype=dtype)
+
+def vector_norm(
+    x: Array,
+    /,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    # JustFloat stands for inf | -inf, which are not valid for Literal
+    ord: JustInt | JustFloat = 2,
+    **kwargs: object,
+) -> Array:
+    # torch.vector_norm incorrectly treats axis=() the same as axis=None
+    if axis == ():
+        out = kwargs.get('out')
+        if out is None:
+            dtype = None
+            if x.dtype == torch.complex64:
+                dtype = torch.float32
+            elif x.dtype == torch.complex128:
+                dtype = torch.float64
+
+            out = torch.zeros_like(x, dtype=dtype)
+
+        # The norm of a single scalar works out to abs(x) in every case except
+        # for ord=0, which is x != 0.
+        if ord == 0:
+            out[:] = (x != 0)
+        else:
+            out[:] = torch.abs(x)
+        return out
+    return torch.linalg.vector_norm(x, ord=ord, axis=axis, keepdim=keepdims, **kwargs)
+
+__all__ += ['outer', 'matmul', 'matrix_transpose', 'tensordot',
+            'cross', 'vecdot', 'solve', 'trace', 'vector_norm']
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b54d102d315bdcea785794bd4cd0b4bde207451
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__init__.py
@@ -0,0 +1,53 @@
+"""Extra array functions built on top of the array API standard."""
+
+from ._delegation import (
+    argpartition,
+    atleast_nd,
+    cov,
+    create_diagonal,
+    expand_dims,
+    isclose,
+    isin,
+    nan_to_num,
+    one_hot,
+    pad,
+    partition,
+    setdiff1d,
+    sinc,
+)
+from ._lib._at import at
+from ._lib._funcs import (
+    apply_where,
+    broadcast_shapes,
+    default_dtype,
+    kron,
+    nunique,
+)
+from ._lib._lazy import lazy_apply
+
+__version__ = "0.9.1"
+
+# pylint: disable=duplicate-code
+__all__ = [
+    "__version__",
+    "apply_where",
+    "argpartition",
+    "at",
+    "atleast_nd",
+    "broadcast_shapes",
+    "cov",
+    "create_diagonal",
+    "default_dtype",
+    "expand_dims",
+    "isclose",
+    "isin",
+    "kron",
+    "lazy_apply",
+    "nan_to_num",
+    "nunique",
+    "one_hot",
+    "pad",
+    "partition",
+    "setdiff1d",
+    "sinc",
+]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5979cc4f5f9440f1482efc128f685b499c6e613d
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/_delegation.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/_delegation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b2910cbf4e2496fffd9fc19327ccbda05a53ded
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/_delegation.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/testing.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/testing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6c0f16aea88f3d8d5eb857e5b34b2c0ca881ca5
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/__pycache__/testing.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_delegation.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_delegation.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb115ee3a8e3339515884933df4c74857bd176e8
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_delegation.py
@@ -0,0 +1,1028 @@
+"""Delegation to existing implementations for Public API Functions."""
+
+from collections.abc import Sequence
+from types import ModuleType
+from typing import Literal
+
+from ._lib import _funcs
+from ._lib._utils._compat import (
+    array_namespace,
+    is_cupy_namespace,
+    is_dask_namespace,
+    is_jax_namespace,
+    is_numpy_namespace,
+    is_pydata_sparse_namespace,
+    is_torch_namespace,
+)
+from ._lib._utils._compat import device as get_device
+from ._lib._utils._helpers import asarrays, eager_shape
+from ._lib._utils._typing import Array, DType
+
+__all__ = [
+    "atleast_nd",
+    "cov",
+    "create_diagonal",
+    "expand_dims",
+    "isclose",
+    "nan_to_num",
+    "one_hot",
+    "pad",
+    "sinc",
+]
+
+
+def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType | None = None) -> Array:
+    """
+    Recursively expand the dimension of an array to at least `ndim`.
+
+    Parameters
+    ----------
+    x : array
+        Input array.
+    ndim : int
+        The minimum number of dimensions for the result.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    array
+        An array with ``res.ndim`` >= `ndim`.
+        If ``x.ndim`` >= `ndim`, `x` is returned.
+        If ``x.ndim`` < `ndim`, `x` is expanded by prepending new axes
+        until ``res.ndim`` equals `ndim`.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([1])
+    >>> xpx.atleast_nd(x, ndim=3, xp=xp)
+    Array([[[1]]], dtype=array_api_strict.int64)
+
+    >>> x = xp.asarray([[[1, 2],
+    ...                  [3, 4]]])
+    >>> xpx.atleast_nd(x, ndim=1, xp=xp) is x
+    True
+    """
+    if xp is None:
+        xp = array_namespace(x)
+
+    if 1 <= ndim <= 2 and (
+        is_numpy_namespace(xp)
+        or is_jax_namespace(xp)
+        or is_dask_namespace(xp)
+        or is_cupy_namespace(xp)
+        or is_torch_namespace(xp)
+    ):
+        return getattr(xp, f"atleast_{ndim}d")(x)
+
+    return _funcs.atleast_nd(x, ndim=ndim, xp=xp)
+
+
+def cov(m: Array, /, *, xp: ModuleType | None = None) -> Array:
+    """
+    Estimate a covariance matrix (or a stack of covariance matrices).
+
+    Covariance indicates the level to which two variables vary together.
+    If we examine *N*-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
+    each with *M* observations, then element :math:`C_{ij}` of the
+    :math:`N \times N` covariance matrix is the covariance of
+    :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
+    of :math:`x_i`.
+
+    With the exception of supporting batch input, this provides a subset of
+    the functionality of ``numpy.cov``.
+
+    Parameters
+    ----------
+    m : array
+        An array of shape ``(..., N, M)`` whose innermost two dimensions
+        contain *M* observations of *N* variables. That is,
+        each row of `m` represents a variable, and each column a single
+        observation of all those variables.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `m`. Default: infer.
+
+    Returns
+    -------
+    array
+        An array having shape (..., N, N) whose innermost two dimensions represent
+        the covariance matrix of the variables.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+
+    Consider two variables, :math:`x_0` and :math:`x_1`, which
+    correlate perfectly, but in opposite directions:
+
+    >>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T
+    >>> x
+    Array([[0, 1, 2],
+           [2, 1, 0]], dtype=array_api_strict.int64)
+
+    Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
+    matrix shows this clearly:
+
+    >>> xpx.cov(x, xp=xp)
+    Array([[ 1., -1.],
+           [-1.,  1.]], dtype=array_api_strict.float64)
+
+    Note that element :math:`C_{0,1}`, which shows the correlation between
+    :math:`x_0` and :math:`x_1`, is negative.
+
+    Further, note how `x` and `y` are combined:
+
+    >>> x = xp.asarray([-2.1, -1,  4.3])
+    >>> y = xp.asarray([3,  1.1,  0.12])
+    >>> X = xp.stack((x, y), axis=0)
+    >>> xpx.cov(X, xp=xp)
+    Array([[11.71      , -4.286     ],
+           [-4.286     ,  2.14413333]], dtype=array_api_strict.float64)
+
+    >>> xpx.cov(x, xp=xp)
+    Array(11.71, dtype=array_api_strict.float64)
+
+    >>> xpx.cov(y, xp=xp)
+    Array(2.14413333, dtype=array_api_strict.float64)
+
+    Input with more than two dimensions is treated as a stack of
+    two-dimensional input.
+
+    >>> stack = xp.stack((X, 2*X))
+    >>> xpx.cov(stack)
+    Array([[[ 11.71      ,  -4.286     ],
+            [ -4.286     ,   2.14413333]],
+
+           [[ 46.84      , -17.144     ],
+            [-17.144     ,   8.57653333]]], dtype=array_api_strict.float64)
+    """
+
+    if xp is None:
+        xp = array_namespace(m)
+
+    if (
+        is_numpy_namespace(xp)
+        or is_cupy_namespace(xp)
+        or is_torch_namespace(xp)
+        or is_dask_namespace(xp)
+        or is_jax_namespace(xp)
+    ) and m.ndim <= 2:
+        return xp.cov(m)
+
+    return _funcs.cov(m, xp=xp)
+
+
+def create_diagonal(
+    x: Array, /, *, offset: int = 0, xp: ModuleType | None = None
+) -> Array:
+    """
+    Construct a diagonal array.
+
+    Parameters
+    ----------
+    x : array
+        An array having shape ``(*batch_dims, k)``.
+    offset : int, optional
+        Offset from the leading diagonal (default is ``0``).
+        Use positive ints for diagonals above the leading diagonal,
+        and negative ints for diagonals below the leading diagonal.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    array
+        An array having shape ``(*batch_dims, k+abs(offset), k+abs(offset))`` with `x`
+        on the diagonal (offset by `offset`).
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([2, 4, 8])
+
+    >>> xpx.create_diagonal(x, xp=xp)
+    Array([[2, 0, 0],
+           [0, 4, 0],
+           [0, 0, 8]], dtype=array_api_strict.int64)
+
+    >>> xpx.create_diagonal(x, offset=-2, xp=xp)
+    Array([[0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [2, 0, 0, 0, 0],
+           [0, 4, 0, 0, 0],
+           [0, 0, 8, 0, 0]], dtype=array_api_strict.int64)
+    """
+    if xp is None:
+        xp = array_namespace(x)
+
+    if x.ndim == 0:
+        err_msg = "`x` must be at least 1-dimensional."
+        raise ValueError(err_msg)
+
+    if is_torch_namespace(xp):
+        return xp.diag_embed(x, offset=offset, dim1=-2, dim2=-1)
+
+    if (is_dask_namespace(xp) or is_cupy_namespace(xp)) and x.ndim < 2:
+        return xp.diag(x, k=offset)
+
+    if (is_jax_namespace(xp) or is_numpy_namespace(xp)) and x.ndim < 3:
+        batch_dim, n = eager_shape(x)[:-1], eager_shape(x, -1)[0] + abs(offset)
+        return xp.reshape(xp.diag(x, k=offset), (*batch_dim, n, n))
+
+    return _funcs.create_diagonal(x, offset=offset, xp=xp)
+
+
+def expand_dims(
+    a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType | None = None
+) -> Array:
+    """
+    Expand the shape of an array.
+
+    Insert (a) new axis/axes that will appear at the position(s) specified by
+    `axis` in the expanded array shape.
+
+    This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*.
+    Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays.
+
+    Parameters
+    ----------
+    a : array
+        Array to have its shape expanded.
+    axis : int or tuple of ints, optional
+        Position(s) in the expanded axes where the new axis (or axes) is/are placed.
+        If multiple positions are provided, they should be unique (note that a position
+        given by a positive index could also be referred to by a negative index -
+        that will also result in an error).
+        Default: ``(0,)``.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `a`. Default: infer.
+
+    Returns
+    -------
+    array
+        `a` with an expanded shape.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([1, 2])
+    >>> x.shape
+    (2,)
+
+    The following is equivalent to ``x[xp.newaxis, :]`` or ``x[xp.newaxis]``:
+
+    >>> y = xpx.expand_dims(x, axis=0, xp=xp)
+    >>> y
+    Array([[1, 2]], dtype=array_api_strict.int64)
+    >>> y.shape
+    (1, 2)
+
+    The following is equivalent to ``x[:, xp.newaxis]``:
+
+    >>> y = xpx.expand_dims(x, axis=1, xp=xp)
+    >>> y
+    Array([[1],
+           [2]], dtype=array_api_strict.int64)
+    >>> y.shape
+    (2, 1)
+
+    ``axis`` may also be a tuple:
+
+    >>> y = xpx.expand_dims(x, axis=(0, 1), xp=xp)
+    >>> y
+    Array([[[1, 2]]], dtype=array_api_strict.int64)
+
+    >>> y = xpx.expand_dims(x, axis=(2, 0), xp=xp)
+    >>> y
+    Array([[[1],
+            [2]]], dtype=array_api_strict.int64)
+    """
+    if xp is None:
+        xp = array_namespace(a)
+
+    if not isinstance(axis, tuple):
+        axis = (axis,)
+    ndim = a.ndim + len(axis)
+    if axis != () and (min(axis) < -ndim or max(axis) >= ndim):
+        err_msg = (
+            f"a provided axis position is out of bounds for array of dimension {a.ndim}"
+        )
+        raise IndexError(err_msg)
+    axis = tuple(dim % ndim for dim in axis)
+    if len(set(axis)) != len(axis):
+        err_msg = "Duplicate dimensions specified in `axis`."
+        raise ValueError(err_msg)
+
+    if is_numpy_namespace(xp) or is_dask_namespace(xp) or is_jax_namespace(xp):
+        return xp.expand_dims(a, axis=axis)
+
+    return _funcs.expand_dims(a, axis=axis, xp=xp)
+
+
+def isclose(
+    a: Array | complex,
+    b: Array | complex,
+    *,
+    rtol: float = 1e-05,
+    atol: float = 1e-08,
+    equal_nan: bool = False,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Return a boolean array where two arrays are element-wise equal within a tolerance.
+
+    The tolerance values are positive, typically very small numbers. The relative
+    difference ``(rtol * abs(b))`` and the absolute difference `atol` are added together
+    to compare against the absolute difference between `a` and `b`.
+
+    NaNs are treated as equal if they are in the same place and if ``equal_nan=True``.
+    Infs are treated as equal if they are in the same place and of the same sign in both
+    arrays.
+
+    Parameters
+    ----------
+    a, b : Array | int | float | complex | bool
+        Input objects to compare. At least one must be an array.
+    rtol : array_like, optional
+        The relative tolerance parameter (see Notes).
+    atol : array_like, optional
+        The absolute tolerance parameter (see Notes).
+    equal_nan : bool, optional
+        Whether to compare NaN's as equal. If True, NaN's in `a` will be considered
+        equal to NaN's in `b` in the output array.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `a` and `b`. Default: infer.
+
+    Returns
+    -------
+    Array
+        A boolean array of shape broadcasted from `a` and `b`, containing ``True`` where
+        `a` is close to `b`, and ``False`` otherwise.
+
+    Warnings
+    --------
+    The default `atol` is not appropriate for comparing numbers with magnitudes much
+    smaller than one (see notes).
+
+    See Also
+    --------
+    math.isclose : Similar function in stdlib for Python scalars.
+
+    Notes
+    -----
+    For finite values, `isclose` uses the following equation to test whether two
+    floating point values are equivalent::
+
+        absolute(a - b) <= (atol + rtol * absolute(b))
+
+    Unlike the built-in `math.isclose`,
+    the above equation is not symmetric in `a` and `b`,
+    so that ``isclose(a, b)`` might be different from ``isclose(b, a)`` in some rare
+    cases.
+
+    The default value of `atol` is not appropriate when the reference value `b` has
+    magnitude smaller than one. For example, it is unlikely that ``a = 1e-9`` and
+    ``b = 2e-9`` should be considered "close", yet ``isclose(1e-9, 2e-9)`` is ``True``
+    with default settings. Be sure to select `atol` for the use case at hand, especially
+    for defining the threshold below which a non-zero value in `a` will be considered
+    "close" to a very small or zero value in `b`.
+
+    The comparison of `a` and `b` uses standard broadcasting, which means that `a` and
+    `b` need not have the same shape in order for ``isclose(a, b)`` to evaluate to
+    ``True``.
+
+    `isclose` is not defined for non-numeric data types.
+    ``bool`` is considered a numeric data-type for this purpose.
+    """
+    xp = array_namespace(a, b) if xp is None else xp
+
+    if (
+        is_numpy_namespace(xp)
+        or is_cupy_namespace(xp)
+        or is_dask_namespace(xp)
+        or is_jax_namespace(xp)
+    ):
+        return xp.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
+
+    if is_torch_namespace(xp):
+        a, b = asarrays(a, b, xp=xp)  # Array API 2024.12 support
+        return xp.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
+
+    return _funcs.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan, xp=xp)
+
+
+def nan_to_num(
+    x: Array | float | complex,
+    /,
+    *,
+    fill_value: int | float = 0.0,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Replace NaN with zero and infinity with large finite numbers (default behaviour).
+
+    If `x` is inexact, NaN is replaced by zero or by the user defined value in the
+    `fill_value` keyword, infinity is replaced by the largest finite floating
+    point value representable by ``x.dtype``, and -infinity is replaced by the
+    most negative finite floating point value representable by ``x.dtype``.
+
+    For complex dtypes, the above is applied to each of the real and
+    imaginary components of `x` separately.
+
+    Parameters
+    ----------
+    x : array | float | complex
+        Input data.
+    fill_value : int | float, optional
+        Value to be used to fill NaN values. If no value is passed
+        then NaN values will be replaced with 0.0.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    array
+        `x`, with the non-finite values replaced.
+
+    See Also
+    --------
+    array_api.isnan : Shows which elements are Not a Number (NaN).
+
+    Examples
+    --------
+    >>> import array_api_extra as xpx
+    >>> import array_api_strict as xp
+    >>> xpx.nan_to_num(xp.inf)
+    1.7976931348623157e+308
+    >>> xpx.nan_to_num(-xp.inf)
+    -1.7976931348623157e+308
+    >>> xpx.nan_to_num(xp.nan)
+    0.0
+    >>> x = xp.asarray([xp.inf, -xp.inf, xp.nan, -128, 128])
+    >>> xpx.nan_to_num(x)
+    array([ 1.79769313e+308, -1.79769313e+308,  0.00000000e+000, # may vary
+           -1.28000000e+002,  1.28000000e+002])
+    >>> y = xp.asarray([complex(xp.inf, xp.nan), xp.nan, complex(xp.nan, xp.inf)])
+    array([  1.79769313e+308,  -1.79769313e+308,   0.00000000e+000, # may vary
+         -1.28000000e+002,   1.28000000e+002])
+    >>> xpx.nan_to_num(y)
+    array([  1.79769313e+308 +0.00000000e+000j, # may vary
+             0.00000000e+000 +0.00000000e+000j,
+             0.00000000e+000 +1.79769313e+308j])
+    """
+    if isinstance(fill_value, complex):
+        msg = "Complex fill values are not supported."
+        raise TypeError(msg)
+
+    xp = array_namespace(x) if xp is None else xp
+
+    # for scalars we want to output an array
+    y = xp.asarray(x)
+
+    if (
+        is_cupy_namespace(xp)
+        or is_jax_namespace(xp)
+        or is_numpy_namespace(xp)
+        or is_torch_namespace(xp)
+    ):
+        return xp.nan_to_num(y, nan=fill_value)
+
+    return _funcs.nan_to_num(y, fill_value=fill_value, xp=xp)
+
+
+def one_hot(
+    x: Array,
+    /,
+    num_classes: int,
+    *,
+    dtype: DType | None = None,
+    axis: int = -1,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    One-hot encode the given indices.
+
+    Each index in the input `x` is encoded as a vector of zeros of length `num_classes`
+    with the element at the given index set to one.
+
+    Parameters
+    ----------
+    x : array
+        An array with integral dtype whose values are between `0` and `num_classes - 1`.
+    num_classes : int
+        Number of classes in the one-hot dimension.
+    dtype : DType, optional
+        The dtype of the return value.  Defaults to the default float dtype (usually
+        float64).
+    axis : int, optional
+        Position in the expanded axes where the new axis is placed. Default: -1.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    array
+        An array having the same shape as `x` except for a new axis at the position
+        given by `axis` having size `num_classes`.  If `axis` is unspecified, it
+        defaults to -1, which appends a new axis.
+
+        If ``x < 0`` or ``x >= num_classes``, then the result is undefined, may raise
+        an exception, or may even cause a bad state.  `x` is not checked.
+
+    Examples
+    --------
+    >>> import array_api_extra as xpx
+    >>> import array_api_strict as xp
+    >>> xpx.one_hot(xp.asarray([1, 2, 0]), 3)
+    Array([[0., 1., 0.],
+          [0., 0., 1.],
+          [1., 0., 0.]], dtype=array_api_strict.float64)
+    """
+    # Validate inputs.
+    if xp is None:
+        xp = array_namespace(x)
+    if not xp.isdtype(x.dtype, "integral"):
+        msg = "x must have an integral dtype."
+        raise TypeError(msg)
+    if dtype is None:
+        dtype = _funcs.default_dtype(xp, device=get_device(x))
+    # Delegate where possible.
+    if is_jax_namespace(xp):
+        from jax.nn import one_hot as jax_one_hot
+
+        return jax_one_hot(x, num_classes, dtype=dtype, axis=axis)
+    if is_torch_namespace(xp):
+        from torch.nn.functional import one_hot as torch_one_hot
+
+        x = xp.astype(x, xp.int64)  # PyTorch only supports int64 here.
+        try:
+            out = torch_one_hot(x, num_classes)
+        except RuntimeError as e:
+            raise IndexError from e
+    else:
+        out = _funcs.one_hot(x, num_classes, xp=xp)
+    out = xp.astype(out, dtype, copy=False)
+    if axis != -1:
+        out = xp.moveaxis(out, -1, axis)
+    return out
+
+
+def pad(
+    x: Array,
+    pad_width: int | tuple[int, int] | Sequence[tuple[int, int]],
+    mode: Literal["constant"] = "constant",
+    *,
+    constant_values: complex = 0,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Pad the input array.
+
+    Parameters
+    ----------
+    x : array
+        Input array.
+    pad_width : int or tuple of ints or sequence of pairs of ints
+        Pad the input array with this many elements from each side.
+        If a sequence of tuples, ``[(before_0, after_0), ... (before_N, after_N)]``,
+        each pair applies to the corresponding axis of ``x``.
+        A single tuple, ``(before, after)``, is equivalent to a list of ``x.ndim``
+        copies of this tuple.
+    mode : str, optional
+        Only "constant" mode is currently supported, which pads with
+        the value passed to `constant_values`.
+    constant_values : python scalar, optional
+        Use this value to pad the input. Default is zero.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    array
+        The input array,
+        padded with ``pad_width`` elements equal to ``constant_values``.
+    """
+    xp = array_namespace(x) if xp is None else xp
+
+    if mode != "constant":
+        msg = "Only `'constant'` mode is currently supported"
+        raise NotImplementedError(msg)
+
+    if (
+        is_numpy_namespace(xp)
+        or is_cupy_namespace(xp)
+        or is_jax_namespace(xp)
+        or is_pydata_sparse_namespace(xp)
+    ):
+        return xp.pad(x, pad_width, mode, constant_values=constant_values)
+
+    # https://github.com/pytorch/pytorch/blob/cf76c05b4dc629ac989d1fb8e789d4fac04a095a/torch/_numpy/_funcs_impl.py#L2045-L2056
+    if is_torch_namespace(xp):
+        pad_width = xp.asarray(pad_width)
+        pad_width = xp.broadcast_to(pad_width, (x.ndim, 2))
+        pad_width = xp.flip(pad_width, axis=(0,)).flatten()
+        return xp.nn.functional.pad(x, tuple(pad_width), value=constant_values)  # type: ignore[arg-type]  # pyright: ignore[reportArgumentType]
+
+    return _funcs.pad(x, pad_width, constant_values=constant_values, xp=xp)
+
+
+def setdiff1d(
+    x1: Array | complex,
+    x2: Array | complex,
+    /,
+    *,
+    assume_unique: bool = False,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Find the set difference of two arrays.
+
+    Return the unique values in `x1` that are not in `x2`.
+
+    Parameters
+    ----------
+    x1 : array | int | float | complex | bool
+        Input array.
+    x2 : array
+        Input comparison array.
+    assume_unique : bool
+        If ``True``, the input arrays are both assumed to be unique, which
+        can speed up the calculation. Default is ``False``.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x1` and `x2`. Default: infer.
+
+    Returns
+    -------
+    array
+        1D array of values in `x1` that are not in `x2`. The result
+        is sorted when `assume_unique` is ``False``, but otherwise only sorted
+        if the input is sorted.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+
+    >>> x1 = xp.asarray([1, 2, 3, 2, 4, 1])
+    >>> x2 = xp.asarray([3, 4, 5, 6])
+    >>> xpx.setdiff1d(x1, x2, xp=xp)
+    Array([1, 2], dtype=array_api_strict.int64)
+    """
+
+    if xp is None:
+        xp = array_namespace(x1, x2)
+
+    if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp):
+        x1, x2 = asarrays(x1, x2, xp=xp)
+        return xp.setdiff1d(x1, x2, assume_unique=assume_unique)
+
+    return _funcs.setdiff1d(x1, x2, assume_unique=assume_unique, xp=xp)
+
+
+def sinc(x: Array, /, *, xp: ModuleType | None = None) -> Array:
+    r"""
+    Return the normalized sinc function.
+
+    The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument
+    :math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not
+    only everywhere continuous but also infinitely differentiable.
+
+    .. note::
+
+        Note the normalization factor of ``pi`` used in the definition.
+        This is the most commonly used definition in signal processing.
+        Use ``sinc(x / xp.pi)`` to obtain the unnormalized sinc function
+        :math:`\sin(x)/x` that is more common in mathematics.
+
+    Parameters
+    ----------
+    x : array
+        Array (possibly multi-dimensional) of values for which to calculate
+        ``sinc(x)``. Must have a real floating point dtype.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    array
+        ``sinc(x)`` calculated elementwise, which has the same shape as the input.
+
+    Notes
+    -----
+    The name sinc is short for "sine cardinal" or "sinus cardinalis".
+
+    The sinc function is used in various signal processing applications,
+    including in anti-aliasing, in the construction of a Lanczos resampling
+    filter, and in interpolation.
+
+    For bandlimited interpolation of discrete-time signals, the ideal
+    interpolation kernel is proportional to the sinc function.
+
+    References
+    ----------
+    #. Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
+       Resource. https://mathworld.wolfram.com/SincFunction.html
+    #. Wikipedia, "Sinc function",
+       https://en.wikipedia.org/wiki/Sinc_function
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.linspace(-4, 4, 41)
+    >>> xpx.sinc(x, xp=xp)
+    Array([-3.89817183e-17, -4.92362781e-02,
+           -8.40918587e-02, -8.90384387e-02,
+           -5.84680802e-02,  3.89817183e-17,
+            6.68206631e-02,  1.16434881e-01,
+            1.26137788e-01,  8.50444803e-02,
+           -3.89817183e-17, -1.03943254e-01,
+           -1.89206682e-01, -2.16236208e-01,
+           -1.55914881e-01,  3.89817183e-17,
+            2.33872321e-01,  5.04551152e-01,
+            7.56826729e-01,  9.35489284e-01,
+            1.00000000e+00,  9.35489284e-01,
+            7.56826729e-01,  5.04551152e-01,
+            2.33872321e-01,  3.89817183e-17,
+           -1.55914881e-01, -2.16236208e-01,
+           -1.89206682e-01, -1.03943254e-01,
+           -3.89817183e-17,  8.50444803e-02,
+            1.26137788e-01,  1.16434881e-01,
+            6.68206631e-02,  3.89817183e-17,
+           -5.84680802e-02, -8.90384387e-02,
+           -8.40918587e-02, -4.92362781e-02,
+           -3.89817183e-17], dtype=array_api_strict.float64)
+    """
+
+    if xp is None:
+        xp = array_namespace(x)
+
+    if not xp.isdtype(x.dtype, "real floating"):
+        err_msg = "`x` must have a real floating data type."
+        raise ValueError(err_msg)
+
+    if (
+        is_numpy_namespace(xp)
+        or is_cupy_namespace(xp)
+        or is_jax_namespace(xp)
+        or is_torch_namespace(xp)
+        or is_dask_namespace(xp)
+    ):
+        return xp.sinc(x)
+
+    return _funcs.sinc(x, xp=xp)
+
+
+def partition(
+    a: Array,
+    kth: int,
+    /,
+    axis: int | None = -1,
+    *,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Return a partitioned copy of an array.
+
+    Creates a copy of the array and partially sorts it in such a way that the value
+    of the element in k-th position is in the position it would be in a sorted array.
+    In the output array, all elements smaller than the k-th element are located to
+    the left of this element and all equal or greater are located to its right.
+    The ordering of the elements in the two partitions on the either side of
+    the k-th element in the output array is undefined.
+
+    Parameters
+    ----------
+    a : Array
+        Input array.
+    kth : int
+        Element index to partition by.
+    axis : int, optional
+        Axis along which to partition. The default is ``-1`` (the last axis).
+        If ``None``, the flattened array is used.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    partitioned_array
+        Array of the same type and shape as `a`.
+
+    Notes
+    -----
+    If `xp` implements ``partition`` or an equivalent function
+    (e.g. ``topk`` for torch), complexity will likely be O(n).
+    If not, this function simply calls ``xp.sort`` and complexity is O(n log n).
+    """
+    # Validate inputs.
+    if xp is None:
+        xp = array_namespace(a)
+    if a.ndim < 1:
+        msg = "`a` must be at least 1-dimensional"
+        raise TypeError(msg)
+    if axis is None:
+        return partition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp)
+    (size,) = eager_shape(a, axis)
+    if not (0 <= kth < size):
+        msg = f"kth(={kth}) out of bounds [0 {size})"
+        raise ValueError(msg)
+
+    # Delegate where possible.
+    if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp):
+        return xp.partition(a, kth, axis=axis)
+
+    # Use top-k when possible:
+    if is_torch_namespace(xp):
+        if not (axis == -1 or axis == a.ndim - 1):
+            a = xp.transpose(a, axis, -1)
+
+        out = xp.empty_like(a)
+        ranks = xp.arange(a.shape[-1]).expand_as(a)
+
+        split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True)
+        del indices  # indices won't be used => del ASAP to reduce peak memory usage
+
+        # fill the left-side of the partition
+        mask_src = a < split_value
+        n_left = mask_src.sum(dim=-1, keepdim=True)
+        mask_dest = ranks < n_left
+        out[mask_dest] = a[mask_src]
+
+        # fill the middle of the partition
+        mask_src = a == split_value
+        n_left += mask_src.sum(dim=-1, keepdim=True)
+        mask_dest ^= ranks < n_left
+        out[mask_dest] = a[mask_src]
+
+        # fill the right-side of the partition
+        mask_src = a > split_value
+        mask_dest = ranks >= n_left
+        out[mask_dest] = a[mask_src]
+
+        if not (axis == -1 or axis == a.ndim - 1):
+            out = xp.transpose(out, axis, -1)
+        return out
+
+    # Note: dask topk/argtopk sort the return values, so it's
+    # not much more efficient than sorting everything when
+    # kth is not small compared to x.size
+
+    return _funcs.partition(a, kth, axis=axis, xp=xp)
+
+
+def argpartition(
+    a: Array,
+    kth: int,
+    /,
+    axis: int | None = -1,
+    *,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Perform an indirect partition along the given axis.
+
+    It returns an array of indices of the same shape as `a` that
+    index data along the given axis in partitioned order.
+
+    Parameters
+    ----------
+    a : Array
+        Input array.
+    kth : int
+        Element index to partition by.
+    axis : int, optional
+        Axis along which to partition. The default is ``-1`` (the last axis).
+        If ``None``, the flattened array is used.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    index_array
+        Array of indices that partition `a` along the specified axis.
+
+    Notes
+    -----
+    If `xp` implements ``argpartition`` or an equivalent function
+    e.g. ``topk`` for torch), complexity will likely be O(n).
+    If not, this function simply calls ``xp.argsort`` and complexity is O(n log n).
+    """
+    # Validate inputs.
+    if xp is None:
+        xp = array_namespace(a)
+    if is_pydata_sparse_namespace(xp):
+        msg = "Not implemented for sparse backend: no argsort"
+        raise NotImplementedError(msg)
+    if a.ndim < 1:
+        msg = "`a` must be at least 1-dimensional"
+        raise TypeError(msg)
+    if axis is None:
+        return argpartition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp)
+    (size,) = eager_shape(a, axis)
+    if not (0 <= kth < size):
+        msg = f"kth(={kth}) out of bounds [0 {size})"
+        raise ValueError(msg)
+
+    # Delegate where possible.
+    if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp):
+        return xp.argpartition(a, kth, axis=axis)
+
+    # Use top-k when possible:
+    if is_torch_namespace(xp):
+        # see `partition` above for commented details of those steps:
+        if not (axis == -1 or axis == a.ndim - 1):
+            a = xp.transpose(a, axis, -1)
+
+        ranks = xp.arange(a.shape[-1]).expand_as(a)
+        out = xp.empty_like(ranks)
+
+        split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True)
+        del indices  # indices won't be used => del ASAP to reduce peak memory usage
+
+        mask_src = a < split_value
+        n_left = mask_src.sum(dim=-1, keepdim=True)
+        mask_dest = ranks < n_left
+        out[mask_dest] = ranks[mask_src]
+
+        mask_src = a == split_value
+        n_left += mask_src.sum(dim=-1, keepdim=True)
+        mask_dest ^= ranks < n_left
+        out[mask_dest] = ranks[mask_src]
+
+        mask_src = a > split_value
+        mask_dest = ranks >= n_left
+        out[mask_dest] = ranks[mask_src]
+
+        if not (axis == -1 or axis == a.ndim - 1):
+            out = xp.transpose(out, axis, -1)
+        return out
+
+    # Note: dask topk/argtopk sort the return values, so it's
+    # not much more efficient than sorting everything when
+    # kth is not small compared to x.size
+
+    return _funcs.argpartition(a, kth, axis=axis, xp=xp)
+
+
+def isin(
+    a: Array,
+    b: Array,
+    /,
+    *,
+    assume_unique: bool = False,
+    invert: bool = False,
+    kind: str | None = None,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Determine whether each element in `a` is present in `b`.
+
+    Return a boolean array of the same shape as `a` that is True for elements
+    that are in `b` and False otherwise.
+
+    Parameters
+    ----------
+    a : array
+        Input elements.
+    b : array
+        The elements against which to test each element of `a`.
+    assume_unique : bool, optional
+        If True, the input arrays are both assumed to be unique which can speed
+        up the calculation. Default: False.
+    invert : bool, optional
+        If True, the values in the returned array are inverted. Default: False.
+    kind : str | None, optional
+        The algorithm or method to use. This will not affect the final result,
+        but will affect the speed and memory use.
+        For NumPy the options are {None, "sort", "table"}.
+        For Jax the mapped parameter is instead `method` and the options are
+        {"compare_all", "binary_search", "sort", and "auto" (default)}
+        For CuPy, Dask, Torch and the default case this parameter is not present and
+        thus ignored. Default: None.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `a` and `b`. Default: infer.
+
+    Returns
+    -------
+    array
+        An array having the same shape as that of `a` that is True for elements
+        that are in `b` and False otherwise.
+    """
+    if xp is None:
+        xp = array_namespace(a, b)
+
+    if is_numpy_namespace(xp):
+        return xp.isin(a, b, assume_unique=assume_unique, invert=invert, kind=kind)
+    if is_jax_namespace(xp):
+        if kind is None:
+            kind = "auto"
+        return xp.isin(a, b, assume_unique=assume_unique, invert=invert, method=kind)
+    if is_cupy_namespace(xp) or is_torch_namespace(xp) or is_dask_namespace(xp):
+        return xp.isin(a, b, assume_unique=assume_unique, invert=invert)
+
+    return _funcs.isin(a, b, assume_unique=assume_unique, invert=invert, xp=xp)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c517948b8a47b9c2dad04a00211cff52bfdd4ea
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__init__.py
@@ -0,0 +1 @@
+"""Internals of array-api-extra."""
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..136c5e2342b3af4899a1d3b8d5a3848dfdae1fb9
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_at.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_at.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5d7de7656747ca42f8d734afb037495510a0187
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_at.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_funcs.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_funcs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a07dd6753f7382c8051fdb1d8932a871a436a57
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_funcs.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_lazy.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_lazy.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e76d46e180985037b571b6a533096c4e61aaabb0
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_lazy.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_at.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_at.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b1d4356982a05f4754e1c677b09909f47536902
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_at.py
@@ -0,0 +1,463 @@
+"""Update operations for read-only arrays."""
+
+from __future__ import annotations
+
+import operator
+from collections.abc import Callable
+from enum import Enum
+from types import ModuleType
+from typing import TYPE_CHECKING, ClassVar, cast
+
+from ._utils import _compat
+from ._utils._compat import (
+    array_namespace,
+    is_dask_array,
+    is_jax_array,
+    is_torch_array,
+    is_writeable_array,
+)
+from ._utils._helpers import meta_namespace
+from ._utils._typing import Array, SetIndex
+
+if TYPE_CHECKING:  # pragma: no cover
+    # TODO import from typing (requires Python >=3.11)
+    from typing_extensions import Self
+
+
+class _AtOp(Enum):
+    """Operations for use in `xpx.at`."""
+
+    SET = "set"
+    ADD = "add"
+    SUBTRACT = "subtract"
+    MULTIPLY = "multiply"
+    DIVIDE = "divide"
+    POWER = "power"
+    MIN = "min"
+    MAX = "max"
+
+    # @override from Python 3.12
+    def __str__(self) -> str:  # pyright: ignore[reportImplicitOverride]
+        """
+        Return string representation (useful for pytest logs).
+
+        Returns
+        -------
+        str
+            The operation's name.
+        """
+        return self.value
+
+
+class Undef(Enum):
+    """Sentinel for undefined values."""
+
+    UNDEF = 0
+
+
+_undef = Undef.UNDEF
+
+
+class at:  # pylint: disable=invalid-name  # numpydoc ignore=PR02
+    """
+    Update operations for read-only arrays.
+
+    This implements ``jax.numpy.ndarray.at`` for all writeable
+    backends (those that support ``__setitem__``) and routes
+    to the ``.at[]`` method for JAX arrays.
+
+    Parameters
+    ----------
+    x : array
+        Input array.
+    idx : index, optional
+        Only `array API standard compliant indices
+        `_
+        are supported.
+
+        You may use two alternate syntaxes::
+
+          >>> import array_api_extra as xpx
+          >>> xpx.at(x, idx).set(value)  # or add(value), etc.
+          >>> xpx.at(x)[idx].set(value)
+
+    copy : bool, optional
+        None (default)
+            The array parameter *may* be modified in place if it is
+            possible and beneficial for performance.
+            You should not reuse it after calling this function.
+        True
+            Ensure that the inputs are not modified.
+        False
+            Ensure that the update operation writes back to the input.
+            Raise ``ValueError`` if a copy cannot be avoided.
+
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    Updated input array.
+
+    Warnings
+    --------
+    (a) When you omit the ``copy`` parameter, you should never reuse the parameter
+    array later on; ideally, you should reassign it immediately::
+
+        >>> import array_api_extra as xpx
+        >>> x = xpx.at(x, 0).set(2)
+
+    The above best practice pattern ensures that the behaviour won't change depending
+    on whether ``x`` is writeable or not, as the original ``x`` object is dereferenced
+    as soon as ``xpx.at`` returns; this way there is no risk to accidentally update it
+    twice.
+
+    On the reverse, the anti-pattern below must be avoided, as it will result in
+    different behaviour on read-only versus writeable arrays::
+
+        >>> x = xp.asarray([0, 0, 0])
+        >>> y = xpx.at(x, 0).set(2)
+        >>> z = xpx.at(x, 1).set(3)
+
+    In the above example, both calls to ``xpx.at`` update ``x`` in place *if possible*.
+    This causes the behaviour to diverge depending on whether ``x`` is writeable or not:
+
+    - If ``x`` is writeable, then after the snippet above you'll have
+      ``x == y == z == [2, 3, 0]``
+    - If ``x`` is read-only, then you'll end up with
+      ``x == [0, 0, 0]``, ``y == [2, 0, 0]`` and ``z == [0, 3, 0]``.
+
+    The correct pattern to use if you want diverging outputs from the same input is
+    to enforce copies::
+
+        >>> x = xp.asarray([0, 0, 0])
+        >>> y = xpx.at(x, 0).set(2, copy=True)  # Never updates x
+        >>> z = xpx.at(x, 1).set(3)  # May or may not update x in place
+        >>> del x  # avoid accidental reuse of x as we don't know its state anymore
+
+    (b) The array API standard does not support integer array indices.
+    The behaviour of update methods when the index is an array of integers is
+    undefined and will vary between backends; this is particularly true when the
+    index contains multiple occurrences of the same index, e.g.::
+
+        >>> import numpy as np
+        >>> import jax.numpy as jnp
+        >>> import array_api_extra as xpx
+        >>> xpx.at(np.asarray([123]), np.asarray([0, 0])).add(1)
+        array([124])
+        >>> xpx.at(jnp.asarray([123]), jnp.asarray([0, 0])).add(1)
+        Array([125], dtype=int32)
+
+    See Also
+    --------
+    jax.numpy.ndarray.at : Equivalent array method in JAX.
+
+    Notes
+    -----
+    `sparse `_, as well as read-only arrays from libraries
+    not explicitly covered by ``array-api-compat``, are not supported by update
+    methods.
+
+    Boolean masks are supported on Dask and jitted JAX arrays exclusively
+    when `idx` has the same shape as `x` and `y` is 0-dimensional.
+    Note that this support is not available in JAX's native
+    ``x.at[mask].set(y)``.
+
+    This pattern::
+
+        >>> mask = m(x)
+        >>> x[mask] = f(x[mask])
+
+    Can't be replaced by `at`, as it won't work on Dask and JAX inside jax.jit::
+
+        >>> mask = m(x)
+        >>> x = xpx.at(x, mask).set(f(x[mask])  # Crash on Dask and jax.jit
+
+    You should instead use::
+
+        >>> x = xp.where(m(x), f(x), x)
+
+    Examples
+    --------
+    Given either of these equivalent expressions::
+
+      >>> import array_api_extra as xpx
+      >>> x = xpx.at(x)[1].add(2)
+      >>> x = xpx.at(x, 1).add(2)
+
+    If x is a JAX array, they are the same as::
+
+      >>> x = x.at[1].add(2)
+
+    If x is a read-only NumPy array, they are the same as::
+
+      >>> x = x.copy()
+      >>> x[1] += 2
+
+    For other known backends, they are the same as::
+
+      >>> x[1] += 2
+    """
+
+    _x: Array
+    _idx: SetIndex | Undef
+    __slots__: ClassVar[tuple[str, ...]] = ("_idx", "_x")
+
+    def __init__(
+        self, x: Array, idx: SetIndex | Undef = _undef, /
+    ) -> None:  # numpydoc ignore=GL08
+        self._x = x
+        self._idx = idx
+
+    def __getitem__(self, idx: SetIndex, /) -> Self:  # numpydoc ignore=PR01,RT01
+        """
+        Allow for the alternate syntax ``at(x)[start:stop:step]``.
+
+        It looks prettier than ``at(x, slice(start, stop, step))``
+        and feels more intuitive coming from the JAX documentation.
+        """
+        if self._idx is not _undef:
+            msg = "Index has already been set"
+            raise ValueError(msg)
+        return type(self)(self._x, idx)
+
+    def _op(
+        self,
+        at_op: _AtOp,
+        in_place_op: Callable[[Array, Array | complex], Array] | None,
+        out_of_place_op: Callable[[Array, Array], Array] | None,
+        y: Array | complex,
+        /,
+        copy: bool | None,
+        xp: ModuleType | None,
+    ) -> Array:
+        """
+        Implement all update operations.
+
+        Parameters
+        ----------
+        at_op : _AtOp
+            Method of JAX's Array.at[].
+        in_place_op : Callable[[Array, Array | complex], Array] | None
+            In-place operation to apply on mutable backends::
+
+                x[idx] = in_place_op(x[idx], y)
+
+            If None::
+
+                x[idx] = y
+
+        out_of_place_op : Callable[[Array, Array], Array] | None
+            Out-of-place operation to apply when idx is a boolean mask and the backend
+            doesn't support in-place updates::
+
+                x = xp.where(idx, out_of_place_op(x, y), x)
+
+            If None::
+
+                x = xp.where(idx, y, x)
+
+        y : array or complex
+            Right-hand side of the operation.
+        copy : bool or None
+            Whether to copy the input array. See the class docstring for details.
+        xp : array_namespace, optional
+            The array namespace for the input array. Default: infer.
+
+        Returns
+        -------
+        Array
+            Updated `x`.
+        """
+        from ._funcs import apply_where  # pylint: disable=cyclic-import
+
+        x, idx = self._x, self._idx
+        xp = array_namespace(x, y) if xp is None else xp
+
+        if isinstance(idx, Undef):
+            msg = (
+                "Index has not been set.\n"
+                "Usage: either\n"
+                "    at(x, idx).set(value)\n"
+                "or\n"
+                "    at(x)[idx].set(value)\n"
+                "(same for all other methods)."
+            )
+            raise ValueError(msg)
+
+        if copy not in (True, False, None):
+            msg = f"copy must be True, False, or None; got {copy!r}"
+            raise ValueError(msg)
+
+        writeable = None if copy else is_writeable_array(x)
+
+        # JAX inside jax.jit doesn't support in-place updates with boolean
+        # masks; Dask exclusively supports __setitem__ but not iops.
+        # We can handle the common special case of 0-dimensional y
+        # with where(idx, y, x) instead.
+        if (
+            (is_dask_array(idx) or is_jax_array(idx))
+            and idx.dtype == xp.bool
+            and idx.shape == x.shape
+        ):
+            y_xp = xp.asarray(y, dtype=x.dtype, device=_compat.device(x))
+            if y_xp.ndim == 0:
+                if out_of_place_op:  # add(), subtract(), ...
+                    # suppress inf warnings on Dask
+                    out = apply_where(
+                        idx, (x, y_xp), out_of_place_op, fill_value=x, xp=xp
+                    )
+                    # Undo int->float promotion on JAX after _AtOp.DIVIDE
+                    out = xp.astype(out, x.dtype, copy=False)
+                else:  # set()
+                    out = xp.where(idx, y_xp, x)
+
+                if copy is False:
+                    x[()] = out
+                    return x
+                return out
+
+            # else: this will work on eager JAX and crash on jax.jit and Dask
+
+        if copy or (copy is None and not writeable):
+            if is_jax_array(x):
+                # Use JAX's at[]
+                func = cast(
+                    Callable[[Array | complex], Array],
+                    getattr(x.at[idx], at_op.value),  # type: ignore[attr-defined]  # pyright: ignore[reportAttributeAccessIssue,reportUnknownArgumentType]
+                )
+                out = func(y)
+                # Undo int->float promotion on JAX after _AtOp.DIVIDE
+                return xp.astype(out, x.dtype, copy=False)
+
+            # Emulate at[] behaviour for non-JAX arrays
+            # with a copy followed by an update
+
+            x = xp.asarray(x, copy=True)
+            # A copy of a read-only numpy array is writeable
+            # Note: this assumes that a copy of a writeable array is writeable
+            assert not writeable
+            writeable = None
+
+        if writeable is None:
+            writeable = is_writeable_array(x)
+        if not writeable:
+            # sparse crashes here
+            msg = f"Can't update read-only array {x}"
+            raise ValueError(msg)
+
+        # Work around bug in PyTorch where __setitem__ doesn't
+        # always support mismatched dtypes
+        # https://github.com/pytorch/pytorch/issues/150017
+        if is_torch_array(y):
+            y = xp.astype(y, x.dtype, copy=False)
+
+        # Backends without boolean indexing (other than JAX) crash here
+        if in_place_op:  # add(), subtract(), ...
+            x[idx] = in_place_op(x[idx], y)
+        else:  # set()
+            x[idx] = y
+        return x
+
+    def set(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] = y`` and return the update array."""
+        return self._op(_AtOp.SET, None, None, y, copy=copy, xp=xp)
+
+    def add(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] += y`` and return the updated array."""
+
+        # Note for this and all other methods based on _iop:
+        # operator.iadd and operator.add subtly differ in behaviour, as
+        # only iadd will trigger exceptions when y has an incompatible dtype.
+        return self._op(_AtOp.ADD, operator.iadd, operator.add, y, copy=copy, xp=xp)
+
+    def subtract(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] -= y`` and return the updated array."""
+        return self._op(
+            _AtOp.SUBTRACT, operator.isub, operator.sub, y, copy=copy, xp=xp
+        )
+
+    def multiply(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] *= y`` and return the updated array."""
+        return self._op(
+            _AtOp.MULTIPLY, operator.imul, operator.mul, y, copy=copy, xp=xp
+        )
+
+    def divide(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] /= y`` and return the updated array."""
+        return self._op(
+            _AtOp.DIVIDE, operator.itruediv, operator.truediv, y, copy=copy, xp=xp
+        )
+
+    def power(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] **= y`` and return the updated array."""
+        return self._op(_AtOp.POWER, operator.ipow, operator.pow, y, copy=copy, xp=xp)
+
+    def min(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] = minimum(x[idx], y)`` and return the updated array."""
+        # On Dask, this function runs on the chunks, so we need to determine the
+        # namespace that Dask is wrapping.
+        # Note that da.minimum _incidentally_ works on NumPy, CuPy, and sparse
+        # thanks to all these meta-namespaces implementing the __array_ufunc__
+        # interface, but there's no guarantee that it will work for other
+        # wrapped libraries in the future.
+        xp = array_namespace(self._x) if xp is None else xp
+        mxp = meta_namespace(self._x, xp=xp)
+        y = xp.asarray(y)
+        return self._op(_AtOp.MIN, mxp.minimum, mxp.minimum, y, copy=copy, xp=xp)
+
+    def max(
+        self,
+        y: Array | complex,
+        /,
+        copy: bool | None = None,
+        xp: ModuleType | None = None,
+    ) -> Array:  # numpydoc ignore=PR01,RT01
+        """Apply ``x[idx] = maximum(x[idx], y)`` and return the updated array."""
+        # See note on min()
+        xp = array_namespace(self._x) if xp is None else xp
+        mxp = meta_namespace(self._x, xp=xp)
+        y = xp.asarray(y)
+        return self._op(_AtOp.MAX, mxp.maximum, mxp.maximum, y, copy=copy, xp=xp)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_backends.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..716bad72e166acbf7f50a4cb25c50c85154d90c0
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_backends.py
@@ -0,0 +1,72 @@
+"""Backends against which array-api-extra runs its tests."""
+
+from __future__ import annotations
+
+from enum import Enum
+from typing import Any
+
+import numpy as np
+import pytest
+
+__all__ = ["NUMPY_VERSION", "Backend"]
+
+NUMPY_VERSION = tuple(int(v) for v in np.__version__.split(".")[:3])  # pyright: ignore[reportUnknownArgumentType]
+
+
+class Backend(Enum):  # numpydoc ignore=PR02
+    """
+    All array library backends explicitly tested by array-api-extra.
+
+    Parameters
+    ----------
+    value : str
+        Tag of the backend's module, in the format ``[:]``.
+    """
+
+    # Use : to prevent Enum from deduplicating items with the same value
+    ARRAY_API_STRICT = "array_api_strict"
+    ARRAY_API_STRICTEST = "array_api_strict:strictest"
+    NUMPY = "numpy"
+    NUMPY_READONLY = "numpy:readonly"
+    CUPY = "cupy"
+    TORCH = "torch"
+    TORCH_GPU = "torch:gpu"
+    DASK = "dask.array"
+    SPARSE = "sparse"
+    JAX = "jax.numpy"
+    JAX_GPU = "jax.numpy:gpu"
+
+    @property
+    def modname(self) -> str:  # numpydoc ignore=RT01
+        """Module name to be imported."""
+        return self.value.split(":")[0]
+
+    def like(self, *others: Backend) -> bool:  # numpydoc ignore=PR01,RT01
+        """Check if this backend uses the same module as others."""
+        return any(self.modname == other.modname for other in others)
+
+    def pytest_param(self) -> Any:
+        """
+        Backend as a pytest parameter
+
+        Returns
+        -------
+        pytest.mark.ParameterSet
+        """
+        id_ = (
+            self.name.lower().replace("_gpu", ":gpu").replace("_readonly", ":readonly")
+        )
+
+        marks = []
+        if self.like(Backend.ARRAY_API_STRICT):
+            marks.append(
+                pytest.mark.skipif(
+                    NUMPY_VERSION < (1, 26),
+                    reason="array_api_strict is untested on NumPy <1.26",
+                )
+            )
+        if self.like(Backend.DASK, Backend.JAX):
+            # Monkey-patched by lazy_xp_function
+            marks.append(pytest.mark.thread_unsafe)
+
+        return pytest.param(self, id=id_, marks=marks)  # pyright: ignore[reportUnknownArgumentType]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_funcs.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_funcs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8942b99aa80638e7e5f93d8b02f2de4779831047
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_funcs.py
@@ -0,0 +1,744 @@
+"""Array-agnostic implementations for the public API."""
+
+import math
+import warnings
+from collections.abc import Callable, Sequence
+from types import ModuleType, NoneType
+from typing import Literal, cast, overload
+
+from ._at import at
+from ._utils import _compat, _helpers
+from ._utils._compat import array_namespace, is_dask_namespace, is_jax_array
+from ._utils._helpers import (
+    asarrays,
+    capabilities,
+    eager_shape,
+    meta_namespace,
+    ndindex,
+)
+from ._utils._typing import Array, Device, DType
+
+__all__ = [
+    "apply_where",
+    "atleast_nd",
+    "broadcast_shapes",
+    "cov",
+    "create_diagonal",
+    "expand_dims",
+    "kron",
+    "nunique",
+    "pad",
+    "setdiff1d",
+    "sinc",
+]
+
+
+@overload
+def apply_where(  # numpydoc ignore=GL08
+    cond: Array,
+    args: Array | tuple[Array, ...],
+    f1: Callable[..., Array],
+    f2: Callable[..., Array],
+    /,
+    *,
+    xp: ModuleType | None = None,
+) -> Array: ...
+
+
+@overload
+def apply_where(  # numpydoc ignore=GL08
+    cond: Array,
+    args: Array | tuple[Array, ...],
+    f1: Callable[..., Array],
+    /,
+    *,
+    fill_value: Array | complex,
+    xp: ModuleType | None = None,
+) -> Array: ...
+
+
+def apply_where(  # numpydoc ignore=PR01,PR02
+    cond: Array,
+    args: Array | tuple[Array, ...],
+    f1: Callable[..., Array],
+    f2: Callable[..., Array] | None = None,
+    /,
+    *,
+    fill_value: Array | complex | None = None,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Run one of two elementwise functions depending on a condition.
+
+    Equivalent to ``f1(*args) if cond else fill_value`` performed elementwise
+    when `fill_value` is defined, otherwise to ``f1(*args) if cond else f2(*args)``.
+
+    Parameters
+    ----------
+    cond : array
+        The condition, expressed as a boolean array.
+    args : Array or tuple of Arrays
+        Argument(s) to `f1` (and `f2`). Must be broadcastable with `cond`.
+    f1 : callable
+        Elementwise function of `args`, returning a single array.
+        Where `cond` is True, output will be ``f1(arg0[cond], arg1[cond], ...)``.
+    f2 : callable, optional
+        Elementwise function of `args`, returning a single array.
+        Where `cond` is False, output will be ``f2(arg0[cond], arg1[cond], ...)``.
+        Mutually exclusive with `fill_value`.
+    fill_value : Array or scalar, optional
+        If provided, value with which to fill output array where `cond` is False.
+        It does not need to be scalar; it needs however to be broadcastable with
+        `cond` and `args`.
+        Mutually exclusive with `f2`. You must provide one or the other.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `cond` and `args`. Default: infer.
+
+    Returns
+    -------
+    Array
+        An array with elements from the output of `f1` where `cond` is True and either
+        the output of `f2` or `fill_value` where `cond` is False. The returned array has
+        data type determined by type promotion rules between the output of `f1` and
+        either `fill_value` or the output of `f2`.
+
+    Notes
+    -----
+    ``xp.where(cond, f1(*args), f2(*args))`` requires explicitly evaluating `f1` even
+    when `cond` is False, and `f2` when cond is True. This function evaluates each
+    function only for their matching condition, if the backend allows for it.
+
+    On Dask, `f1` and `f2` are applied to the individual chunks and should use functions
+    from the namespace of the chunks.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> a = xp.asarray([5, 4, 3])
+    >>> b = xp.asarray([0, 2, 2])
+    >>> def f(a, b):
+    ...     return a // b
+    >>> xpx.apply_where(b != 0, (a, b), f, fill_value=xp.nan)
+    array([ nan,  2., 1.])
+    """
+    # Parse and normalize arguments
+    if (f2 is None) == (fill_value is None):
+        msg = "Exactly one of `fill_value` or `f2` must be given."
+        raise TypeError(msg)
+    args_ = list(args) if isinstance(args, tuple) else [args]
+    del args
+
+    xp = array_namespace(cond, fill_value, *args_) if xp is None else xp
+
+    if isinstance(fill_value, int | float | complex | NoneType):
+        cond, *args_ = xp.broadcast_arrays(cond, *args_)
+    else:
+        cond, fill_value, *args_ = xp.broadcast_arrays(cond, fill_value, *args_)
+
+    if is_dask_namespace(xp):
+        meta_xp = meta_namespace(cond, fill_value, *args_, xp=xp)
+        # map_blocks doesn't descend into tuples of Arrays
+        return xp.map_blocks(_apply_where, cond, f1, f2, fill_value, *args_, xp=meta_xp)
+    return _apply_where(cond, f1, f2, fill_value, *args_, xp=xp)
+
+
+def _apply_where(  # numpydoc ignore=PR01,RT01
+    cond: Array,
+    f1: Callable[..., Array],
+    f2: Callable[..., Array] | None,
+    fill_value: Array | int | float | complex | bool | None,
+    *args: Array,
+    xp: ModuleType,
+) -> Array:
+    """Helper of `apply_where`. On Dask, this runs on a single chunk."""
+
+    if not capabilities(xp, device=_compat.device(cond))["boolean indexing"]:
+        # jax.jit does not support assignment by boolean mask
+        return xp.where(cond, f1(*args), f2(*args) if f2 is not None else fill_value)
+
+    temp1 = f1(*(arr[cond] for arr in args))
+
+    if f2 is None:
+        dtype = xp.result_type(temp1, fill_value)
+        if isinstance(fill_value, int | float | complex):
+            out = xp.full_like(cond, dtype=dtype, fill_value=fill_value)
+        else:
+            out = xp.astype(fill_value, dtype, copy=True)
+    else:
+        ncond = ~cond
+        temp2 = f2(*(arr[ncond] for arr in args))
+        dtype = xp.result_type(temp1, temp2)
+        out = xp.empty_like(cond, dtype=dtype)
+        out = at(out, ncond).set(temp2)
+
+    return at(out, cond).set(temp1)
+
+
+def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array:
+    # numpydoc ignore=PR01,RT01
+    """See docstring in array_api_extra._delegation."""
+
+    if x.ndim < ndim:
+        x = xp.expand_dims(x, axis=0)
+        x = atleast_nd(x, ndim=ndim, xp=xp)
+    return x
+
+
+# `float` in signature to accept `math.nan` for Dask.
+# `int`s are still accepted as `float` is a superclass of `int` in typing
+def broadcast_shapes(*shapes: tuple[float | None, ...]) -> tuple[int | None, ...]:
+    """
+    Compute the shape of the broadcasted arrays.
+
+    Duplicates :func:`numpy.broadcast_shapes`, with additional support for
+    None and NaN sizes.
+
+    This is equivalent to ``xp.broadcast_arrays(arr1, arr2, ...)[0].shape``
+    without needing to worry about the backend potentially deep copying
+    the arrays.
+
+    Parameters
+    ----------
+    *shapes : tuple[int | None, ...]
+        Shapes of the arrays to broadcast.
+
+    Returns
+    -------
+    tuple[int | None, ...]
+        The shape of the broadcasted arrays.
+
+    See Also
+    --------
+    numpy.broadcast_shapes : Equivalent NumPy function.
+    array_api.broadcast_arrays : Function to broadcast actual arrays.
+
+    Notes
+    -----
+    This function accepts the Array API's ``None`` for unknown sizes,
+    as well as Dask's non-standard ``math.nan``.
+    Regardless of input, the output always contains ``None`` for unknown sizes.
+
+    Examples
+    --------
+    >>> import array_api_extra as xpx
+    >>> xpx.broadcast_shapes((2, 3), (2, 1))
+    (2, 3)
+    >>> xpx.broadcast_shapes((4, 2, 3), (2, 1), (1, 3))
+    (4, 2, 3)
+    """
+    if not shapes:
+        return ()  # Match NumPy output
+
+    ndim = max(len(shape) for shape in shapes)
+    out: list[int | None] = []
+    for axis in range(-ndim, 0):
+        sizes = {shape[axis] for shape in shapes if axis >= -len(shape)}
+        # Dask uses NaN for unknown shape, which predates the Array API spec for None
+        none_size = None in sizes or math.nan in sizes  # noqa: PLW0177
+        sizes -= {1, None, math.nan}
+        if len(sizes) > 1:
+            msg = (
+                "shape mismatch: objects cannot be broadcast to a single shape: "
+                f"{shapes}."
+            )
+            raise ValueError(msg)
+        out.append(None if none_size else cast(int, sizes.pop()) if sizes else 1)
+
+    return tuple(out)
+
+
+def cov(m: Array, /, *, xp: ModuleType) -> Array:  # numpydoc ignore=PR01,RT01
+    """See docstring in array_api_extra._delegation."""
+    m = xp.asarray(m, copy=True)
+    dtype = (
+        xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64)
+    )
+
+    m = atleast_nd(m, ndim=2, xp=xp)
+    m = xp.astype(m, dtype)
+
+    avg = _helpers.mean(m, axis=-1, keepdims=True, xp=xp)
+
+    m_shape = eager_shape(m)
+    fact = m_shape[-1] - 1
+
+    if fact <= 0:
+        warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2)
+        fact = 0
+
+    m -= avg
+    m_transpose = xp.matrix_transpose(m)
+    if xp.isdtype(m_transpose.dtype, "complex floating"):
+        m_transpose = xp.conj(m_transpose)
+    c = xp.matmul(m, m_transpose)
+    c /= fact
+    axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1)
+    return xp.squeeze(c, axis=axes)
+
+
+def one_hot(
+    x: Array,
+    /,
+    num_classes: int,
+    *,
+    xp: ModuleType,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """See docstring in `array_api_extra._delegation.py`."""
+    # TODO: Benchmark whether this is faster on the NumPy backend:
+    # if is_numpy_array(x):
+    #     out = xp.zeros((x.size, num_classes), dtype=dtype)
+    #     out[xp.arange(x.size), xp.reshape(x, (-1,))] = 1
+    #     return xp.reshape(out, (*x.shape, num_classes))
+    range_num_classes = xp.arange(num_classes, dtype=x.dtype, device=_compat.device(x))
+    return x[..., xp.newaxis] == range_num_classes
+
+
+def create_diagonal(
+    x: Array, /, *, offset: int = 0, xp: ModuleType
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """See docstring in array_api_extra._delegation."""
+    x_shape = eager_shape(x)
+    batch_dims = x_shape[:-1]
+    n = x_shape[-1] + abs(offset)
+    diag = xp.zeros((*batch_dims, n**2), dtype=x.dtype, device=_compat.device(x))
+
+    target_slice = slice(
+        offset if offset >= 0 else abs(offset) * n,
+        min(n * (n - offset), diag.shape[-1]),
+        n + 1,
+    )
+    for index in ndindex(*batch_dims):
+        diag = at(diag)[(*index, target_slice)].set(x[(*index, slice(None))])
+    return xp.reshape(diag, (*batch_dims, n, n))
+
+
+def default_dtype(
+    xp: ModuleType,
+    kind: Literal[
+        "real floating", "complex floating", "integral", "indexing"
+    ] = "real floating",
+    *,
+    device: Device | None = None,
+) -> DType:
+    """
+    Return the default dtype for the given namespace and device.
+
+    This is a convenience shorthand for
+    ``xp.__array_namespace_info__().default_dtypes(device=device)[kind]``.
+
+    Parameters
+    ----------
+    xp : array_namespace
+        The standard-compatible namespace for which to get the default dtype.
+    kind : {'real floating', 'complex floating', 'integral', 'indexing'}, optional
+        The kind of dtype to return. Default is 'real floating'.
+    device : Device, optional
+        The device for which to get the default dtype. Default: current device.
+
+    Returns
+    -------
+    dtype
+        The default dtype for the given namespace, kind, and device.
+    """
+    dtypes = xp.__array_namespace_info__().default_dtypes(device=device)
+    try:
+        return dtypes[kind]
+    except KeyError as e:
+        domain = ("real floating", "complex floating", "integral", "indexing")
+        assert set(dtypes) == set(domain), f"Non-compliant namespace: {dtypes}"
+        msg = f"Unknown kind '{kind}'. Expected one of {domain}."
+        raise ValueError(msg) from e
+
+
+def expand_dims(a: Array, /, *, axis: tuple[int, ...] = (0,), xp: ModuleType) -> Array:
+    # numpydoc ignore=PR01,RT01
+    """See docstring in array_api_extra._delegation."""
+    for i in sorted(axis):
+        a = xp.expand_dims(a, axis=i)
+    return a
+
+
+def isclose(
+    a: Array | complex,
+    b: Array | complex,
+    *,
+    rtol: float = 1e-05,
+    atol: float = 1e-08,
+    equal_nan: bool = False,
+    xp: ModuleType,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """See docstring in array_api_extra._delegation."""
+    a, b = asarrays(a, b, xp=xp)
+
+    a_inexact = xp.isdtype(a.dtype, ("real floating", "complex floating"))
+    b_inexact = xp.isdtype(b.dtype, ("real floating", "complex floating"))
+    if a_inexact or b_inexact:
+        # prevent warnings on NumPy and Dask on inf - inf
+        mxp = meta_namespace(a, b, xp=xp)
+        out = apply_where(
+            xp.isinf(a) | xp.isinf(b),
+            (a, b),
+            lambda a, b: mxp.isinf(a) & mxp.isinf(b) & (mxp.sign(a) == mxp.sign(b)),  # pyright: ignore[reportUnknownArgumentType]
+            # Note: inf <= inf is True!
+            lambda a, b: mxp.abs(a - b) <= (atol + rtol * mxp.abs(b)),  # pyright: ignore[reportUnknownArgumentType]
+            xp=xp,
+        )
+        if equal_nan:
+            out = xp.where(xp.isnan(a) & xp.isnan(b), True, out)
+        return out
+
+    if xp.isdtype(a.dtype, "bool") or xp.isdtype(b.dtype, "bool"):
+        if atol >= 1 or rtol >= 1:
+            return xp.ones_like(a == b)
+        return a == b
+
+    # integer types
+    atol = int(atol)
+    if rtol == 0:
+        return xp.abs(a - b) <= atol
+
+    # Don't rely on OverflowError, as it is not guaranteed by the Array API.
+    nrtol = int(1.0 / rtol)
+    if nrtol > xp.iinfo(b.dtype).max:
+        # rtol * max_int < 1, so it's inconsequential
+        return xp.abs(a - b) <= atol
+    return xp.abs(a - b) <= (atol + xp.abs(b) // nrtol)
+
+
+def kron(
+    a: Array | complex,
+    b: Array | complex,
+    /,
+    *,
+    xp: ModuleType | None = None,
+) -> Array:
+    """
+    Kronecker product of two arrays.
+
+    Computes the Kronecker product, a composite array made of blocks of the
+    second array scaled by the first.
+
+    Equivalent to ``numpy.kron`` for NumPy arrays.
+
+    Parameters
+    ----------
+    a, b : Array | int | float | complex
+        Input arrays or scalars. At least one must be an array.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `a` and `b`. Default: infer.
+
+    Returns
+    -------
+    array
+        The Kronecker product of `a` and `b`.
+
+    Notes
+    -----
+    The function assumes that the number of dimensions of `a` and `b`
+    are the same, if necessary prepending the smallest with ones.
+    If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
+    the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
+    The elements are products of elements from `a` and `b`, organized
+    explicitly by::
+
+        kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
+
+    where::
+
+        kt = it * st + jt,  t = 0,...,N
+
+    In the common 2-D case (N=1), the block structure can be visualized::
+
+        [[ a[0,0]*b,   a[0,1]*b,  ... , a[0,-1]*b  ],
+         [  ...                              ...   ],
+         [ a[-1,0]*b,  a[-1,1]*b, ... , a[-1,-1]*b ]]
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> xpx.kron(xp.asarray([1, 10, 100]), xp.asarray([5, 6, 7]), xp=xp)
+    Array([  5,   6,   7,  50,  60,  70, 500,
+           600, 700], dtype=array_api_strict.int64)
+
+    >>> xpx.kron(xp.asarray([5, 6, 7]), xp.asarray([1, 10, 100]), xp=xp)
+    Array([  5,  50, 500,   6,  60, 600,   7,
+            70, 700], dtype=array_api_strict.int64)
+
+    >>> xpx.kron(xp.eye(2), xp.ones((2, 2)), xp=xp)
+    Array([[1., 1., 0., 0.],
+           [1., 1., 0., 0.],
+           [0., 0., 1., 1.],
+           [0., 0., 1., 1.]], dtype=array_api_strict.float64)
+
+    >>> a = xp.reshape(xp.arange(100), (2, 5, 2, 5))
+    >>> b = xp.reshape(xp.arange(24), (2, 3, 4))
+    >>> c = xpx.kron(a, b, xp=xp)
+    >>> c.shape
+    (2, 10, 6, 20)
+    >>> I = (1, 3, 0, 2)
+    >>> J = (0, 2, 1)
+    >>> J1 = (0,) + J             # extend to ndim=4
+    >>> S1 = (1,) + b.shape
+    >>> K = tuple(xp.asarray(I) * xp.asarray(S1) + xp.asarray(J1))
+    >>> c[K] == a[I]*b[J]
+    Array(True, dtype=array_api_strict.bool)
+    """
+    if xp is None:
+        xp = array_namespace(a, b)
+    a, b = asarrays(a, b, xp=xp)
+
+    singletons = (1,) * (b.ndim - a.ndim)
+    a = cast(Array, xp.broadcast_to(a, singletons + a.shape))
+
+    nd_b, nd_a = b.ndim, a.ndim
+    nd_max = max(nd_b, nd_a)
+    if nd_a == 0 or nd_b == 0:
+        return xp.multiply(a, b)
+
+    a_shape = eager_shape(a)
+    b_shape = eager_shape(b)
+
+    # Equalise the shapes by prepending smaller one with 1s
+    a_shape = (1,) * max(0, nd_b - nd_a) + a_shape
+    b_shape = (1,) * max(0, nd_a - nd_b) + b_shape
+
+    # Insert empty dimensions
+    a_arr = expand_dims(a, axis=tuple(range(nd_b - nd_a)), xp=xp)
+    b_arr = expand_dims(b, axis=tuple(range(nd_a - nd_b)), xp=xp)
+
+    # Compute the product
+    a_arr = expand_dims(a_arr, axis=tuple(range(1, nd_max * 2, 2)), xp=xp)
+    b_arr = expand_dims(b_arr, axis=tuple(range(0, nd_max * 2, 2)), xp=xp)
+    result = xp.multiply(a_arr, b_arr)
+
+    # Reshape back and return
+    res_shape = tuple(a_s * b_s for a_s, b_s in zip(a_shape, b_shape, strict=True))
+    return xp.reshape(result, res_shape)
+
+
+def nan_to_num(  # numpydoc ignore=PR01,RT01
+    x: Array,
+    /,
+    fill_value: int | float = 0.0,
+    *,
+    xp: ModuleType,
+) -> Array:
+    """See docstring in `array_api_extra._delegation.py`."""
+
+    def perform_replacements(  # numpydoc ignore=PR01,RT01
+        x: Array,
+        fill_value: int | float,
+        xp: ModuleType,
+    ) -> Array:
+        """Internal function to perform the replacements."""
+        x = xp.where(xp.isnan(x), fill_value, x)
+
+        # convert infinities to finite values
+        finfo = xp.finfo(x.dtype)
+        idx_posinf = xp.isinf(x) & ~xp.signbit(x)
+        idx_neginf = xp.isinf(x) & xp.signbit(x)
+        x = xp.where(idx_posinf, finfo.max, x)
+        return xp.where(idx_neginf, finfo.min, x)
+
+    if xp.isdtype(x.dtype, "complex floating"):
+        return perform_replacements(
+            xp.real(x),
+            fill_value,
+            xp,
+        ) + 1j * perform_replacements(
+            xp.imag(x),
+            fill_value,
+            xp,
+        )
+
+    if xp.isdtype(x.dtype, "numeric"):
+        return perform_replacements(x, fill_value, xp)
+
+    return x
+
+
+def nunique(x: Array, /, *, xp: ModuleType | None = None) -> Array:
+    """
+    Count the number of unique elements in an array.
+
+    Compatible with JAX and Dask, whose laziness would be otherwise
+    problematic.
+
+    Parameters
+    ----------
+    x : Array
+        Input array.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    array: 0-dimensional integer array
+        The number of unique elements in `x`. It can be lazy.
+    """
+    if xp is None:
+        xp = array_namespace(x)
+
+    if is_jax_array(x):
+        # size= is JAX-specific
+        # https://github.com/data-apis/array-api/issues/883
+        _, counts = xp.unique_counts(x, size=_compat.size(x))
+        return (counts > 0).sum()
+
+    # There are 3 general use cases:
+    # 1. backend has unique_counts and it returns an array with known shape
+    # 2. backend has unique_counts and it returns a None-sized array;
+    #    e.g. Dask, ndonnx
+    # 3. backend does not have unique_counts; e.g. wrapped JAX
+    if capabilities(xp, device=_compat.device(x))["data-dependent shapes"]:
+        # xp has unique_counts; O(n) complexity
+        _, counts = xp.unique_counts(x)
+        n = _compat.size(counts)
+        if n is None:
+            return xp.sum(xp.ones_like(counts))
+        return xp.asarray(n, device=_compat.device(x))
+
+    # xp does not have unique_counts; O(n*logn) complexity
+    x = xp.reshape(x, (-1,))
+    x = xp.sort(x, stable=False)
+    mask = x != xp.roll(x, -1)
+    default_int = default_dtype(xp, "integral", device=_compat.device(x))
+    return xp.maximum(
+        # Special cases:
+        # - array is size 0
+        # - array has all elements equal to each other
+        xp.astype(xp.any(~mask), default_int),
+        xp.sum(xp.astype(mask, default_int)),
+    )
+
+
+def pad(
+    x: Array,
+    pad_width: int | tuple[int, int] | Sequence[tuple[int, int]],
+    *,
+    constant_values: complex = 0,
+    xp: ModuleType,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """See docstring in `array_api_extra._delegation.py`."""
+    # make pad_width a list of length-2 tuples of ints
+    if isinstance(pad_width, int):
+        pad_width_seq = [(pad_width, pad_width)] * x.ndim
+    elif (
+        isinstance(pad_width, tuple)
+        and len(pad_width) == 2
+        and all(isinstance(i, int) for i in pad_width)
+    ):
+        pad_width_seq = [cast(tuple[int, int], pad_width)] * x.ndim
+    else:
+        pad_width_seq = cast(list[tuple[int, int]], list(pad_width))
+
+    slices: list[slice] = []
+    newshape: list[int] = []
+    for ax, w_tpl in enumerate(pad_width_seq):
+        if len(w_tpl) != 2:
+            msg = f"expect a 2-tuple (before, after), got {w_tpl}."
+            raise ValueError(msg)
+
+        sh = eager_shape(x)[ax]
+
+        if w_tpl[0] == 0 and w_tpl[1] == 0:
+            sl = slice(None, None, None)
+        else:
+            stop: int | None
+            start, stop = w_tpl
+            stop = None if stop == 0 else -stop
+
+            sl = slice(start, stop, None)
+            sh += w_tpl[0] + w_tpl[1]
+
+        newshape.append(sh)
+        slices.append(sl)
+
+    padded = xp.full(
+        tuple(newshape),
+        fill_value=constant_values,
+        dtype=x.dtype,
+        device=_compat.device(x),
+    )
+    return at(padded, tuple(slices)).set(x)
+
+
+def setdiff1d(
+    x1: Array | complex,
+    x2: Array | complex,
+    /,
+    *,
+    assume_unique: bool = False,
+    xp: ModuleType,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """See docstring in `array_api_extra._delegation.py`."""
+
+    # https://github.com/microsoft/pyright/issues/10103
+    x1_, x2_ = asarrays(x1, x2, xp=xp)
+
+    if assume_unique:
+        x1_ = xp.reshape(x1_, (-1,))
+        x2_ = xp.reshape(x2_, (-1,))
+    else:
+        x1_ = xp.unique_values(x1_)
+        x2_ = xp.unique_values(x2_)
+
+    return x1_[_helpers.in1d(x1_, x2_, assume_unique=True, invert=True, xp=xp)]
+
+
+def sinc(x: Array, /, *, xp: ModuleType) -> Array:
+    # numpydoc ignore=PR01,RT01
+    """See docstring in `array_api_extra._delegation.py`."""
+
+    # no scalars in `where` - array-api#807
+    y = xp.pi * xp.where(
+        xp.astype(x, xp.bool),
+        x,
+        xp.asarray(xp.finfo(x.dtype).eps, dtype=x.dtype, device=_compat.device(x)),
+    )
+    return xp.sin(y) / y
+
+
+def partition(  # numpydoc ignore=PR01,RT01
+    x: Array,
+    kth: int,  # noqa: ARG001
+    /,
+    axis: int = -1,
+    *,
+    xp: ModuleType,
+) -> Array:
+    """See docstring in `array_api_extra._delegation.py`."""
+    return xp.sort(x, axis=axis, stable=False)
+
+
+def argpartition(  # numpydoc ignore=PR01,RT01
+    x: Array,
+    kth: int,  # noqa: ARG001
+    /,
+    axis: int = -1,
+    *,
+    xp: ModuleType,
+) -> Array:
+    """See docstring in `array_api_extra._delegation.py`."""
+    return xp.argsort(x, axis=axis, stable=False)
+
+
+def isin(  # numpydoc ignore=PR01,RT01
+    a: Array,
+    b: Array,
+    /,
+    *,
+    assume_unique: bool = False,
+    invert: bool = False,
+    xp: ModuleType,
+) -> Array:
+    """See docstring in `array_api_extra._delegation.py`."""
+    original_a_shape = a.shape
+    a = xp.reshape(a, (-1,))
+    b = xp.reshape(b, (-1,))
+    return xp.reshape(
+        _helpers.in1d(a, b, assume_unique=assume_unique, invert=invert, xp=xp),
+        original_a_shape,
+    )
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_lazy.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_lazy.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f40d776de64ed336ddd2b6e81b5608c00b005b2
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_lazy.py
@@ -0,0 +1,357 @@
+"""Public API Functions."""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from functools import partial, wraps
+from types import ModuleType
+from typing import TYPE_CHECKING, Any, ParamSpec, TypeAlias, cast, overload
+
+from ._funcs import broadcast_shapes
+from ._utils import _compat
+from ._utils._compat import (
+    array_namespace,
+    is_dask_namespace,
+    is_jax_namespace,
+)
+from ._utils._helpers import is_python_scalar
+from ._utils._typing import Array, DType
+
+if TYPE_CHECKING:  # pragma: no cover
+    import numpy as np
+    from numpy.typing import ArrayLike
+
+    NumPyObject: TypeAlias = np.ndarray[Any, Any] | np.generic
+else:
+    # Sphinx hack
+    NumPyObject = Any
+
+P = ParamSpec("P")
+
+
+@overload
+def lazy_apply(  # type: ignore[valid-type]
+    func: Callable[P, Array | ArrayLike],
+    *args: Array | complex | None,
+    shape: tuple[int | None, ...] | None = None,
+    dtype: DType | None = None,
+    as_numpy: bool = False,
+    xp: ModuleType | None = None,
+    **kwargs: P.kwargs,  # pyright: ignore[reportGeneralTypeIssues]
+) -> Array: ...  # numpydoc ignore=GL08
+
+
+@overload
+def lazy_apply(  # type: ignore[valid-type]
+    func: Callable[P, Sequence[Array | ArrayLike]],
+    *args: Array | complex | None,
+    shape: Sequence[tuple[int | None, ...]],
+    dtype: Sequence[DType] | None = None,
+    as_numpy: bool = False,
+    xp: ModuleType | None = None,
+    **kwargs: P.kwargs,  # pyright: ignore[reportGeneralTypeIssues]
+) -> tuple[Array, ...]: ...  # numpydoc ignore=GL08
+
+
+def lazy_apply(  # type: ignore[valid-type]  # numpydoc ignore=GL07,SA04
+    func: Callable[P, Array | ArrayLike | Sequence[Array | ArrayLike]],
+    *args: Array | complex | None,
+    shape: tuple[int | None, ...] | Sequence[tuple[int | None, ...]] | None = None,
+    dtype: DType | Sequence[DType] | None = None,
+    as_numpy: bool = False,
+    xp: ModuleType | None = None,
+    **kwargs: P.kwargs,  # pyright: ignore[reportGeneralTypeIssues]
+) -> Array | tuple[Array, ...]:
+    """
+    Lazily apply an eager function.
+
+    If the backend of the input arrays is lazy, e.g. Dask or jitted JAX, the execution
+    of the function is delayed until the graph is materialized; if it's eager, the
+    function is executed immediately.
+
+    Parameters
+    ----------
+    func : callable
+        The function to apply.
+
+        It must accept one or more array API compliant arrays as positional arguments.
+        If `as_numpy=True`, inputs are converted to NumPy before they are passed to
+        `func`.
+        It must return either a single array-like or a sequence of array-likes.
+
+        `func` must be a pure function, i.e. without side effects, as depending on the
+        backend it may be executed more than once or never.
+    *args : Array | int | float | complex | bool | None
+        One or more Array API compliant arrays, Python scalars, or None's.
+
+        If `as_numpy=True`, you need to be able to apply :func:`numpy.asarray` to
+        non-None args to convert them to NumPy; read notes below about specific
+        backends.
+    shape : tuple[int | None, ...] | Sequence[tuple[int | None, ...]], optional
+        Output shape or sequence of output shapes, one for each output of `func`.
+        Default: assume single output and broadcast shapes of the input arrays.
+    dtype : DType | Sequence[DType], optional
+        Output dtype or sequence of output dtypes, one for each output of `func`.
+        dtype(s) must belong to the same array namespace as the input arrays.
+        Default: infer the result type(s) from the input arrays.
+    as_numpy : bool, optional
+        If True, convert the input arrays to NumPy before passing them to `func`.
+        This is particularly useful to make NumPy-only functions, e.g. written in Cython
+       or Numba, work transparently with array API-compliant arrays.
+        Default: False.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `args`. Default: infer.
+    **kwargs : Any, optional
+        Additional keyword arguments to pass verbatim to `func`.
+        They cannot contain Array objects.
+
+    Returns
+    -------
+    Array | tuple[Array, ...]
+        The result(s) of `func` applied to the input arrays, wrapped in the same
+        array namespace as the inputs.
+        If shape is omitted or a single `tuple[int | None, ...]`, return a single array.
+        Otherwise, return a tuple of arrays.
+
+    Notes
+    -----
+    JAX
+        This allows applying eager functions to jitted JAX arrays, which are lazy.
+        The function won't be applied until the JAX array is materialized.
+        When running inside ``jax.jit``, `shape` must be fully known, i.e. it cannot
+        contain any `None` elements.
+
+        .. warning::
+
+            `func` must never raise inside ``jax.jit``, as the resulting behavior is
+            undefined.
+
+        Using this with `as_numpy=False` is particularly useful to apply non-jittable
+        JAX functions to arrays on GPU devices.
+        If ``as_numpy=True``, the :doc:`jax:transfer_guard` may prevent arrays on a GPU
+        device from being transferred back to CPU. This is treated as an implicit
+        transfer.
+
+    PyTorch, CuPy
+        If ``as_numpy=True``, these backends raise by default if you attempt to convert
+        arrays on a GPU device to NumPy.
+
+    Sparse
+        If ``as_numpy=True``, by default sparse prevents implicit densification through
+        :func:`numpy.asarray`. `This safety mechanism can be disabled
+        `_.
+
+    Dask
+        This allows applying eager functions to Dask arrays.
+        The Dask graph won't be computed until the user calls ``compute()`` or
+        ``persist()`` down the line.
+
+        The function name will be prominently visible on the user-facing Dask
+        dashboard and on Prometheus metrics, so it is recommended for it to be
+        meaningful.
+
+        `lazy_apply` doesn't know if `func` reduces along any axes; also, shape
+        changes are non-trivial in chunked Dask arrays. For these reasons, all inputs
+        will be rechunked into a single chunk.
+
+        .. warning::
+
+           The whole operation needs to fit in memory all at once on a single worker.
+
+        The outputs will also be returned as a single chunk and you should consider
+        rechunking them into smaller chunks afterwards.
+
+        If you want to distribute the calculation across multiple workers, you
+        should use :func:`dask.array.map_blocks`, :func:`dask.array.map_overlap`,
+        :func:`dask.array.blockwise`, or a native Dask wrapper instead of
+        `lazy_apply`.
+
+    Dask wrapping around other backends
+        If ``as_numpy=False``, `func` will receive in input eager arrays of the meta
+        namespace, as defined by the ``._meta`` attribute of the input Dask arrays.
+        The outputs of `func` will be wrapped by the meta namespace, and then wrapped
+        again by Dask.
+
+    Raises
+    ------
+    ValueError
+        When ``xp=jax.numpy``, the output `shape` is unknown (it contains ``None`` on
+        one or more axes) and this function was called inside ``jax.jit``.
+    RuntimeError
+        When ``xp=sparse`` and auto-densification is disabled.
+    Exception (backend-specific)
+        When the backend disallows implicit device to host transfers and the input
+        arrays are on a non-CPU device, e.g. on GPU.
+
+    See Also
+    --------
+    jax.transfer_guard
+    jax.pure_callback
+    dask.array.map_blocks
+    dask.array.map_overlap
+    dask.array.blockwise
+    """
+    args_not_none = [arg for arg in args if arg is not None]
+    array_args = [arg for arg in args_not_none if not is_python_scalar(arg)]
+    if not array_args:
+        msg = "Must have at least one argument array"
+        raise ValueError(msg)
+    if xp is None:
+        xp = array_namespace(*args)
+
+    # Normalize and validate shape and dtype
+    shapes: list[tuple[int | None, ...]]
+    dtypes: list[DType]
+    multi_output = False
+
+    if shape is None:
+        shapes = [broadcast_shapes(*(arg.shape for arg in array_args))]
+    elif all(isinstance(s, int | None) for s in shape):
+        # Do not test for shape to be a tuple
+        # https://github.com/data-apis/array-api/issues/891#issuecomment-2637430522
+        shapes = [cast(tuple[int | None, ...], shape)]
+    else:
+        shapes = list(shape)  # type: ignore[arg-type]  # pyright: ignore[reportAssignmentType]
+        multi_output = True
+
+    if dtype is None:
+        dtypes = [xp.result_type(*args_not_none)] * len(shapes)
+    elif multi_output:
+        if not isinstance(dtype, Sequence):
+            msg = "Got multiple shapes but only one dtype"
+            raise ValueError(msg)
+        dtypes = list(dtype)  # pyright: ignore[reportUnknownArgumentType]
+    else:
+        if isinstance(dtype, Sequence):
+            msg = "Got single shape but multiple dtypes"
+            raise ValueError(msg)
+
+        dtypes = [dtype]
+
+    if len(shapes) != len(dtypes):
+        msg = f"Got {len(shapes)} shapes and {len(dtypes)} dtypes"
+        raise ValueError(msg)
+    del shape
+    del dtype
+    # End of shape and dtype parsing
+
+    # Backend-specific branches
+    if is_dask_namespace(xp):
+        import dask
+
+        metas: list[Array] = [arg._meta for arg in array_args]  # pylint: disable=protected-access    # pyright: ignore[reportAttributeAccessIssue]
+        meta_xp = array_namespace(*metas)
+
+        wrapped = dask.delayed(  # type: ignore[attr-defined]  # pyright: ignore[reportPrivateImportUsage]
+            _lazy_apply_wrapper(func, as_numpy, multi_output, meta_xp),
+            pure=True,
+        )
+        # This finalizes each arg, which is the same as arg.rechunk(-1).
+        # Please read docstring above for why we're not using
+        # dask.array.map_blocks or dask.array.blockwise!
+        delayed_out = wrapped(*args, **kwargs)
+
+        out = tuple(
+            xp.from_delayed(
+                delayed_out[i],  # pyright: ignore[reportIndexIssue]
+                # Dask's unknown shapes diverge from the Array API specification
+                shape=tuple(math.nan if s is None else s for s in shape),
+                dtype=dtype,
+                meta=metas[0],
+            )
+            for i, (shape, dtype) in enumerate(zip(shapes, dtypes, strict=True))
+        )
+
+    elif is_jax_namespace(xp) and _is_jax_jit_enabled(xp):
+        # Delay calling func with jax.pure_callback, which will forward to func eager
+        # JAX arrays. Do not use jax.pure_callback when running outside of the JIT,
+        # as it does not support raising exceptions:
+        # https://github.com/jax-ml/jax/issues/26102
+        import jax
+
+        if any(None in shape for shape in shapes):
+            msg = "Output shape must be fully known when running inside jax.jit"
+            raise ValueError(msg)
+
+        # Shield kwargs from being coerced into JAX arrays.
+        # jax.pure_callback calls jax.jit under the hood, but without the chance of
+        # passing static_argnames / static_argnums.
+        wrapped = _lazy_apply_wrapper(
+            partial(func, **kwargs), as_numpy, multi_output, xp
+        )
+
+        # suppress unused-ignore to run mypy in -e lint as well as -e dev
+        out = cast(  # type: ignore[bad-cast,unused-ignore]
+            tuple[Array, ...],
+            jax.pure_callback(
+                wrapped,
+                tuple(
+                    jax.ShapeDtypeStruct(shape, dtype)  # pyright: ignore[reportUnknownArgumentType]
+                    for shape, dtype in zip(shapes, dtypes, strict=True)
+                ),
+                *args,
+            ),
+        )
+
+    else:
+        # Eager backends, including non-jitted JAX
+        wrapped = _lazy_apply_wrapper(func, as_numpy, multi_output, xp)
+        out = wrapped(*args, **kwargs)
+
+    return out if multi_output else out[0]
+
+
+def _is_jax_jit_enabled(xp: ModuleType) -> bool:  # numpydoc ignore=PR01,RT01
+    """Return True if this function is being called inside ``jax.jit``."""
+    import jax  # pylint: disable=import-outside-toplevel
+
+    x = xp.asarray(False)
+    try:
+        return bool(x)
+    except jax.errors.TracerBoolConversionError:
+        return True
+
+
+def _lazy_apply_wrapper(  # numpydoc ignore=PR01,RT01
+    func: Callable[..., Array | ArrayLike | Sequence[Array | ArrayLike]],
+    as_numpy: bool,
+    multi_output: bool,
+    xp: ModuleType,
+) -> Callable[..., tuple[Array, ...]]:
+    """
+    Helper of `lazy_apply`.
+
+    Given a function that accepts one or more arrays as positional arguments and returns
+    a single array-like or a sequence of array-likes, return a function that accepts the
+    same number of Array API arrays and always returns a tuple of Array API array.
+
+    Any keyword arguments are passed through verbatim to the wrapped function.
+    """
+
+    # On Dask, @wraps causes the graph key to contain the wrapped function's name
+    @wraps(func)
+    def wrapper(
+        *args: Array | complex | None, **kwargs: Any
+    ) -> tuple[Array, ...]:  # numpydoc ignore=GL08
+        args_list = []
+        device = None
+        for arg in args:
+            if arg is not None and not is_python_scalar(arg):
+                if device is None:
+                    device = _compat.device(arg)
+                if as_numpy:
+                    import numpy as np
+
+                    arg = cast(Array, np.asarray(arg))  # pyright: ignore[reportInvalidCast] # noqa: PLW2901
+            args_list.append(arg)
+        assert device is not None
+
+        out = func(*args_list, **kwargs)
+
+        if multi_output:
+            assert isinstance(out, Sequence)
+            return tuple(xp.asarray(o, device=device) for o in out)
+        return (xp.asarray(out, device=device),)
+
+    return wrapper
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_testing.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..34780bd604029386fe9ced649b229895f699780b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_testing.py
@@ -0,0 +1,304 @@
+"""
+Testing utilities.
+
+Note that this is private API; don't expect it to be stable.
+See also ..testing for public testing utilities.
+"""
+
+from __future__ import annotations
+
+import math
+from types import ModuleType
+from typing import Any, cast
+
+import numpy as np
+import pytest
+
+from ._utils._compat import (
+    array_namespace,
+    is_array_api_strict_namespace,
+    is_cupy_namespace,
+    is_dask_namespace,
+    is_jax_namespace,
+    is_numpy_namespace,
+    is_pydata_sparse_namespace,
+    is_torch_array,
+    is_torch_namespace,
+    to_device,
+)
+from ._utils._typing import Array, Device
+
+__all__ = ["as_numpy_array", "xp_assert_close", "xp_assert_equal", "xp_assert_less"]
+
+
+def _check_ns_shape_dtype(
+    actual: Array,
+    desired: Array,
+    check_dtype: bool,
+    check_shape: bool,
+    check_scalar: bool,
+) -> ModuleType:  # numpydoc ignore=RT03
+    """
+    Assert that namespace, shape and dtype of the two arrays match.
+
+    Parameters
+    ----------
+    actual : Array
+        The array produced by the tested function.
+    desired : Array
+        The expected array (typically hardcoded).
+    check_dtype, check_shape : bool, default: True
+        Whether to check agreement between actual and desired dtypes and shapes
+    check_scalar : bool, default: False
+        NumPy only: whether to check agreement between actual and desired types -
+        0d array vs scalar.
+
+    Returns
+    -------
+    Arrays namespace.
+    """
+    actual_xp = array_namespace(actual)  # Raises on scalars and lists
+    desired_xp = array_namespace(desired)
+
+    msg = f"namespaces do not match: {actual_xp} != f{desired_xp}"
+    assert actual_xp == desired_xp, msg
+
+    # Dask uses nan instead of None for unknown shapes
+    actual_shape = cast(tuple[float, ...], actual.shape)
+    desired_shape = cast(tuple[float, ...], desired.shape)
+    assert None not in actual_shape  # Requires explicit support
+    assert None not in desired_shape
+    if is_dask_namespace(desired_xp):
+        if any(math.isnan(i) for i in actual_shape):
+            actual_shape = actual.compute().shape  # type: ignore[attr-defined]  # pyright: ignore[reportAttributeAccessIssue]
+        if any(math.isnan(i) for i in desired_shape):
+            desired_shape = desired.compute().shape  # type: ignore[attr-defined]  # pyright: ignore[reportAttributeAccessIssue]
+
+    if check_shape:
+        msg = f"shapes do not match: {actual_shape} != f{desired_shape}"
+        assert actual_shape == desired_shape, msg
+    else:
+        # Ignore shape, but check flattened size. This is normally done by
+        # np.testing.assert_array_equal etc even when strict=False, but not for
+        # non-materializable arrays.
+        actual_size = math.prod(actual_shape)  # pyright: ignore[reportUnknownArgumentType]
+        desired_size = math.prod(desired_shape)  # pyright: ignore[reportUnknownArgumentType]
+        msg = f"sizes do not match: {actual_size} != f{desired_size}"
+        assert actual_size == desired_size, msg
+
+    if check_dtype:
+        msg = f"dtypes do not match: {actual.dtype} != {desired.dtype}"
+        assert actual.dtype == desired.dtype, msg
+
+    if is_numpy_namespace(actual_xp) and check_scalar:
+        # only NumPy distinguishes between scalars and arrays; we do if check_scalar.
+        _msg = (
+            "array-ness does not match:\n Actual: "
+            f"{type(actual)}\n Desired: {type(desired)}"
+        )
+        assert np.isscalar(actual) == np.isscalar(desired), _msg
+
+    return desired_xp
+
+
+def _is_materializable(x: Array) -> bool:
+    """
+    Return True if you can call `as_numpy_array(x)`; False otherwise.
+    """
+    # Important: here we assume that we're not tracing -
+    # e.g. we're not inside `jax.jit`` nor `cupy.cuda.Stream.begin_capture`.
+    return not is_torch_array(x) or x.device.type != "meta"  # type: ignore[attr-defined]  # pyright: ignore[reportAttributeAccessIssue]
+
+
+def as_numpy_array(array: Array, *, xp: ModuleType) -> np.typing.NDArray[Any]:
+    """
+    Convert array to NumPy, bypassing GPU-CPU transfer guards and densification guards.
+    """
+    if is_cupy_namespace(xp):
+        return xp.asnumpy(array)
+    if is_pydata_sparse_namespace(xp):
+        return array.todense()  # type: ignore[attr-defined]  # pyright: ignore[reportAttributeAccessIssue]
+
+    if is_torch_namespace(xp):
+        array = to_device(array, "cpu")
+    if is_array_api_strict_namespace(xp):
+        cpu: Device = xp.Device("CPU_DEVICE")
+        array = to_device(array, cpu)
+    if is_jax_namespace(xp):
+        import jax
+
+        # Note: only needed if the transfer guard is enabled
+        cpu = cast(Device, jax.devices("cpu")[0])
+        array = to_device(array, cpu)
+
+    return np.asarray(array)
+
+
+def xp_assert_equal(
+    actual: Array,
+    desired: Array,
+    *,
+    err_msg: str = "",
+    check_dtype: bool = True,
+    check_shape: bool = True,
+    check_scalar: bool = False,
+) -> None:
+    """
+    Array-API compatible version of `np.testing.assert_array_equal`.
+
+    Parameters
+    ----------
+    actual : Array
+        The array produced by the tested function.
+    desired : Array
+        The expected array (typically hardcoded).
+    err_msg : str, optional
+        Error message to display on failure.
+    check_dtype, check_shape : bool, default: True
+        Whether to check agreement between actual and desired dtypes and shapes
+    check_scalar : bool, default: False
+        NumPy only: whether to check agreement between actual and desired types -
+        0d array vs scalar.
+
+    See Also
+    --------
+    xp_assert_close : Similar function for inexact equality checks.
+    numpy.testing.assert_array_equal : Similar function for NumPy arrays.
+    """
+    xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar)
+    if not _is_materializable(actual):
+        return
+    actual_np = as_numpy_array(actual, xp=xp)
+    desired_np = as_numpy_array(desired, xp=xp)
+    np.testing.assert_array_equal(actual_np, desired_np, err_msg=err_msg)
+
+
+def xp_assert_less(
+    x: Array,
+    y: Array,
+    *,
+    err_msg: str = "",
+    check_dtype: bool = True,
+    check_shape: bool = True,
+    check_scalar: bool = False,
+) -> None:
+    """
+    Array-API compatible version of `np.testing.assert_array_less`.
+
+    Parameters
+    ----------
+    x, y : Array
+        The arrays to compare according to ``x < y`` (elementwise).
+    err_msg : str, optional
+        Error message to display on failure.
+    check_dtype, check_shape : bool, default: True
+        Whether to check agreement between actual and desired dtypes and shapes
+    check_scalar : bool, default: False
+        NumPy only: whether to check agreement between actual and desired types -
+        0d array vs scalar.
+
+    See Also
+    --------
+    xp_assert_close : Similar function for inexact equality checks.
+    numpy.testing.assert_array_equal : Similar function for NumPy arrays.
+    """
+    xp = _check_ns_shape_dtype(x, y, check_dtype, check_shape, check_scalar)
+    if not _is_materializable(x):
+        return
+    x_np = as_numpy_array(x, xp=xp)
+    y_np = as_numpy_array(y, xp=xp)
+    np.testing.assert_array_less(x_np, y_np, err_msg=err_msg)
+
+
+def xp_assert_close(
+    actual: Array,
+    desired: Array,
+    *,
+    rtol: float | None = None,
+    atol: float = 0,
+    err_msg: str = "",
+    check_dtype: bool = True,
+    check_shape: bool = True,
+    check_scalar: bool = False,
+) -> None:
+    """
+    Array-API compatible version of `np.testing.assert_allclose`.
+
+    Parameters
+    ----------
+    actual : Array
+        The array produced by the tested function.
+    desired : Array
+        The expected array (typically hardcoded).
+    rtol : float, optional
+        Relative tolerance. Default: dtype-dependent.
+    atol : float, optional
+        Absolute tolerance. Default: 0.
+    err_msg : str, optional
+        Error message to display on failure.
+    check_dtype, check_shape : bool, default: True
+        Whether to check agreement between actual and desired dtypes and shapes
+    check_scalar : bool, default: False
+        NumPy only: whether to check agreement between actual and desired types -
+        0d array vs scalar.
+
+    See Also
+    --------
+    xp_assert_equal : Similar function for exact equality checks.
+    isclose : Public function for checking closeness.
+    numpy.testing.assert_allclose : Similar function for NumPy arrays.
+
+    Notes
+    -----
+    The default `atol` and `rtol` differ from `xp.all(xpx.isclose(a, b))`.
+    """
+    xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar)
+    if not _is_materializable(actual):
+        return
+
+    if rtol is None:
+        if xp.isdtype(actual.dtype, ("real floating", "complex floating")):
+            # multiplier of 4 is used as for `np.float64` this puts the default `rtol`
+            # roughly half way between sqrt(eps) and the default for
+            # `numpy.testing.assert_allclose`, 1e-7
+            rtol = xp.finfo(actual.dtype).eps ** 0.5 * 4
+        else:
+            rtol = 1e-7
+
+    actual_np = as_numpy_array(actual, xp=xp)
+    desired_np = as_numpy_array(desired, xp=xp)
+    np.testing.assert_allclose(  # pyright: ignore[reportCallIssue]
+        actual_np,
+        desired_np,
+        rtol=rtol,  # pyright: ignore[reportArgumentType]
+        atol=atol,
+        err_msg=err_msg,
+    )
+
+
+def xfail(
+    request: pytest.FixtureRequest, *, reason: str, strict: bool | None = None
+) -> None:
+    """
+    XFAIL the currently running test.
+
+    Unlike ``pytest.xfail``, allow rest of test to execute instead of immediately
+    halting it, so that it may result in a XPASS.
+    xref https://github.com/pandas-dev/pandas/issues/38902
+
+    Parameters
+    ----------
+    request : pytest.FixtureRequest
+        ``request`` argument of the test function.
+    reason : str
+        Reason for the expected failure.
+    strict: bool, optional
+        If True, the test will be marked as failed if it passes.
+        If False, the test will be marked as passed if it fails.
+        Default: ``xfail_strict`` value in ``pyproject.toml``, or False if absent.
+    """
+    if strict is not None:
+        marker = pytest.mark.xfail(reason=reason, strict=strict)
+    else:
+        marker = pytest.mark.xfail(reason=reason)
+    request.node.add_marker(marker)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1b1f7b6de9c8e305d92a25270f7b965b2411713
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__init__.py
@@ -0,0 +1 @@
+"""Modules housing private utility functions."""
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbd4b865a011c8c56c3f580422020d22ba857a59
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..08962c9d2b5fb094feac22a4bca9d3eec304637b
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed8154768673507942a7b70f5038581ff46f6c8d
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07e6f49a750d4a722a31c62f6f3e4760394c5df7
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f8af00debd92d1f32b64f11e0807445dd13f2a6
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.py
@@ -0,0 +1,74 @@
+"""Acquire helpers from array-api-compat."""
+# Allow packages that vendor both `array-api-extra` and
+# `array-api-compat` to override the import location
+
+# pylint: disable=duplicate-code
+try:
+    from ...._array_api_compat_vendor import (
+        array_namespace,
+        device,
+        is_array_api_obj,
+        is_array_api_strict_namespace,
+        is_cupy_array,
+        is_cupy_namespace,
+        is_dask_array,
+        is_dask_namespace,
+        is_jax_array,
+        is_jax_namespace,
+        is_lazy_array,
+        is_numpy_array,
+        is_numpy_namespace,
+        is_pydata_sparse_array,
+        is_pydata_sparse_namespace,
+        is_torch_array,
+        is_torch_namespace,
+        is_writeable_array,
+        size,
+        to_device,
+    )
+except ImportError:
+    from array_api_compat import (
+        array_namespace,
+        device,
+        is_array_api_obj,
+        is_array_api_strict_namespace,
+        is_cupy_array,
+        is_cupy_namespace,
+        is_dask_array,
+        is_dask_namespace,
+        is_jax_array,
+        is_jax_namespace,
+        is_lazy_array,
+        is_numpy_array,
+        is_numpy_namespace,
+        is_pydata_sparse_array,
+        is_pydata_sparse_namespace,
+        is_torch_array,
+        is_torch_namespace,
+        is_writeable_array,
+        size,
+        to_device,
+    )
+
+__all__ = [
+    "array_namespace",
+    "device",
+    "is_array_api_obj",
+    "is_array_api_strict_namespace",
+    "is_cupy_array",
+    "is_cupy_namespace",
+    "is_dask_array",
+    "is_dask_namespace",
+    "is_jax_array",
+    "is_jax_namespace",
+    "is_lazy_array",
+    "is_numpy_array",
+    "is_numpy_namespace",
+    "is_pydata_sparse_array",
+    "is_pydata_sparse_namespace",
+    "is_torch_array",
+    "is_torch_namespace",
+    "is_writeable_array",
+    "size",
+    "to_device",
+]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.pyi b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..3cd63e016056e399601cdb38158c44ec0c5fb86b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.pyi
@@ -0,0 +1,45 @@
+"""Static type stubs for `_compat.py`."""
+
+# https://github.com/scikit-learn/scikit-learn/pull/27910#issuecomment-2568023972
+from __future__ import annotations
+
+from types import ModuleType
+from typing import Any, TypeGuard
+
+# TODO import from typing (requires Python >=3.13)
+from typing_extensions import TypeIs
+
+from ._typing import Array, Device
+
+# pylint: disable=missing-class-docstring,unused-argument
+
+def array_namespace(
+    *xs: Array | complex | None,
+    api_version: str | None = None,
+    use_compat: bool | None = None,
+) -> ModuleType: ...
+def device(x: Array, /) -> Device: ...
+def is_array_api_obj(x: object, /) -> TypeIs[Array]: ...
+def is_array_api_strict_namespace(xp: ModuleType, /) -> bool: ...
+def is_cupy_namespace(xp: ModuleType, /) -> bool: ...
+def is_dask_namespace(xp: ModuleType, /) -> bool: ...
+def is_jax_namespace(xp: ModuleType, /) -> bool: ...
+def is_numpy_namespace(xp: ModuleType, /) -> bool: ...
+def is_pydata_sparse_namespace(xp: ModuleType, /) -> bool: ...
+def is_torch_namespace(xp: ModuleType, /) -> bool: ...
+def is_cupy_array(x: object, /) -> TypeGuard[Array]: ...
+def is_dask_array(x: object, /) -> TypeGuard[Array]: ...
+def is_jax_array(x: object, /) -> TypeGuard[Array]: ...
+def is_numpy_array(x: object, /) -> TypeGuard[Array]: ...
+def is_pydata_sparse_array(x: object, /) -> TypeGuard[Array]: ...
+def is_torch_array(x: object, /) -> TypeGuard[Array]: ...
+def is_lazy_array(x: object, /) -> TypeGuard[Array]: ...
+def is_writeable_array(x: object, /) -> TypeGuard[Array]: ...
+def size(x: Array, /) -> int | None: ...
+def to_device(
+    x: Array,
+    device: Device,  # pylint: disable=redefined-outer-name
+    /,
+    *,
+    stream: int | Any | None = None,
+) -> Array: ...
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd3315fed3b4387157799346388fe6cb3723c356
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_helpers.py
@@ -0,0 +1,619 @@
+"""Helper functions used by `array_api_extra/_funcs.py`."""
+
+from __future__ import annotations
+
+import io
+import math
+import pickle
+import types
+from collections.abc import Callable, Generator, Iterable, Iterator
+from functools import wraps
+from types import ModuleType
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    ClassVar,
+    Generic,
+    Literal,
+    ParamSpec,
+    TypeAlias,
+    TypeVar,
+    cast,
+)
+
+from . import _compat
+from ._compat import (
+    array_namespace,
+    is_array_api_obj,
+    is_dask_namespace,
+    is_jax_namespace,
+    is_numpy_array,
+    is_pydata_sparse_namespace,
+    is_torch_namespace,
+)
+from ._typing import Array, Device
+
+if TYPE_CHECKING:  # pragma: no cover
+    # TODO import from typing (requires Python >=3.12 and >=3.13)
+    from typing_extensions import TypeIs, override
+else:
+
+    def override(func):
+        return func
+
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+__all__ = [
+    "asarrays",
+    "capabilities",
+    "eager_shape",
+    "in1d",
+    "is_python_scalar",
+    "jax_autojit",
+    "mean",
+    "meta_namespace",
+    "pickle_flatten",
+    "pickle_unflatten",
+]
+
+
+def in1d(
+    x1: Array,
+    x2: Array,
+    /,
+    *,
+    assume_unique: bool = False,
+    invert: bool = False,
+    xp: ModuleType | None = None,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """
+    Check whether each element of an array is also present in a second array.
+
+    Returns a boolean array the same length as `x1` that is True
+    where an element of `x1` is in `x2` and False otherwise.
+
+    This function has been adapted using the original implementation
+    present in numpy:
+    https://github.com/numpy/numpy/blob/v1.26.0/numpy/lib/arraysetops.py#L524-L758
+    """
+    if xp is None:
+        xp = array_namespace(x1, x2)
+
+    x1_shape = eager_shape(x1)
+    x2_shape = eager_shape(x2)
+
+    # This code is run to make the code significantly faster
+    if x2_shape[0] < 10 * x1_shape[0] ** 0.145 and isinstance(x2, Iterable):
+        if invert:
+            mask = xp.ones(x1_shape[0], dtype=xp.bool, device=_compat.device(x1))
+            for a in x2:
+                mask &= x1 != a
+        else:
+            mask = xp.zeros(x1_shape[0], dtype=xp.bool, device=_compat.device(x1))
+            for a in x2:
+                mask |= x1 == a
+        return mask
+
+    rev_idx = xp.empty(0)  # placeholder
+    if not assume_unique:
+        x1, rev_idx = xp.unique_inverse(x1)
+        x2 = xp.unique_values(x2)
+
+    ar = xp.concat((x1, x2))
+    device_ = _compat.device(ar)
+    # We need this to be a stable sort.
+    order = xp.argsort(ar, stable=True)
+    reverse_order = xp.argsort(order, stable=True)
+    sar = xp.take(ar, order, axis=0)
+    ar_size = _compat.size(sar)
+    assert ar_size is not None, "xp.unique*() on lazy backends raises"
+    if ar_size >= 1:
+        bool_ar = sar[1:] != sar[:-1] if invert else sar[1:] == sar[:-1]
+    else:
+        bool_ar = xp.asarray([False]) if invert else xp.asarray([True])
+    flag = xp.concat((bool_ar, xp.asarray([invert], device=device_)))
+    ret = xp.take(flag, reverse_order, axis=0)
+
+    if assume_unique:
+        return ret[: x1.shape[0]]
+    return xp.take(ret, rev_idx, axis=0)
+
+
+def mean(
+    x: Array,
+    /,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    xp: ModuleType | None = None,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """
+    Complex mean, https://github.com/data-apis/array-api/issues/846.
+    """
+    if xp is None:
+        xp = array_namespace(x)
+
+    if xp.isdtype(x.dtype, "complex floating"):
+        x_real = xp.real(x)
+        x_imag = xp.imag(x)
+        mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims)
+        mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims)
+        return mean_real + (mean_imag * xp.asarray(1j))
+    return xp.mean(x, axis=axis, keepdims=keepdims)
+
+
+def is_python_scalar(x: object) -> TypeIs[complex]:  # numpydoc ignore=PR01,RT01
+    """Return True if `x` is a Python scalar, False otherwise."""
+    # isinstance(x, float) returns True for np.float64
+    # isinstance(x, complex) returns True for np.complex128
+    # bool is a subclass of int
+    return isinstance(x, int | float | complex) and not is_numpy_array(x)
+
+
+def asarrays(
+    a: Array | complex,
+    b: Array | complex,
+    xp: ModuleType,
+) -> tuple[Array, Array]:
+    """
+    Ensure both `a` and `b` are arrays.
+
+    If `b` is a python scalar, it is converted to the same dtype as `a`, and vice versa.
+
+    Behavior is not specified when mixing a Python ``float`` and an array with an
+    integer data type; this may give ``float32``, ``float64``, or raise an exception.
+    Behavior is implementation-specific.
+
+    Similarly, behavior is not specified when mixing a Python ``complex`` and an array
+    with a real-valued data type; this may give ``complex64``, ``complex128``, or raise
+    an exception. Behavior is implementation-specific.
+
+    Parameters
+    ----------
+    a, b : Array | int | float | complex | bool
+        Input arrays or scalars. At least one must be an array.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    Array, Array
+        The input arrays, possibly converted to arrays if they were scalars.
+
+    See Also
+    --------
+    mixing-arrays-with-python-scalars : Array API specification for the behavior.
+    """
+    a_scalar = is_python_scalar(a)
+    b_scalar = is_python_scalar(b)
+    if not a_scalar and not b_scalar:
+        # This includes misc. malformed input e.g. str
+        return a, b  # type: ignore[return-value]
+
+    swap = False
+    if a_scalar:
+        swap = True
+        b, a = a, b
+
+    if is_array_api_obj(a):
+        # a is an Array API object
+        # b is a int | float | complex | bool
+        xa = a
+
+        # https://data-apis.org/array-api/draft/API_specification/type_promotion.html#mixing-arrays-with-python-scalars
+        same_dtype = {
+            bool: "bool",
+            int: ("integral", "real floating", "complex floating"),
+            float: ("real floating", "complex floating"),
+            complex: "complex floating",
+        }
+        kind = same_dtype[type(cast(complex, b))]
+        if xp.isdtype(a.dtype, kind):
+            xb = xp.asarray(b, dtype=a.dtype, device=_compat.device(a))
+        else:
+            # Undefined behaviour. Let the function deal with it, if it can.
+            xb = xp.asarray(b, device=_compat.device(a))
+
+    else:
+        # Neither a nor b are Array API objects.
+        # Note: we can only reach this point when one explicitly passes
+        # xp=xp to the calling function; otherwise we fail earlier on
+        # array_namespace(a, b).
+        xa, xb = xp.asarray(a), xp.asarray(b)
+
+    return (xb, xa) if swap else (xa, xb)
+
+
+def ndindex(*x: int) -> Generator[tuple[int, ...]]:
+    """
+    Generate all N-dimensional indices for a given array shape.
+
+    Given the shape of an array, an ndindex instance iterates over the N-dimensional
+    index of the array. At each iteration a tuple of indices is returned, the last
+    dimension is iterated over first.
+
+    This has an identical API to numpy.ndindex.
+
+    Parameters
+    ----------
+    *x : int
+        The shape of the array.
+    """
+    if not x:
+        yield ()
+        return
+    for i in ndindex(*x[:-1]):
+        for j in range(x[-1]):
+            yield *i, j
+
+
+def eager_shape(x: Array, /, axis: int | None = None) -> tuple[int, ...]:
+    """
+    Return shape of an array. Raise if shape is not fully defined.
+
+    Parameters
+    ----------
+    x : Array
+        Input array.
+    axis : int, optional
+        If provided, only returns the tuple (shape[axis],).
+
+    Returns
+    -------
+    tuple[int, ...]
+        Shape of the array.
+    """
+    shape = x.shape
+    if axis is not None:
+        s = shape[axis]
+        # Dask arrays uses non-standard NaN instead of None
+        if s is None or math.isnan(s):
+            msg = f"Unsupported lazy shape for axis {axis}"
+            raise TypeError(msg)
+        return (s,)
+
+    if any(s is None or math.isnan(s) for s in shape):
+        msg = "Unsupported lazy shape"
+        raise TypeError(msg)
+    return cast(tuple[int, ...], shape)
+
+
+def meta_namespace(
+    *arrays: Array | complex | None, xp: ModuleType | None = None
+) -> ModuleType:
+    """
+    Get the namespace of Dask chunks.
+
+    On all other backends, just return the namespace of the arrays.
+
+    Parameters
+    ----------
+    *arrays : Array | int | float | complex | bool | None
+        Input arrays.
+    xp : array_namespace, optional
+        The standard-compatible namespace for the input arrays. Default: infer.
+
+    Returns
+    -------
+    array_namespace
+        If xp is Dask, the namespace of the Dask chunks;
+        otherwise, the namespace of the arrays.
+    """
+    xp = array_namespace(*arrays) if xp is None else xp
+    if not is_dask_namespace(xp):
+        return xp
+    # Quietly skip scalars and None's
+    metas = [cast(Array | None, getattr(a, "_meta", None)) for a in arrays]
+    return array_namespace(*metas)
+
+
+def capabilities(
+    xp: ModuleType, *, device: Device | None = None
+) -> dict[str, int | None]:
+    """
+    Return patched ``xp.__array_namespace_info__().capabilities()``.
+
+    TODO this helper should be eventually removed once all the special cases
+    it handles are fixed in the respective backends.
+
+    Parameters
+    ----------
+    xp : array_namespace
+        The standard-compatible namespace.
+    device : Device, optional
+        The device to use.
+
+    Returns
+    -------
+    dict
+        Capabilities of the namespace.
+    """
+    out = xp.__array_namespace_info__().capabilities()
+    if is_pydata_sparse_namespace(xp):
+        if out["boolean indexing"]:
+            # FIXME https://github.com/pydata/sparse/issues/876
+            # boolean indexing is supported, but not when the index is a sparse array.
+            # boolean indexing by list or numpy array is not part of the Array API.
+            out = out.copy()
+            out["boolean indexing"] = False
+    elif is_jax_namespace(xp):
+        if out["boolean indexing"]:  # pragma: no cover
+            # Backwards compatibility with jax <0.6.0
+            # https://github.com/jax-ml/jax/issues/27418
+            out = out.copy()
+            out["boolean indexing"] = False
+    elif is_torch_namespace(xp):
+        # FIXME https://github.com/data-apis/array-api/issues/945
+        device = xp.get_default_device() if device is None else xp.device(device)
+        if device.type == "meta":  # type: ignore[union-attr]  # pyright: ignore[reportAttributeAccessIssue,reportOptionalMemberAccess]
+            out = out.copy()
+            out["boolean indexing"] = False
+            out["data-dependent shapes"] = False
+
+    return out
+
+
+_BASIC_PICKLED_TYPES = frozenset((
+    bool, int, float, complex, str, bytes, bytearray,
+    list, tuple, dict, set, frozenset, range, slice,
+    types.NoneType, types.EllipsisType,
+))  # fmt: skip
+_BASIC_REST_TYPES = frozenset((
+    type, types.BuiltinFunctionType, types.FunctionType, types.ModuleType
+))  # fmt: skip
+
+FlattenRest: TypeAlias = tuple[object, ...]
+
+
+def pickle_flatten(
+    obj: object, cls: type[T] | tuple[type[T], ...]
+) -> tuple[list[T], FlattenRest]:
+    """
+    Use the pickle machinery to extract objects out of an arbitrary container.
+
+    Unlike regular ``pickle.dumps``, this function always succeeds.
+
+    Parameters
+    ----------
+    obj : object
+        The object to pickle.
+    cls : type | tuple[type, ...]
+        One or multiple classes to extract from the object.
+        The instances of these classes inside ``obj`` will not be pickled.
+
+    Returns
+    -------
+    instances : list[cls]
+        All instances of ``cls`` found inside ``obj`` (not pickled).
+    rest
+        Opaque object containing the pickled bytes plus all other objects where
+        ``__reduce__`` / ``__reduce_ex__`` is either not implemented or raised.
+        These are unpickleable objects, types, modules, and functions.
+
+        This object is *typically* hashable save for fairly exotic objects
+        that are neither pickleable nor hashable.
+
+        This object is pickleable if everything except ``instances`` was pickleable
+        in the input object.
+
+    See Also
+    --------
+    pickle_unflatten : Reverse function.
+
+    Examples
+    --------
+    >>> class A:
+    ...     def __repr__(self):
+    ...         return ""
+    >>> class NS:
+    ...     def __repr__(self):
+    ...         return ""
+    ...     def __reduce__(self):
+    ...         assert False, "not serializable"
+    >>> obj = {1: A(), 2: [A(), NS(), A()]}
+    >>> instances, rest = pickle_flatten(obj, A)
+    >>> instances
+    [, , ]
+    >>> pickle_unflatten(instances, rest)
+    {1: , 2: [, , ]}
+
+    This can be also used to swap inner objects; the only constraint is that
+    the number of objects in and out must be the same:
+
+    >>> pickle_unflatten(["foo", "bar", "baz"], rest)
+    {1: "foo", 2: ["bar", , "baz"]}
+    """
+    instances: list[T] = []
+    rest: list[object] = []
+
+    class Pickler(pickle.Pickler):  # numpydoc ignore=GL08
+        """
+        Use the `pickle.Pickler.persistent_id` hook to extract objects.
+        """
+
+        @override
+        def persistent_id(
+            self, obj: object
+        ) -> Literal[0, 1, None]:  # numpydoc ignore=GL08
+            if isinstance(obj, cls):
+                instances.append(obj)  # type: ignore[arg-type]
+                return 0
+
+            typ_ = type(obj)
+            if typ_ in _BASIC_PICKLED_TYPES:  # No subclasses!
+                # If obj is a collection, recursively descend inside it
+                return None
+            if typ_ in _BASIC_REST_TYPES:
+                rest.append(obj)
+                return 1
+
+            try:
+                # Note: a class that defines __slots__ without defining __getstate__
+                # cannot be pickled with __reduce__(), but can with __reduce_ex__(5)
+                _ = obj.__reduce_ex__(pickle.HIGHEST_PROTOCOL)
+            except Exception:  # pylint: disable=broad-exception-caught
+                rest.append(obj)
+                return 1
+
+            # Object can be pickled. Let the Pickler recursively descend inside it.
+            return None
+
+    f = io.BytesIO()
+    p = Pickler(f, protocol=pickle.HIGHEST_PROTOCOL)
+    p.dump(obj)
+    return instances, (f.getvalue(), *rest)
+
+
+def pickle_unflatten(instances: Iterable[object], rest: FlattenRest) -> Any:
+    """
+    Reverse of ``pickle_flatten``.
+
+    Parameters
+    ----------
+    instances : Iterable
+        Inner objects to be reinserted into the flattened container.
+    rest : FlattenRest
+        Extra bits, as returned by ``pickle_flatten``.
+
+    Returns
+    -------
+    object
+        The outer object originally passed to ``pickle_flatten`` after a
+        pickle->unpickle round-trip.
+
+    See Also
+    --------
+    pickle_flatten : Serializing function.
+    pickle.loads : Standard unpickle function.
+
+    Notes
+    -----
+    The `instances` iterable must yield at least the same number of elements as the ones
+    returned by ``pickle_flatten``, but the elements do not need to be the same objects
+    or even the same types of objects. Excess elements, if any, will be left untouched.
+    """
+    iters = iter(instances), iter(rest)
+    pik = cast(bytes, next(iters[1]))
+
+    class Unpickler(pickle.Unpickler):  # numpydoc ignore=GL08
+        """Mirror of the overridden Pickler in pickle_flatten."""
+
+        @override
+        def persistent_load(self, pid: Literal[0, 1]) -> object:  # numpydoc ignore=GL08
+            try:
+                return next(iters[pid])
+            except StopIteration as e:
+                msg = "Not enough objects to unpickle"
+                raise ValueError(msg) from e
+
+    f = io.BytesIO(pik)
+    return Unpickler(f).load()
+
+
+class _AutoJITWrapper(Generic[T]):  # numpydoc ignore=PR01
+    """
+    Helper of :func:`jax_autojit`.
+
+    Wrap arbitrary inputs and outputs of the jitted function and
+    convert them to/from PyTrees.
+    """
+
+    _obj: Any
+    _is_iter: bool
+    _registered: ClassVar[bool] = False
+    __slots__: tuple[str, ...] = ("_is_iter", "_obj")
+
+    def __init__(self, obj: T) -> None:  # numpydoc ignore=GL08
+        self._register()
+        if isinstance(obj, Iterator):
+            self._obj = list(obj)
+            self._is_iter = True
+        else:
+            self._obj = obj
+            self._is_iter = False
+
+    @property
+    def obj(self) -> T:  # numpydoc ignore=RT01
+        """Return wrapped object."""
+        return iter(self._obj) if self._is_iter else self._obj
+
+    @classmethod
+    def _register(cls) -> None:  # numpydoc ignore=SS06
+        """
+        Register upon first use instead of at import time, to avoid
+        globally importing JAX.
+        """
+        if not cls._registered:
+            import jax
+
+            jax.tree_util.register_pytree_node(
+                cls,
+                lambda instance: pickle_flatten(instance, jax.Array),  # pyright: ignore[reportUnknownArgumentType]
+                lambda aux_data, children: pickle_unflatten(children, aux_data),  # pyright: ignore[reportUnknownArgumentType]
+            )
+            cls._registered = True
+
+
+def jax_autojit(
+    func: Callable[P, T],
+) -> Callable[P, T]:  # numpydoc ignore=PR01,RT01,SS03
+    """
+    Wrap `func` with ``jax.jit``, with the following differences:
+
+    - Python scalar arguments and return values are not automatically converted to
+      ``jax.Array`` objects.
+    - All non-array arguments are automatically treated as static.
+      Unlike ``jax.jit``, static arguments must be either hashable or serializable with
+      ``pickle``.
+    - Unlike ``jax.jit``, non-array arguments and return values are not limited to
+      tuple/list/dict, but can be any object serializable with ``pickle``.
+    - Automatically descend into non-array arguments and find ``jax.Array`` objects
+      inside them, then rebuild the arguments when entering `func`, swapping the JAX
+      concrete arrays with tracer objects.
+    - Automatically descend into non-array return values and find ``jax.Array`` objects
+      inside them, then rebuild them downstream of exiting the JIT, swapping the JAX
+      tracer objects with concrete arrays.
+    - Returned iterators are immediately completely consumed.
+
+    See Also
+    --------
+    jax.jit : JAX JIT compilation function.
+
+    Notes
+    -----
+    These are useful choices *for testing purposes only*, which is how this function is
+    intended to be used. The output of ``jax.jit`` is a C++ level callable, that
+    directly dispatches to the compiled kernel after the initial call. In comparison,
+    ``jax_autojit`` incurs a much higher dispatch time.
+
+    Additionally, consider::
+
+        def f(x: Array, y: float, plus: bool) -> Array:
+            return x + y if plus else x - y
+
+        j1 = jax.jit(f, static_argnames="plus")
+        j2 = jax_autojit(f)
+
+    In the above example, ``j2`` requires a lot less setup to be tested effectively than
+    ``j1``, but on the flip side it means that it will be re-traced for every different
+    value of ``y``, which likely makes it not fit for purpose in production.
+    """
+    import jax
+
+    @jax.jit  # type: ignore[misc]  # pyright: ignore[reportUntypedFunctionDecorator]
+    def inner(  # numpydoc ignore=GL08
+        wargs: _AutoJITWrapper[Any],
+    ) -> _AutoJITWrapper[T]:
+        args, kwargs = wargs.obj
+        res = func(*args, **kwargs)  # pyright: ignore[reportCallIssue]
+        return _AutoJITWrapper(res)
+
+    @wraps(func)
+    def outer(*args: P.args, **kwargs: P.kwargs) -> T:  # numpydoc ignore=GL08
+        wargs = _AutoJITWrapper((args, kwargs))
+        return inner(wargs).obj
+
+    return outer
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0d4c445b41b2e8a4cfe4006a6892fa5ddd8ec10
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.py
@@ -0,0 +1,10 @@
+# numpydoc ignore=GL08
+# pylint: disable=missing-module-docstring,duplicate-code
+
+Array = object
+DType = object
+Device = object
+GetIndex = object
+SetIndex = object
+
+__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.pyi b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..dd864c3e702c2316f3ff52e12af19f25479b4935
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.pyi
@@ -0,0 +1,105 @@
+"""Static typing helpers."""
+
+from __future__ import annotations
+
+from types import EllipsisType
+from typing import Protocol, TypeAlias
+
+# TODO import from typing (requires Python >=3.12)
+from typing_extensions import override
+
+# TODO: use array-api-typing once it is available
+
+class Array(Protocol):  # pylint: disable=missing-class-docstring
+    # Unary operations
+    def __abs__(self) -> Array: ...
+    def __pos__(self) -> Array: ...
+    def __neg__(self) -> Array: ...
+    def __invert__(self) -> Array: ...
+    # Binary operations
+    def __add__(self, other: Array | complex, /) -> Array: ...
+    def __sub__(self, other: Array | complex, /) -> Array: ...
+    def __mul__(self, other: Array | complex, /) -> Array: ...
+    def __truediv__(self, other: Array | complex, /) -> Array: ...
+    def __floordiv__(self, other: Array | complex, /) -> Array: ...
+    def __mod__(self, other: Array | complex, /) -> Array: ...
+    def __pow__(self, other: Array | complex, /) -> Array: ...
+    def __matmul__(self, other: Array, /) -> Array: ...
+    def __and__(self, other: Array | int, /) -> Array: ...
+    def __or__(self, other: Array | int, /) -> Array: ...
+    def __xor__(self, other: Array | int, /) -> Array: ...
+    def __lshift__(self, other: Array | int, /) -> Array: ...
+    def __rshift__(self, other: Array | int, /) -> Array: ...
+    def __lt__(self, other: Array | complex, /) -> Array: ...
+    def __le__(self, other: Array | complex, /) -> Array: ...
+    def __gt__(self, other: Array | complex, /) -> Array: ...
+    def __ge__(self, other: Array | complex, /) -> Array: ...
+    @override
+    def __eq__(self, other: Array | complex, /) -> Array: ...  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
+    @override
+    def __ne__(self, other: Array | complex, /) -> Array: ...  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
+    # Reflected operations
+    def __radd__(self, other: Array | complex, /) -> Array: ...
+    def __rsub__(self, other: Array | complex, /) -> Array: ...
+    def __rmul__(self, other: Array | complex, /) -> Array: ...
+    def __rtruediv__(self, other: Array | complex, /) -> Array: ...
+    def __rfloordiv__(self, other: Array | complex, /) -> Array: ...
+    def __rmod__(self, other: Array | complex, /) -> Array: ...
+    def __rpow__(self, other: Array | complex, /) -> Array: ...
+    def __rmatmul__(self, other: Array, /) -> Array: ...
+    def __rand__(self, other: Array | int, /) -> Array: ...
+    def __ror__(self, other: Array | int, /) -> Array: ...
+    def __rxor__(self, other: Array | int, /) -> Array: ...
+    def __rlshift__(self, other: Array | int, /) -> Array: ...
+    def __rrshift__(self, other: Array | int, /) -> Array: ...
+    # Attributes
+    @property
+    def dtype(self) -> DType: ...
+    @property
+    def device(self) -> Device: ...
+    @property
+    def mT(self) -> Array: ...  # pylint: disable=invalid-name
+    @property
+    def ndim(self) -> int: ...
+    @property
+    def shape(self) -> tuple[int | None, ...]: ...
+    @property
+    def size(self) -> int | None: ...
+    @property
+    def T(self) -> Array: ...  # pylint: disable=invalid-name
+    # Collection operations (note: an Array does not have to be Sized or Iterable)
+    def __getitem__(self, key: GetIndex, /) -> Array: ...
+    def __setitem__(self, key: SetIndex, value: Array | complex, /) -> None: ...
+    # Materialization methods (may raise on lazy arrays)
+    def __bool__(self) -> bool: ...
+    def __complex__(self) -> complex: ...
+    def __float__(self) -> float: ...
+    def __index__(self) -> int: ...
+    def __int__(self) -> int: ...
+
+    # Misc methods (frequently not implemented in Arrays wrapped by array-api-compat)
+    # def __array_namespace__(*, api_version: str | None) -> ModuleType: ...
+    # def __dlpack__(
+    #     *,
+    #     stream: int | Any | None = None,
+    #     max_version: tuple[int, int] | None = None,
+    #     dl_device: tuple[int, int] | None = None,  # tuple[Enum, int]
+    #     copy: bool | None = None,
+    # ) -> Any: ...
+    # def __dlpack_device__() -> tuple[int, int]: ...  # tuple[Enum, int]
+    # def to_device(device: Device, /, *, stream: int | Any | None = None) -> Array: ...
+
+class DType(Protocol):  # pylint: disable=missing-class-docstring
+    pass
+
+class Device(Protocol):  # pylint: disable=missing-class-docstring
+    pass
+
+SetIndex: TypeAlias = (
+    int | slice | EllipsisType | Array | tuple[int | slice | EllipsisType | Array, ...]
+)
+GetIndex: TypeAlias = (
+    SetIndex | None | tuple[int | slice | EllipsisType | None | Array, ...]
+)
+
+__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/testing.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c1be71ea428b418ce4a6dd43c5467dae6225d37
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/array_api_extra/testing.py
@@ -0,0 +1,415 @@
+"""
+Public testing utilities.
+
+See also _lib._testing for additional private testing utilities.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import enum
+import warnings
+from collections.abc import Callable, Generator, Iterator, Sequence
+from functools import wraps
+from types import ModuleType
+from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, cast
+
+from ._lib._utils._compat import is_dask_namespace, is_jax_namespace
+from ._lib._utils._helpers import jax_autojit, pickle_flatten, pickle_unflatten
+
+__all__ = ["lazy_xp_function", "patch_lazy_xp_functions"]
+
+if TYPE_CHECKING:  # pragma: no cover
+    # TODO import override from typing (requires Python >=3.12)
+    import pytest
+    from dask.typing import Graph, Key, SchedulerGetCallable
+    from typing_extensions import override
+
+else:
+    # Sphinx hacks
+    SchedulerGetCallable = object
+
+    def override(func):
+        return func
+
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+_ufuncs_tags: dict[object, dict[str, Any]] = {}
+
+
+class Deprecated(enum.Enum):
+    """Unique type for deprecated parameters."""
+
+    DEPRECATED = 1
+
+
+DEPRECATED = Deprecated.DEPRECATED
+
+
+def lazy_xp_function(
+    func: Callable[..., Any],
+    *,
+    allow_dask_compute: bool | int = False,
+    jax_jit: bool = True,
+    static_argnums: Deprecated = DEPRECATED,
+    static_argnames: Deprecated = DEPRECATED,
+) -> None:  # numpydoc ignore=GL07
+    """
+    Tag a function to be tested on lazy backends.
+
+    Tag a function so that when any tests are executed with ``xp=jax.numpy`` the
+    function is replaced with a jitted version of itself, and when it is executed with
+    ``xp=dask.array`` the function will raise if it attempts to materialize the graph.
+    This will be later expanded to provide test coverage for other lazy backends.
+
+    In order for the tag to be effective, the test or a fixture must call
+    :func:`patch_lazy_xp_functions`.
+
+    Parameters
+    ----------
+    func : callable
+        Function to be tested.
+    allow_dask_compute : bool | int, optional
+        Whether `func` is allowed to internally materialize the Dask graph, or maximum
+        number of times it is allowed to do so. This is typically triggered by
+        ``bool()``, ``float()``, or ``np.asarray()``.
+
+        Set to 1 if you are aware that `func` converts the input parameters to NumPy and
+        want to let it do so at least for the time being, knowing that it is going to be
+        extremely detrimental for performance.
+
+        If a test needs values higher than 1 to pass, it is a canary that the conversion
+        to NumPy/bool/float is happening multiple times, which translates to multiple
+        computations of the whole graph. Short of making the function fully lazy, you
+        should at least add explicit calls to ``np.asarray()`` early in the function.
+        *Note:* the counter of `allow_dask_compute` resets after each call to `func`, so
+        a test function that invokes `func` multiple times should still work with this
+        parameter set to 1.
+
+        Set to True to allow `func` to materialize the graph an unlimited number
+        of times.
+
+        Default: False, meaning that `func` must be fully lazy and never materialize the
+        graph.
+    jax_jit : bool, optional
+        Set to True to replace `func` with a smart variant of ``jax.jit(func)`` after
+        calling the :func:`patch_lazy_xp_functions` test helper with ``xp=jax.numpy``.
+        This is the default behaviour.
+        Set to False if `func` is only compatible with eager (non-jitted) JAX.
+
+        Unlike with vanilla ``jax.jit``, all arguments and return types that are not JAX
+        arrays are treated as static; the function can accept and return arbitrary
+        wrappers around JAX arrays. This difference is because, in real life, most users
+        won't wrap the function directly with ``jax.jit`` but rather they will use it
+        within their own code, which is itself then wrapped by ``jax.jit``, and
+        internally consume the function's outputs.
+
+        In other words, the pattern that is being tested is::
+
+            >>> @jax.jit
+            ... def user_func(x):
+            ...     y = user_prepares_inputs(x)
+            ...     z = func(y, some_static_arg=True)
+            ...     return user_consumes(z)
+
+        Default: True.
+    static_argnums :
+        Deprecated; ignored
+    static_argnames :
+        Deprecated; ignored
+
+    See Also
+    --------
+    patch_lazy_xp_functions : Companion function to call from the test or fixture.
+    jax.jit : JAX function to compile a function for performance.
+
+    Examples
+    --------
+    In ``test_mymodule.py``::
+
+      from array_api_extra.testing import lazy_xp_function from mymodule import myfunc
+
+      lazy_xp_function(myfunc)
+
+      def test_myfunc(xp):
+          a = xp.asarray([1, 2])
+          # When xp=jax.numpy, this is similar to `b = jax.jit(myfunc)(a)`
+          # When xp=dask.array, crash on compute() or persist()
+          b = myfunc(a)
+
+    Notes
+    -----
+    In order for this tag to be effective, the test function must be imported into the
+    test module globals without its namespace; alternatively its namespace must be
+    declared in a ``lazy_xp_modules`` list in the test module globals.
+
+    Example 1::
+
+      from mymodule import myfunc
+
+      lazy_xp_function(myfunc)
+
+      def test_myfunc(xp):
+          x = myfunc(xp.asarray([1, 2]))
+
+    Example 2::
+
+      import mymodule
+
+      lazy_xp_modules = [mymodule]
+      lazy_xp_function(mymodule.myfunc)
+
+      def test_myfunc(xp):
+          x = mymodule.myfunc(xp.asarray([1, 2]))
+
+    A test function can circumvent this monkey-patching system by using a namespace
+    outside of the two above patterns. You need to sanitize your code to make sure this
+    only happens intentionally.
+
+    Example 1::
+
+      import mymodule
+      from mymodule import myfunc
+
+      lazy_xp_function(myfunc)
+
+      def test_myfunc(xp):
+          a = xp.asarray([1, 2])
+          b = myfunc(a)  # This is wrapped when xp=jax.numpy or xp=dask.array
+          c = mymodule.myfunc(a)  # This is not
+
+    Example 2::
+
+      import mymodule
+
+      class naked:
+          myfunc = mymodule.myfunc
+
+      lazy_xp_modules = [mymodule]
+      lazy_xp_function(mymodule.myfunc)
+
+      def test_myfunc(xp):
+          a = xp.asarray([1, 2])
+          b = mymodule.myfunc(a)  # This is wrapped when xp=jax.numpy or xp=dask.array
+          c = naked.myfunc(a)  # This is not
+    """
+    if static_argnums is not DEPRECATED or static_argnames is not DEPRECATED:
+        warnings.warn(
+            (
+                "The `static_argnums` and `static_argnames` parameters are deprecated "
+                "and ignored. They will be removed in a future version."
+            ),
+            DeprecationWarning,
+            stacklevel=2,
+        )
+    tags = {
+        "allow_dask_compute": allow_dask_compute,
+        "jax_jit": jax_jit,
+    }
+
+    try:
+        func._lazy_xp_function = tags  # type: ignore[attr-defined]  # pylint: disable=protected-access  # pyright: ignore[reportFunctionMemberAccess]
+    except AttributeError:  # @cython.vectorize
+        _ufuncs_tags[func] = tags
+
+
+def patch_lazy_xp_functions(
+    request: pytest.FixtureRequest,
+    monkeypatch: pytest.MonkeyPatch | None = None,
+    *,
+    xp: ModuleType,
+) -> contextlib.AbstractContextManager[None]:
+    """
+    Test lazy execution of functions tagged with :func:`lazy_xp_function`.
+
+    If ``xp==jax.numpy``, search for all functions which have been tagged with
+    :func:`lazy_xp_function` in the globals of the module that defines the current test,
+    as well as in the ``lazy_xp_modules`` list in the globals of the same module,
+    and wrap them with :func:`jax.jit`. Unwrap them at the end of the test.
+
+    If ``xp==dask.array``, wrap the functions with a decorator that disables
+    ``compute()`` and ``persist()`` and ensures that exceptions and warnings are raised
+    eagerly.
+
+    This function should be typically called by your library's `xp` fixture that runs
+    tests on multiple backends::
+
+        @pytest.fixture(params=[
+            numpy,
+            array_api_strict,
+            pytest.param(jax.numpy, marks=pytest.mark.thread_unsafe),
+            pytest.param(dask.array, marks=pytest.mark.thread_unsafe),
+        ])
+        def xp(request):
+            with patch_lazy_xp_functions(request, xp=request.param):
+                yield request.param
+
+    but it can be otherwise be called by the test itself too.
+
+    Parameters
+    ----------
+    request : pytest.FixtureRequest
+        Pytest fixture, as acquired by the test itself or by one of its fixtures.
+    monkeypatch : pytest.MonkeyPatch
+        Deprecated
+    xp : array_namespace
+        Array namespace to be tested.
+
+    See Also
+    --------
+    lazy_xp_function : Tag a function to be tested on lazy backends.
+    pytest.FixtureRequest : `request` test function parameter.
+
+    Notes
+    -----
+    This context manager monkey-patches modules and as such is thread unsafe
+    on Dask and JAX. If you run your test suite with
+    `pytest-run-parallel `_,
+    you should mark these backends with ``@pytest.mark.thread_unsafe``, as shown in
+    the example above.
+    """
+    mod = cast(ModuleType, request.module)
+    mods = [mod, *cast(list[ModuleType], getattr(mod, "lazy_xp_modules", []))]
+
+    to_revert: list[tuple[ModuleType, str, object]] = []
+
+    def temp_setattr(mod: ModuleType, name: str, func: object) -> None:
+        """
+        Variant of monkeypatch.setattr, which allows monkey-patching only selected
+        parameters of a test so that pytest-run-parallel can run on the remainder.
+        """
+        assert hasattr(mod, name)
+        to_revert.append((mod, name, getattr(mod, name)))
+        setattr(mod, name, func)
+
+    if monkeypatch is not None:
+        warnings.warn(
+            (
+                "The `monkeypatch` parameter is deprecated and will be removed in a "
+                "future version. "
+                "Use `patch_lazy_xp_function` as a context manager instead."
+            ),
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        # Enable using patch_lazy_xp_function not as a context manager
+        temp_setattr = monkeypatch.setattr  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]
+
+    def iter_tagged() -> Iterator[
+        tuple[ModuleType, str, Callable[..., Any], dict[str, Any]]
+    ]:
+        for mod in mods:
+            for name, func in mod.__dict__.items():
+                tags: dict[str, Any] | None = None
+                with contextlib.suppress(AttributeError):
+                    tags = func._lazy_xp_function  # pylint: disable=protected-access
+                if tags is None:
+                    with contextlib.suppress(KeyError, TypeError):
+                        tags = _ufuncs_tags[func]
+                if tags is not None:
+                    yield mod, name, func, tags
+
+    if is_dask_namespace(xp):
+        for mod, name, func, tags in iter_tagged():
+            n = tags["allow_dask_compute"]
+            if n is True:
+                n = 1_000_000
+            elif n is False:
+                n = 0
+            wrapped = _dask_wrap(func, n)
+            temp_setattr(mod, name, wrapped)
+
+    elif is_jax_namespace(xp):
+        for mod, name, func, tags in iter_tagged():
+            if tags["jax_jit"]:
+                wrapped = jax_autojit(func)
+                temp_setattr(mod, name, wrapped)
+
+    # We can't just decorate patch_lazy_xp_functions with
+    # @contextlib.contextmanager because it would not work with the
+    # deprecated monkeypatch when not used as a context manager.
+    @contextlib.contextmanager
+    def revert_on_exit() -> Generator[None]:
+        try:
+            yield
+        finally:
+            for mod, name, orig_func in to_revert:
+                setattr(mod, name, orig_func)
+
+    return revert_on_exit()
+
+
+class CountingDaskScheduler(SchedulerGetCallable):
+    """
+    Dask scheduler that counts how many times `dask.compute` is called.
+
+    If the number of times exceeds 'max_count', it raises an error.
+    This is a wrapper around Dask's own 'synchronous' scheduler.
+
+    Parameters
+    ----------
+    max_count : int
+        Maximum number of allowed calls to `dask.compute`.
+    msg : str
+        Assertion to raise when the count exceeds `max_count`.
+    """
+
+    count: int
+    max_count: int
+    msg: str
+
+    def __init__(self, max_count: int, msg: str):  # numpydoc ignore=GL08
+        self.count = 0
+        self.max_count = max_count
+        self.msg = msg
+
+    @override
+    def __call__(
+        self, dsk: Graph, keys: Sequence[Key] | Key, **kwargs: Any
+    ) -> Any:  # numpydoc ignore=GL08
+        import dask
+
+        self.count += 1
+        # This should yield a nice traceback to the
+        # offending line in the user's code
+        assert self.count <= self.max_count, self.msg
+
+        return dask.get(dsk, keys, **kwargs)  # type: ignore[attr-defined]  # pyright: ignore[reportPrivateImportUsage]
+
+
+def _dask_wrap(
+    func: Callable[P, T], n: int
+) -> Callable[P, T]:  # numpydoc ignore=PR01,RT01
+    """
+    Wrap `func` to raise if it attempts to call `dask.compute` more than `n` times.
+
+    After the function returns, materialize the graph in order to re-raise exceptions.
+    """
+    import dask
+    import dask.array as da
+
+    func_name = getattr(func, "__name__", str(func))
+    n_str = f"only up to {n}" if n else "no"
+    msg = (
+        f"Called `dask.compute()` or `dask.persist()` {n + 1} times, "
+        f"but {n_str} calls are allowed. Set "
+        f"`lazy_xp_function({func_name}, allow_dask_compute={n + 1})` "
+        "to allow for more (but note that this will harm performance). "
+    )
+
+    @wraps(func)
+    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:  # numpydoc ignore=GL08
+        scheduler = CountingDaskScheduler(n, msg)
+        with dask.config.set({"scheduler": scheduler}):  # pyright: ignore[reportPrivateImportUsage]
+            out = func(*args, **kwargs)
+
+        # Block until the graph materializes and reraise exceptions. This allows
+        # `pytest.raises` and `pytest.warns` to work as expected. Note that this would
+        # not work on scheduler='distributed', as it would not block.
+        arrays, rest = pickle_flatten(out, da.Array)
+        arrays = dask.persist(arrays, scheduler="threads")[0]  # type: ignore[attr-defined,no-untyped-call]  # pyright: ignore[reportPrivateImportUsage]
+        return pickle_unflatten(arrays, rest)  # pyright: ignore[reportUnknownArgumentType]
+
+    return wrapper
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..02230ccce8984cb30dc1763d234bf4a52af9693e
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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.3"
+
+__all__ = ["minimize", "show_versions"]
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/framework.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/framework.py
new file mode 100644
index 0000000000000000000000000000000000000000..59b8ea0442c81af1f39ff12381bc993e83dbb0f5
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/main.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e8fd966e40bb5fc93248f0b62cb64ccfd0f3e90
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/models.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ba8aac4688650740d662ef26614ce446f0407f8
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/models.py
@@ -0,0 +1,1531 @@
+import warnings
+
+import numpy as np
+from scipy.linalg import eigh
+
+from .settings import Options
+from .utils import MaxEvalError, TargetSuccess, FeasibleSuccess
+
+
+EPS = np.finfo(float).eps
+
+
+class Interpolation:
+    """
+    Interpolation set.
+
+    This class stores a base point around which the models are expanded and the
+    interpolation points. The coordinates of the interpolation points are
+    relative to the base point.
+    """
+
+    def __init__(self, pb, options):
+        """
+        Initialize the interpolation set.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to be solved.
+        options : dict
+            Options of the solver.
+        """
+        # Reduce the initial trust-region radius if necessary.
+        self._debug = options[Options.DEBUG]
+        max_radius = 0.5 * np.min(pb.bounds.xu - pb.bounds.xl)
+        if options[Options.RHOBEG] > max_radius:
+            options[Options.RHOBEG.value] = max_radius
+            options[Options.RHOEND.value] = np.min(
+                [
+                    options[Options.RHOEND],
+                    max_radius,
+                ]
+            )
+
+        # Set the initial point around which the models are expanded.
+        self._x_base = np.copy(pb.x0)
+        very_close_xl_idx = (
+            self.x_base <= pb.bounds.xl + 0.5 * options[Options.RHOBEG]
+        )
+        self.x_base[very_close_xl_idx] = pb.bounds.xl[very_close_xl_idx]
+        close_xl_idx = (
+            pb.bounds.xl + 0.5 * options[Options.RHOBEG] < self.x_base
+        ) & (self.x_base <= pb.bounds.xl + options[Options.RHOBEG])
+        self.x_base[close_xl_idx] = np.minimum(
+            pb.bounds.xl[close_xl_idx] + options[Options.RHOBEG],
+            pb.bounds.xu[close_xl_idx],
+        )
+        very_close_xu_idx = (
+            self.x_base >= pb.bounds.xu - 0.5 * options[Options.RHOBEG]
+        )
+        self.x_base[very_close_xu_idx] = pb.bounds.xu[very_close_xu_idx]
+        close_xu_idx = (
+            self.x_base < pb.bounds.xu - 0.5 * options[Options.RHOBEG]
+        ) & (pb.bounds.xu - options[Options.RHOBEG] <= self.x_base)
+        self.x_base[close_xu_idx] = np.maximum(
+            pb.bounds.xu[close_xu_idx] - options[Options.RHOBEG],
+            pb.bounds.xl[close_xu_idx],
+        )
+
+        # Set the initial interpolation set.
+        self._xpt = np.zeros((pb.n, options[Options.NPT]))
+        for k in range(1, options[Options.NPT]):
+            if k <= pb.n:
+                if very_close_xu_idx[k - 1]:
+                    self.xpt[k - 1, k] = -options[Options.RHOBEG]
+                else:
+                    self.xpt[k - 1, k] = options[Options.RHOBEG]
+            elif k <= 2 * pb.n:
+                if very_close_xl_idx[k - pb.n - 1]:
+                    self.xpt[k - pb.n - 1, k] = 2.0 * options[Options.RHOBEG]
+                elif very_close_xu_idx[k - pb.n - 1]:
+                    self.xpt[k - pb.n - 1, k] = -2.0 * options[Options.RHOBEG]
+                else:
+                    self.xpt[k - pb.n - 1, k] = -options[Options.RHOBEG]
+            else:
+                spread = (k - pb.n - 1) // pb.n
+                k1 = k - (1 + spread) * pb.n - 1
+                k2 = (k1 + spread) % pb.n
+                self.xpt[k1, k] = self.xpt[k1, k1 + 1]
+                self.xpt[k2, k] = self.xpt[k2, k2 + 1]
+        self._lhs_cache = None
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self.xpt.shape[0]
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points.
+
+        Returns
+        -------
+        int
+            Number of interpolation points.
+        """
+        return self.xpt.shape[1]
+
+    @property
+    def xpt(self):
+        """
+        Interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, npt)
+            Interpolation points.
+        """
+        return self._xpt
+
+    @xpt.setter
+    def xpt(self, xpt):
+        """
+        Set the interpolation points.
+
+        Parameters
+        ----------
+        xpt : `numpy.ndarray`, shape (n, npt)
+            New interpolation points.
+        """
+        if self._debug:
+            assert xpt.shape == (
+                self.n,
+                self.npt,
+            ), "The shape of `xpt` is not valid."
+        self._xpt = xpt
+
+    @property
+    def x_base(self):
+        """
+        Base point around which the models are expanded.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Base point around which the models are expanded.
+        """
+        return self._x_base
+
+    @x_base.setter
+    def x_base(self, x_base):
+        """
+        Set the base point around which the models are expanded.
+
+        Parameters
+        ----------
+        x_base : `numpy.ndarray`, shape (n,)
+            New base point around which the models are expanded.
+        """
+        if self._debug:
+            assert x_base.shape == (
+                self.n,
+            ), "The shape of `x_base` is not valid."
+        self._x_base = x_base
+
+    def point(self, k):
+        """
+        Get the `k`-th interpolation point.
+
+        The return point is relative to the origin.
+
+        Parameters
+        ----------
+        k : int
+            Index of the interpolation point.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            `k`-th interpolation point.
+        """
+        if self._debug:
+            assert 0 <= k < self.npt, "The index `k` is not valid."
+        return self.x_base + self.xpt[:, k]
+
+
+def build_system(interpolation):
+    """
+    Build the left-hand side matrix of the interpolation system. The
+    matrix below stores W * diag(right_scaling),
+    where W is the theoretical matrix of the interpolation system. The
+    right scaling matrices is chosen to keep the elements in
+    the matrix well-balanced.
+
+    Parameters
+    ----------
+    interpolation : `cobyqa.models.Interpolation`
+        Interpolation set.
+    """
+
+    _cache = interpolation._lhs_cache
+    # Compute the scaled directions from the base point to the
+    # interpolation points. We scale the directions to avoid numerical
+    # difficulties.
+    if _cache is not None and np.array_equal(
+        interpolation.xpt, _cache["xpt"]
+    ):
+        return _cache["a"], _cache["right_scaling"], _cache["eigh"]
+
+    scale = np.max(np.linalg.norm(interpolation.xpt, axis=0), initial=EPS)
+    xpt_scale = interpolation.xpt / scale
+
+    n, npt = xpt_scale.shape
+    a = np.zeros((npt + n + 1, npt + n + 1))
+    a[:npt, :npt] = 0.5 * (xpt_scale.T @ xpt_scale) ** 2.0
+    a[:npt, npt] = 1.0
+    a[:npt, npt + 1:] = xpt_scale.T
+    a[npt, :npt] = 1.0
+    a[npt + 1:, :npt] = xpt_scale
+
+    # Build the left and right scaling diagonal matrices.
+    right_scaling = np.empty(npt + n + 1)
+    right_scaling[:npt] = 1.0 / scale**2.0
+    right_scaling[npt] = scale**2.0
+    right_scaling[npt + 1:] = scale
+
+    eig_values, eig_vectors = eigh(a, check_finite=False)
+
+    new_cache = {
+        "xpt": np.copy(interpolation.xpt),
+        "a": np.copy(a),
+        "right_scaling": np.copy(right_scaling),
+        "eigh": (eig_values, eig_vectors),
+    }
+    interpolation._lhs_cache = new_cache
+
+    return a, right_scaling, (eig_values, eig_vectors)
+
+
+class Quadratic:
+    """
+    Quadratic model.
+
+    This class stores the Hessian matrix of the quadratic model using the
+    implicit/explicit representation designed by Powell for NEWUOA [1]_.
+
+    References
+    ----------
+    .. [1] M. J. D. Powell. The NEWUOA software for unconstrained optimization
+       without derivatives. In G. Di Pillo and M. Roma, editors, *Large-Scale
+       Nonlinear Optimization*, volume 83 of Nonconvex Optim. Appl., pages
+       255--297. Springer, Boston, MA, USA, 2006. `doi:10.1007/0-387-30065-1_16
+       `_.
+    """
+
+    def __init__(self, interpolation, values, debug):
+        """
+        Initialize the quadratic model.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        values : `numpy.ndarray`, shape (npt,)
+            Values of the interpolated function at the interpolation points.
+        debug : bool
+            Whether to make debugging tests during the execution.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        self._debug = debug
+        if self._debug:
+            assert values.shape == (
+                interpolation.npt,
+            ), "The shape of `values` is not valid."
+        if interpolation.npt < interpolation.n + 1:
+            raise ValueError(
+                f"The number of interpolation points must be at least "
+                f"{interpolation.n + 1}."
+            )
+        self._const, self._grad, self._i_hess, _ = self._get_model(
+            interpolation,
+            values,
+        )
+        self._e_hess = np.zeros((self.n, self.n))
+
+    def __call__(self, x, interpolation):
+        """
+        Evaluate the quadratic model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the quadratic model is evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        float
+            Value of the quadratic model at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        x_diff = x - interpolation.x_base
+        return (
+            self._const
+            + self._grad @ x_diff
+            + 0.5
+            * (
+                self._i_hess @ (interpolation.xpt.T @ x_diff) ** 2.0
+                + x_diff @ self._e_hess @ x_diff
+            )
+        )
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self._grad.size
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points used to define the quadratic model.
+
+        Returns
+        -------
+        int
+            Number of interpolation points used to define the quadratic model.
+        """
+        return self._i_hess.size
+
+    def grad(self, x, interpolation):
+        """
+        Evaluate the gradient of the quadratic model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the gradient of the quadratic model is evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        x_diff = x - interpolation.x_base
+        return self._grad + self.hess_prod(x_diff, interpolation)
+
+    def hess(self, interpolation):
+        """
+        Evaluate the Hessian matrix of the quadratic model.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the quadratic model.
+        """
+        return self._e_hess + interpolation.xpt @ (
+            self._i_hess[:, np.newaxis] * interpolation.xpt.T
+        )
+
+    def hess_prod(self, v, interpolation):
+        """
+        Evaluate the right product of the Hessian matrix of the quadratic model
+        with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the quadratic model is
+            multiplied from the right.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the quadratic model with
+            `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._e_hess @ v + interpolation.xpt @ (
+            self._i_hess * (interpolation.xpt.T @ v)
+        )
+
+    def curv(self, v, interpolation):
+        """
+        Evaluate the curvature of the quadratic model along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic model is
+            evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        float
+            Curvature of the quadratic model along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return (
+            v @ self._e_hess @ v
+            + self._i_hess @ (interpolation.xpt.T @ v) ** 2.0
+        )
+
+    def update(self, interpolation, k_new, dir_old, values_diff):
+        """
+        Update the quadratic model.
+
+        This method applies the derivative-free symmetric Broyden update to the
+        quadratic model. The `knew`-th interpolation point must be updated
+        before calling this method.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Updated interpolation set.
+        k_new : int
+            Index of the updated interpolation point.
+        dir_old : `numpy.ndarray`, shape (n,)
+            Value of ``interpolation.xpt[:, k_new]`` before the update.
+        values_diff : `numpy.ndarray`, shape (npt,)
+            Differences between the values of the interpolated nonlinear
+            function and the previous quadratic model at the updated
+            interpolation points.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
+            assert dir_old.shape == (
+                self.n,
+            ), "The shape of `dir_old` is not valid."
+            assert values_diff.shape == (
+                self.npt,
+            ), "The shape of `values_diff` is not valid."
+
+        # Forward the k_new-th element of the implicit Hessian matrix to the
+        # explicit Hessian matrix. This must be done because the implicit
+        # Hessian matrix is related to the interpolation points, and the
+        # k_new-th interpolation point is modified.
+        self._e_hess += self._i_hess[k_new] * np.outer(dir_old, dir_old)
+        self._i_hess[k_new] = 0.0
+
+        # Update the quadratic model.
+        const, grad, i_hess, ill_conditioned = self._get_model(
+            interpolation,
+            values_diff,
+        )
+        self._const += const
+        self._grad += grad
+        self._i_hess += i_hess
+        return ill_conditioned
+
+    def shift_x_base(self, interpolation, new_x_base):
+        """
+        Shift the point around which the quadratic model is defined.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Previous interpolation set.
+        new_x_base : `numpy.ndarray`, shape (n,)
+            Point that will replace ``interpolation.x_base``.
+        """
+        if self._debug:
+            assert new_x_base.shape == (
+                self.n,
+            ), "The shape of `new_x_base` is not valid."
+        self._const = self(new_x_base, interpolation)
+        self._grad = self.grad(new_x_base, interpolation)
+        shift = new_x_base - interpolation.x_base
+        update = np.outer(
+            shift,
+            (interpolation.xpt - 0.5 * shift[:, np.newaxis]) @ self._i_hess,
+        )
+        self._e_hess += update + update.T
+
+    @staticmethod
+    def solve_systems(interpolation, rhs):
+        """
+        Solve the interpolation systems.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        rhs : `numpy.ndarray`, shape (npt + n + 1, m)
+            Right-hand side vectors of the ``m`` interpolation systems.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt + n + 1, m)
+            Solutions of the interpolation systems.
+        `numpy.ndarray`, shape (m, )
+            Whether the interpolation systems are ill-conditioned.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation systems are ill-defined.
+        """
+        n, npt = interpolation.xpt.shape
+        assert (
+            rhs.ndim == 2 and rhs.shape[0] == npt + n + 1
+        ), "The shape of `rhs` is not valid."
+
+        # Build the left-hand side matrix of the interpolation system. The
+        # matrix below stores diag(left_scaling) * W * diag(right_scaling),
+        # where W is the theoretical matrix of the interpolation system. The
+        # left and right scaling matrices are chosen to keep the elements in
+        # the matrix well-balanced.
+        a, right_scaling, eig = build_system(interpolation)
+
+        # Build the solution. After a discussion with Mike Saunders and Alexis
+        # Montoison during their visit to the Hong Kong Polytechnic University
+        # in 2024, we decided to use the eigendecomposition of the symmetric
+        # matrix a. This is more stable than the previously employed LBL
+        # decomposition, and allows us to directly detect ill-conditioning of
+        # the system and to build the least-squares solution if necessary.
+        # Numerical experiments have shown that this strategy improves the
+        # performance of the solver.
+        rhs_scaled = rhs * right_scaling[:, np.newaxis]
+        if not (np.all(np.isfinite(a)) and np.all(np.isfinite(rhs_scaled))):
+            raise np.linalg.LinAlgError(
+                "The interpolation system is ill-defined."
+            )
+
+        # calculated in build_system
+        eig_values, eig_vectors = eig
+
+        large_eig_values = np.abs(eig_values) > EPS
+        eig_vectors = eig_vectors[:, large_eig_values]
+        inv_eig_values = 1.0 / eig_values[large_eig_values]
+        ill_conditioned = ~np.all(large_eig_values, 0)
+        left_scaled_solutions = eig_vectors @ (
+            (eig_vectors.T @ rhs_scaled) * inv_eig_values[:, np.newaxis]
+        )
+        return (
+            left_scaled_solutions * right_scaling[:, np.newaxis],
+            ill_conditioned,
+        )
+
+    @staticmethod
+    def _get_model(interpolation, values):
+        """
+        Solve the interpolation system.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        values : `numpy.ndarray`, shape (npt,)
+            Values of the interpolated function at the interpolation points.
+
+        Returns
+        -------
+        float
+            Constant term of the quadratic model.
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model at ``interpolation.x_base``.
+        `numpy.ndarray`, shape (npt,)
+            Implicit Hessian matrix of the quadratic model.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        assert values.shape == (
+            interpolation.npt,
+        ), "The shape of `values` is not valid."
+        n, npt = interpolation.xpt.shape
+        x, ill_conditioned = Quadratic.solve_systems(
+            interpolation,
+            np.block(
+                [
+                    [
+                        values,
+                        np.zeros(n + 1),
+                    ]
+                ]
+            ).T,
+        )
+        return x[npt, 0], x[npt + 1:, 0], x[:npt, 0], ill_conditioned
+
+
+class Models:
+    """
+    Models for a nonlinear optimization problem.
+    """
+
+    def __init__(self, pb, options, penalty):
+        """
+        Initialize the models.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to be solved.
+        options : dict
+            Options of the solver.
+        penalty : float
+            Penalty parameter used to select the point in the filter to forward
+            to the callback function.
+
+        Raises
+        ------
+        `cobyqa.utils.MaxEvalError`
+            If the maximum number of evaluations is reached.
+        `cobyqa.utils.TargetSuccess`
+            If a nearly feasible point has been found with an objective
+            function value below the target.
+        `cobyqa.utils.FeasibleSuccess`
+            If a feasible point has been found for a feasibility problem.
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        # Set the initial interpolation set.
+        self._debug = options[Options.DEBUG]
+        self._interpolation = Interpolation(pb, options)
+
+        # Evaluate the nonlinear functions at the initial interpolation points.
+        x_eval = self.interpolation.point(0)
+        fun_init, cub_init, ceq_init = pb(x_eval, penalty)
+        self._fun_val = np.full(options[Options.NPT], np.nan)
+        self._cub_val = np.full((options[Options.NPT], cub_init.size), np.nan)
+        self._ceq_val = np.full((options[Options.NPT], ceq_init.size), np.nan)
+        for k in range(options[Options.NPT]):
+            if k >= options[Options.MAX_EVAL]:
+                raise MaxEvalError
+            if k == 0:
+                self.fun_val[k] = fun_init
+                self.cub_val[k, :] = cub_init
+                self.ceq_val[k, :] = ceq_init
+            else:
+                x_eval = self.interpolation.point(k)
+                self.fun_val[k], self.cub_val[k, :], self.ceq_val[k, :] = pb(
+                    x_eval,
+                    penalty,
+                )
+
+            # Stop the iterations if the problem is a feasibility problem and
+            # the current interpolation point is feasible.
+            if (
+                pb.is_feasibility
+                and pb.maxcv(
+                    self.interpolation.point(k),
+                    self.cub_val[k, :],
+                    self.ceq_val[k, :],
+                )
+                <= options[Options.FEASIBILITY_TOL]
+            ):
+                raise FeasibleSuccess
+
+            # Stop the iterations if the current interpolation point is nearly
+            # feasible and has an objective function value below the target.
+            if (
+                self._fun_val[k] <= options[Options.TARGET]
+                and pb.maxcv(
+                    self.interpolation.point(k),
+                    self.cub_val[k, :],
+                    self.ceq_val[k, :],
+                )
+                <= options[Options.FEASIBILITY_TOL]
+            ):
+                raise TargetSuccess
+
+        # Build the initial quadratic models.
+        self._fun = Quadratic(
+            self.interpolation,
+            self._fun_val,
+            options[Options.DEBUG],
+        )
+        self._cub = np.empty(self.m_nonlinear_ub, dtype=Quadratic)
+        self._ceq = np.empty(self.m_nonlinear_eq, dtype=Quadratic)
+        for i in range(self.m_nonlinear_ub):
+            self._cub[i] = Quadratic(
+                self.interpolation,
+                self.cub_val[:, i],
+                options[Options.DEBUG],
+            )
+        for i in range(self.m_nonlinear_eq):
+            self._ceq[i] = Quadratic(
+                self.interpolation,
+                self.ceq_val[:, i],
+                options[Options.DEBUG],
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+
+    @property
+    def n(self):
+        """
+        Dimension of the problem.
+
+        Returns
+        -------
+        int
+            Dimension of the problem.
+        """
+        return self.interpolation.n
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points.
+
+        Returns
+        -------
+        int
+            Number of interpolation points.
+        """
+        return self.interpolation.npt
+
+    @property
+    def m_nonlinear_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+        """
+        return self.cub_val.shape[1]
+
+    @property
+    def m_nonlinear_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+        """
+        return self.ceq_val.shape[1]
+
+    @property
+    def interpolation(self):
+        """
+        Interpolation set.
+
+        Returns
+        -------
+        `cobyqa.models.Interpolation`
+            Interpolation set.
+        """
+        return self._interpolation
+
+    @property
+    def fun_val(self):
+        """
+        Values of the objective function at the interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt,)
+            Values of the objective function at the interpolation points.
+        """
+        return self._fun_val
+
+    @property
+    def cub_val(self):
+        """
+        Values of the nonlinear inequality constraint functions at the
+        interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt, m_nonlinear_ub)
+            Values of the nonlinear inequality constraint functions at the
+            interpolation points.
+        """
+        return self._cub_val
+
+    @property
+    def ceq_val(self):
+        """
+        Values of the nonlinear equality constraint functions at the
+        interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt, m_nonlinear_eq)
+            Values of the nonlinear equality constraint functions at the
+            interpolation points.
+        """
+        return self._ceq_val
+
+    def fun(self, x):
+        """
+        Evaluate the quadratic model of the objective function at a given
+        point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic model of the objective
+            function.
+
+        Returns
+        -------
+        float
+            Value of the quadratic model of the objective function at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        return self._fun(x, self.interpolation)
+
+    def fun_grad(self, x):
+        """
+        Evaluate the gradient of the quadratic model of the objective function
+        at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradient of the quadratic model of
+            the objective function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model of the objective function at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        return self._fun.grad(x, self.interpolation)
+
+    def fun_hess(self):
+        """
+        Evaluate the Hessian matrix of the quadratic model of the objective
+        function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the quadratic model of the objective function.
+        """
+        return self._fun.hess(self.interpolation)
+
+    def fun_hess_prod(self, v):
+        """
+        Evaluate the right product of the Hessian matrix of the quadratic model
+        of the objective function with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the quadratic model of the
+            objective function is multiplied from the right.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the quadratic model of the
+            objective function with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._fun.hess_prod(v, self.interpolation)
+
+    def fun_curv(self, v):
+        """
+        Evaluate the curvature of the quadratic model of the objective function
+        along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic model of the
+            objective function is evaluated.
+
+        Returns
+        -------
+        float
+            Curvature of the quadratic model of the objective function along
+            `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._fun.curv(v, self.interpolation)
+
+    def fun_alt_grad(self, x):
+        """
+        Evaluate the gradient of the alternative quadratic model of the
+        objective function at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradient of the alternative
+            quadratic model of the objective function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the alternative quadratic model of the objective
+            function at `x`.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        model = Quadratic(self.interpolation, self.fun_val, self._debug)
+        return model.grad(x, self.interpolation)
+
+    def cub(self, x, mask=None):
+        """
+        Evaluate the quadratic models of the nonlinear inequality functions at
+        a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic models of the nonlinear
+            inequality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Values of the quadratic model of the nonlinear inequality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model(x, self.interpolation) for model in self._get_cub(mask)]
+        )
+
+    def cub_grad(self, x, mask=None):
+        """
+        Evaluate the gradients of the quadratic models of the nonlinear
+        inequality functions at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradients of the quadratic models of
+            the nonlinear inequality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Gradients of the quadratic model of the nonlinear inequality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.grad(x, self.interpolation)
+             for model in self._get_cub(mask)],
+            (-1, self.n),
+        )
+
+    def cub_hess(self, mask=None):
+        """
+        Evaluate the Hessian matrices of the quadratic models of the nonlinear
+        inequality functions.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Hessian matrices of the quadratic models of the nonlinear
+            inequality functions.
+        """
+        if self._debug:
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.hess(self.interpolation) for model in self._get_cub(mask)],
+            (-1, self.n, self.n),
+        )
+
+    def cub_hess_prod(self, v, mask=None):
+        """
+        Evaluate the right product of the Hessian matrices of the quadratic
+        models of the nonlinear inequality functions with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrices of the quadratic models of
+            the nonlinear inequality functions are multiplied from the right.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Right products of the Hessian matrices of the quadratic models of
+            the nonlinear inequality functions with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [
+                model.hess_prod(v, self.interpolation)
+                for model in self._get_cub(mask)
+            ],
+            (-1, self.n),
+        )
+
+    def cub_curv(self, v, mask=None):
+        """
+        Evaluate the curvature of the quadratic models of the nonlinear
+        inequality functions along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic models of the
+            nonlinear inequality functions is evaluated.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Curvature of the quadratic models of the nonlinear inequality
+            functions along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model.curv(v, self.interpolation)
+             for model in self._get_cub(mask)]
+        )
+
+    def ceq(self, x, mask=None):
+        """
+        Evaluate the quadratic models of the nonlinear equality functions at a
+        given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic models of the nonlinear
+            equality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Values of the quadratic model of the nonlinear equality functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model(x, self.interpolation) for model in self._get_ceq(mask)]
+        )
+
+    def ceq_grad(self, x, mask=None):
+        """
+        Evaluate the gradients of the quadratic models of the nonlinear
+        equality functions at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradients of the quadratic models of
+            the nonlinear equality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Gradients of the quadratic model of the nonlinear equality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.grad(x, self.interpolation)
+             for model in self._get_ceq(mask)],
+            (-1, self.n),
+        )
+
+    def ceq_hess(self, mask=None):
+        """
+        Evaluate the Hessian matrices of the quadratic models of the nonlinear
+        equality functions.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Hessian matrices of the quadratic models of the nonlinear equality
+            functions.
+        """
+        if self._debug:
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.hess(self.interpolation) for model in self._get_ceq(mask)],
+            (-1, self.n, self.n),
+        )
+
+    def ceq_hess_prod(self, v, mask=None):
+        """
+        Evaluate the right product of the Hessian matrices of the quadratic
+        models of the nonlinear equality functions with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrices of the quadratic models of
+            the nonlinear equality functions are multiplied from the right.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Right products of the Hessian matrices of the quadratic models of
+            the nonlinear equality functions with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [
+                model.hess_prod(v, self.interpolation)
+                for model in self._get_ceq(mask)
+            ],
+            (-1, self.n),
+        )
+
+    def ceq_curv(self, v, mask=None):
+        """
+        Evaluate the curvature of the quadratic models of the nonlinear
+        equality functions along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic models of the
+            nonlinear equality functions is evaluated.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Curvature of the quadratic models of the nonlinear equality
+            functions along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model.curv(v, self.interpolation)
+             for model in self._get_ceq(mask)]
+        )
+
+    def reset_models(self):
+        """
+        Set the quadratic models of the objective function, nonlinear
+        inequality constraints, and nonlinear equality constraints to the
+        alternative quadratic models.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        self._fun = Quadratic(self.interpolation, self.fun_val, self._debug)
+        for i in range(self.m_nonlinear_ub):
+            self._cub[i] = Quadratic(
+                self.interpolation,
+                self.cub_val[:, i],
+                self._debug,
+            )
+        for i in range(self.m_nonlinear_eq):
+            self._ceq[i] = Quadratic(
+                self.interpolation,
+                self.ceq_val[:, i],
+                self._debug,
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+
+    def update_interpolation(self, k_new, x_new, fun_val, cub_val, ceq_val):
+        """
+        Update the interpolation set.
+
+        This method updates the interpolation set by replacing the `knew`-th
+        interpolation point with `xnew`. It also updates the function values
+        and the quadratic models.
+
+        Parameters
+        ----------
+        k_new : int
+            Index of the updated interpolation point.
+        x_new : `numpy.ndarray`, shape (n,)
+            New interpolation point. Its value is interpreted as relative to
+            the origin, not the base point.
+        fun_val : float
+            Value of the objective function at `x_new`.
+            Objective function value at `x_new`.
+        cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Values of the nonlinear inequality constraints at `x_new`.
+        ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Values of the nonlinear equality constraints at `x_new`.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
+            assert x_new.shape == (self.n,), \
+                "The shape of `x_new` is not valid."
+            assert isinstance(fun_val, float), \
+                "The function value is not valid."
+            assert cub_val.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `cub_val` is not valid."
+            assert ceq_val.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `ceq_val` is not valid."
+
+        # Compute the updates in the interpolation conditions.
+        fun_diff = np.zeros(self.npt)
+        cub_diff = np.zeros(self.cub_val.shape)
+        ceq_diff = np.zeros(self.ceq_val.shape)
+        fun_diff[k_new] = fun_val - self.fun(x_new)
+        cub_diff[k_new, :] = cub_val - self.cub(x_new)
+        ceq_diff[k_new, :] = ceq_val - self.ceq(x_new)
+
+        # Update the function values.
+        self.fun_val[k_new] = fun_val
+        self.cub_val[k_new, :] = cub_val
+        self.ceq_val[k_new, :] = ceq_val
+
+        # Update the interpolation set.
+        dir_old = np.copy(self.interpolation.xpt[:, k_new])
+        self.interpolation.xpt[:, k_new] = x_new - self.interpolation.x_base
+
+        # Update the quadratic models.
+        ill_conditioned = self._fun.update(
+            self.interpolation,
+            k_new,
+            dir_old,
+            fun_diff,
+        )
+        for i in range(self.m_nonlinear_ub):
+            ill_conditioned = ill_conditioned or self._cub[i].update(
+                self.interpolation,
+                k_new,
+                dir_old,
+                cub_diff[:, i],
+            )
+        for i in range(self.m_nonlinear_eq):
+            ill_conditioned = ill_conditioned or self._ceq[i].update(
+                self.interpolation,
+                k_new,
+                dir_old,
+                ceq_diff[:, i],
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+        return ill_conditioned
+
+    def determinants(self, x_new, k_new=None):
+        """
+        Compute the normalized determinants of the new interpolation systems.
+
+        Parameters
+        ----------
+        x_new : `numpy.ndarray`, shape (n,)
+            New interpolation point. Its value is interpreted as relative to
+            the origin, not the base point.
+        k_new : int, optional
+            Index of the updated interpolation point. If `k_new` is not
+            specified, all the possible determinants are computed.
+
+        Returns
+        -------
+        {float, `numpy.ndarray`, shape (npt,)}
+            Determinant(s) of the new interpolation system.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+
+        Notes
+        -----
+        The determinants are normalized by the determinant of the current
+        interpolation system. For stability reasons, the calculations are done
+        using the formula (2.12) in [1]_.
+
+        References
+        ----------
+        .. [1] M. J. D. Powell. On updating the inverse of a KKT matrix.
+           Technical Report DAMTP 2004/NA01, Department of Applied Mathematics
+           and Theoretical Physics, University of Cambridge, Cambridge, UK,
+           2004.
+        """
+        if self._debug:
+            assert x_new.shape == (self.n,), \
+                "The shape of `x_new` is not valid."
+            assert (
+                k_new is None or 0 <= k_new < self.npt
+            ), "The index `k_new` is not valid."
+
+        # Compute the values independent of k_new.
+        shift = x_new - self.interpolation.x_base
+        new_col = np.empty((self.npt + self.n + 1, 1))
+        new_col[: self.npt, 0] = (
+                0.5 * (self.interpolation.xpt.T @ shift) ** 2.0)
+        new_col[self.npt, 0] = 1.0
+        new_col[self.npt + 1:, 0] = shift
+        inv_new_col = Quadratic.solve_systems(self.interpolation, new_col)[0]
+        beta = 0.5 * (shift @ shift) ** 2.0 - new_col[:, 0] @ inv_new_col[:, 0]
+
+        # Compute the values that depend on k.
+        if k_new is None:
+            coord_vec = np.eye(self.npt + self.n + 1, self.npt)
+            alpha = np.diag(
+                Quadratic.solve_systems(
+                    self.interpolation,
+                    coord_vec,
+                )[0]
+            )
+            tau = inv_new_col[: self.npt, 0]
+        else:
+            coord_vec = np.eye(self.npt + self.n + 1, 1, -k_new)
+            alpha = Quadratic.solve_systems(
+                self.interpolation,
+                coord_vec,
+            )[
+                0
+            ][k_new, 0]
+            tau = inv_new_col[k_new, 0]
+        return alpha * beta + tau**2.0
+
+    def shift_x_base(self, new_x_base, options):
+        """
+        Shift the base point without changing the interpolation set.
+
+        Parameters
+        ----------
+        new_x_base : `numpy.ndarray`, shape (n,)
+            New base point.
+        options : dict
+            Options of the solver.
+        """
+        if self._debug:
+            assert new_x_base.shape == (
+                self.n,
+            ), "The shape of `new_x_base` is not valid."
+
+        # Update the models.
+        self._fun.shift_x_base(self.interpolation, new_x_base)
+        for model in self._cub:
+            model.shift_x_base(self.interpolation, new_x_base)
+        for model in self._ceq:
+            model.shift_x_base(self.interpolation, new_x_base)
+
+        # Update the base point and the interpolation points.
+        shift = new_x_base - self.interpolation.x_base
+        self.interpolation.x_base += shift
+        self.interpolation.xpt -= shift[:, np.newaxis]
+        if options[Options.DEBUG]:
+            self._check_interpolation_conditions()
+
+    def _get_cub(self, mask=None):
+        """
+        Get the quadratic models of the nonlinear inequality constraints.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to return.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Quadratic models of the nonlinear inequality constraints.
+        """
+        return self._cub if mask is None else self._cub[mask]
+
+    def _get_ceq(self, mask=None):
+        """
+        Get the quadratic models of the nonlinear equality constraints.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to return.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Quadratic models of the nonlinear equality constraints.
+        """
+        return self._ceq if mask is None else self._ceq[mask]
+
+    def _check_interpolation_conditions(self):
+        """
+        Check the interpolation conditions of all quadratic models.
+        """
+        error_fun = 0.0
+        error_cub = 0.0
+        error_ceq = 0.0
+        for k in range(self.npt):
+            error_fun = np.max(
+                [
+                    error_fun,
+                    np.abs(
+                        self.fun(self.interpolation.point(k)) - self.fun_val[k]
+                    ),
+                ]
+            )
+            error_cub = np.max(
+                np.abs(
+                    self.cub(self.interpolation.point(k)) - self.cub_val[k, :]
+                ),
+                initial=error_cub,
+            )
+            error_ceq = np.max(
+                np.abs(
+                    self.ceq(self.interpolation.point(k)) - self.ceq_val[k, :]
+                ),
+                initial=error_ceq,
+            )
+        tol = 10.0 * np.sqrt(EPS) * max(self.n, self.npt)
+        if error_fun > tol * np.max(np.abs(self.fun_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the objective function are "
+                "not satisfied.",
+                RuntimeWarning,
+                2,
+            )
+        if error_cub > tol * np.max(np.abs(self.cub_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the inequality constraint "
+                "function are not satisfied.",
+                RuntimeWarning,
+                2,
+            )
+        if error_ceq > tol * np.max(np.abs(self.ceq_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the equality constraint "
+                "function are not satisfied.",
+                RuntimeWarning,
+                2,
+            )
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/problem.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/problem.py
new file mode 100644
index 0000000000000000000000000000000000000000..046441a76486eab3d665af26147f6843d8bfaef2
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/settings.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..fec9a091c40f7da974c8752e2143c67922483c77
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..43719b8a45d6b56b2f088fc2466d1b3cee4d951d
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..65bb0620a21391faa01f102523c6dd220d3d36ca
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py
new file mode 100644
index 0000000000000000000000000000000000000000..8638f2b382b01d2b9051a31fcbe6e6945dcf638d
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff8d6fb0c047ae54e7e1fa68e96cbd023c228c69
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/exceptions.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bb1bf42be088e26ca74f6aadcb7bc3199a43c3b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/math.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/math.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dd197a890f23107f830fe3dc2742a0ea59313f9
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/versions.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/cobyqa/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..386d01e691adeaa9ddfc3138ed1fa2254dda8f41
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/deprecation.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..85d34d2fe291fd0c770df28c4aecb9825b18b430
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/deprecation.py
@@ -0,0 +1,274 @@
+from inspect import Parameter, signature
+import functools
+import warnings
+from importlib import import_module
+from scipy._lib._docscrape import FunctionDoc
+
+
+__all__ = ["_deprecated"]
+
+
+# Object to use as default value for arguments to be deprecated. This should
+# be used over 'None' as the user could parse 'None' as a positional argument
+_NoValue = object()
+
+def _sub_module_deprecation(*, sub_package, module, private_modules, all,
+                            attribute, correct_module=None, dep_version="1.16.0"):
+    """Helper function for deprecating modules that are public but were
+    intended to be private.
+
+    Parameters
+    ----------
+    sub_package : str
+        Subpackage the module belongs to eg. stats
+    module : str
+        Public but intended private module to deprecate
+    private_modules : list
+        Private replacement(s) for `module`; should contain the
+        content of ``all``, possibly spread over several modules.
+    all : list
+        ``__all__`` belonging to `module`
+    attribute : str
+        The attribute in `module` being accessed
+    correct_module : str, optional
+        Module in `sub_package` that `attribute` should be imported from.
+        Default is that `attribute` should be imported from ``scipy.sub_package``.
+    dep_version : str, optional
+        Version in which deprecated attributes will be removed.
+    """
+    if correct_module is not None:
+        correct_import = f"scipy.{sub_package}.{correct_module}"
+    else:
+        correct_import = f"scipy.{sub_package}"
+
+    if attribute not in all:
+        raise AttributeError(
+            f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
+            f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+
+    attr = getattr(import_module(correct_import), attribute, None)
+
+    if attr is not None:
+        message = (
+            f"Please import `{attribute}` from the `{correct_import}` namespace; "
+            f"the `scipy.{sub_package}.{module}` namespace is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+    else:
+        message = (
+            f"`scipy.{sub_package}.{module}.{attribute}` is deprecated along with "
+            f"the `scipy.{sub_package}.{module}` namespace. "
+            f"`scipy.{sub_package}.{module}.{attribute}` will be removed "
+            f"in SciPy {dep_version}, and the `scipy.{sub_package}.{module}` namespace "
+            f"will be removed in SciPy 2.0.0."
+        )
+
+    warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+    for module in private_modules:
+        try:
+            return getattr(import_module(f"scipy.{sub_package}.{module}"), attribute)
+        except AttributeError as e:
+            # still raise an error if the attribute isn't in any of the expected
+            # private modules
+            if module == private_modules[-1]:
+                raise e
+            continue
+    
+
+def _deprecated(msg, stacklevel=2):
+    """Deprecate a function by emitting a warning on use."""
+    def wrap(fun):
+        if isinstance(fun, type):
+            warnings.warn(
+                f"Trying to deprecate class {fun!r}",
+                category=RuntimeWarning, stacklevel=2)
+            return fun
+
+        @functools.wraps(fun)
+        def call(*args, **kwargs):
+            warnings.warn(msg, category=DeprecationWarning,
+                          stacklevel=stacklevel)
+            return fun(*args, **kwargs)
+        call.__doc__ = fun.__doc__
+        return call
+
+    return wrap
+
+
+class _DeprecationHelperStr:
+    """
+    Helper class used by deprecate_cython_api
+    """
+    def __init__(self, content, message):
+        self._content = content
+        self._message = message
+
+    def __hash__(self):
+        return hash(self._content)
+
+    def __eq__(self, other):
+        res = (self._content == other)
+        if res:
+            warnings.warn(self._message, category=DeprecationWarning,
+                          stacklevel=2)
+        return res
+
+
+def deprecate_cython_api(module, routine_name, new_name=None, message=None):
+    """
+    Deprecate an exported cdef function in a public Cython API module.
+
+    Only functions can be deprecated; typedefs etc. cannot.
+
+    Parameters
+    ----------
+    module : module
+        Public Cython API module (e.g. scipy.linalg.cython_blas).
+    routine_name : str
+        Name of the routine to deprecate. May also be a fused-type
+        routine (in which case its all specializations are deprecated).
+    new_name : str
+        New name to include in the deprecation warning message
+    message : str
+        Additional text in the deprecation warning message
+
+    Examples
+    --------
+    Usually, this function would be used in the top-level of the
+    module ``.pyx`` file:
+
+    >>> from scipy._lib.deprecation import deprecate_cython_api
+    >>> import scipy.linalg.cython_blas as mod
+    >>> deprecate_cython_api(mod, "dgemm", "dgemm_new",
+    ...                      message="Deprecated in Scipy 1.5.0")
+    >>> del deprecate_cython_api, mod
+
+    After this, Cython modules that use the deprecated function emit a
+    deprecation warning when they are imported.
+
+    """
+    old_name = f"{module.__name__}.{routine_name}"
+
+    if new_name is None:
+        depdoc = f"`{old_name}` is deprecated!"
+    else:
+        depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
+
+    if message is not None:
+        depdoc += "\n" + message
+
+    d = module.__pyx_capi__
+
+    # Check if the function is a fused-type function with a mangled name
+    j = 0
+    has_fused = False
+    while True:
+        fused_name = f"__pyx_fuse_{j}{routine_name}"
+        if fused_name in d:
+            has_fused = True
+            d[_DeprecationHelperStr(fused_name, depdoc)] = d.pop(fused_name)
+            j += 1
+        else:
+            break
+
+    # If not, apply deprecation to the named routine
+    if not has_fused:
+        d[_DeprecationHelperStr(routine_name, depdoc)] = d.pop(routine_name)
+
+
+# taken from scikit-learn, see
+# https://github.com/scikit-learn/scikit-learn/blob/1.3.0/sklearn/utils/validation.py#L38
+def _deprecate_positional_args(func=None, *, version=None,
+                               deprecated_args=None, custom_message=""):
+    """Decorator for methods that issues warnings for positional arguments.
+
+    Using the keyword-only argument syntax in pep 3102, arguments after the
+    * will issue a warning when passed as a positional argument.
+
+    Parameters
+    ----------
+    func : callable, default=None
+        Function to check arguments on.
+    version : callable, default=None
+        The version when positional arguments will result in error.
+    deprecated_args : set of str, optional
+        Arguments to deprecate - whether passed by position or keyword.
+    custom_message : str, optional
+        Custom message to add to deprecation warning and documentation.
+    """
+    if version is None:
+        msg = "Need to specify a version where signature will be changed"
+        raise ValueError(msg)
+
+    deprecated_args = set() if deprecated_args is None else set(deprecated_args)
+
+    def _inner_deprecate_positional_args(f):
+        sig = signature(f)
+        kwonly_args = []
+        all_args = []
+
+        for name, param in sig.parameters.items():
+            if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
+                all_args.append(name)
+            elif param.kind == Parameter.KEYWORD_ONLY:
+                kwonly_args.append(name)
+
+        def warn_deprecated_args(kwargs):
+            intersection = deprecated_args.intersection(kwargs)
+            if intersection:
+                message = (f"Arguments {intersection} are deprecated, whether passed "
+                           "by position or keyword. They will be removed in SciPy "
+                           f"{version}. ")
+                message += custom_message
+                warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+        @functools.wraps(f)
+        def inner_f(*args, **kwargs):
+
+            extra_args = len(args) - len(all_args)
+            if extra_args <= 0:
+                warn_deprecated_args(kwargs)
+                return f(*args, **kwargs)
+
+            # extra_args > 0
+            kwonly_extra_args = set(kwonly_args[:extra_args]) - deprecated_args
+            args_msg = ", ".join(kwonly_extra_args)
+            warnings.warn(
+                (
+                    f"You are passing as positional arguments: {args_msg}. "
+                    "Please change your invocation to use keyword arguments. "
+                    f"From SciPy {version}, passing these as positional "
+                    "arguments will result in an error."
+                ),
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            kwargs.update(zip(sig.parameters, args))
+            warn_deprecated_args(kwargs)
+            return f(**kwargs)
+
+        doc = FunctionDoc(inner_f)
+        kwonly_extra_args = set(kwonly_args) - deprecated_args
+        admonition = f"""
+.. deprecated:: {version}
+    Use of argument(s) ``{kwonly_extra_args}`` by position is deprecated; beginning in 
+    SciPy {version}, these will be keyword-only. """
+        if deprecated_args:
+            admonition += (f"Argument(s) ``{deprecated_args}`` are deprecated, whether "
+                           "passed by position or keyword; they will be removed in "
+                           f"SciPy {version}. ")
+        admonition += custom_message
+        doc['Extended Summary'] += [admonition]
+
+        doc = str(doc).split("\n", 1)[1].lstrip(" \n")  # remove signature
+        inner_f.__doc__ = str(doc)
+
+        return inner_f
+
+    if func is not None:
+        return _inner_deprecate_positional_args(func)
+
+    return _inner_deprecate_positional_args
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/doccer.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..20e625b0c2ac0cc2b81d8bce0dfd071b95bc4fc4
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/doccer.py
@@ -0,0 +1,366 @@
+"""Utilities to allow inserting docstring fragments for common
+parameters into function and method docstrings."""
+
+from collections.abc import Callable, Iterable, Mapping
+from typing import Protocol, TypeVar
+import sys
+
+__all__ = [
+    "docformat",
+    "inherit_docstring_from",
+    "indentcount_lines",
+    "filldoc",
+    "unindent_dict",
+    "unindent_string",
+    "extend_notes_in_docstring",
+    "replace_notes_in_docstring",
+    "doc_replace",
+]
+
+_F = TypeVar("_F", bound=Callable[..., object])
+
+
+class Decorator(Protocol):
+    """A decorator of a function."""
+
+    def __call__(self, func: _F, /) -> _F: ...
+
+
+def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str:
+    """Fill a function docstring from variables in dictionary.
+
+    Adapt the indent of the inserted docs
+
+    Parameters
+    ----------
+    docstring : str
+        A docstring from a function, possibly with dict formatting strings.
+    docdict : dict[str, str], optional
+        A dictionary with keys that match the dict formatting strings
+        and values that are docstring fragments to be inserted. The
+        indentation of the inserted docstrings is set to match the
+        minimum indentation of the ``docstring`` by adding this
+        indentation to all lines of the inserted string, except the
+        first.
+
+    Returns
+    -------
+    docstring : str
+        string with requested ``docdict`` strings inserted.
+
+    Examples
+    --------
+    >>> docformat(' Test string with %(value)s', {'value':'inserted value'})
+    ' Test string with inserted value'
+    >>> docstring = 'First line\\n    Second line\\n    %(value)s'
+    >>> inserted_string = "indented\\nstring"
+    >>> docdict = {'value': inserted_string}
+    >>> docformat(docstring, docdict)
+    'First line\\n    Second line\\n    indented\\n    string'
+    """
+    if not docstring:
+        return docstring
+    if docdict is None:
+        docdict = {}
+    if not docdict:
+        return docstring
+    lines = docstring.expandtabs().splitlines()
+    # Find the minimum indent of the main docstring, after first line
+    if len(lines) < 2:
+        icount = 0
+    else:
+        icount = indentcount_lines(lines[1:])
+    indent = " " * icount
+    # Insert this indent to dictionary docstrings
+    indented = {}
+    for name, dstr in docdict.items():
+        lines = dstr.expandtabs().splitlines()
+        indented[name] = ("\n" + indent).join(lines)
+    return docstring % indented
+
+
+def inherit_docstring_from(cls: object) -> Decorator:
+    """This decorator modifies the decorated function's docstring by
+    replacing occurrences of '%(super)s' with the docstring of the
+    method of the same name from the class `cls`.
+
+    If the decorated method has no docstring, it is simply given the
+    docstring of `cls`s method.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces '%(super)s' in the
+        docstring of the decorated method.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+
+    Examples
+    --------
+    In the following, the docstring for Bar.func created using the
+    docstring of `Foo.func`.
+
+    >>> class Foo:
+    ...     def func(self):
+    ...         '''Do something useful.'''
+    ...         return
+    ...
+    >>> class Bar(Foo):
+    ...     @inherit_docstring_from(Foo)
+    ...     def func(self):
+    ...         '''%(super)s
+    ...         Do it fast.
+    ...         '''
+    ...         return
+    ...
+    >>> b = Bar()
+    >>> b.func.__doc__
+    'Do something useful.\n        Do it fast.\n        '
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        func_docstring = func.__doc__
+        if func_docstring is None:
+            func.__doc__ = cls_docstring
+        else:
+            new_docstring = func_docstring % dict(super=cls_docstring)
+            func.__doc__ = new_docstring
+        return func
+
+    return _doc
+
+
+def extend_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It extends the 'Notes' section of that docstring to include
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        Additional notes to append to the 'Notes' section of the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def replace_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It replaces the 'Notes' section of that docstring with
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        The notes to replace the existing 'Notes' section with.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        notes_header = "        Notes\n        -----\n"
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        start_of_notes = cls_docstring.find(notes_header)
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[: start_of_notes + len(notes_header)]
+            + notes
+            + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def indentcount_lines(lines: Iterable[str]) -> int:
+    """Minimum indent for all lines in line list
+
+    Parameters
+    ----------
+    lines : Iterable[str]
+        The lines to find the minimum indent of.
+
+    Returns
+    -------
+    indent : int
+        The minimum indent.
+
+
+    Examples
+    --------
+    >>> lines = [' one', '  two', '   three']
+    >>> indentcount_lines(lines)
+    1
+    >>> lines = []
+    >>> indentcount_lines(lines)
+    0
+    >>> lines = [' one']
+    >>> indentcount_lines(lines)
+    1
+    >>> indentcount_lines(['    '])
+    0
+    """
+    indentno = sys.maxsize
+    for line in lines:
+        stripped = line.lstrip()
+        if stripped:
+            indentno = min(indentno, len(line) - len(stripped))
+    if indentno == sys.maxsize:
+        return 0
+    return indentno
+
+
+def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator:
+    """Return docstring decorator using docdict variable dictionary.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary containing name, docstring fragment pairs.
+    unindent_params : bool, optional
+        If True, strip common indentation from all parameters in docdict.
+        Default is False.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that applies dictionary to its
+        argument's __doc__ attribute.
+    """
+    if unindent_params:
+        docdict = unindent_dict(docdict)
+
+    def decorate(func: _F) -> _F:
+        # __doc__ may be None for optimized Python (-OO)
+        doc = func.__doc__ or ""
+        func.__doc__ = docformat(doc, docdict)
+        return func
+
+    return decorate
+
+
+def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]:
+    """Unindent all strings in a docdict.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary with string values to unindent.
+
+    Returns
+    -------
+    docdict : dict[str, str]
+        The `docdict` dictionary but each of its string values are unindented.
+    """
+    can_dict: dict[str, str] = {}
+    for name, dstr in docdict.items():
+        can_dict[name] = unindent_string(dstr)
+    return can_dict
+
+
+def unindent_string(docstring: str) -> str:
+    """Set docstring to minimum indent for all lines, including first.
+
+    Parameters
+    ----------
+    docstring : str
+        The input docstring to unindent.
+
+    Returns
+    -------
+    docstring : str
+        The unindented docstring.
+
+    Examples
+    --------
+    >>> unindent_string(' two')
+    'two'
+    >>> unindent_string('  two\\n   three')
+    'two\\n three'
+    """
+    lines = docstring.expandtabs().splitlines()
+    icount = indentcount_lines(lines)
+    if icount == 0:
+        return docstring
+    return "\n".join([line[icount:] for line in lines])
+
+
+def doc_replace(obj: object, oldval: str, newval: str) -> Decorator:
+    """Decorator to take the docstring from obj, with oldval replaced by newval
+
+    Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)``
+
+    Parameters
+    ----------
+    obj : object
+        A class or object whose docstring will be used as the basis for the
+        replacement operation.
+    oldval : str
+        The string to search for in the docstring.
+    newval : str
+        The string to replace `oldval` with in the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        A decorator function that replaces occurrences of `oldval` with `newval`
+        in the docstring of the decorated function.
+    """
+    # __doc__ may be None for optimized Python (-OO)
+    doc = (obj.__doc__ or "").replace(oldval, newval)
+
+    def inner(func: _F) -> _F:
+        func.__doc__ = doc
+        return func
+
+    return inner
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..4aa1a52c068467125b5738d54b21e29672f0af68
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..ec2f0ef0d3a584ea2bbeb65ad04fd47ffd543d55
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.pyd differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..791a7fb93cb8c69b9c73a20f737816e9eb550d29
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/__init__.py
@@ -0,0 +1,212 @@
+# Bounds may appear unused in this file but we need to import it to make it available to the user
+from scipy.optimize import NonlinearConstraint, LinearConstraint, Bounds
+from .common._nonlinear_constraints import process_nl_constraints
+from .common._linear_constraints import (
+    combine_multiple_linear_constraints,
+    separate_LC_into_eq_and_ineq,
+)
+from .common._bounds import process_bounds
+from enum import Enum
+from .common._project import _project
+from .common.linalg import get_arrays_tol
+from .cobyla.cobyla import cobyla
+import numpy as np
+from collections.abc import Iterable
+
+
+class ConstraintType(Enum):
+    LINEAR_OBJECT = 5
+    NONLINEAR_OBJECT = 10
+    LINEAR_DICT = 15
+    NONLINEAR_DICT = 20
+
+
+def get_constraint_type(constraint):
+    if isinstance(constraint, dict) and ("A" in constraint) and ("lb" in constraint) and ("ub" in constraint):
+        return ConstraintType.LINEAR_DICT
+    elif isinstance(constraint, dict) and ("fun" in constraint) and ("lb" in constraint) and ("ub" in constraint):
+        return ConstraintType.NONLINEAR_DICT
+    elif hasattr(constraint, "A") and hasattr(constraint, "lb") and hasattr(constraint, "ub"):
+        return ConstraintType.LINEAR_OBJECT
+    elif hasattr(constraint, "fun") and hasattr(constraint, "lb") and hasattr(constraint, "ub"):
+        return ConstraintType.NONLINEAR_OBJECT
+    else:
+        raise ValueError(f"Constraint type {type(constraint)} not recognized")
+
+
+def process_constraints(constraints):
+    # First throw it back if it's an empty tuple
+    if not constraints:
+        return None, None
+    # Next figure out if it's a list of constraints or a single constraint
+    # If it's a single constraint, make it a list, and then the remaining logic
+    # doesn't have to change
+    if not isinstance(constraints, Iterable):
+        constraints = [constraints]
+
+    # Separate out the linear and nonlinear constraints
+    linear_constraints = []
+    nonlinear_constraints = []
+    for constraint in constraints:
+        constraint_type = get_constraint_type(constraint)
+        if constraint_type is ConstraintType.LINEAR_OBJECT:
+            linear_constraints.append(constraint)
+        elif constraint_type is ConstraintType.NONLINEAR_OBJECT:
+            nonlinear_constraints.append(constraint)
+        elif constraint_type == ConstraintType.LINEAR_DICT:
+            linear_constraints.append(LinearConstraint(constraint["A"], constraint["lb"], constraint["ub"]))
+        elif constraint_type == ConstraintType.NONLINEAR_DICT:
+            nonlinear_constraints.append(NonlinearConstraint(constraint["fun"], constraint["lb"], constraint["ub"]))
+        else:
+            raise ValueError("Constraint type not recognized")
+
+    if len(nonlinear_constraints) > 0:
+        nonlinear_constraint_function = process_nl_constraints(nonlinear_constraints)
+    else:
+        nonlinear_constraint_function = None
+
+    # Determine if we have multiple linear constraints, just 1, or none, and process accordingly
+    if len(linear_constraints) > 1:
+        linear_constraint = combine_multiple_linear_constraints(linear_constraints)
+    elif len(linear_constraints) == 1:
+        linear_constraint = linear_constraints[0]
+    else:
+        linear_constraint = None
+
+    return linear_constraint, nonlinear_constraint_function
+
+
+def minimize(fun, x0, args=(), method=None, bounds=None, constraints=(), callback=None, options=None):
+
+    linear_constraint, nonlinear_constraint_function = process_constraints(constraints)
+
+    options = {'quiet': True} if options is None else options
+    quiet = options.get("quiet", True)
+
+    if method is None:
+        if nonlinear_constraint_function is not None:
+            if not quiet: print("Nonlinear constraints detected, applying COBYLA")
+            method = "cobyla"
+        elif linear_constraint is not None:
+            if not quiet: print("Linear constraints detected without nonlinear constraints, applying LINCOA")
+            method = "lincoa"
+        elif bounds is not None:
+            if not quiet: print("Bounds without linear or nonlinear constraints detected, applying BOBYQA")
+            method = "bobyqa"
+        else:
+            if not quiet: print("No bounds or constraints detected, applying NEWUOA")
+            method = "newuoa"
+    else:
+        # Raise some errors if methods were called with inappropriate options
+        method = method.lower()
+        if method not in ('newuoa', 'uobyqa', 'bobyqa', 'cobyla', 'lincoa'):
+            raise ValueError(f"Method must be one of NEWUOA, UOBYQA, BOBYQA, COBYLA, or LINCOA, not '{method}'")
+        if method != "cobyla" and nonlinear_constraint_function is not None:
+            raise ValueError("Nonlinear constraints were provided for an algorithm that cannot handle them")
+        if method not in ("cobyla", "lincoa") and linear_constraint is not None:
+            raise ValueError("Linear constraints were provided for an algorithm that cannot handle them")
+        if method not in ("cobyla", "bobyqa", "lincoa") and bounds is not None:
+            raise ValueError("Bounds were provided for an algorithm that cannot handle them")
+
+    # Try to get the length of x0. If we can't that likely means it's a scalar, and
+    # in that case we turn it into an array and wrap the original function so that it
+    # can accept an array and return a scalar.
+    try:
+        lenx0 = len(x0)
+    except TypeError:
+        x0 = np.array([x0])
+        original_scalar_fun = fun
+        def scalar_fun(x):
+            return original_scalar_fun(x[0], *args)
+        fun = scalar_fun
+        lenx0 = 1
+
+    lb, ub = process_bounds(bounds, lenx0)
+
+    # Check which variables are fixed and eliminate them from the problem.
+    # Save the indices and values so that we can call the original function with
+    # an array of the appropriate size, and so that we can add the fixed values to the
+    # result when COBYLA returns.
+    tol = get_arrays_tol(lb, ub)
+    _fixed_idx = (
+        (lb <= ub)
+        & (np.abs(lb - ub) < tol)
+    )
+    if any(_fixed_idx):
+        _fixed_values = 0.5 * (
+            lb[_fixed_idx] + ub[_fixed_idx]
+        )
+        _fixed_values = np.clip(
+            _fixed_values,
+            lb[_fixed_idx],
+            ub[_fixed_idx],
+        )
+        x0 = x0[~_fixed_idx]
+        lb = lb[~_fixed_idx]
+        ub = ub[~_fixed_idx]
+        original_fun = fun
+        def fixed_fun(x):
+            newx = np.zeros(lenx0)
+            newx[_fixed_idx] = _fixed_values
+            newx[~_fixed_idx] = x
+            return original_fun(newx, *args)
+        fun = fixed_fun
+
+
+    # Project x0 onto the feasible set
+    if nonlinear_constraint_function is None:
+        result = _project(x0, lb, ub, {"linear": linear_constraint, "nonlinear": None})
+        x0 = result.x
+    
+    if linear_constraint is not None:
+        A_eq, b_eq, A_ineq, b_ineq = separate_LC_into_eq_and_ineq(linear_constraint)
+    else:
+        A_eq, b_eq, A_ineq, b_ineq = None, None, None, None
+
+    if nonlinear_constraint_function is not None:
+        # If there is a nonlinear constraint function, we will call COBYLA, which needs the number of nonlinear
+        # constraints (m_nlcon). In order to get this number we need to evaluate the constraint function at x0.
+        # The constraint value at x0 (nlconstr0) is not discarded but passed down to the Fortran backend, as its
+        # evaluation is assumed to be expensive. We also evaluate the objective function at x0 and pass the result
+        # (f0) down to the Fortran backend, which expects nlconstr0 and f0 to be provided in sync.
+        def calcfc(x):
+            f = fun(x, *args)
+            nlconstr = nonlinear_constraint_function(x)
+            return f, nlconstr
+    else:
+        def calcfc(x):
+            f = fun(x, *args)
+            constr = np.zeros(0)
+            return f, constr
+
+    f0, nlconstr0 = calcfc(x0)
+
+    if 'quiet' in options:
+        del options['quiet']
+
+    if 'maxfev' in options:
+        options['maxfun'] = options['maxfev']
+        del options['maxfev']
+
+    result = cobyla(
+        calcfc,
+        len(nlconstr0),
+        x0,
+        A_ineq,
+        b_ineq,
+        A_eq,
+        b_eq,
+        lb,
+        ub,
+        f0=f0,
+        nlconstr0=nlconstr0,
+        callback=callback,
+        **options
+    )
+
+    if any(_fixed_idx):
+        newx = np.zeros(lenx0)
+        newx[_fixed_idx] = _fixed_values
+        newx[~_fixed_idx] = result.x
+        result.x = newx
+    return result
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/cobyla.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bd8b532fc44f530384ab5ef2fc0b34e570da28e
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/cobyla.py
@@ -0,0 +1,559 @@
+'''
+This module provides Powell's COBYLA algorithm.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+
+N.B.:
+
+1. The modern-Fortran reference implementation in PRIMA contains bug fixes and improvements over the
+original Fortran 77 implementation by Powell. Consequently, the PRIMA implementation behaves differently
+from the original Fortran 77 implementation by Powell. Therefore, it is important to point out that
+you are using PRIMA rather than the original solvers if you want your results to be reproducible.
+
+2. Compared to Powell's Fortran 77 implementation, the modern-Fortran implementation and hence any
+faithful translation like this one generally produce better solutions with fewer function evaluations,
+making them preferable for applications with expensive function evaluations. However, if function
+evaluations are not the dominant cost in your application, the Fortran 77 solvers are likely to be
+faster, as they are more efficient in terms of memory usage and flops thanks to the careful and
+ingenious (but unmaintained and unmaintainable) implementation by Powell.
+
+See the PRIMA documentation (www.libprima.net) for more information.
+'''
+
+from ..common.evaluate import evaluate, moderatex, moderatef, moderatec
+from ..common.consts import (EPS, RHOBEG_DEFAULT, RHOEND_DEFAULT, CTOL_DEFAULT,
+                                   CWEIGHT_DEFAULT, FTARGET_DEFAULT, IPRINT_DEFAULT,
+                                   MAXFUN_DIM_DEFAULT, DEBUGGING, BOUNDMAX,
+                                   ETA1_DEFAULT, ETA2_DEFAULT, GAMMA1_DEFAULT,
+                                   GAMMA2_DEFAULT)
+from ..common.preproc import preproc
+from ..common.present import present
+from ..common.linalg import matprod
+from .cobylb import cobylb
+import numpy as np
+from dataclasses import dataclass
+from copy import copy
+
+
+@dataclass
+class COBYLAResult:
+    x: np.ndarray
+    f: float
+    constr: np.ndarray
+    cstrv: float
+    nf: int
+    xhist: np.ndarray | None
+    fhist: np.ndarray | None
+    chist: np.ndarray | None
+    conhist: np.ndarray | None
+    info: int
+
+
+def cobyla(calcfc, m_nlcon, x, Aineq=None, bineq=None, Aeq=None, beq=None,
+           xl=None, xu=None, f0=None, nlconstr0=None, rhobeg=None, rhoend=None,
+           ftarget=FTARGET_DEFAULT, ctol=CTOL_DEFAULT, cweight=CWEIGHT_DEFAULT,
+           maxfun=None, iprint=IPRINT_DEFAULT, eta1=None, eta2=None,
+           gamma1=GAMMA1_DEFAULT, gamma2=GAMMA2_DEFAULT, maxhist=None, maxfilt=2000,
+           callback=None):
+    """
+    Among all the arguments, only CALCFC, M_NLCON, and X are obligatory. The others are
+    OPTIONAL and you can neglect them unless you are familiar with the algorithm. Any
+    unspecified optional input will take the default value detailed below. For
+    instance, we may invoke the solver as follows.
+
+    # First define CALCFC, M_NLCON, and X, and then do the following.
+    result = cobyla(calcfc, m_nlcon, x)
+
+    or
+
+    # First define CALCFC, M_NLCON, X, Aineq, and Bineq, and then do the following.
+    result = cobyla(calcfc, m_nlcon, x, Aineq=Aineq, bineq=bineq, rhobeg=1.0e0,
+        rhoend=1.0e-6)
+
+    ####################################################################################
+    # IMPORTANT NOTICE: The user must set M_NLCON correctly to the number of nonlinear
+    # constraints, namely the size of NLCONSTR introduced below. Set it to 0 if there
+    # is no nonlinear constraint.
+    ####################################################################################
+
+    See examples/cobyla/cobyla_example.py for a concrete example.
+
+    A detailed introduction to the arguments is as follows.
+
+    ####################################################################################
+    # INPUTS
+    ####################################################################################
+
+    CALCFC
+      Input, function.
+      f, nlconstr = CALCFC(X) should evaluate the objective function and nonlinear
+      constraints at the given vector X; it should return a tuple consisting of the
+      objective function value and the nonlinear constraint value. It must be provided
+      by the user, and its definition must conform to the following interface:
+      #-------------------------------------------------------------------------#
+       def calcfc(x):
+           f = 0.0
+           nlconstr = np.zeros(m_nlcon)
+           return f, nlconstr
+      #-------------------------------------------------------------------------#
+
+    M_NLCON
+      Input, scalar.
+      M_NLCON must be set to the number of nonlinear constraints, namely the size of
+      NLCONSTR(X).
+      N.B.:
+      1. Why don't we define M_NLCON as optional and default it to 0 when it is absent?
+      This is because we need to allocate memory for CONSTR_LOC using M_NLCON. To
+      ensure that the size of CONSTR_LOC is correct, we require the user to specify
+      M_NLCON explicitly.
+
+    X
+      Input, vector.
+      As an input, X should be an N-dimensional vector that contains the starting
+      point, N being the dimension of the problem.
+
+    Aineq, Bineq
+      Input, matrix of size [Mineq, N] and vector of size Mineq unless they are both
+      empty, default: None and None.
+      Aineq and Bineq represent the linear inequality constraints: Aineq*X <= Bineq.
+
+    Aeq, Beq
+      Input, matrix of size [Meq, N] and vector of size Meq unless they are both
+      empty, default: None and None.
+      Aeq and Beq represent the linear equality constraints: Aeq*X = Beq.
+
+    XL, XU
+      Input, vectors of size N unless they are both None, default: None and None.
+      XL is the lower bound for X. If XL is None, X has no
+      lower bound. Any entry of XL that is NaN or below -BOUNDMAX will be taken as
+      -BOUNDMAX, which effectively means there is no lower bound for the corresponding
+      entry of X. The value of BOUNDMAX is 0.25*HUGE(X), which is about 8.6E37 for
+      single precision and 4.5E307 for double precision. XU is similar.
+
+    F0
+      Input, scalar.
+      F0, if present, should be set to the objective function value of the starting X.
+
+    NLCONSTR0
+      Input, vector.
+      NLCONSTR0, if present, should be set to the nonlinear constraint value at the
+      starting X; in addition, SIZE(NLCONSTR0) must be M_NLCON, or the solver will
+      abort.
+
+    RHOBEG, RHOEND
+      Inputs, scalars, default: RHOBEG = 1, RHOEND = 10^-6. RHOBEG and RHOEND must be
+      set to the initial and final values of a trust-region radius, both being positive
+      and RHOEND <= RHOBEG. Typically RHOBEG should be about one tenth of the greatest
+      expected change to a variable, and RHOEND should indicate the accuracy that is
+      required in the final values of the variables.
+
+    FTARGET
+      Input, scalar, default: -Inf.
+      FTARGET is the target function value. The algorithm will terminate when a
+      feasible point with a function value <= FTARGET is found.
+
+    CTOL
+      Input, scalar, default: sqrt(machine epsilon).
+      CTOL is the tolerance of constraint violation. X is considered feasible if
+      CSTRV(X) <= CTOL.
+      N.B.:
+        1. CTOL is absolute, not relative.
+        2. CTOL is used only when selecting the returned X. It does not affect the
+           iterations of the algorithm.
+
+    CWEIGHT
+      Input, scalar, default: CWEIGHT_DFT defined in common/consts.py.
+      CWEIGHT is the weight that the constraint violation takes in the selection of the
+      returned X.
+
+    MAXFUN
+      Input, integer scalar, default: MAXFUN_DIM_DFT*N with MAXFUN_DIM_DFT defined in
+      common/consts.py. MAXFUN is the maximal number of calls of CALCFC.
+
+    IPRINT
+      Input, integer scalar, default: 0.
+      The value of IPRINT should be set to 0, 1, -1, 2, -2, 3, or -3, which controls
+      how much information will be printed during the computation:
+      0: there will be no printing;
+      1: a message will be printed to the screen at the return, showing the best vector
+         of variables found and its objective function value;
+      2: in addition to 1, each new value of RHO is printed to the screen, with the
+         best vector of variables so far and its objective function value; each new
+         value of CPEN is also printed;
+      3: in addition to 2, each function evaluation with its variables will be printed
+         to the screen; -1, -2, -3: the same information as 1, 2, 3 will be printed,
+         not to the screen but to a file named COBYLA_output.txt; the file will be
+         created if it does not exist; the new output will be appended to the end of
+         this file if it already exists.
+      Note that IPRINT = +/-3 can be costly in terms of time and/or space.
+
+    ETA1, ETA2, GAMMA1, GAMMA2
+      Input, scalars, default: ETA1 = 0.1, ETA2 = 0.7, GAMMA1 = 0.5, and GAMMA2 = 2.
+      ETA1, ETA2, GAMMA1, and GAMMA2 are parameters in the updating scheme of the
+      trust-region radius detailed in the subroutine TRRAD in trustregion.py. Roughly
+      speaking, the trust-region radius is contracted by a factor of GAMMA1 when the
+      reduction ratio is below ETA1, and enlarged by a factor of GAMMA2 when the
+      reduction ratio is above ETA2. It is required that 0 < ETA1 <= ETA2 < 1 and
+      0 < GAMMA1 < 1 < GAMMA2. Normally, ETA1 <= 0.25. It is NOT advised to set
+      ETA1 >= 0.5.
+
+    MAXFILT
+      Input, scalar.
+      MAXFILT is a nonnegative integer indicating the maximal length of the filter used
+      for selecting the returned solution; default: MAXFILT_DFT (a value lower than
+      MIN_MAXFILT is not recommended);
+      see common/consts.py for the definitions of MAXFILT_DFT and MIN_MAXFILT.
+
+    CALLBACK
+      Input, function to report progress and optionally request termination.
+
+
+    ####################################################################################
+    # OUTPUTS
+    ####################################################################################
+
+    The output is a single data structure, COBYLAResult, with the following fields:
+
+    X
+      Output, vector.
+      As an output, X will be set to an approximate minimizer.
+
+    F
+      Output, scalar.
+      F will be set to the objective function value of X at exit.
+
+    CONSTR
+      Output, vector.
+      CONSTR will be set to the constraint value of X at exit.
+
+    CSTRV
+      Output, scalar.
+      CSTRV will be set to the constraint violation of X at exit, i.e.,
+      max([0, XL - X, X - XU, Aineq*X - Bineq, ABS(Aeq*X -Beq), NLCONSTR(X)]).
+
+    NF
+      Output, scalar.
+      NF will be set to the number of calls of CALCFC at exit.
+
+    XHIST, FHIST, CHIST, CONHIST, MAXHIST
+      XHIST: Output, rank 2 array;
+      FHIST: Output, rank 1 array;
+      CHIST: Output, rank 1 array;
+      CONHIST: Output, rank 2 array;
+      MAXHIST: Input, scalar, default: MAXFUN
+      XHIST, if present, will output the history of iterates; FHIST, if present, will
+      output the history function values; CHIST, if present, will output the history of
+      constraint violations; CONHIST, if present, will output the history of constraint
+      values; MAXHIST should be a nonnegative integer, and XHIST/FHIST/CHIST/CONHIST
+      will output only the history of the last MAXHIST iterations.
+      Therefore, MAXHIST= 0 means XHIST/FHIST/CONHIST/CHIST will output
+      nothing, while setting MAXHIST = MAXFUN requests XHIST/FHIST/CHIST/CONHIST to
+      output all the history. If XHIST is present, its size at exit will be
+      (N, min(NF, MAXHIST)); if FHIST is present, its size at exit will be
+      min(NF, MAXHIST); if CHIST is present, its size at exit will be min(NF, MAXHIST);
+      if CONHIST is present, its size at exit will be (M, min(NF, MAXHIST)).
+
+      IMPORTANT NOTICE:
+      Setting MAXHIST to a large value can be costly in terms of memory for large
+      problems.
+      MAXHIST will be reset to a smaller value if the memory needed exceeds MAXHISTMEM
+      defined in common/consts.py
+      Use *HIST with caution!!! (N.B.: the algorithm is NOT designed for large
+      problems).
+
+    INFO
+      Output, scalar.
+      INFO is the exit flag. It will be set to one of the following values defined in
+      common/infos.py:
+      SMALL_TR_RADIUS: the lower bound for the trust region radius is reached;
+      FTARGET_ACHIEVED: the target function value is reached;
+      MAXFUN_REACHED: the objective function has been evaluated MAXFUN times;
+      MAXTR_REACHED: the trust region iteration has been performed MAXTR times (MAXTR = 2*MAXFUN);
+      NAN_INF_X: NaN or Inf occurs in X;
+      DAMAGING_ROUNDING: rounding errors are becoming damaging.
+      #--------------------------------------------------------------------------#
+      The following case(s) should NEVER occur unless there is a bug.
+      NAN_INF_F: the objective function returns NaN or +Inf;
+      NAN_INF_MODEL: NaN or Inf occurs in the model;
+      TRSUBP_FAILED: a trust region step failed to reduce the model
+      #--------------------------------------------------------------------------#
+    """
+
+    # Local variables
+    solver = "COBYLA"
+    srname = "COBYLA"
+
+    # Sizes
+    mineq = len(bineq) if present(bineq) else 0
+    meq = len(beq) if present(beq) else 0
+    mxl = sum(xl > -BOUNDMAX) if present(xl) else 0
+    mxu = sum(xu < BOUNDMAX) if present(xu) else 0
+    mmm = mxu + mxl + 2*meq + mineq + m_nlcon
+    num_vars = len(x)
+
+    # Preconditions
+    if DEBUGGING:
+        assert m_nlcon >= 0, f'{srname} M_NLCON >= 0'
+        assert num_vars >= 1, f'{srname} N >= 1'
+
+        assert present(Aineq) == present(bineq), \
+            f'{srname} Aineq and Bineq are both present or both absent'
+        if (present(Aineq)):
+            assert Aineq.shape == (mineq, num_vars), f'{srname} SIZE(Aineq) == [Mineq, N]'
+
+        assert present(Aeq) == present(beq), \
+            f'{srname} Aeq and Beq are both present or both absent'
+        if (present(Aeq)):
+            assert Aeq.shape == (meq, num_vars), f'{srname} SIZE(Aeq) == [Meq, N]'
+
+        if (present(xl)):
+            assert len(xl) == num_vars, f'{srname} SIZE(XL) == N'
+        if (present(xu)):
+            assert len(xu) == num_vars, f'{srname} SIZE(XU) == N'
+
+
+        # N.B.: If NLCONSTR0 is present, then F0 must be present, and we assume that
+        # F(X0) = F0 even if F0 is NaN; if NLCONSTR0 is absent, then F0 must be either
+        # absent or NaN, both of which will be interpreted as F(X0) is not provided.
+        if present(nlconstr0):
+            assert present(f0), f'{srname} If NLCONSTR0 is present, then F0 is present'
+        if present(f0):
+            assert np.isnan(f0) or present(nlconstr0), \
+                f'{srname} If F0 is present and not NaN, then NLCONSTR0 is present'
+
+
+
+    # Exit if the size of NLCONSTR0 is inconsistent with M_NLCON.
+    if present(nlconstr0):
+        assert np.size(nlconstr0) == m_nlcon
+
+    # Read the inputs.
+
+    if xl is not None:
+      xl = copy(xl)
+      xl[np.isnan(xl)] = -BOUNDMAX
+      xl[xl < -BOUNDMAX] = -BOUNDMAX
+
+    if xu is not None:
+      xu = copy(xu)
+      xu[np.isnan(xu)] = BOUNDMAX
+      xu[xu > BOUNDMAX] = BOUNDMAX
+
+    # Wrap the linear and bound constraints into a single constraint: AMAT@X <= BVEC.
+    amat, bvec = get_lincon(Aeq, Aineq, beq, bineq, xl, xu)
+
+    # Create constraint vector
+    constr = np.zeros(mmm)
+
+    # Set [F_LOC, CONSTR_LOC] to [F(X0), CONSTR(X0)] after evaluating the latter if
+    # needed. In this way, COBYLB only needs one interface.
+    # N.B.: Due to the preconditions above, there are two possibilities for F0 and
+    # NLCONSTR0.
+    # If NLCONSTR0 is present, then F0 must be present, and we assume that F(X0) = F0
+    # even if F0 is NaN.
+    # If NLCONSTR0 is absent, then F0 must be either absent or NaN, both of which will
+    # be interpreted as F(X0) is not provided and we have to evaluate F(X0) and
+    # NLCONSTR(X0) now.
+    if (present(f0) and present(nlconstr0) and all(np.isfinite(x))):
+        f = moderatef(f0)
+        if amat is not None:
+          constr[:mmm - m_nlcon] = moderatec(matprod(amat, x) - bvec)
+        constr[mmm - m_nlcon:] = moderatec(nlconstr0)
+    else:
+        x = moderatex(x)
+        f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+        constr[:mmm - m_nlcon] = moderatec(constr[:mmm - m_nlcon])
+        # N.B.: Do NOT call FMSG, SAVEHIST, or SAVEFILT for the function/constraint evaluation at X0.
+        # They will be called during the initialization, which will read the function/constraint at X0.
+    cstrv = max(np.append(0, constr))
+
+
+    # If RHOBEG is present, use it; otherwise, RHOBEG takes the default value for
+    # RHOBEG, taking the value of RHOEND into account. Note that RHOEND is considered
+    # only if it is present and it is VALID (i.e., finite and positive). The other
+    # inputs are read similarly.
+    if present(rhobeg):
+        rhobeg = rhobeg
+    elif present(rhoend) and np.isfinite(rhoend) and rhoend > 0:
+        rhobeg = max(10 * rhoend, RHOBEG_DEFAULT)
+    else:
+        rhobeg = RHOBEG_DEFAULT
+
+    if present(rhoend):
+        rhoend = rhoend
+    elif rhobeg > 0:
+        rhoend = max(EPS, min(RHOEND_DEFAULT/RHOBEG_DEFAULT * rhobeg, RHOEND_DEFAULT))
+    else:
+        rhoend = RHOEND_DEFAULT
+
+    maxfun = maxfun if present(maxfun) else MAXFUN_DIM_DEFAULT * num_vars
+
+    if present(eta1):
+        eta1 = eta1
+    elif present(eta2) and 0 < eta2 < 1:
+        eta1 = max(EPS, eta2 / 7)
+    else:
+        eta1 = ETA1_DEFAULT
+
+    if present(eta2):
+        eta2 = eta2
+    elif 0 < eta1 < 1:
+        eta2 = (eta1 + 2) / 3
+    else:
+        eta2 = ETA2_DEFAULT
+
+    maxhist = (
+        maxhist
+        if present(maxhist)
+        else max(maxfun, num_vars + 2, MAXFUN_DIM_DEFAULT * num_vars)
+    )
+
+    # Preprocess the inputs in case some of them are invalid. It does nothing if all
+    # inputs are valid.
+    (
+        iprint,
+        maxfun,
+        maxhist,
+        ftarget,
+        rhobeg,
+        rhoend,
+        npt,  # Unused in COBYLA
+        maxfilt,
+        ctol,
+        cweight,
+        eta1,
+        eta2,
+        gamma1,
+        gamma2,
+        _x0,  # Unused in COBYLA
+    ) = preproc(
+        solver,
+        num_vars,
+        iprint,
+        maxfun,
+        maxhist,
+        ftarget,
+        rhobeg,
+        rhoend,
+        num_constraints=mmm,
+        maxfilt=maxfilt,
+        ctol=ctol,
+        cweight=cweight,
+        eta1=eta1,
+        eta2=eta2,
+        gamma1=gamma1,
+        gamma2=gamma2,
+        is_constrained=(mmm > 0),
+    )
+
+    # Further revise MAXHIST according to MAXHISTMEM, and allocate memory for the history.
+    # In MATLAB/Python/Julia/R implementation, we should simply set MAXHIST = MAXFUN and initialize
+    # CHIST = NaN(1, MAXFUN), CONHIST = NaN(M, MAXFUN), FHIST = NaN(1, MAXFUN), XHIST = NaN(N, MAXFUN)
+    # if they are requested; replace MAXFUN with 0 for the history that is not requested.
+    # prehist(maxhist, num_vars, present(xhist), xhist_loc, present(fhist), fhist_loc, &
+    #     & present(chist), chist_loc, m, present(conhist), conhist_loc)
+
+    # call cobylb, which performs the real calculations
+    x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info = cobylb(
+        calcfc,
+        iprint,
+        maxfilt,
+        maxfun,
+        amat,
+        bvec,
+        ctol,
+        cweight,
+        eta1,
+        eta2,
+        ftarget,
+        gamma1,
+        gamma2,
+        rhobeg,
+        rhoend,
+        constr,
+        f,
+        x,
+        maxhist,
+        callback
+    )
+
+    return COBYLAResult(x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info)
+
+
+def get_lincon(Aeq=None, Aineq=None, beq=None, bineq=None, xl=None, xu=None):
+    """
+    This subroutine wraps the linear and bound constraints into a single constraint:
+        AMAT*X <= BVEC.
+
+    N.B.:
+
+    LINCOA normalizes the linear constraints so that each constraint has a gradient
+    of norm 1. However, COBYLA does not do this.
+    """
+
+    # Sizes
+    if Aeq is not None:
+        num_vars = Aeq.shape[1]
+    elif Aineq is not None:
+        num_vars = Aineq.shape[1]
+    elif xl is not None:
+        num_vars = len(xl)
+    elif xu is not None:
+        num_vars = len(xu)
+    else:
+        return None, None
+
+    # Preconditions
+    if DEBUGGING:
+        assert Aineq is None or Aineq.shape == (len(bineq), num_vars)
+        assert Aeq is None or Aeq.shape == (len(beq), num_vars)
+        assert (xl is None or xu is None) or len(xl) == len(xu) == num_vars
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Define the indices of the nontrivial bound constraints.
+    ixl = np.where(xl > -BOUNDMAX)[0] if xl is not None else None
+    ixu = np.where(xu < BOUNDMAX)[0] if xu is not None else None
+
+    # Wrap the linear constraints.
+    # The bound constraint XL <= X <= XU is handled as two constraints:
+    # -X <= -XL, X <= XU.
+    # The equality constraint Aeq*X = Beq is handled as two constraints:
+    # -Aeq*X <= -Beq, Aeq*X <= Beq.
+    # N.B.:
+    # 1. The treatment of the equality constraints is naive. One may choose to
+    #    eliminate them instead.
+    idmat = np.eye(num_vars)
+    amat = np.vstack([
+        -idmat[ixl, :] if ixl is not None else np.empty((0, num_vars)),
+        idmat[ixu, :] if ixu is not None else np.empty((0, num_vars)),
+        -Aeq if Aeq is not None else np.empty((0, num_vars)),
+        Aeq if Aeq is not None else np.empty((0, num_vars)),
+        Aineq if Aineq is not None else np.empty((0, num_vars))
+    ])
+    bvec = np.hstack([
+        -xl[ixl] if ixl is not None else np.empty(0),
+        xu[ixu] if ixu is not None else np.empty(0),
+        -beq if beq is not None else np.empty(0),
+        beq if beq is not None else np.empty(0),
+        bineq if bineq is not None else np.empty(0)
+    ])
+
+    amat = amat if amat.shape[0] > 0 else None
+    bvec = bvec if bvec.shape[0] > 0 else None
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert (amat is None and bvec is None) or amat.shape == (len(bvec), num_vars)
+
+    return amat, bvec
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/cobylb.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/cobylb.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cf0c526cff81eea84ff024cf4f074c6d12b92b2
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/cobylb.py
@@ -0,0 +1,714 @@
+'''
+This module performs the major calculations of COBYLA.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from ..common.checkbreak import checkbreak_con
+from ..common.consts import REALMAX, EPS, DEBUGGING, MIN_MAXFILT
+from ..common.infos import INFO_DEFAULT, MAXTR_REACHED, DAMAGING_ROUNDING, \
+                    SMALL_TR_RADIUS, CALLBACK_TERMINATE
+from ..common.evaluate import evaluate
+from ..common.history import savehist
+from ..common.linalg import isinv, matprod, inprod, norm, primasum, primapow2
+from ..common.message import fmsg, retmsg, rhomsg
+from ..common.ratio import redrat
+from ..common.redrho import redrho
+from ..common.selectx import savefilt, selectx
+from .update import updatepole, findpole, updatexfc
+from .geometry import setdrop_tr, geostep
+from .trustregion import trstlp, trrad
+from .initialize import initxfc, initfilt
+
+
+def cobylb(calcfc, iprint, maxfilt, maxfun, amat, bvec, ctol, cweight, eta1, eta2,
+           ftarget, gamma1, gamma2, rhobeg, rhoend, constr, f, x, maxhist, callback):
+    '''
+    This subroutine performs the actual computations of COBYLA.
+    '''
+
+    # Outputs
+    xhist = []
+    fhist = []
+    chist = []
+    conhist = []
+
+    # Local variables
+    solver = 'COBYLA'
+    A = np.zeros((np.size(x), np.size(constr))) # A contains the approximate gradient for the constraints
+    distsq = np.zeros(np.size(x) + 1)
+    # CPENMIN is the minimum of the penalty parameter CPEN for the L-infinity
+    # constraint violation in the merit function. Note that CPENMIN = 0 in Powell's
+    # implementation, which allows CPEN to be 0. Here, we take CPENMIN > 0 so that CPEN
+    # is always positive. This avoids the situation where PREREM becomes 0 when
+    # PREREF = 0 = CPEN. It brings two advantages as follows.
+    # 1. If the trust-region subproblem solver works correctly and the trust-region
+    #    center is not optimal for the subproblem, then PREREM > 0 is guaranteed. This
+    #    is because, in theory, PREREC >= 0 and MAX(PREREC, PREREF) > 0, and the
+    #    definition of CPEN in GETCPEN ensures that PREREM > 0.
+    # 2. There is no need to revise ACTREM and PREREM when CPEN = 0 and F = FVAL(N+1)
+    #    as in lines 312--314 of Powell's cobylb.f code. Powell's code revises ACTREM
+    #    to CVAL(N + 1) - CSTRV and PREREM to PREREC in this case, which is crucial for
+    #    feasibility problems.
+    cpenmin = EPS
+
+    # Sizes
+    m_lcon = np.size(bvec) if bvec is not None else 0
+    num_constraints = np.size(constr)
+    m_nlcon = num_constraints - m_lcon
+    num_vars = np.size(x)
+
+    # Preconditions
+    if DEBUGGING:
+        assert abs(iprint) <= 3
+        assert num_constraints >= m_lcon and m_lcon >= 0
+        assert num_vars >= 1
+        assert maxfun >= num_vars + 2
+        assert rhobeg >= rhoend and rhoend > 0
+        assert all(np.isfinite(x))
+        assert 0 <= eta1 <= eta2 < 1
+        assert 0 < gamma1 < 1 < gamma2
+        assert 0 <= ctol
+        assert 0 <= cweight
+        assert 0 <= maxhist <= maxfun
+        assert amat is None or np.shape(amat) == (m_lcon, num_vars)
+        assert min(MIN_MAXFILT, maxfun) <= maxfilt <= maxfun
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Initialize SIM, FVAL, CONMAT, and CVAL, together with the history.
+    # After the initialization, SIM[:, NUM_VARS] holds the vertex of the initial
+    # simplex with the smallest function value (regardless of the constraint
+    # violation), and SIM[:, :NUM_VARS] holds the displacements from the other vertices
+    # to SIM[:, NUM_VARS]. FVAL, CONMAT, and CVAL hold the function values, constraint
+    # values, and constraint violations on the vertices in the order corresponding to
+    # SIM.
+    evaluated, conmat, cval, sim, simi, fval, nf, subinfo = initxfc(calcfc, iprint,
+      maxfun, constr, amat, bvec, ctol, f, ftarget, rhobeg, x,
+      xhist, fhist, chist, conhist, maxhist)
+
+    # Initialize the filter, including xfilt, ffilt, confilt, cfilt, and nfilt.
+    # N.B.: The filter is used only when selecting which iterate to return. It does not
+    # interfere with the iterations. COBYLA is NOT a filter method but a trust-region
+    # method based on an L-infinity merit function. Powell's implementation does not
+    # use a filter to select the iterate, possibly returning a suboptimal iterate.
+    cfilt = np.zeros(np.minimum(np.maximum(maxfilt, 1), maxfun))
+    confilt = np.zeros((np.size(constr), np.size(cfilt)))
+    ffilt = np.zeros(np.size(cfilt))
+    xfilt = np.zeros((np.size(x), np.size(cfilt)))
+    nfilt = initfilt(conmat, ctol, cweight, cval, fval, sim, evaluated, cfilt, confilt,
+                     ffilt, xfilt)
+
+    # Check whether to return due to abnormal cases that may occur during the initialization.
+    if subinfo != INFO_DEFAULT:
+        info = subinfo
+        # Return the best calculated values of the variables
+        # N.B: Selectx and findpole choose X by different standards, one cannot replace the other
+        kopt = selectx(ffilt[:nfilt], cfilt[:nfilt], cweight, ctol)
+        x = xfilt[:, kopt]
+        f = ffilt[kopt]
+        constr = confilt[:, kopt]
+        cstrv = cfilt[kopt]
+        # print a return message according to IPRINT.
+        retmsg(solver, info, iprint, nf, f, x, cstrv, constr)
+        # Postconditions
+        if DEBUGGING:
+            assert nf <= maxfun
+            assert np.size(x) == num_vars and not any(np.isnan(x))
+            assert not (np.isnan(f) or np.isposinf(f))
+            # assert np.size(xhist, 0) == n and np.size(xhist, 1) == maxxhist
+            # assert not any(np.isnan(xhist(:, 1:min(nf, maxxhist))))
+            # The last calculated X can be Inf (finite + finite can be Inf numerically).
+            # assert np.size(fhist) == maxfhist
+            # assert not any(np.isnan(fhist(1:min(nf, maxfhist))) or np.isposinf(fhist(1:min(nf, maxfhist))))
+            # assert np.size(conhist, 0) == m and np.size(conhist, 1) == maxconhist
+            # assert not any(np.isnan(conhist(:, 1:min(nf, maxconhist))) or np.isneginf(conhist(:, 1:min(nf, maxconhist))))
+            # assert np.size(chist) == maxchist
+            # assert not any(chist(1:min(nf, maxchist)) < 0 or np.isnan(chist(1:min(nf, maxchist))) or np.isposinf(chist(1:min(nf, maxchist))))
+            # nhist = minval([nf, maxfhist, maxchist])
+            # assert not any(isbetter(fhist(1:nhist), chist(1:nhist), f, cstrv, ctol))
+        return x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info
+
+
+    # Set some more initial values.
+    # We must initialize shortd, ratio, and jdrop_tr because these get defined on
+    # branches that are not guaranteed to be executed, but their values are used later.
+    # Our initialization of CPEN differs from Powell's in two ways. First, we use the
+    # ratio defined in (13) of Powell's COBYLA paper to initialize CPEN. Second, we
+    # impose CPEN >= CPENMIN > 0. Powell's code simply initializes CPEN to 0.
+    rho = rhobeg
+    delta = rhobeg
+    cpen = np.maximum(cpenmin, np.minimum(1.0E3, fcratio(conmat, fval)))  # Powell's code: CPEN = ZERO
+    shortd = False
+    ratio = -1
+    jdrop_tr = 0
+
+    # If DELTA <= GAMMA3*RHO after an update, we set DELTA to RHO. GAMMA3 must be less
+    # than GAMMA2. The reason is as follows. Imagine a very successful step with
+    # DNORM = the un-updated DELTA = RHO. The TRRAD will update DELTA to GAMMA2*RHO.
+    # If GAMMA3 >= GAMMA2, then DELTA will be reset to RHO, which is not reasonable as
+    # D is very successful. See paragraph two of Sec 5.2.5 in T. M. Ragonneau's thesis:
+    # "Model-Based Derivative-Free Optimization Methods and Software." According to
+    # test on 20230613, for COBYLA, this Powellful updating scheme of DELTA works
+    # slightly better than setting directly DELTA = max(NEW_DELTA, RHO).
+    gamma3 = np.maximum(1, np.minimum(0.75 * gamma2, 1.5))
+
+    # MAXTR is the maximal number of trust region iterations. Each trust-region
+    # iteration takes 1 or 2 function evaluations unless the trust-region step is short
+    # or the trust-region subproblem solver fails but the geometry step is not invoked.
+    # Thus the following MAXTR is unlikely to be reached.
+    maxtr = 10 * maxfun
+    info = MAXTR_REACHED
+
+    # Begin the iterative procedure
+    # After solving a trust-region subproblem, we use three boolean variables to
+    # control the workflow.
+    # SHORTD - Is the trust-region trial step too short to invoke # a function
+    #          evaluation?
+    # IMPROVE_GEO - Will we improve the model after the trust-region iteration? If yes,
+    #               a geometry step will be taken, corresponding to the "Branch (Delta)"
+    #               in the COBYLA paper.
+    # REDUCE_RHO - Will we reduce rho after the trust-region iteration?
+    # COBYLA never sets IMPROVE_GEO and REDUCE_RHO to True simultaneously.
+    for tr in range(maxtr):
+        # Increase the penalty parameter CPEN, if needed, so that
+        # PREREM = PREREF + CPEN * PREREC > 0.
+        # This is the first (out of two) update of CPEN, where CPEN increases or
+        # remains the same.
+        # N.B.: CPEN and the merit function PHI = FVAL + CPEN*CVAL are used in three
+        # places only.
+        # 1. In FINDPOLE/UPDATEPOLE, deciding the optimal vertex of the current simplex.
+        # 2. After the trust-region trial step, calculating the reduction ratio.
+        # 3. In GEOSTEP, deciding the direction of the geometry step.
+        # They do not appear explicitly in the trust-region subproblem, though the
+        # trust-region center (i.e. the current optimal vertex) is defined by them.
+        cpen = getcpen(amat, bvec, conmat, cpen, cval, delta, fval, rho, sim, simi)
+
+        # Switch the best vertex of the current simplex to SIM[:, NUM_VARS].
+        conmat, cval, fval, sim, simi, subinfo = updatepole(cpen, conmat, cval, fval,
+                                                            sim, simi)
+        # Check whether to exit due to damaging rounding in UPDATEPOLE.
+        if subinfo == DAMAGING_ROUNDING:
+            info = subinfo
+            break  # Better action to take? Geometry step, or simply continue?
+
+        # Does the interpolation set have adequate geometry? It affects improve_geo and
+        # reduce_rho.
+        adequate_geo = all(primasum(primapow2(sim[:, :num_vars]), axis=0) <= 4 * primapow2(delta))
+
+        # Calculate the linear approximations to the objective and constraint functions.
+        # N.B.: TRSTLP accesses A mostly by columns, so it is more reasonable to save A
+        # instead of A^T.
+        # Zaikun 2023108: According to a test on 2023108, calculating G and
+        # A(:, M_LCON+1:M) by solving the linear systems SIM^T*G = FVAL(1:N)-FVAL(N+1)
+        # and SIM^T*A = CONMAT(:, 1:N)-CONMAT(:, N+1) does not seem to improve or worsen
+        # the performance of COBYLA in terms of the number of function evaluations. The
+        # system was solved by SOLVE in LINALG_MOD based on a QR factorization of SIM
+        # (not necessarily a good algorithm). No preconditioning or scaling was used.
+        g = matprod((fval[:num_vars] - fval[num_vars]), simi)
+        A[:, :m_lcon] = amat.T if amat is not None else amat
+        A[:, m_lcon:] = matprod((conmat[m_lcon:, :num_vars] -
+                          np.tile(conmat[m_lcon:, num_vars], (num_vars, 1)).T), simi).T
+
+        # Calculate the trust-region trial step d. Note that d does NOT depend on cpen.
+        d = trstlp(A, -conmat[:, num_vars], delta, g)
+        dnorm = min(delta, norm(d))
+
+        # Is the trust-region trial step short? N.B.: we compare DNORM with RHO, not
+        # DELTA. Powell's code especially defines SHORTD by SHORTD = (DNORM < 0.5 *
+        # RHO). In our tests 1/10 seems to work better than 1/2 or 1/4, especially for
+        # linearly constrained problems. Note that LINCOA has a slightly more
+        # sophisticated way of defining SHORTD, taking into account whether D causes a
+        # change to the active set. Should we try the same here?
+        shortd = (dnorm <= 0.1 * rho)
+
+        # Predict the change to F (PREREF) and to the constraint violation (PREREC) due
+        # to D. We have the following in precise arithmetic. They may fail to hold due
+        # to rounding errors.
+        # 1. B[:NUM_CONSTRAINTS] = -CONMAT[:, NUM_VARS] and hence
+        # np.max(np.append(B[:NUM_CONSTRAINTS] - D@A[:, :NUM_CONSTRAINTS], 0)) is the
+        # L-infinity violation of the linearized constraints corresponding to D. When
+        # D=0, the violation is np.max(np.append(B[:NUM_CONSTRAINTS], 0)) =
+        # CVAL[NUM_VARS]. PREREC is the reduction of this violation achieved by D,
+        # which is nonnegative in theory; PREREC = 0 iff B[:NUM_CONSTRAINTS] <= 0, i.e.
+        # the trust-region center satisfies the linearized constraints.
+        # 2. PREREF may be negative or 0, but it is positive when PREREC = 0 and shortd
+        # is False
+        # 3. Due to 2, in theory, max(PREREC, PREREF) > 0 if shortd is False.
+        preref = -inprod(d, g)  # Can be negative
+        prerec = cval[num_vars] - np.max(np.append(0, conmat[:, num_vars] + matprod(d, A)))
+
+        # Evaluate PREREM, which is the predicted reduction in the merit function.
+        # In theory, PREREM >= 0 and it is 0 iff CPEN = 0 = PREREF. This may not be true
+        # numerically.
+        prerem = preref + cpen * prerec
+        trfail = not (prerem > 1.0E-6 * min(cpen, 1) * rho)
+
+        if shortd or trfail:
+            # Reduce DELTA if D is short or if D fails to render PREREM > 0. The latter
+            # can only happen due to rounding errors. This seems quite important for
+            # performance
+            delta *= 0.1
+            if delta <= gamma3 * rho:
+                delta = rho  # set delta to rho when it is close to or below
+        else:
+            # Calculate the next value of the objective and constraint functions.
+            # If X is close to one of the points in the interpolation set, then we do
+            # not evaluate the objective and constraints at X, assuming them to have
+            # the values at the closest point.
+            # N.B.: If this happens, do NOT include X into the filter, as F and CONSTR
+            # are inaccurate.
+            x = sim[:, num_vars] + d
+            distsq[num_vars] = primasum(primapow2(x - sim[:, num_vars]))
+            distsq[:num_vars] = primasum(primapow2(x.reshape(num_vars, 1) -
+                (sim[:, num_vars].reshape(num_vars, 1) + sim[:, :num_vars])), axis=0)
+            j = np.argmin(distsq)
+            if distsq[j] <= primapow2(1e-4 * rhoend):
+                f = fval[j]
+                constr = conmat[:, j]
+                cstrv = cval[j]
+            else:
+                # Evaluate the objective and constraints at X, taking care of possible
+                # inf/nan values.
+                f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+                cstrv = np.max(np.append(0, constr))
+                nf += 1
+                # Save X, F, CONSTR, CSTRV into the history.
+                savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+                # Save X, F, CONSTR, CSTRV into the filter.
+                nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cstrv, ctol, cweight, f,
+                                                               x, nfilt, cfilt, ffilt,
+                                                               xfilt, constr, confilt)
+
+            # Print a message about the function/constraint evaluation according to
+            # iprint
+            fmsg(solver, 'Trust region', iprint, nf, delta, f, x, cstrv, constr)
+
+            # Evaluate ACTREM, which is the actual reduction in the merit function
+            actrem = (fval[num_vars] + cpen * cval[num_vars]) - (f + cpen * cstrv)
+
+            # Calculate the reduction  ratio by redrat, which hands inf/nan carefully
+            ratio = redrat(actrem, prerem, eta1)
+
+            # Update DELTA. After this, DELTA < DNORM may hold.
+            # N.B.:
+            # 1. Powell's code uses RHO as the trust-region radius and updates it as
+            #    follows.
+            #    Reduce RHO to GAMMA1*RHO if ADEQUATE_GEO is TRUE and either SHORTD is
+            #    TRUE or RATIO < ETA1, and then revise RHO to RHOEND if its new value is
+            #    not more than GAMMA3*RHOEND; RHO remains unchanged in all other cases;
+            #    in particular, RHO is never increased.
+            # 2. Our implementation uses DELTA as the trust-region radius, while using
+            #    RHO as a lower bound for DELTA. DELTA is updated in a way that is
+            #    typical for trust-region methods, and it is revised to RHO if its new
+            #    value is not more than GAMMA3*RHO. RHO reflects the current resolution
+            #    of the algorithm; its update is essentially the same as the update of
+            #    RHO in Powell's code (see the definition of REDUCE_RHO below). Our
+            #    implementation aligns with UOBYQA/NEWUOA/BOBYQA/LINCOA and improves the
+            #    performance of COBYLA.
+            # 3. The same as Powell's code, we do not reduce RHO unless ADEQUATE_GEO is
+            #    TRUE. This is also how Powell updated RHO in
+            #    UOBYQA/NEWUOA/BOBYQA/LINCOA. What about we also use ADEQUATE_GEO ==
+            #    TRUE as a prerequisite for reducing DELTA? The argument would be that
+            #    the bad (small) value of RATIO may be because of a bad geometry (and
+            #    hence a bad model) rather than an improperly large DELTA, and it might
+            #    be good to try improving the geometry first without reducing DELTA.
+            #    However, according to a test on 20230206, it does not improve the
+            #    performance if we skip the update of DELTA when ADEQUATE_GEO is FALSE
+            #    and RATIO < 0.1. Therefore, we choose to update DELTA without checking
+            #    ADEQUATE_GEO.
+
+            delta = trrad(delta, dnorm, eta1, eta2, gamma1, gamma2, ratio)
+            if delta <= gamma3*rho:
+                delta = rho  # Set delta to rho when it is close to or below.
+
+            # Is the newly generated X better than the current best point?
+            ximproved = actrem > 0  # If ACTREM is NaN, then XIMPROVED should and will be False
+
+            # Set JDROP_TR to the index of the vertex to be replaced with X. JDROP_TR = 0 means there
+            # is no good point to replace, and X will not be included into the simplex; in this case,
+            # the geometry of the simplex likely needs improvement, which will be handled below.
+            jdrop_tr = setdrop_tr(ximproved, d, delta, rho, sim, simi)
+
+            # Update SIM, SIMI, FVAL, CONMAT, and CVAL so that SIM[:, JDROP_TR] is replaced with D.
+            # UPDATEXFC does nothing if JDROP_TR is None, as the algorithm decides to discard X.
+            sim, simi, fval, conmat, cval, subinfo = updatexfc(jdrop_tr, constr, cpen, cstrv, d, f, conmat, cval, fval, sim, simi)
+            # Check whether to break due to damaging rounding in UPDATEXFC
+            if subinfo == DAMAGING_ROUNDING:
+                info = subinfo
+                break  # Better action to take? Geometry step, or a RESCUE as in BOBYQA?
+
+            # Check whether to break due to maxfun, ftarget, etc.
+            subinfo = checkbreak_con(maxfun, nf, cstrv, ctol, f, ftarget, x)
+            if subinfo != INFO_DEFAULT:
+                info = subinfo
+                break
+        # End of if SHORTD or TRFAIL. The normal trust-region calculation ends.
+
+        # Before the next trust-region iteration, we possibly improve the geometry of the simplex or
+        # reduce RHO according to IMPROVE_GEO and REDUCE_RHO. Now we decide these indicators.
+        # N.B.: We must ensure that the algorithm does not set IMPROVE_GEO = True at infinitely many
+        # consecutive iterations without moving SIM[:, NUM_VARS] or reducing RHO. Otherwise, the algorithm
+        # will get stuck in repetitive invocations of GEOSTEP. This is ensured by the following facts:
+        # 1. If an iteration sets IMPROVE_GEO to True, it must also reduce DELTA or set DELTA to RHO.
+        # 2. If SIM[:, NUM_VARS] and RHO remain unchanged, then ADEQUATE_GEO will become True after at
+        # most NUM_VARS invocations of GEOSTEP.
+
+        # BAD_TRSTEP: Is the last trust-region step bad?
+        bad_trstep = shortd or trfail or ratio <= 0 or jdrop_tr is None
+        # IMPROVE_GEO: Should we take a geometry step to improve the geometry of the interpolation set?
+        improve_geo = bad_trstep and not adequate_geo
+        # REDUCE_RHO: Should we enhance the resolution by reducing rho?
+        reduce_rho = bad_trstep and adequate_geo and max(delta, dnorm) <= rho
+
+        # COBYLA never sets IMPROVE_GEO and REDUCE_RHO to True simultaneously.
+        # assert not (IMPROVE_GEO and REDUCE_RHO), 'IMPROVE_GEO or REDUCE_RHO are not both TRUE, COBYLA'
+
+        # If SHORTD or TRFAIL is True, then either IMPROVE_GEO or REDUCE_RHO is True unless ADEQUATE_GEO
+        # is True and max(DELTA, DNORM) > RHO.
+        # assert not (shortd or trfail) or (improve_geo or reduce_rho or (adequate_geo and max(delta, dnorm) > rho)), \
+        #     'If SHORTD or TRFAIL is TRUE, then either IMPROVE_GEO or REDUCE_RHO is TRUE unless ADEQUATE_GEO is TRUE and MAX(DELTA, DNORM) > RHO'
+
+        # Comments on BAD_TRSTEP:
+        # 1. Powell's definition of BAD_TRSTEP is as follows. The one used above seems to work better,
+        # especially for linearly constrained problems due to the factor TENTH (= ETA1).
+        # !bad_trstep = (shortd .or. actrem <= 0 .or. actrem < TENTH * prerem .or. jdrop_tr == 0)
+        # Besides, Powell did not check PREREM > 0 in BAD_TRSTEP, which is reasonable to do but has
+        # little impact upon the performance.
+        # 2. NEWUOA/BOBYQA/LINCOA would define BAD_TRSTEP, IMPROVE_GEO, and REDUCE_RHO as follows. Two
+        # different thresholds are used in BAD_TRSTEP. It outperforms Powell's version.
+        # !bad_trstep = (shortd .or. trfail .or. ratio <= eta1 .or. jdrop_tr == 0)
+        # !improve_geo = bad_trstep .and. .not. adequate_geo
+        # !bad_trstep = (shortd .or. trfail .or. ratio <= 0 .or. jdrop_tr == 0)
+        # !reduce_rho = bad_trstep .and. adequate_geo .and. max(delta, dnorm) <= rho
+        # 3. Theoretically, JDROP_TR > 0 when ACTREM > 0 (guaranteed by RATIO > 0). However, in Powell's
+        # implementation, JDROP_TR may be 0 even RATIO > 0 due to NaN. The modernized code has rectified
+        # this in the function SETDROP_TR. After this rectification, we can indeed simplify the
+        # definition of BAD_TRSTEP by removing the condition JDROP_TR == 0. We retain it for robustness.
+
+        # Comments on REDUCE_RHO:
+        # When SHORTD is TRUE, UOBYQA/NEWUOA/BOBYQA/LINCOA all set REDUCE_RHO to TRUE if the recent
+        # models are sufficiently accurate according to certain criteria. See the paragraph around (37)
+        # in the UOBYQA paper and the discussions about Box 14 in the NEWUOA paper. This strategy is
+        # crucial for the performance of the solvers. However, as of 20221111, we have not managed to
+        # make it work in COBYLA. As in NEWUOA, we recorded the errors of the recent models, and set
+        # REDUCE_RHO to true if they are small (e.g., ALL(ABS(MODERR_REC) <= 0.1 * MAXVAL(ABS(A))*RHO) or
+        # ALL(ABS(MODERR_REC) <= RHO**2)) when SHORTD is TRUE. It made little impact on the performance.
+
+
+        # Since COBYLA never sets IMPROVE_GEO and REDUCE_RHO to TRUE simultaneously, the following
+        # two blocks are exchangeable: IF (IMPROVE_GEO) ... END IF and IF (REDUCE_RHO) ... END IF.
+
+        # Improve the geometry of the simplex by removing a point and adding a new one.
+        # If the current interpolation set has acceptable geometry, then we skip the geometry step.
+        # The code has a small difference from Powell's original code here: If the current geometry
+        # is acceptable, then we will continue with a new trust-region iteration; however, at the
+        # beginning of the iteration, CPEN may be updated, which may alter the pole point SIM(:, N+1)
+        # by UPDATEPOLE; the quality of the interpolation point depends on SIM(:, N + 1), meaning
+        # that the same interpolation set may have good or bad geometry with respect to different
+        # "poles"; if the geometry turns out bad with the new pole, the original COBYLA code will
+        # take a geometry step, but our code here will NOT do it but continue to take a trust-region
+        # step. The argument is this: even if the geometry step is not skipped in the first place, the
+        # geometry may turn out bad again after the pole is altered due to an update to CPEN; should
+        # we take another geometry step in that case? If no, why should we do it here? Indeed, this
+        # distinction makes no practical difference for CUTEst problems with at most 100 variables
+        # and 5000 constraints, while the algorithm framework is simplified.
+        if improve_geo and not all(primasum(primapow2(sim[:, :num_vars]), axis=0) <= 4 * primapow2(delta)):
+            # Before the geometry step, updatepole has been called either implicitly by UPDATEXFC or
+            # explicitly after CPEN is updated, so that SIM[:, :NUM_VARS] is the optimal vertex.
+
+            # Decide a vertex to drop from the simplex. It will be replaced with SIM[:, NUM_VARS] + D to
+            # improve the geometry of the simplex.
+            # N.B.:
+            # 1. COBYLA never sets JDROP_GEO = num_vars.
+            # 2. The following JDROP_GEO comes from UOBYQA/NEWUOA/BOBYQA/LINCOA.
+            # 3. In Powell's original algorithm, the geometry of the simplex is considered acceptable
+            # iff the distance between any vertex and the pole is at most 2.1*DELTA, and the distance
+            # between any vertex and the opposite face of the simplex is at least 0.25*DELTA, as
+            # specified in (14) of the COBYLA paper. Correspondingly, JDROP_GEO is set to the index of
+            # the vertex with the largest distance to the pole provided that the distance is larger than
+            # 2.1*DELTA, or the vertex with the smallest distance to the opposite face of the simplex,
+            # in which case the distance must be less than 0.25*DELTA, as the current simplex does not
+            # have acceptable geometry (see (15)--(16) of the COBYLA paper). Once JDROP_GEO is set, the
+            # algorithm replaces SIM(:, JDROP_GEO) with D specified in (17) of the COBYLA paper, which
+            # is orthogonal to the face opposite to SIM(:, JDROP_GEO) and has a length of 0.5*DELTA,
+            # intending to improve the geometry of the simplex as per (14).
+            # 4. Powell's geometry-improving procedure outlined above has an intrinsic flaw: it may lead
+            # to infinite cycling, as was observed in a test on 20240320. In this test, the geometry-
+            # improving point introduced in the previous iteration was replaced with the trust-region
+            # trial point in the current iteration, which was then replaced with the same geometry-
+            # improving point in the next iteration, and so on. In this process, the simplex alternated
+            # between two configurations, neither of which had acceptable geometry. Thus RHO was never
+            # reduced, leading to infinite cycling. (N.B.: Our implementation uses DELTA as the trust
+            # region radius, with RHO being its lower bound. When the infinite cycling occurred in this
+            # test, DELTA = RHO and it could not be reduced due to the requirement that DELTA >= RHO.)
+            jdrop_geo = np.argmax(primasum(primapow2(sim[:, :num_vars]), axis=0), axis=0)
+
+            # Calculate the geometry step D.
+            delbar = delta/2
+            d = geostep(jdrop_geo, amat, bvec, conmat, cpen, cval, delbar, fval, simi)
+
+            # Calculate the next value of the objective and constraint functions.
+            # If X is close to one of the points in the interpolation set, then we do not evaluate the
+            # objective and constraints at X, assuming them to have the values at the closest point.
+            # N.B.:
+            # 1. If this happens, do NOT include X into the filter, as F and CONSTR are inaccurate.
+            # 2. In precise arithmetic, the geometry improving step ensures that the distance between X
+            # and any interpolation point is at least DELBAR, yet X may be close to them due to
+            # rounding. In an experiment with single precision on 20240317, X = SIM(:, N+1) occurred.
+            x = sim[:, num_vars] + d
+            distsq[num_vars] = primasum(primapow2(x - sim[:, num_vars]))
+            distsq[:num_vars] = primasum(primapow2(x.reshape(num_vars, 1) -
+                (sim[:, num_vars].reshape(num_vars, 1) + sim[:, :num_vars])), axis=0)
+            j = np.argmin(distsq)
+            if distsq[j] <= primapow2(1e-4 * rhoend):
+                f = fval[j]
+                constr = conmat[:, j]
+                cstrv = cval[j]
+            else:
+                # Evaluate the objective and constraints at X, taking care of possible
+                # inf/nan values.
+                f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+                cstrv = np.max(np.append(0, constr))
+                nf += 1
+                # Save X, F, CONSTR, CSTRV into the history.
+                savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+                # Save X, F, CONSTR, CSTRV into the filter.
+                nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cstrv, ctol, cweight, f,
+                                                               x, nfilt, cfilt, ffilt,
+                                                               xfilt, constr, confilt)
+
+            # Print a message about the function/constraint evaluation according to iprint
+            fmsg(solver, 'Geometry', iprint, nf, delta, f, x, cstrv, constr)
+            # Update SIM, SIMI, FVAL, CONMAT, and CVAL so that SIM(:, JDROP_GEO) is replaced with D.
+            sim, simi, fval, conmat, cval, subinfo = updatexfc(jdrop_geo, constr, cpen, cstrv, d, f, conmat, cval, fval, sim, simi)
+            # Check whether to break due to damaging rounding in UPDATEXFC
+            if subinfo == DAMAGING_ROUNDING:
+                info = subinfo
+                break  # Better action to take? Geometry step, or simply continue?
+
+            # Check whether to break due to maxfun, ftarget, etc.
+            subinfo = checkbreak_con(maxfun, nf, cstrv, ctol, f, ftarget, x)
+            if subinfo != INFO_DEFAULT:
+                info = subinfo
+                break
+        # end of if improve_geo. The procedure of improving the geometry ends.
+
+        # The calculations with the current RHO are complete. Enhance the resolution of the algorithm
+        # by reducing RHO; update DELTA and CPEN at the same time.
+        if reduce_rho:
+            if rho <= rhoend:
+                info = SMALL_TR_RADIUS
+                break
+            delta = max(0.5 * rho, redrho(rho, rhoend))
+            rho = redrho(rho, rhoend)
+            # THe second (out of two) updates of CPEN, where CPEN decreases or remains the same.
+            # Powell's code: cpen = min(cpen, fcratio(fval, conmat)), which may set CPEN to 0.
+            cpen = np.maximum(cpenmin, np.minimum(cpen, fcratio(conmat, fval)))
+            # Print a message about the reduction of rho according to iprint
+            rhomsg(solver, iprint, nf, fval[num_vars], rho, sim[:, num_vars], cval[num_vars], conmat[:, num_vars], cpen)
+            conmat, cval, fval, sim, simi, subinfo = updatepole(cpen, conmat, cval, fval, sim, simi)
+            # Check whether to break due to damaging rounding detected in updatepole
+            if subinfo == DAMAGING_ROUNDING:
+                info = subinfo
+                break  # Better action to take? Geometry step, or simply continue?
+        # End of if reduce_rho. The procedure of reducing RHO ends.
+        # Report the current best value, and check if user asks for early termination.
+        if callback:
+            terminate = callback(sim[:, num_vars], fval[num_vars], nf, tr, cval[num_vars], conmat[:, num_vars])
+            if terminate:
+                info = CALLBACK_TERMINATE
+                break
+    # End of for loop. The iterative procedure ends
+
+    # Return from the calculation, after trying the last trust-region step if it has not been tried yet.
+    # Ensure that D has not been updated after SHORTD == TRUE occurred, or the code below is incorrect.
+    x = sim[:, num_vars] + d
+    if (info == SMALL_TR_RADIUS and
+            shortd and
+            norm(x - sim[:, num_vars]) > 1.0E-3 * rhoend and
+            nf < maxfun):
+        # Zaikun 20230615: UPDATEXFC or UPDATEPOLE is not called since the last trust-region step. Hence
+        # SIM[:, NUM_VARS] remains unchanged. Otherwise SIM[:, NUM_VARS] + D would not make sense.
+        f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+        cstrv = np.max(np.append(0, constr))
+        nf += 1
+        savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+        nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cstrv, ctol, cweight, f, x, nfilt, cfilt, ffilt, xfilt, constr, confilt)
+        # Zaikun 20230512: DELTA has been updated. RHO is only indicative here. TO BE IMPROVED.
+        fmsg(solver, 'Trust region', iprint, nf, rho, f, x, cstrv, constr)
+
+    # Return the best calculated values of the variables
+    # N.B.: SELECTX and FINDPOLE choose X by different standards, one cannot replace the other.
+    kopt = selectx(ffilt[:nfilt], cfilt[:nfilt], max(cpen, cweight), ctol)
+    x = xfilt[:, kopt]
+    f = ffilt[kopt]
+    constr = confilt[:, kopt]
+    cstrv = cfilt[kopt]
+
+    # Print a return message according to IPRINT.
+    retmsg(solver, info, iprint, nf, f, x, cstrv, constr)
+    return x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info
+
+
+
+def getcpen(amat, bvec, conmat, cpen, cval, delta, fval, rho, sim, simi):
+    '''
+    This function gets the penalty parameter CPEN so that PREREM = PREREF + CPEN * PREREC > 0.
+    See the discussions around equation (9) of the COBYLA paper.
+    '''
+
+    # Even after nearly all of the pycutest problems were showing nearly bit for bit
+    # identical results between Python and the Fortran bindings, HS102 was still off by
+    # more than machine epsilon. It turned out to be due to the fact that getcpen was
+    # modifying fval, among other. It just goes to show that even when you're nearly
+    # perfect, you can still have non trivial bugs.
+    conmat = conmat.copy()
+    cval = cval.copy()
+    fval = fval.copy()
+    sim = sim.copy()
+    simi = simi.copy()
+
+    # Intermediate variables
+    A = np.zeros((np.size(sim, 0), np.size(conmat, 0)))
+    itol = 1
+
+    # Sizes
+    m_lcon = np.size(bvec) if bvec is not None else 0
+    num_constraints = np.size(conmat, 0)
+    num_vars = np.size(sim, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert cpen > 0
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and \
+            not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+        assert delta >= rho and rho > 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Initialize INFO which is needed in the postconditions
+    info = INFO_DEFAULT
+
+    # Increase CPEN if necessary to ensure PREREM > 0. Branch back for the next loop
+    # if this change alters the optimal vertex of the current simplex.
+    # Note the following:
+    # 1. In each loop, CPEN is changed only if PREREC > 0 > PREREF, in which case
+    #    PREREM is guaranteed positive after the update. Note that PREREC >= 0 and
+    #    max(PREREC, PREREF) > 0 in theory. If this holds numerically as well then CPEN
+    #    is not changed only if PREREC = 0 or PREREF >= 0, in which case PREREM is
+    #    currently positive, explaining why CPEN needs no update.
+    # 2. Even without an upper bound for the loop counter, the loop can occur at most
+    #    NUM_VARS+1 times. This is because the update of CPEN does not decrease CPEN,
+    #    and hence it can make vertex J (J <= NUM_VARS) become the new optimal vertex
+    #    only if CVAL[J] is less than CVAL[NUM_VARS], which can happen at most NUM_VARS
+    #    times. See the paragraph below (9) in the COBYLA paper. After the "correct"
+    #    optimal vertex is found, one more loop is needed to calculate CPEN, and hence
+    #    the loop can occur at most NUM_VARS+1 times.
+    for iter in range(num_vars + 1):
+        # Switch the best vertex of the current simplex to SIM[:, NUM_VARS]
+        conmat, cval, fval, sim, simi, info = updatepole(cpen, conmat, cval, fval, sim,
+                                                         simi)
+        # Check whether to exit due to damaging rounding in UPDATEPOLE
+        if info == DAMAGING_ROUNDING:
+            break
+
+        # Calculate the linear approximations to the objective and constraint functions.
+        g = matprod(fval[:num_vars] - fval[num_vars], simi)
+        A[:, :m_lcon] = amat.T if amat is not None else amat
+        A[:, m_lcon:] = matprod((conmat[m_lcon:, :num_vars] -
+                          np.tile(conmat[m_lcon:, num_vars], (num_vars, 1)).T), simi).T
+
+        # Calculate the trust-region trial step D. Note that D does NOT depend on CPEN.
+        d = trstlp(A, -conmat[:, num_vars], delta, g)
+
+        # Predict the change to F (PREREF) and to the constraint violation (PREREC) due
+        # to D.
+        preref = -inprod(d, g)  # Can be negative
+        prerec = cval[num_vars] - np.max(np.append(0, conmat[:, num_vars] + matprod(d, A)))
+
+        # PREREC <= 0 or PREREF >=0 or either is NaN
+        if not (prerec > 0 and preref < 0):
+            break
+
+        # Powell's code defines BARMU = -PREREF / PREREC, and CPEN is increased to
+        # 2*BARMU if and only if it is currently less than 1.5*BARMU, a very
+        # "Powellful" scheme. In our implementation, however, we set CPEN directly to
+        # the maximum between its current value and 2*BARMU while handling possible
+        # overflow. The simplifies the scheme without worsening the performance of
+        # COBYLA.
+        cpen = max(cpen, min(-2 * preref / prerec, REALMAX))
+
+        if findpole(cpen, cval, fval) == num_vars:
+            break
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert cpen >= cpen and cpen > 0
+        assert preref + cpen * prerec > 0 or info == DAMAGING_ROUNDING or \
+            not (prerec >= 0 and np.maximum(prerec, preref) > 0) or not np.isfinite(preref)
+
+    return cpen
+
+
+def fcratio(conmat, fval):
+    '''
+    This function calculates the ratio between the "typical change" of F and that of CONSTR.
+    See equations (12)-(13) in Section 3 of the COBYLA paper for the definition of the ratio.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert np.size(fval) >= 1
+        assert np.size(conmat, 1) == np.size(fval)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    cmin = np.min(-conmat, axis=1)
+    cmax = np.max(-conmat, axis=1)
+    fmin = min(fval)
+    fmax = max(fval)
+    if any(cmin < 0.5 * cmax) and fmin < fmax:
+        denom = np.min(np.maximum(cmax, 0) - cmin, where=cmin < 0.5 * cmax, initial=np.inf)
+        # Powell mentioned the following alternative in section 4 of his COBYLA paper. According to a test
+        # on 20230610, it does not make much difference to the performance.
+        # denom = np.max(max(*cmax, 0) - cmin, mask=(cmin < 0.5 * cmax))
+        r = (fmax - fmin) / denom
+    else:
+        r = 0
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert r >= 0
+
+    return r
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/geometry.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..03f8486997f8d177a552df11cd0a41adc969380d
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/geometry.py
@@ -0,0 +1,226 @@
+'''
+This module contains subroutines concerning the geometry-improving of the interpolation set.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from ..common.consts import DEBUGGING
+from ..common.linalg import isinv, matprod, inprod, norm, primasum, primapow2
+import numpy as np
+
+
+def setdrop_tr(ximproved, d, delta, rho, sim, simi):
+    '''
+    This function finds (the index) of a current interpolation point to be replaced with
+    the trust-region trial point. See (19)-(22) of the COBYLA paper.
+    N.B.:
+    1. If XIMPROVED == True, then JDROP > 0 so that D is included into XPT. Otherwise,
+       it is a bug.
+    2. COBYLA never sets JDROP = NUM_VARS
+    TODO: Check whether it improves the performance if JDROP = NUM_VARS is allowed when
+    XIMPROVED is True. Note that UPDATEXFC should be revised accordingly.
+    '''
+
+    # Local variables
+    itol = 0.1
+
+    # Sizes
+    num_vars = np.size(sim, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        assert np.size(d) == num_vars and all(np.isfinite(d))
+        assert delta >= rho and rho > 0
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # -------------------------------------------------------------------------------------------------- #
+    #  The following code is Powell's scheme for defining JDROP.
+    # -------------------------------------------------------------------------------------------------- #
+    # ! JDROP = 0 by default. It cannot be removed, as JDROP may not be set below in some cases (e.g.,
+    # ! when XIMPROVED == FALSE, MAXVAL(ABS(SIMID)) <= 1, and MAXVAL(VETA) <= EDGMAX).
+    # jdrop = 0
+    #
+    # ! SIMID(J) is the value of the J-th Lagrange function at D. It is the counterpart of VLAG in UOBYQA
+    # ! and DEN in NEWUOA/BOBYQA/LINCOA, but it excludes the value of the (N+1)-th Lagrange function.
+    # simid = matprod(simi, d)
+    # if (any(abs(simid) > 1) .or. (ximproved .and. any(.not. is_nan(simid)))) then
+    #     jdrop = int(maxloc(abs(simid), mask=(.not. is_nan(simid)), dim=1), kind(jdrop))
+    #     !!MATLAB: [~, jdrop] = max(simid, [], 'omitnan');
+    # end if
+    #
+    # ! VETA(J) is the distance from the J-th vertex of the simplex to the best vertex, taking the trial
+    # ! point SIM(:, N+1) + D into account.
+    # if (ximproved) then
+    #     veta = sqrt(sum((sim(:, 1:n) - spread(d, dim=2, ncopies=n))**2, dim=1))
+    #     !!MATLAB: veta = sqrt(sum((sim(:, 1:n) - d).^2));  % d should be a column! Implicit expansion
+    # else
+    #     veta = sqrt(sum(sim(:, 1:n)**2, dim=1))
+    # end if
+    #
+    # ! VSIG(J) (J=1, .., N) is the Euclidean distance from vertex J to the opposite face of the simplex.
+    # vsig = ONE / sqrt(sum(simi**2, dim=2))
+    # sigbar = abs(simid) * vsig
+    #
+    # ! The following JDROP will overwrite the previous one if its premise holds.
+    # mask = (veta > factor_delta * delta .and. (sigbar >= factor_alpha * delta .or. sigbar >= vsig))
+    # if (any(mask)) then
+    #     jdrop = int(maxloc(veta, mask=mask, dim=1), kind(jdrop))
+    #     !!MATLAB: etamax = max(veta(mask)); jdrop = find(mask & ~(veta < etamax), 1, 'first');
+    # end if
+    #
+    # ! Powell's code does not include the following instructions. With Powell's code, if SIMID consists
+    # ! of only NaN, then JDROP can be 0 even when XIMPROVED == TRUE (i.e., D reduces the merit function).
+    # ! With the following code, JDROP cannot be 0 when XIMPROVED == TRUE, unless VETA is all NaN, which
+    # ! should not happen if X0 does not contain NaN, the trust-region/geometry steps never contain NaN,
+    # ! and we exit once encountering an iterate containing Inf (due to overflow).
+    # if (ximproved .and. jdrop <= 0) then  ! Write JDROP <= 0 instead of JDROP == 0 for robustness.
+    #     jdrop = int(maxloc(veta, mask=(.not. is_nan(veta)), dim=1), kind(jdrop))
+    #     !!MATLAB: [~, jdrop] = max(veta, [], 'omitnan');
+    # end if
+    # -------------------------------------------------------------------------------------------------- #
+    #  Powell's scheme ends here.
+    # -------------------------------------------------------------------------------------------------- #
+
+    # The following definition of JDROP is inspired by SETDROP_TR in UOBYQA/NEWUOA/BOBYQA/LINCOA.
+    # It is simpler and works better than Powell's scheme. Note that we allow JDROP to be NUM_VARS+1 if
+    # XIMPROVED is True, whereas Powell's code does not.
+    # See also (4.1) of Scheinberg-Toint-2010: Self-Correcting Geometry in Model-Based Algorithms for
+    # Derivative-Free Unconstrained Optimization, which refers to the strategy here as the "combined
+    # distance/poisedness criteria".
+
+    # DISTSQ[j] is the square of the distance from the jth vertex of the simplex to get "best" point so
+    # far, taking the trial point SIM[:, NUM_VARS] + D into account.
+    distsq = np.zeros(np.size(sim, 1))
+    if ximproved:
+        distsq[:num_vars] = primasum(primapow2(sim[:, :num_vars] - np.tile(d, (num_vars, 1)).T), axis=0)
+        distsq[num_vars] = primasum(d*d)
+    else:
+        distsq[:num_vars] = primasum(primapow2(sim[:, :num_vars]), axis=0)
+        distsq[num_vars] = 0
+
+    weight = np.maximum(1, distsq / primapow2(np.maximum(rho, delta/10)))  # Similar to Powell's NEWUOA code.
+
+    # Other possible definitions of weight. They work almost the same as the one above.
+    # weight = distsq  # Similar to Powell's LINCOA code, but WRONG. See comments in LINCOA/geometry.f90.
+    # weight = max(1, max(25 * distsq / delta**2))  # Similar to Powell's BOBYQA code, works well.
+    # weight = max(1, max(10 * distsq / delta**2))
+    # weight = max(1, max(1e2 * distsq / delta**2))
+    # weight = max(1, max(distsq / rho**2))  ! Similar to Powell's UOBYQA
+
+    # If 0 <= j < NUM_VARS, SIMID[j] is the value of the jth Lagrange function at D; the value of the
+    # (NUM_VARS+1)th Lagrange function is 1 - sum(SIMID). [SIMID, 1 - sum(SIMID)] is the counterpart of
+    # VLAG in UOBYQA and DEN in NEWUOA/BOBYQA/LINCOA.
+    simid = matprod(simi, d)
+    score = weight * abs(np.array([*simid, 1 - primasum(simid)]))
+
+    # If XIMPROVED = False (D does not render a better X), set SCORE[NUM_VARS] = -1 to avoid JDROP = NUM_VARS.
+    if not ximproved:
+        score[num_vars] = -1
+
+    # score[j] is NaN implies SIMID[j] is NaN, but we want abs(SIMID) to be big. So we
+    # exclude such j.
+    score[np.isnan(score)] = -1
+
+    jdrop = None
+    # The following if statement works a bit better than
+    # `if any(score > 1) or (any(score > 0) and ximproved)` from Powell's UOBYQA and
+    # NEWUOA code.
+    if any(score > 0):  # Powell's BOBYQA and LINCOA code.
+        jdrop = np.argmax(score)
+
+    if (ximproved and jdrop is None):
+        jdrop = np.argmax(distsq)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert jdrop is None or (0 <= jdrop < num_vars + 1)
+        assert jdrop <= num_vars or ximproved
+        assert jdrop >= 0 or not ximproved
+        # JDROP >= 1 when XIMPROVED = TRUE unless NaN occurs in DISTSQ, which should not happen if the
+        # starting point does not contain NaN and the trust-region/geometry steps never contain NaN.
+
+    return jdrop
+
+
+
+
+def geostep(jdrop, amat, bvec, conmat, cpen, cval, delbar, fval, simi):
+    '''
+    This function calculates a geometry step so that the geometry of the interpolation set is improved
+    when SIM[: JDROP_GEO] is replaced with SIM[:, NUM_VARS] + D. See (15)--(17) of the COBYLA paper.
+    '''
+
+    # Sizes
+    m_lcon = np.size(bvec, 0) if bvec is not None else 0
+    num_constraints = np.size(conmat, 0)
+    num_vars = np.size(simi, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= m_lcon >= 0
+        assert num_vars >= 1
+        assert delbar > 0
+        assert cpen > 0
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not np.any(np.isnan(conmat) | np.isposinf(conmat))
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert 0 <= jdrop < num_vars
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # SIMI[JDROP, :] is a vector perpendicular to the face of the simplex to the opposite of vertex
+    # JDROP. Set D to the vector in this direction and with length DELBAR.
+    d = simi[jdrop, :]
+    d = delbar * (d / norm(d))
+
+    # The code below chooses the direction of D according to an approximation of the merit function.
+    # See (17) of the COBYLA paper and  line 225 of Powell's cobylb.f.
+
+    # Calculate the coefficients of the linear approximations to the objective and constraint functions.
+    # N.B.: CONMAT and SIMI have been updated after the last trust-region step, but G and A have not.
+    # So we cannot pass G and A from outside.
+    g = matprod(fval[:num_vars] - fval[num_vars], simi)
+    A = np.zeros((num_vars, num_constraints))
+    A[:, :m_lcon] = amat.T if amat is not None else amat
+    A[:, m_lcon:] = matprod((conmat[m_lcon:, :num_vars] -
+                          np.tile(conmat[m_lcon:, num_vars], (num_vars, 1)).T), simi).T
+    # CVPD and CVND are the predicted constraint violation of D and -D by the linear models.
+    cvpd = np.max(np.append(0, conmat[:, num_vars] + matprod(d, A)))
+    cvnd = np.max(np.append(0, conmat[:, num_vars] - matprod(d, A)))
+    if -inprod(d, g) + cpen * cvnd < inprod(d, g) + cpen * cvpd:
+        d *= -1
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert np.size(d) == num_vars and all(np.isfinite(d))
+        # In theory, ||S|| == DELBAR, which may be false due to rounding, but not too far.
+        # It is crucial to ensure that the geometry step is nonzero, which holds in theory.
+        assert 0.9 * delbar < np.linalg.norm(d) <= 1.1 * delbar
+    return d
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/initialize.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/initialize.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f0640b49ede87f54c7e128487b921f7f68d645f
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/initialize.py
@@ -0,0 +1,215 @@
+'''
+This module contains subroutines for initialization.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from ..common.checkbreak import checkbreak_con
+from ..common.consts import DEBUGGING, REALMAX
+from ..common.infos import INFO_DEFAULT
+from ..common.evaluate import evaluate
+from ..common.history import savehist
+from ..common.linalg import inv
+from ..common.message import fmsg
+from ..common.selectx import savefilt
+
+import numpy as np
+
+def initxfc(calcfc, iprint, maxfun, constr0, amat, bvec, ctol, f0, ftarget, rhobeg, x0,
+            xhist, fhist, chist, conhist, maxhist):
+    '''
+    This subroutine does the initialization concerning X, function values, and
+    constraints.
+    '''
+
+    # Local variables
+    solver = 'COBYLA'
+    srname = "INITIALIZE"
+
+    # Sizes
+    num_constraints = np.size(constr0)
+    m_lcon = np.size(bvec) if bvec is not None else 0
+    m_nlcon = num_constraints - m_lcon
+    num_vars = np.size(x0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0, f'M >= 0 {srname}'
+        assert num_vars >= 1, f'N >= 1 {srname}'
+        assert abs(iprint) <= 3, f'IPRINT is 0, 1, -1, 2, -2, 3, or -3 {srname}'
+        # assert conmat.shape == (num_constraints , num_vars + 1), f'CONMAT.shape = [M, N+1] {srname}'
+        # assert cval.size == num_vars + 1, f'CVAL.size == N+1 {srname}'
+        # assert maxchist * (maxchist - maxhist) == 0, f'CHIST.shape == 0 or MAXHIST {srname}'
+        # assert conhist.shape[0] == num_constraints and maxconhist * (maxconhist - maxhist) == 0, 'CONHIST.shape[0] == num_constraints, SIZE(CONHIST, 2) == 0 or MAXHIST {srname)}'
+        # assert maxfhist * (maxfhist - maxhist) == 0, f'FHIST.shape == 0 or MAXHIST {srname}'
+        # assert xhist.shape[0] == num_vars and maxxhist * (maxxhist - maxhist) == 0, 'XHIST.shape[0] == N, SIZE(XHIST, 2) == 0 or MAXHIST {srname)}'
+        assert all(np.isfinite(x0)), f'X0 is finite {srname}'
+        assert rhobeg > 0, f'RHOBEG > 0 {srname}'
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Initialize info to the default value. At return, a value different from this
+    # value will indicate an abnormal return
+    info = INFO_DEFAULT
+
+    # Initialize the simplex. It will be revised during the initialization.
+    sim = np.eye(num_vars, num_vars+1) * rhobeg
+    sim[:, num_vars] = x0
+
+    # Initialize the matrix simi. In most cases simi is overwritten, but not always.
+    simi = np.eye(num_vars) / rhobeg
+
+    # evaluated[j] = True iff the function/constraint of SIM[:, j] has been evaluated.
+    evaluated = np.zeros(num_vars+1, dtype=bool)
+
+    # Initialize fval
+    fval = np.zeros(num_vars+1) + REALMAX
+    cval = np.zeros(num_vars+1) + REALMAX
+    conmat = np.zeros((num_constraints, num_vars+1)) + REALMAX
+
+
+    for k in range(num_vars + 1):
+        x = sim[:, num_vars].copy()
+        # We will evaluate F corresponding to SIM(:, J).
+        if k == 0:
+            j = num_vars
+            f = f0
+            constr = constr0
+        else:
+            j = k - 1
+            x[j] += rhobeg
+            f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+        cstrv = np.max(np.append(0, constr))
+
+        # Print a message about the function/constraint evaluation according to IPRINT.
+        fmsg(solver, 'Initialization', iprint, k, rhobeg, f, x, cstrv, constr)
+
+        # Save X, F, CONSTR, CSTRV into the history.
+        savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+
+        # Save F, CONSTR, and CSTRV to FVAL, CONMAT, and CVAL respectively.
+        evaluated[j] = True
+        fval[j] = f
+        conmat[:, j] = constr
+        cval[j] = cstrv
+
+        # Check whether to exit.
+        subinfo = checkbreak_con(maxfun, k, cstrv, ctol, f, ftarget, x)
+        if subinfo != INFO_DEFAULT:
+            info = subinfo
+            break
+
+        # Exchange the new vertex of the initial simplex with the optimal vertex if necessary.
+        # This is the ONLY part that is essentially non-parallel.
+        if j < num_vars and fval[j] < fval[num_vars]:
+            fval[j], fval[num_vars] = fval[num_vars], fval[j]
+            cval[j], cval[num_vars] = cval[num_vars], cval[j]
+            conmat[:, [j, num_vars]] = conmat[:, [num_vars, j]]
+            sim[:, num_vars] = x
+            sim[j, :j+1] = -rhobeg  # SIM[:, :j+1] is lower triangular
+
+    nf = np.count_nonzero(evaluated)
+
+    if evaluated.all():
+        # Initialize SIMI to the inverse of SIM[:, :num_vars]
+        simi = inv(sim[:, :num_vars])
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert nf <= maxfun, f'NF <= MAXFUN {srname}'
+        assert evaluated.size == num_vars + 1, f'EVALUATED.size == Num_vars + 1 {srname}'
+        # assert chist.size == maxchist, f'CHIST.size == MAXCHIST {srname}'
+        # assert conhist.shape== (num_constraints, maxconhist), f'CONHIST.shape == [M, MAXCONHIST] {srname}'
+        assert conmat.shape == (num_constraints, num_vars + 1), f'CONMAT.shape = [M, N+1] {srname}'
+        assert not (np.isnan(conmat).any() or np.isneginf(conmat).any()), f'CONMAT does not contain NaN/-Inf {srname}'
+        assert cval.size == num_vars + 1 and not (any(cval < 0) or any(np.isnan(cval)) or any(np.isposinf(cval))), f'CVAL.shape == Num_vars+1 and CVAL does not contain negative values or NaN/+Inf {srname}'
+        # assert fhist.shape == maxfhist, f'FHIST.shape == MAXFHIST {srname}'
+        # assert maxfhist * (maxfhist - maxhist) == 0, f'FHIST.shape == 0 or MAXHIST {srname}'
+        assert fval.size == num_vars + 1 and not (any(np.isnan(fval)) or any(np.isposinf(fval))), f'FVAL.shape == Num_vars+1 and FVAL is not NaN/+Inf {srname}'
+        # assert xhist.shape == (num_vars, maxxhist), f'XHIST.shape == [N, MAXXHIST] {srname}'
+        assert sim.shape == (num_vars, num_vars + 1), f'SIM.shape == [N, N+1] {srname}'
+        assert np.isfinite(sim).all(), f'SIM is finite {srname}'
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0), f'SIM(:, 1:N) has no zero column {srname}'
+        assert simi.shape == (num_vars, num_vars), f'SIMI.shape == [N, N] {srname}'
+        assert np.isfinite(simi).all(), f'SIMI is finite {srname}'
+        assert np.allclose(sim[:, :num_vars] @ simi, np.eye(num_vars), rtol=0.1, atol=0.1) or not all(evaluated), f'SIMI = SIM(:, 1:N)^{-1} {srname}'
+
+    return evaluated, conmat, cval, sim, simi, fval, nf, info
+
+
+def initfilt(conmat, ctol, cweight, cval, fval, sim, evaluated, cfilt, confilt, ffilt, xfilt):
+    '''
+    This function initializes the filter (XFILT, etc) that will be used when selecting
+    x at the end of the solver.
+    N.B.:
+    1. Why not initialize the filters using XHIST, etc? Because the history is empty if
+    the user chooses not to output it.
+    2. We decouple INITXFC and INITFILT so that it is easier to parallelize the former
+    if needed.
+    '''
+
+    # Sizes
+    num_constraints = conmat.shape[0]
+    num_vars = sim.shape[0]
+    maxfilt = len(ffilt)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert maxfilt >= 1
+        assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+        assert np.size(cfilt) == maxfilt
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert np.size(ffilt) == maxfilt
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(evaluated) == num_vars + 1
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+
+    nfilt = 0
+    for i in range(num_vars+1):
+        if evaluated[i]:
+            if i < num_vars:
+                x = sim[:, i] + sim[:, num_vars]
+            else:
+                x = sim[:, i]  # i == num_vars, i.e. the last column
+            nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cval[i], ctol, cweight, fval[i], x, nfilt, cfilt, ffilt, xfilt, conmat[:, i], confilt)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert nfilt <= maxfilt
+        assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+        assert not (np.isnan(confilt[:, :nfilt]) | np.isneginf(confilt[:, :nfilt])).any()
+        assert np.size(cfilt) == maxfilt
+        assert not any(cfilt[:nfilt] < 0 | np.isnan(cfilt[:nfilt]) | np.isposinf(cfilt[:nfilt]))
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert not (np.isnan(xfilt[:, :nfilt])).any()
+        # The last calculated X can be Inf (finite + finite can be Inf numerically).
+        assert np.size(ffilt) == maxfilt
+        assert not any(np.isnan(ffilt[:nfilt]) | np.isposinf(ffilt[:nfilt]))
+
+    return nfilt
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/trustregion.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..50682e967164e7724132ac680fdd7b03b4f38b3a
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/trustregion.py
@@ -0,0 +1,492 @@
+'''
+This module provides subroutines concerning the trust-region calculations of COBYLA.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+import numpy.typing as npt
+from ..common.consts import DEBUGGING, REALMIN, REALMAX, EPS
+from ..common.powalg import qradd_Rdiag, qrexc_Rdiag
+from ..common.linalg import isminor, matprod, inprod, lsqr, primasum
+
+
+def trstlp(A, b, delta, g):
+    '''
+    This function calculated an n-component vector d by the following two stages. In the first
+    stage, d is set to the shortest vector that minimizes the greatest violation of the constraints
+        A.T @ D <= B,  K = 1, 2, 3, ..., M,
+    subject to the Euclidean length of d being at most delta. If its length is strictly less than
+    delta, then the second stage uses the resultant freedom in d to minimize the objective function
+        G.T @ D
+    subject to no increase in any greatest constraint violation.
+
+    It is possible but rare that a degeneracy may prevent d from attaining the target length delta.
+
+    cviol is the largest constraint violation of the current d: max(max(A.T@D - b), 0)
+    icon is the index of a most violated constraint if cviol is positive.
+
+    nact is the number of constraints in the active set and iact[0], ..., iact[nact-1] are their indices,
+    while the remainder of the iact contains a permutation of the remaining constraint indicies.
+    N.B.: nact <= min(num_constraints, num_vars). Obviously nact <= num_constraints. In addition, the constraints
+    in iact[0, ..., nact-1] have linearly independent gradients (see the comments above the instruction
+    that delete a constraint from the active set to make room for the new active constraint with index iact[icon]);
+    it can also be seen from the update of nact: starting from 0, nact is incremented only if nact < n.
+
+    Further, Z is an orthogonal matrix whose first nact columns can be regarded as the result of
+    Gram-Schmidt applied to the active constraint gradients. For j = 0, 1, ..., nact-1, the number
+    zdota[j] is the scalar product of the jth column of Z with the gradient of the jth active
+    constraint. d is the current vector of variables and here the residuals of the active constraints
+    should be zero. Further, the active constraints have nonnegative Lagrange multipliers that are
+    held at the beginning of vmultc. The remainder of this vector holds the residuals of the inactive
+    constraints at d, the ordering of the components of vmultc being in agreement with the permutation
+    of the indices of the constraints that is in iact. All these residuals are nonnegative, which is
+    achieved by the shift cviol that makes the least residual zero.
+
+    N.B.:
+    0. In Powell's implementation, the constraints are A.T @ D >= B. In other words, the A and B in
+    our implementation are the negative of those in Powell's implementation.
+    1. The algorithm was NOT documented in the COBYLA paper. A note should be written to introduce it!
+    2. As a major part of the algorithm (see trstlp_sub), the code maintains and updates the QR
+    factorization of A[iact[:nact]], i.e. the gradients of all the active (linear) constraints. The
+    matrix Z is indeed Q, and the vector zdota is the diagonal of R. The factorization is updated by
+    Givens rotations when an index is added in or removed from iact.
+    3. There are probably better algorithms available for the trust-region linear programming problem.
+    '''
+
+    # Sizes
+    num_constraints = A.shape[1]
+    num_vars = A.shape[0]
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        assert num_constraints >= 0
+        assert np.size(g) == num_vars
+        assert np.size(b) == num_constraints
+        assert delta > 0
+
+
+    vmultc = np.zeros(num_constraints + 1)
+    iact = np.zeros(num_constraints + 1, dtype=int)
+    nact = 0
+    d = np.zeros(num_vars)
+    z = np.zeros((num_vars, num_vars))
+
+    # ==================
+    # Calculation starts
+    # ==================
+
+    # Form A_aug and B_aug. This allows the gradient of the objective function to be regarded as the
+    # gradient of a constraint in the second stage.
+    A_aug = np.hstack([A, g.reshape((num_vars, 1))])
+    b_aug = np.hstack([b, 0])
+
+
+    # Scale the problem if A contains large values. Otherwise floating point exceptions may occur.
+    # Note that the trust-region step is scale invariant.
+    for i in range(num_constraints+1):  # Note that A_aug.shape[1] == num_constraints+1
+        if (maxval:=max(abs(A_aug[:, i]))) > 1e12:
+            modscal = max(2*REALMIN, 1/maxval)
+            A_aug[:, i] *= modscal
+            b_aug[i] *= modscal
+
+    # Stage 1: minimize the 1+infinity constraint violation of the linearized constraints.
+    iact[:num_constraints], nact, d, vmultc[:num_constraints], z = trstlp_sub(iact[:num_constraints], nact, 1, A_aug[:, :num_constraints], b_aug[:num_constraints], delta, d, vmultc[:num_constraints], z)
+
+    # Stage 2: minimize the linearized objective without increasing the 1_infinity constraint violation.
+    iact, nact, d, vmultc, z = trstlp_sub(iact, nact, 2, A_aug, b_aug, delta, d, vmultc, z)
+
+    # ================
+    # Calculation ends
+    # ================
+
+    # Postconditions
+    if DEBUGGING:
+        assert all(np.isfinite(d))
+        # Due to rounding, it may happen that ||D|| > DELTA, but ||D|| > 2*DELTA is highly improbable.
+        assert np.linalg.norm(d) <= 2 * delta
+
+    return d
+
+def trstlp_sub(iact: npt.NDArray, nact: int, stage, A, b, delta, d, vmultc, z):
+    '''
+    This subroutine does the real calculations for trstlp, both stage 1 and stage 2.
+    Major differences between stage 1 and stage 2:
+    1. Initialization. Stage 2 inherits the values of some variables from stage 1, so they are
+    initialized in stage 1 but not in stage 2.
+    2. cviol. cviol is updated after at iteration in stage 1, while it remains a constant in stage2.
+    3. sdirn. See the definition of sdirn in the code for details.
+    4. optnew. The two stages have different objectives, so optnew is updated differently.
+    5. step. step <= cviol in stage 1.
+    '''
+    zdasav = np.zeros(z.shape[1])
+    vmultd = np.zeros(np.size(vmultc))
+    zdota = np.zeros(np.size(z, 1))
+
+    # Sizes
+    mcon = np.size(A, 1)
+    num_vars = np.size(A, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        assert stage == 1 or stage == 2
+        assert (mcon >= 0 and stage == 1) or (mcon >= 1 and stage == 2)
+        assert np.size(b) == mcon
+        assert np.size(iact) == mcon
+        assert np.size(vmultc) == mcon
+        assert np.size(d) == num_vars
+        assert np.size(z, 0) == num_vars and np.size(z, 1) == num_vars
+        assert delta > 0
+        if stage == 2:
+            assert all(np.isfinite(d)) and np.linalg.norm(d) <= 2 * delta
+            assert nact >= 0 and nact <= np.minimum(mcon, num_vars)
+            assert all(vmultc[:mcon]) >= 0
+            # N.B.: Stage 1 defines only VMULTC(1:M); VMULTC(M+1) is undefined!
+
+
+    # Initialize according to stage
+    if stage == 1:
+        iact = np.linspace(0, mcon-1, mcon, dtype=int)
+        nact = 0
+        d = np.zeros(num_vars)
+        cviol = np.max(np.append(0, -b))
+        vmultc = cviol + b
+        z = np.eye(num_vars)
+        if mcon == 0 or cviol <= 0:
+            # Check whether a quick return is possible. Make sure the in-outputs have been initialized.
+            return iact, nact, d, vmultc, z
+
+        if all(np.isnan(b)):
+            return iact, nact, d, vmultc, z
+        else:
+            icon = np.nanargmax(-b)
+        num_constraints = mcon
+        sdirn = np.zeros(len(d))
+    else:
+        if inprod(d, d) >= delta*delta:
+            # Check whether a quick return is possible.
+            return iact, nact, d, vmultc, z
+
+        iact[mcon-1] = mcon-1
+        vmultc[mcon-1] = 0
+        num_constraints = mcon - 1
+        icon = mcon - 1
+
+        # In Powell's code, stage 2 uses the zdota and cviol calculated by stage1. Here we recalculate
+        # them so that they need not be passed from stage 1 to 2, and hence the coupling is reduced.
+        cviol = np.max(np.append(0, matprod(d, A[:, :num_constraints]) - b[:num_constraints]))
+    zdota[:nact] = [inprod(z[:, k], A[:, iact[k]]) for k in range(nact)]
+
+    # More initialization
+    optold = REALMAX
+    nactold = nact
+    nfail = 0
+
+    # Zaikun 20211011: vmultd is computed from scratch at each iteration, but vmultc is inherited
+
+    # Powell's code can encounter infinite cycling, which did happen when testing the following CUTEst
+    # problems: DANWOODLS, GAUSS1LS, GAUSS2LS, GAUSS3LS, KOEBHELB, TAX13322, TAXR13322. Indeed, in all
+    # these cases, Inf/NaN appear in d due to extremely large values in A (up to 10^219). To resolve
+    # this, we set the maximal number of iterations to maxiter, and terminate if Inf/NaN occurs in d.
+    maxiter = np.minimum(10000, 100*max(num_constraints, num_vars))
+    for iter in range(maxiter):
+        if DEBUGGING:
+            assert all(vmultc >= 0)
+        if stage == 1:
+            optnew = cviol
+        else:
+            optnew = inprod(d, A[:, mcon-1])
+
+        # End the current stage of the calculation if 3 consecutive iterations have either failed to
+        # reduce the best calculated value of the objective function or to increase the number of active
+        # constraints since the best value was calculated. This strategy prevents cycling, but there is
+        # a remote possibility that it will cause premature termination.
+        if optnew < optold or nact > nactold:
+            nactold = nact
+            nfail = 0
+        else:
+            nfail += 1
+        optold = np.minimum(optold, optnew)
+        if nfail == 3:
+            break
+
+        # If icon exceeds nact, then we add the constraint with index iact[icon] to the active set.
+        if icon >= nact:  # In Python this needs to be >= since Python is 0-indexed (in Fortran we have 1 > 0, in Python we need 0 >= 0)
+            zdasav[:nact] = zdota[:nact]
+            nactsav = nact
+            z, zdota, nact = qradd_Rdiag(A[:, iact[icon]], z, zdota, nact)  # May update nact to nact+1
+            # Indeed it suffices to pass zdota[:min(num_vars, nact+1)] to qradd as follows:
+            # qradd(A[:, iact[icon]], z, zdota[:min(num_vars, nact+1)], nact)
+
+            if nact == nactsav + 1:
+                # N.B.: It is possible to index arrays using [nact, icon] when nact == icon.
+                # Zaikun 20211012: Why should vmultc[nact] = 0?
+                if nact != (icon + 1):  # Need to add 1 to Python for 0 indexing
+                    vmultc[[icon, nact-1]] = vmultc[nact-1], 0
+                    iact[[icon, nact-1]] = iact[[nact-1, icon]]
+                else:
+                    vmultc[nact-1] = 0
+            else:
+                # Zaikun 20211011:
+                # 1. VMULTD is calculated from scratch for the first time (out of 2) in one iteration.
+                # 2. Note that IACT has not been updated to replace IACT[NACT] with IACT[ICON]. Thus
+                # A[:, IACT[:NACT]] is the UNUPDATED version before QRADD (note Z[:, :NACT] remains the
+                # same before and after QRADD). Therefore if we supply ZDOTA to LSQR (as Rdiag) as
+                # Powell did, we should use the UNUPDATED version, namely ZDASAV.
+                # vmultd[:nact] = lsqr(A[:, iact[:nact]], A[:, iact[icon]], z[:, :nact], zdasav[:nact])
+                vmultd[:nact] = lsqr(A[:, iact[:nact]], A[:, iact[icon]], z[:, :nact], zdasav[:nact])
+                if not any(np.logical_and(vmultd[:nact] > 0, iact[:nact] <= num_constraints)):
+                    # N.B.: This can be triggered by NACT == 0 (among other possibilities)! This is
+                    # important, because NACT will be used as an index in the sequel.
+                    break
+                # vmultd[NACT+1:mcon] is not used, but we have to initialize it in Fortran, or compilers
+                # complain about the where construct below (another solution: restrict where to 1:NACT).
+                vmultd[nact:mcon] = -1  # len(vmultd) == mcon
+
+                # Revise the Lagrange multipliers. The revision is not applicable to vmultc[nact:num_constraints].
+                fracmult = [vmultc[i]/vmultd[i] if vmultd[i] > 0 and iact[i] <= num_constraints else REALMAX for i in range(nact)]
+                # Only the places with vmultd > 0 and iact <= m is relevant below, if any.
+                frac = min(fracmult[:nact])  # fracmult[nact:mcon] may contain garbage
+                vmultc[:nact] = np.maximum(np.zeros(len(vmultc[:nact])), vmultc[:nact] - frac*vmultd[:nact])
+
+                # Reorder the active constraints so that the one to be replaced is at the end of the list.
+                # Exit if the new value of zdota[nact] is not acceptable. Powell's condition for the
+                # following If: not abs(zdota[nact]) > 0. Note that it is different from
+                # 'abs(zdota[nact]) <=0)' as zdota[nact] can be NaN.
+                # N.B.: We cannot arrive here with nact == 0, which should have triggered a break above
+                if np.isnan(zdota[nact - 1]) or abs(zdota[nact - 1]) <= EPS**2:
+                    break
+                vmultc[[icon, nact - 1]] = 0, frac  # vmultc[[icon, nact]] is valid as icon > nact
+                iact[[icon, nact - 1]] = iact[[nact - 1, icon]]
+            # end if nact == nactsav + 1
+
+            # In stage 2, ensure that the objective continues to be treated as the last active constraint.
+            # Zaikun 20211011, 20211111: Is it guaranteed for stage 2 that iact[nact-1] = mcon when
+            # iact[nact] != mcon??? If not, then how does the following procedure ensure that mcon is
+            # the last of iact[:nact]?
+            if stage == 2 and iact[nact - 1] != (mcon - 1):
+                if nact <= 1:
+                    # We must exit, as nact-2 is used as an index below. Powell's code does not have this.
+                    break
+                z, zdota[:nact] = qrexc_Rdiag(A[:, iact[:nact]], z, zdota[:nact], nact - 2)  # We pass nact-2 in Python instead of nact-1
+                # Indeed, it suffices to pass Z[:, :nact] to qrexc as follows:
+                # z[:, :nact], zdota[:nact] = qrexc(A[:, iact[:nact]], z[:, :nact], zdota[:nact], nact - 1)
+                iact[[nact-2, nact-1]] = iact[[nact-1, nact-2]]
+                vmultc[[nact-2, nact-1]] = vmultc[[nact-1, nact-2]]
+            # Zaikun 20211117: It turns out that the last few lines do not guarantee iact[nact] == num_vars in
+            # stage 2; the following test cannot be passed. IS THIS A BUG?!
+            # assert iact[nact] == mcon or stage == 1, 'iact[nact] must == mcon in stage 2'
+
+            # Powell's code does not have the following. It avoids subsequent floating points exceptions.
+            if np.isnan(zdota[nact-1]) or abs(zdota[nact-1]) <= EPS**2:
+                break
+
+            # Set sdirn to the direction of the next change to the current vector of variables
+            # Usually during stage 1 the vector sdirn gives a search direction that reduces all the
+            # active constraint violations by one simultaneously.
+            if stage == 1:
+                sdirn -= ((inprod(sdirn, A[:, iact[nact-1]]) + 1)/zdota[nact-1])*z[:, nact-1]
+            else:
+                sdirn = -1/zdota[nact-1]*z[:, nact-1]
+        else:  # icon < nact
+            # Delete the constraint with the index iact[icon] from the active set, which is done by
+            # reordering iact[icon:nact] into [iact[icon+1:nact], iact[icon]] and then reduce nact to
+            # nact - 1. In theory, icon > 0.
+            # assert icon > 0, "icon > 0 is required"  #  For Python I think this is irrelevant
+            z, zdota[:nact] = qrexc_Rdiag(A[:, iact[:nact]], z, zdota[:nact], icon)  # qrexc does nothing if icon == nact
+            # Indeed, it suffices to pass Z[:, :nact] to qrexc as follows:
+            # z[:, :nact], zdota[:nact] = qrexc(A[:, iact[:nact]], z[:, :nact], zdota[:nact], icon)
+            iact[icon:nact] = [*iact[icon+1:nact], iact[icon]]
+            vmultc[icon:nact] = [*vmultc[icon+1:nact], vmultc[icon]]
+            nact -= 1
+
+            # Powell's code does not have the following. It avoids subsequent exceptions.
+            # Zaikun 20221212: In theory, nact > 0 in stage 2, as the objective function should always
+            # be considered as an "active constraint" --- more precisely, iact[nact] = mcon. However,
+            # looking at the code, I cannot see why in stage 2 nact must be positive after the reduction
+            # above. It did happen in stage 1 that nact became 0 after the reduction --- this is
+            # extremely rare, and it was never observed until 20221212, after almost one year of
+            # random tests. Maybe nact is theoretically positive even in stage 1?
+            if stage == 2 and nact < 0:
+                break  # If this case ever occurs, we have to break, as nact is used as an index below.
+            if nact > 0:
+                if np.isnan(zdota[nact-1]) or abs(zdota[nact-1]) <= EPS**2:
+                    break
+
+            # Set sdirn to the direction of the next change to the current vector of variables.
+            if stage == 1:
+                sdirn -= inprod(sdirn, z[:, nact]) * z[:, nact]
+                # sdirn is orthogonal to z[:, nact+1]
+            else:
+                sdirn = -1/zdota[nact-1] * z[:, nact-1]
+        # end if icon > nact
+
+        # Calculate the step to the trust region boundary or take the step that reduces cviol to 0.
+        # ----------------------------------------------------------------------------------------- #
+        # The following calculation of step is adopted from NEWUOA/BOBYQA/LINCOA. It seems to improve
+        # the performance of COBYLA. We also found that removing the precaution about underflows is
+        # beneficial to the overall performance of COBYLA --- the underflows are harmless anyway.
+        dd = delta*delta - inprod(d, d)
+        ss = inprod(sdirn, sdirn)
+        sd = inprod(sdirn, d)
+        if dd <= 0 or ss <= EPS * delta*delta or np.isnan(sd):
+            break
+        # sqrtd: square root of a discriminant. The max avoids sqrtd < abs(sd) due to underflow
+        sqrtd = max(np.sqrt(ss*dd + sd*sd), abs(sd), np.sqrt(ss * dd))
+        if sd > 0:
+            step = dd / (sqrtd + sd)
+        else:
+            step = (sqrtd - sd) / ss
+        # step < 0 should not happen. Step can be 0 or NaN when, e.g., sd or ss becomes inf
+        if step <= 0 or not np.isfinite(step):
+            break
+
+        # Powell's approach and comments are as follows.
+        # -------------------------------------------------- #
+        # The two statements below that include the factor eps prevent
+        # some harmless underflows that occurred in a test calculation
+        # (Zaikun: here, eps is the machine epsilon; Powell's original
+        # code used 1.0e-6, and Powell's code was written in single
+        # precision). Further, we skip the step if it could be 0 within
+        # a reasonable tolerance for computer rounding errors.
+
+        #  !dd = delta*delta - sum(d**2, mask=(abs(d) >= EPS * delta))
+        #  !ss = inprod(sdirn, sdirn)
+        #  !if (dd  <= 0) then
+        #  !    exit
+        #  !end if
+        #  !sd = inprod(sdirn, d)
+        #  !if (abs(sd) >= EPS * sqrt(ss * dd)) then
+        #  !    step = dd / (sqrt(ss * dd + sd*sd) + sd)
+        #  !else
+        #  !    step = dd / (sqrt(ss * dd) + sd)
+        #  !end if
+        # -------------------------------------------------- #
+
+        if stage == 1:
+            if isminor(cviol, step):
+                break
+            step = min(step, cviol)
+
+        # Set dnew to the new variables if step is the steplength, and reduce cviol to the corresponding
+        # maximum residual if stage 1 is being done
+        dnew = d + step * sdirn
+        if stage == 1:
+            cviol = np.max(np.append(0, matprod(dnew, A[:, iact[:nact]]) - b[iact[:nact]]))
+            # N.B.: cviol will be used when calculating vmultd[nact+1:mcon].
+
+        # Zaikun 20211011:
+        # 1. vmultd is computed from scratch for the second (out of 2) time in one iteration.
+        # 2. vmultd[:nact] and vmultd[nact:mcon] are calculated separately with no coupling.
+        # 3. vmultd will be calculated from scratch again in the next iteration.
+        # Set vmultd to the vmultc vector that would occur if d became dnew. A device is included to
+        # force vmultd[k] = 0 if deviations from this value can be attributed to computer rounding
+        # errors. First calculate the new Lagrange multipliers.
+        vmultd[:nact] = -lsqr(A[:, iact[:nact]], dnew, z[:, :nact], zdota[:nact])
+        if stage == 2:
+            vmultd[nact-1] = max(0, vmultd[nact-1])  # This seems never activated.
+        # Complete vmultd by finding the new constraint residuals. (Powell wrote "Complete vmultc ...")
+        cvshift = cviol - (matprod(dnew, A[:, iact]) - b[iact])  # Only cvshift[nact+1:mcon] is needed
+        cvsabs = matprod(abs(dnew), abs(A[:, iact])) + abs(b[iact]) + cviol
+        cvshift[isminor(cvshift, cvsabs)] = 0
+        vmultd[nact:mcon] = cvshift[nact:mcon]
+
+        # Calculate the fraction of the step from d to dnew that will be taken
+        fracmult = [vmultc[i]/(vmultc[i] - vmultd[i]) if vmultd[i] < 0 else REALMAX for i in range(len(vmultd))]
+        # Only the places with vmultd < 0 are relevant below, if any.
+        icon = np.argmin(np.append(1, fracmult)) - 1
+        frac = min(np.append(1, fracmult))
+
+        # Update d, vmultc, and cviol
+        dold = d
+        d = (1 - frac)*d + frac * dnew
+        vmultc = np.maximum(0, (1 - frac)*vmultc + frac*vmultd)
+        # Break in the case of inf/nan in d or vmultc.
+        if not (np.isfinite(primasum(abs(d))) and np.isfinite(primasum(abs(vmultc)))):
+            d = dold  # Should we restore also iact, nact, vmultc, and z?
+            break
+
+        if stage == 1:
+            # cviol = (1 - frac) * cvold + frac * cviol  # Powell's version
+            # In theory, cviol = np.max(np.append(d@A - b, 0)), yet the
+            # cviol updated as above can be quite different from this value if A has huge entries (e.g., > 1e20)
+            cviol = np.max(np.append(0, matprod(d, A) - b))
+
+        if icon < 0 or icon >= mcon:
+            # In Powell's code, the condition is icon == 0. Indeed, icon < 0 cannot hold unless
+            # fracmult contains only nan, which should not happen; icon >= mcon should never occur.
+            break
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert np.size(iact) == mcon
+        assert np.size(vmultc) == mcon
+        assert all(vmultc >= 0)
+        assert np.size(d) == num_vars
+        assert all(np.isfinite(d))
+        assert np.linalg.norm(d) <= 2 * delta
+        assert np.size(z, 0) == num_vars and np.size(z, 1) == num_vars
+        assert nact >= 0 and nact <= np.minimum(mcon, num_vars)
+
+    return iact, nact, d, vmultc, z
+
+
+def trrad(delta_in, dnorm, eta1, eta2, gamma1, gamma2, ratio):
+    '''
+    This function updates the trust region radius according to RATIO and DNORM.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert delta_in >= dnorm > 0
+        assert 0 <= eta1 <= eta2 < 1
+        assert 0 < gamma1 < 1 < gamma2
+        # By the definition of RATIO in ratio.f90, RATIO cannot be NaN unless the
+        # actual reduction is NaN, which should NOT happen due to the moderated extreme
+        # barrier.
+        assert not np.isnan(ratio)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if ratio <= eta1:
+        delta = gamma1 * dnorm  # Powell's UOBYQA/NEWUOA
+        # delta = gamma1 * delta_in  # Powell's COBYLA/LINCOA
+        # delta = min(gamma1 * delta_in, dnorm)  # Powell's BOBYQA
+    elif ratio <= eta2:
+        delta = max(gamma1 * delta_in, dnorm)  # Powell's UOBYQA/NEWUOA/BOBYQA/LINCOA
+    else:
+        delta = max(gamma1 * delta_in, gamma2 * dnorm)  # Powell's NEWUOA/BOBYQA
+        # delta = max(delta_in, gamma2 * dnorm)  # Modified version. Works well for UOBYQA
+        # For noise-free CUTEst problems of <= 100 variables, Powell's version works slightly better
+        # than the modified one.
+        # delta = max(delta_in, 1.25*dnorm, dnorm + rho)  # Powell's UOBYQA
+        # delta = min(max(gamma1 * delta_in, gamma2 * dnorm), gamma3 * delta_in)  # Powell's LINCOA, gamma3 = np.sqrt(2)
+
+    # For noisy problems, the following may work better.
+    # if ratio <= eta1:
+    #     delta = gamma1 * dnorm
+    # elseif ratio <= eta2:  # Ensure DELTA >= DELTA_IN
+    #     delta = delta_in
+    # else:  # Ensure DELTA > DELTA_IN with a constant factor
+    #     delta = max(delta_in * (1 + gamma2) / 2, gamma2 * dnorm)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert delta > 0
+    return delta
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/update.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/update.py
new file mode 100644
index 0000000000000000000000000000000000000000..371df99381cc85ed8576ac6d84f7719071cc4732
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/cobyla/update.py
@@ -0,0 +1,289 @@
+'''
+This module contains subroutines concerning the update of the interpolation set.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from ..common.consts import DEBUGGING
+from ..common.infos import DAMAGING_ROUNDING, INFO_DEFAULT
+from ..common.linalg import isinv, matprod, outprod, inprod, inv, primasum
+import numpy as np
+
+
+def updatexfc(jdrop, constr, cpen, cstrv, d, f, conmat, cval, fval, sim, simi):
+    '''
+    This function revises the simplex by updating the elements of SIM, SIMI, FVAL, CONMAT, and CVAL
+    '''
+
+    # Local variables
+    itol = 1
+
+    # Sizes
+    num_constraints = np.size(constr)
+    num_vars = np.size(sim, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert jdrop >= 0 and jdrop <= num_vars + 1
+        assert not any(np.isnan(constr) | np.isneginf(constr))
+        assert not (np.isnan(cstrv) | np.isposinf(cstrv))
+        assert np.size(d) == num_vars and all(np.isfinite(d))
+        assert not (np.isnan(f) | np.isposinf(f))
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+
+    # Do nothing when JDROP is None. This can only happen after a trust-region step.
+    if jdrop is None:  # JDROP is None is impossible if the input is correct.
+        return conmat, cval, fval, sim, simi, INFO_DEFAULT
+
+    sim_old = sim
+    simi_old = simi
+    if jdrop < num_vars:
+        sim[:, jdrop] = d
+        simi_jdrop = simi[jdrop, :] / inprod(simi[jdrop, :], d)
+        simi -= outprod(matprod(simi, d), simi_jdrop)
+        simi[jdrop, :] = simi_jdrop
+    else:  # jdrop == num_vars
+        sim[:, num_vars] += d
+        sim[:, :num_vars] -= np.tile(d, (num_vars, 1)).T
+        simid = matprod(simi, d)
+        sum_simi = primasum(simi, axis=0)
+        simi += outprod(simid, sum_simi / (1 - sum(simid)))
+
+    # Check whether SIMI is a poor approximation to the inverse of SIM[:, :NUM_VARS]
+    # Calculate SIMI from scratch if the current one is damaged by rounding errors.
+    itol = 1
+    erri = np.max(abs(matprod(simi, sim[:, :num_vars]) - np.eye(num_vars)))  # np.max returns NaN if any input is NaN
+    if erri > 0.1 * itol or np.isnan(erri):
+        simi_test = inv(sim[:, :num_vars])
+        erri_test = np.max(abs(matprod(simi_test, sim[:, :num_vars]) - np.eye(num_vars)))
+        if erri_test < erri or (np.isnan(erri) and not np.isnan(erri_test)):
+            simi = simi_test
+            erri = erri_test
+
+    # If SIMI is satisfactory, then update FVAL, CONMAT, CVAL, and the pole position. Otherwise restore
+    # SIM and SIMI, and return with INFO = DAMAGING_ROUNDING.
+    if erri <= itol:
+        fval[jdrop] = f
+        conmat[:, jdrop] = constr
+        cval[jdrop] = cstrv
+        # Switch the best vertex to the pole position SIM[:, NUM_VARS] if it is not there already
+        conmat, cval, fval, sim, simi, info = updatepole(cpen, conmat, cval, fval, sim, simi)
+    else:
+        info = DAMAGING_ROUNDING
+        sim = sim_old
+        simi = simi_old
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol) or info == DAMAGING_ROUNDING
+
+    return sim, simi, fval, conmat, cval, info
+
+def findpole(cpen, cval, fval):
+    '''
+    This subroutine identifies the best vertex of the current simplex with respect to the merit
+    function PHI = F + CPEN * CSTRV.
+    '''
+
+    # Size
+    num_vars = np.size(fval) - 1
+
+    # Preconditions
+    if DEBUGGING:
+        assert cpen > 0
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Identify the optimal vertex of the current simplex
+    jopt = np.size(fval) - 1
+    phi = fval + cpen * cval
+    phimin = min(phi)
+    # Essentially jopt = np.argmin(phi). However, we keep jopt = num_vars unless there
+    # is a strictly better choice. When there are multiple choices, we choose the jopt
+    # with the smallest value of cval.
+    if phimin < phi[jopt] or any((cval < cval[jopt]) & (phi <= phi[jopt])):
+        # While we could use argmin(phi), there may be two places where phi achieves
+        # phimin, and in that case we should choose the one with the smallest cval.
+        jopt = np.ma.array(cval, mask=(phi > phimin)).argmin()
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert jopt >= 0 and jopt < num_vars + 1
+        assert jopt == num_vars or phi[jopt] < phi[num_vars] or (phi[jopt] <= phi[num_vars] and cval[jopt] < cval[num_vars])
+    return jopt
+
+
+def updatepole(cpen, conmat, cval, fval, sim, simi):
+    #--------------------------------------------------------------------------------------------------!
+    # This subroutine identifies the best vertex of the current simplex with respect to the merit
+    # function PHI = F + CPEN * CSTRV, and then switch this vertex to SIM[:, NUM_VARS], which Powell called
+    # the "pole position" in his comments. CONMAT, CVAL, FVAL, and SIMI are updated accordingly.
+    #
+    # N.B. 1: In precise arithmetic, the following two procedures produce the same results:
+    # 1) apply UPDATEPOLE to SIM twice, first with CPEN = CPEN1 and then with CPEN = CPEN2;
+    # 2) apply UPDATEPOLE to SIM with CPEN = CPEN2.
+    # In finite-precision arithmetic, however, they may produce different results unless CPEN1 = CPEN2.
+    #
+    # N.B. 2: When JOPT == N+1, the best vertex is already at the pole position, so there is nothing to
+    # switch. However, as in Powell's code, the code below will check whether SIMI is good enough to
+    # work as the inverse of SIM(:, 1:N) or not. If not, Powell's code would invoke an error return of
+    # COBYLB; our implementation, however, will try calculating SIMI from scratch; if the recalculated
+    # SIMI is still of poor quality, then UPDATEPOLE will return with INFO = DAMAGING_ROUNDING,
+    # informing COBYLB that SIMI is poor due to damaging rounding errors.
+    #
+    # N.B. 3: UPDATEPOLE should be called when and only when FINDPOLE can potentially returns a value
+    # other than N+1. The value of FINDPOLE is determined by CPEN, CVAL, and FVAL, the latter two being
+    # decided by SIM. Thus UPDATEPOLE should be called after CPEN or SIM changes. COBYLA updates CPEN at
+    # only two places: the beginning of each trust-region iteration, and when REDRHO is called;
+    # SIM is updated only by UPDATEXFC, which itself calls UPDATEPOLE internally. Therefore, we only
+    # need to call UPDATEPOLE after updating CPEN at the beginning of each trust-region iteration and
+    # after each invocation of REDRHO.
+
+    # Local variables
+    itol = 1
+
+    # Sizes
+    num_constraints = conmat.shape[0]
+    num_vars = sim.shape[0]
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert cpen > 0
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # INFO must be set, as it is an output.
+    info = INFO_DEFAULT
+
+    # Identify the optimal vertex of the current simplex.
+    jopt = findpole(cpen, cval, fval)
+
+    # Switch the best vertex to the pole position SIM[:, NUM_VARS] if it is not there already and update
+    # SIMI. Before the update, save a copy of SIM and SIMI. If the update is unsuccessful due to
+    # damaging rounding errors, we restore them and return with INFO = DAMAGING_ROUNDING.
+    sim_old = sim.copy()
+    simi_old = simi.copy()
+    if 0 <= jopt < num_vars:
+        # Unless there is a bug in FINDPOLE it is guaranteed that JOPT >= 0
+        # When JOPT == NUM_VARS, there is nothing to switch; in addition SIMI[JOPT, :] will be illegal.
+        # fval[[jopt, -1]] = fval[[-1, jopt]]
+        # conmat[:, [jopt, -1]] = conmat[:, [-1, jopt]] # Exchange CONMAT[:, JOPT] AND CONMAT[:, -1]
+        # cval[[jopt, -1]] = cval[[-1, jopt]]
+        sim[:, num_vars] += sim[:, jopt]
+        sim_jopt = sim[:, jopt].copy()
+        sim[:, jopt] = 0  # np.zeros(num_constraints)?
+        sim[:, :num_vars] -= np.tile(sim_jopt, (num_vars, 1)).T
+        # The above update is equivalent to multiplying SIM[:, :NUM_VARS] from the right side by a matrix whose
+        # JOPT-th row is [-1, -1, ..., -1], while all the other rows are the same as those of the
+        # identity matrix. It is easy to check that the inverse of this matrix is itself. Therefore,
+        # SIMI should be updated by a multiplication with this matrix (i.e. its inverse) from the left
+        # side, as is done in the following line. The JOPT-th row of the updated SIMI is minus the sum
+        # of all rows of the original SIMI, whereas all the other rows remain unchanged.
+        # NDB 20250114: In testing the cutest problem 'SYNTHES2' between the Python implementation and
+        # the Fortran bindings, I saw a difference between the following for loop and the
+        # np.sum command. The differences were small, on the order of 1e-16, i.e. epsilon.
+        # According to numpy documentation, np.sum sometimes uses partial pairwise summation,
+        # depending on the memory layout of the array and the axis specified.
+        # for i in range(simi.shape[1]):
+        #     simi[jopt, i] = -sum(simi[:, i])
+        simi[jopt, :] = -primasum(simi, axis=0)
+
+    # Check whether SIMI is a poor approximation to the inverse of SIM[:, :NUM_VARS]
+    # Calculate SIMI from scratch if the current one is damaged by rounding errors.
+    erri = np.max(abs(matprod(simi, sim[:, :num_vars]) - np.eye(num_vars)))  # np.max returns NaN if any input is NaN
+    itol = 1
+    if erri > 0.1 * itol or np.isnan(erri):
+        simi_test = inv(sim[:, :num_vars])
+        erri_test = np.max(abs(matprod(simi_test, sim[:, :num_vars]) - np.eye(num_vars)))
+        if erri_test < erri or (np.isnan(erri) and not np.isnan(erri_test)):
+            simi = simi_test
+            erri = erri_test
+
+
+    # If SIMI is satisfactory, then update FVAL, CONMAT, and CVAL. Otherwise restore SIM and SIMI, and
+    # return with INFO = DAMAGING_ROUNDING.
+    if erri <= itol:
+        if 0 <= jopt < num_vars:
+            fval[[jopt, num_vars]] = fval[[num_vars, jopt]]
+            conmat[:, [jopt, num_vars]] = conmat[:, [num_vars, jopt]]
+            cval[[jopt, num_vars]] = cval[[num_vars, jopt]]
+    else:  # erri > itol or erri is NaN
+        info = DAMAGING_ROUNDING
+        sim = sim_old
+        simi = simi_old
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert findpole(cpen, cval, fval) == num_vars or info == DAMAGING_ROUNDING
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        # Do not check SIMI = SIM[:, :num_vars]^{-1}, as it may not be true due to damaging rounding.
+        assert isinv(sim[:, :num_vars], simi, itol) or info == DAMAGING_ROUNDING
+
+    return conmat, cval, fval, sim, simi, info
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_bounds.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_bounds.py
new file mode 100644
index 0000000000000000000000000000000000000000..54c793629d898f6d2112f30beeda681c4f207e5c
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_bounds.py
@@ -0,0 +1,34 @@
+import numpy as np
+from scipy.optimize import Bounds
+
+def process_bounds(bounds, lenx0):
+    '''
+    `bounds` can either be an object with the properties lb and ub, or a list of tuples
+    indicating a lower bound and an upper bound for each variable. If the list contains
+    fewer entries than the length of x0, the remaining entries will generated as -/+ infinity.
+    Some examples of valid lists of tuple, assuming len(x0) == 3:
+    [(0, 1), (2, 3), (4, 5)] -> returns [0, 2, 4], [1, 3, 5]
+    [(0, 1), (None, 3)]      -> returns [0, -inf, -inf], [1, 3, inf]
+    [(0, 1), (-np.inf, 3)]   -> returns [0, -inf, -inf], [1, 3, inf]
+    '''
+
+    if bounds is None:
+        lb = np.array([-np.inf]*lenx0, dtype=np.float64)
+        ub = np.array([np.inf]*lenx0, dtype=np.float64)
+        return lb, ub
+    
+    if isinstance(bounds, Bounds):
+        lb = np.array(bounds.lb, dtype=np.float64)
+        ub = np.array(bounds.ub, dtype=np.float64)
+        lb = np.concatenate((lb, -np.inf*np.ones(lenx0 - len(lb))))
+        ub = np.concatenate((ub, np.inf*np.ones(lenx0 - len(ub))))
+        return lb, ub
+    
+    # If neither of the above conditions are true, we assume that bounds is a list of tuples
+    lb = np.array([bound[0] if bound[0] is not None else -np.inf for bound in bounds], dtype=np.float64)
+    ub = np.array([bound[1] if bound[1] is not None else np.inf for bound in bounds], dtype=np.float64)
+    # If there were fewer bounds than variables, pad the rest with -/+ infinity
+    lb = np.concatenate((lb, -np.inf*np.ones(lenx0 - len(lb))))
+    ub = np.concatenate((ub, np.inf*np.ones(lenx0 - len(ub))))
+    
+    return lb, ub
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_linear_constraints.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_linear_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..896b11298acf5bd1fdf9de5ae22d726725d1fc60
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_linear_constraints.py
@@ -0,0 +1,46 @@
+import numpy as np
+from scipy.optimize import LinearConstraint
+
+
+def combine_multiple_linear_constraints(constraints):
+    full_A = constraints[0].A
+    full_lb = constraints[0].lb
+    full_ub = constraints[0].ub
+    for constraint in constraints[1:]:
+        full_A = np.concatenate((full_A, constraint.A), axis=0)
+        full_lb = np.concatenate((full_lb, constraint.lb), axis=0)
+        full_ub = np.concatenate((full_ub, constraint.ub), axis=0)
+    return LinearConstraint(full_A, full_lb, full_ub)
+
+
+def separate_LC_into_eq_and_ineq(linear_constraint):
+    # The Python interface receives linear constraints lb <= A*x <= ub, but the
+    # Fortran backend of PRIMA expects that the linear constraints are specified
+    # as A_eq*x = b_eq, A_ineq*x <= b_ineq.
+    # As such, we must:
+    # 1. for constraints with lb == ub, rewrite them as A_eq*x = lb;
+    # 2. for constraints with lb < ub, rewrite them as A_ineq*x <= b_ineq.
+
+    # We suppose lb == ub if ub <= lb + 2*epsilon, assuming that the preprocessing
+    # ensures lb <= ub.
+    epsilon = np.finfo(np.float64).eps
+
+    eq_indices = (linear_constraint.ub <= (linear_constraint.lb + 2*epsilon))
+    A_eq = linear_constraint.A[eq_indices]
+    b_eq = (linear_constraint.lb[eq_indices] + linear_constraint.ub[eq_indices])/2.0
+
+    ineq_lb_indices = (linear_constraint.lb > -np.inf)
+    A_ineq_lb = -linear_constraint.A[~eq_indices & ineq_lb_indices]
+    b_ineq_lb = -linear_constraint.lb[~eq_indices & ineq_lb_indices]
+    ineq_ub_indices = (linear_constraint.ub < np.inf)
+    A_ineq_ub = linear_constraint.A[~eq_indices & ineq_ub_indices]
+    b_ineq_ub = linear_constraint.ub[~eq_indices & ineq_ub_indices]
+    A_ineq = np.concatenate((A_ineq_lb, A_ineq_ub))
+    b_ineq = np.concatenate((b_ineq_lb, b_ineq_ub))
+
+    # Ensure dtype is float64, or set to None if empty
+    A_eq = np.array(A_eq, dtype=np.float64) if len(A_eq) > 0 else None
+    b_eq = np.array(b_eq, dtype=np.float64) if len(b_eq) > 0 else None
+    A_ineq = np.array(A_ineq, dtype=np.float64) if len(A_ineq) > 0 else None
+    b_ineq = np.array(b_ineq, dtype=np.float64) if len(b_ineq) > 0 else None
+    return A_eq, b_eq, A_ineq, b_ineq
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_nonlinear_constraints.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_nonlinear_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..b12926b43b47dcd95e4c705d01741f390833d6ec
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_nonlinear_constraints.py
@@ -0,0 +1,54 @@
+import numpy as np
+        
+def transform_constraint_function(nlc):
+    '''
+    The Python interfaces receives the constraints as lb <= constraint(x) <= ub, 
+    but the Fortran backend expects the nonlinear constraints to be constraint(x) <= 0.
+    Thus a conversion is needed.
+    
+    In addition to the conversion, we add a check to ensure that the provided lower/upper bounds
+    have a shape consistent with the output of the constraint function.
+    '''
+
+    def newconstraint(x):
+        values = np.atleast_1d(np.array(nlc.fun(x), dtype=np.float64))
+        
+        # Upgrade the lower/upper bounds to vectors if necessary
+        lb = nlc.lb
+        try:
+            _ = len(lb)
+        except TypeError:
+            lb = np.array([nlc.lb]*len(values), dtype=np.float64)
+
+        ub = nlc.ub
+        try:
+            _ = len(ub)
+        except TypeError:
+            ub = np.array([nlc.ub]*len(values), dtype=np.float64)
+        
+        
+        # Check the shapes and raise an exception if they do not match
+        if len(values) != len(lb):
+            raise ValueError("The number of elements in the constraint function's output does not match the number of elements in the lower bound.")
+        if len(values) != len(ub):
+            raise ValueError("The number of elements in the constraint function's output does not match the number of elements in the upper bound.")
+        
+        # Combine the upper and lower bounds to transform the function into the form
+        # expected by the Fortran backend.
+        return np.concatenate(([lb_ii - vi for lb_ii, vi in zip(lb, values) if lb_ii > -np.inf],
+                               [vi - ub_ii for ub_ii, vi in zip(ub, values) if ub_ii < np.inf],
+                            ))
+    return newconstraint
+
+
+def process_nl_constraints(nlcs):
+    functions = []
+    for nlc in nlcs:
+        fun_i = transform_constraint_function(nlc)
+        functions.append(fun_i)
+    def constraint_function(x):
+        values = np.empty(0, dtype=np.float64)
+        for fun in functions:
+            values = np.concatenate((values, fun(x)))
+        return values
+    return constraint_function
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_project.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_project.py
new file mode 100644
index 0000000000000000000000000000000000000000..254604ade452fef2d44fb52eecc30515fedbecf1
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/_project.py
@@ -0,0 +1,173 @@
+'''
+This module provides the _project function that attempts to project the initial guess
+onto the feasible set.
+
+Adapted from the corresponding function in the PDFO package (https://www.pdfo.net) by
+Tom M. Ragonneau (https://ragonneau.github.io) and Zaikun Zhang (https://www.zhangzk.net).
+'''
+
+import numpy as np
+from ._linear_constraints import LinearConstraint
+from scipy.optimize import OptimizeResult
+
+# All the accepted scalar types; np.generic correspond to all NumPy types.
+scalar_types = (int, float, np.generic)
+eps = np.finfo(np.float64).eps
+
+def _project(x0, lb, ub, constraints):
+    """Projection of the initial guess onto the feasible set.
+
+    Parameters
+    ----------
+    x0: ndarray, shape (n,)
+        The same as in prepdfo.
+    lb: ndarray, shape (n,)
+        The same as in prepdfo.
+    ub: ndarray, shape (n,)
+        The same as in prepdfo.
+    constraints: dict
+        The general constraints of the problem, defined as a dictionary with
+        fields:
+            linear: LinearConstraint
+                The linear constraints of the problem.
+            nonlinear: dict
+                The nonlinear constraints of the problem. When ``_project`` is called, the nonlinear constraints are
+                None.
+
+    Returns
+    -------
+    result: OptimizeResult
+        The result of the projection.
+
+    Authors
+    -------
+    Tom M. RAGONNEAU (ragonneau.github.io)
+    and Zaikun ZHANG (www.zhangzk.net)
+
+    Dedicated to the late Professor M. J. D. Powell FRS (1936--2015).
+    """
+    invoker = 'prima'
+
+    # Validate x0.
+    if isinstance(x0, scalar_types):
+        x0_c = [x0]
+    elif hasattr(x0, '__len__'):
+        x0_c = x0
+    else:
+        raise ValueError('{}: UNEXPECTED ERROR: x0 should be a vector.'.format(invoker))
+    try:
+        x0_c = np.asarray(x0_c, dtype=np.float64)
+    except ValueError:
+        raise ValueError('{}: UNEXPECTED ERROR: x0 should contain only scalars.'.format(invoker))
+    if len(x0_c.shape) != 1:
+        raise ValueError('{}: UNEXPECTED ERROR: x0 should be a vector.'.format(invoker))
+    lenx0 = x0_c.size
+
+    # Validate lb.
+    if isinstance(lb, scalar_types):
+        lb_c = [lb]
+    elif hasattr(lb, '__len__'):
+        lb_c = lb
+    else:
+        raise ValueError('{}: UNEXPECTED ERROR: lb should be a vector.'.format(invoker))
+    try:
+        lb_c = np.asarray(lb_c, dtype=np.float64)
+    except ValueError:
+        raise ValueError('{}: UNEXPECTED ERROR: lb should contain only scalars.'.format(invoker))
+    if len(lb_c.shape) != 1 or lb_c.size != lenx0:
+        raise ValueError('{}: UNEXPECTED ERROR: the size of lb is inconsistent with x0.'.format(invoker))
+
+    # Validate ub.
+    if isinstance(ub, scalar_types):
+        ub_c = [ub]
+    elif hasattr(ub, '__len__'):
+        ub_c = ub
+    else:
+        raise ValueError('{}: UNEXPECTED ERROR: ub should be a vector.'.format(invoker))
+    try:
+        ub_c = np.asarray(ub_c, dtype=np.float64)
+    except ValueError:
+        raise ValueError('{}: UNEXPECTED ERROR: ub should contain only scalars.'.format(invoker))
+    if len(ub_c.shape) != 1 or ub_c.size != lenx0:
+        raise ValueError('{}: UNEXPECTED ERROR: the size of ub is inconsistent with x0.'.format(invoker))
+
+    # Validate constraints.
+    if not isinstance(constraints, dict) or not ({'linear', 'nonlinear'} <= set(constraints.keys())) or \
+            not (isinstance(constraints['linear'], LinearConstraint) or constraints['linear'] is None):
+        # the nonlinear constraints will not be taken into account in this function and are, therefore, not validated
+        raise ValueError('{}: UNEXPECTED ERROR: The constraints are ill-defined.'.format(invoker))
+
+    max_con = 1e20  # Decide whether an inequality constraint can be ignored
+
+    # Project onto the feasible set.
+    if constraints['linear'] is None:
+        # Direct projection onto the bound constraints
+        x_proj = np.nanmin((np.nanmax((x0_c, lb_c), axis=0), ub_c), axis=0)
+        return OptimizeResult(x=x_proj)
+    elif all(np.less_equal(np.abs(constraints['linear'].ub - constraints['linear'].lb), eps)) and \
+            np.max(lb_c) <= -max_con and np.min(ub_c) >= max_con:
+        # The linear constraints are all equality constraints. The projection can therefore be done by solving the
+        # least-squares problem: min ||A*x - (b - A*x_0)||.
+        a = constraints['linear'].A
+        b = (constraints['linear'].lb + constraints['linear'].ub) / 2
+        xi, _, _, _ = np.linalg.lstsq(a, b - np.dot(a, x0_c), rcond=None)
+
+        # The problem is not bounded. However, if the least-square solver returned values bigger in absolute value
+        # than max_con, they will be reduced to this bound.
+        x_proj = np.nanmin((np.nanmax((x0_c + xi, lb_c), axis=0), ub_c), axis=0)
+
+        return OptimizeResult(x=x_proj)
+
+    if constraints['linear'] is not None:
+        try:
+            # Project the initial guess onto the linear constraints via SciPy.
+            from scipy.optimize import minimize
+            from scipy.optimize import Bounds as ScipyBounds
+            from scipy.optimize import LinearConstraint as ScipyLinearConstraint
+
+            linear = constraints['linear']
+
+            # To be more efficient, SciPy asks to separate the equality and the inequality constraints into two
+            # different LinearConstraint structures
+            pc_args_ineq, pc_args_eq = dict(), dict()
+            pc_args_ineq['A'], pc_args_eq['A'] = np.asarray([[]]), np.asarray([[]])
+            pc_args_ineq['A'] = pc_args_ineq['A'].reshape(0, linear.A.shape[1])
+            pc_args_eq['A'] = pc_args_eq['A'].reshape(0, linear.A.shape[1])
+            pc_args_ineq['lb'], pc_args_eq['lb'] = np.asarray([]), np.asarray([])
+            pc_args_ineq['ub'], pc_args_eq['ub'] = np.asarray([]), np.asarray([])
+
+            for i in range(linear.lb.size):
+                if linear.lb[i] != linear.ub[i]:
+                    pc_args_ineq['A'] = np.concatenate((pc_args_ineq['A'], linear.A[i:i+1, :]), axis=0)
+                    pc_args_ineq['lb'] = np.r_[pc_args_ineq['lb'], linear.lb[i]]
+                    pc_args_ineq['ub'] = np.r_[pc_args_ineq['ub'], linear.ub[i]]
+                else:
+                    pc_args_eq['A'] = np.concatenate((pc_args_eq['A'], linear.A[i:i+1, :]), axis=0)
+                    pc_args_eq['lb'] = np.r_[pc_args_eq['lb'], linear.lb[i]]
+                    pc_args_eq['ub'] = np.r_[pc_args_eq['ub'], linear.ub[i]]
+
+            if pc_args_ineq['A'].size > 0 and pc_args_ineq['lb'].size > 0 and pc_args_eq['lb'].size > 0:
+                project_constraints = [ScipyLinearConstraint(**pc_args_ineq), ScipyLinearConstraint(**pc_args_eq)]
+            elif pc_args_ineq['A'].size > 0 and pc_args_ineq['lb'].size > 0:
+                project_constraints = ScipyLinearConstraint(**pc_args_ineq)
+            elif pc_args_eq['A'].size > 0:
+                project_constraints = ScipyLinearConstraint(**pc_args_eq)
+            else:
+                project_constraints = ()
+
+            # Perform the actual projection.
+            ax_ineq = np.dot(pc_args_ineq['A'], x0_c)
+            ax_eq = np.dot(pc_args_eq['A'], x0_c)
+            if np.greater(ax_ineq, pc_args_ineq['ub']).any() or np.greater(pc_args_ineq['lb'], ax_ineq).any() or \
+                    np.not_equal(ax_eq, pc_args_eq['lb']).any() or \
+                    np.greater(x0_c, ub_c).any() or np.greater(lb_c, x0_c).any():
+                return minimize(lambda x: np.dot(x - x0_c, x - x0_c) / 2, x0_c, jac=lambda x: (x - x0_c),
+                                bounds=ScipyBounds(lb_c, ub_c), constraints=project_constraints)
+            else:
+                # Do not perform any projection if the initial guess is feasible.
+                return OptimizeResult(x=x0_c)
+
+        except ImportError:
+            return OptimizeResult(x=x0_c)
+
+    return OptimizeResult(x=x0_c)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/checkbreak.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/checkbreak.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b6d827d3a0a34aaed623bdaac755bfca904cf65
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/checkbreak.py
@@ -0,0 +1,93 @@
+'''
+This module checks whether to break out of the solver loop.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .infos import INFO_DEFAULT, NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, MAXFUN_REACHED
+
+import numpy as np
+
+def checkbreak_unc(maxfun, nf, f, ftarget, x):
+    '''
+    This module checks whether to break out of the solver loop in the unconstrained case.
+    '''
+
+    # Outputs
+    info = INFO_DEFAULT
+
+    # Local variables
+    srname = "CHECKbreak_UNC"
+
+    # Preconditions
+    assert INFO_DEFAULT not in [NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, MAXFUN_REACHED], f'NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, and MAXFUN_REACHED differ from INFO_DFT {srname}'
+    # X does not contain NaN if the initial X does not contain NaN and the subroutines generating
+    # trust-region/geometry steps work properly so that they never produce a step containing NaN/Inf.
+    assert not any(np.isnan(x)), f'X does not contain NaN {srname}'
+    # With the moderated extreme barrier, F cannot be NaN/+Inf.
+    assert not (any(np.isnan(f)) or any(np.isposinf(f))), f'F is not NaN/+Inf {srname}'
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Although X should not contain NaN unless there is a bug, we include the following for security.
+    # X can be Inf, as finite + finite can be Inf numerically.
+    if any(np.isnan(x)) or any(np.isinf(x)):
+        info = NAN_INF_X
+
+    # Although NAN_INF_F should not happen unless there is a bug, we include the following for security.
+    if any(np.isnan(f)) or any(np.isposinf(f)):
+        info = NAN_INF_F
+
+    if f <= ftarget:
+        info = FTARGET_ACHIEVED
+
+    if nf >= maxfun:
+        info = MAXFUN_REACHED
+
+    return info
+
+def checkbreak_con(maxfun, nf, cstrv, ctol, f, ftarget, x):
+    '''
+    This module checks whether to break out of the solver loop in the constrained case.
+    '''
+
+    # Outputs
+    info = INFO_DEFAULT
+
+    # Local variables
+    srname = "CHECKbreak_CON"
+
+    # Preconditions
+    assert INFO_DEFAULT not in [NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, MAXFUN_REACHED], f'NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, and MAXFUN_REACHED differ from INFO_DFT {srname}'
+    # X does not contain NaN if the initial X does not contain NaN and the subroutines generating
+    # trust-region/geometry steps work properly so that they never produce a step containing NaN/Inf.
+    assert not any(np.isnan(x)), f'X does not contain NaN {srname}'
+    # With the moderated extreme barrier, F or CSTRV cannot be NaN/+Inf.
+    assert not (np.isnan(f) or np.isposinf(f) or np.isnan(cstrv) or np.isposinf(cstrv)), f'F or CSTRV is not NaN/+Inf {srname}'
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Although X should not contain NaN unless there is a bug, we include the following for security.
+    # X can be Inf, as finite + finite can be Inf numerically.
+    if any(np.isnan(x)) or any(np.isinf(x)):
+        info = NAN_INF_X
+
+    # Although NAN_INF_F should not happen unless there is a bug, we include the following for security.
+    if np.isnan(f) or np.isposinf(f) or np.isnan(cstrv) or np.isposinf(cstrv):
+        info = NAN_INF_F
+
+    if cstrv <= ctol and f <= ftarget:
+        info = FTARGET_ACHIEVED
+
+    if nf >= maxfun:
+        info = MAXFUN_REACHED
+
+    return info
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/consts.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b447f40d42ba61670e64f3cb4322443cd0ebd87
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/consts.py
@@ -0,0 +1,47 @@
+'''
+This is a module defining some constants.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+import os
+
+DEBUGGING = bool(os.getenv('PRIMA_DEBUGGING'))
+
+REALMIN = np.finfo(float).tiny
+REALMAX = np.finfo(float).max
+FUNCMAX = 10.0**30
+CONSTRMAX = FUNCMAX
+EPS = np.finfo(float).eps
+
+# Any bound with an absolute value at least BOUNDMAX is considered as no bound.
+BOUNDMAX = REALMAX/4
+
+# Some default values
+RHOBEG_DEFAULT = 1
+RHOEND_DEFAULT = 1e-6
+FTARGET_DEFAULT = -REALMAX
+CTOL_DEFAULT = np.sqrt(EPS)
+CWEIGHT_DEFAULT = 1e8
+ETA1_DEFAULT = 0.1
+ETA2_DEFAULT = 0.7
+GAMMA1_DEFAULT = 0.5
+GAMMA2_DEFAULT = 2
+IPRINT_DEFAULT = 0
+MAXFUN_DIM_DEFAULT = 500
+
+PRIMA_MAX_HIST_MEM_MB = 300  # 1MB > 10^5*REAL64. 100 can be too small.
+
+# Maximal amount of memory (Byte) allowed for XHIST, FHIST, CONHIST, CHIST, and the filters.
+MHM = PRIMA_MAX_HIST_MEM_MB * 10**6
+# Make sure that MAXHISTMEM does not exceed HUGE(0) to avoid overflow and memory errors.
+MAXHISTMEM = min(MHM, np.iinfo(np.int32).max)
+
+# Maximal length of the filter used in constrained solvers.
+MIN_MAXFILT = 200  # Should be positive; < 200 is not recommended.
+MAXFILT_DEFAULT = 10 * MIN_MAXFILT
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/evaluate.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/evaluate.py
new file mode 100644
index 0000000000000000000000000000000000000000..4583ce2009580135bca280ff1ea0222899d901ff
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/evaluate.py
@@ -0,0 +1,99 @@
+'''
+This is a module evaluating the objective/constraint function with Nan/Inf handling.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from .consts import FUNCMAX, CONSTRMAX, REALMAX, DEBUGGING
+from .linalg import matprod, primasum
+
+# This is a module evaluating the objective/constraint function with Nan/Inf handling.
+
+
+def moderatex(x):
+    '''
+    This function moderates a decision variable. It replaces NaN by 0 and Inf/-Inf by
+    REALMAX/-REALMAX.
+    '''
+    x[np.isnan(x)] = 0
+    x = np.clip(x, -REALMAX, REALMAX)
+    return x
+
+def moderatef(f):
+    """
+    This function moderates the function value of a MINIMIZATION problem. It replaces
+    NaN and any value above FUNCMAX by FUNCMAX.
+    """
+    f = FUNCMAX if np.isnan(f) else f
+    f = np.clip(f, -REALMAX, FUNCMAX)
+    # We may moderate huge negative function values as follows, but we decide not to.
+    # f = np.clip(f, -FUNCMAX, FUNCMAX)
+    return f
+
+
+def moderatec(c):
+    """
+    This function moderates the constraint value, the constraint demanding this value
+    to be NONNEGATIVE. It replaces any value below -CONSTRMAX by -CONSTRMAX, and any
+    NaN or value above CONSTRMAX by CONSTRMAX.
+    """
+    np.nan_to_num(c, copy=False, nan=CONSTRMAX)
+    c = np.clip(c, -CONSTRMAX, CONSTRMAX)
+    return c
+
+
+def evaluate(calcfc, x, m_nlcon, amat, bvec):
+    """
+    This function evaluates CALCFC at X, returning the objective function value and the
+    constraint value. Nan/Inf are handled by a moderated extreme barrier.
+    """
+
+    # Sizes
+    m_lcon = len(bvec) if bvec is not None else 0
+
+    # Preconditions
+    if DEBUGGING:
+        # X should not contain NaN if the initial X does not contain NaN and the
+        # subroutines generating # trust-region/geometry steps work properly so that
+        # they never produce a step containing NaN/Inf.
+        assert not any(np.isnan(x))
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    constr = np.zeros(m_lcon + m_nlcon)
+    if amat is not None:
+        constr[:m_lcon] = matprod(x, amat.T) - bvec
+
+    if any(np.isnan(x)):
+        # Although this should not happen unless there is a bug, we include this case
+        # for robustness.
+        f = primasum(x)
+        constr = np.ones(m_nlcon) * f
+    else:
+        f, constr[m_lcon:] = calcfc(moderatex(x))
+
+        # Moderated extreme barrier: replace NaN/huge objective or constraint values
+        # with a large but finite value. This is naive, and better approaches surely
+        # exist.
+        f = moderatef(f)
+        constr[m_lcon:] = moderatec(constr[m_lcon:])
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        # With X not containing NaN, and with the moderated extreme barrier, F cannot
+        # be NaN/+Inf, and CONSTR cannot be NaN/-Inf.
+        assert not (np.isnan(f) or np.isposinf(f))
+        assert not any(np.isnan(constr) | np.isposinf(constr))
+
+    return f, constr
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/history.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/history.py
new file mode 100644
index 0000000000000000000000000000000000000000..377c7bb62b1299b3973f68815138f76ccf93f6cc
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/history.py
@@ -0,0 +1,38 @@
+'''
+This module provides subroutines that handle the X/F/C histories of the solver, taking into
+account that MAXHIST may be smaller than NF.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+def savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist):
+    '''
+    Save the data values to the history lists.
+
+    The implementation of this function is vastly different from the Fortran implementation.
+    This is mostly due to the ease of creating and appending to lists in Python
+
+    However just like the Fortran version we should be concerned about both performance
+    and memory constraints. It will probably be better to initialize an array of NaN for
+    each of the histories and keep track of how many indices we have stored. Not needed for
+    the moment.
+    '''
+    if len(xhist) < maxhist:
+        xhist.append(x)
+        fhist.append(f)
+        chist.append(cstrv)
+        conhist.append(constr)
+    else:
+        # This effectively accomplishes what rangehist does in the Fortran implementation
+        xhist.pop(0)
+        fhist.pop(0)
+        chist.pop(0)
+        conhist.pop(0)
+        xhist.append(x)
+        fhist.append(f)
+        chist.append(cstrv)
+        conhist.append(constr)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/infos.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/infos.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d056979092c959199780e5f5d7f04498a9f5f45
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/infos.py
@@ -0,0 +1,30 @@
+'''
+This is a module defining exit flags.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+INFO_DEFAULT = 0
+SMALL_TR_RADIUS = 0
+FTARGET_ACHIEVED = 1
+TRSUBP_FAILED = 2
+MAXFUN_REACHED = 3
+MAXTR_REACHED = 20
+NAN_INF_X = -1
+NAN_INF_F = -2
+NAN_INF_MODEL = -3
+NO_SPACE_BETWEEN_BOUNDS = 6
+DAMAGING_ROUNDING = 7
+ZERO_LINEAR_CONSTRAINT = 8
+CALLBACK_TERMINATE = 30
+
+# Stop-codes.
+# The following codes are used by ERROR STOP as stop-codes, which should be default integers.
+INVALID_INPUT = 100
+ASSERTION_FAILS = 101
+VALIDATION_FAILS = 102
+MEMORY_ALLOCATION_FAILS = 103
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/linalg.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..abd24c6528c56a5da72e36af5d0178a45caeacfb
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/linalg.py
@@ -0,0 +1,435 @@
+'''
+This module provides some basic linear algebra procedures.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from .consts import DEBUGGING, EPS, REALMAX, REALMIN
+from .present import present
+
+
+# We use naive implementations of matrix multiplication and other routines for two
+# reasons:
+# 1. When Fortran is compiled in debug mode, and Python is using these routines, we
+#    can get bit for bit identical results as compared to Fortran. This is helpful
+#    for comparing the two implementations. It will be particularly helpful when porting
+#    the other implementations like LINCOA, etc.
+# 2. On some problems this algorithm is very sensitive to errors in finite precision
+#    arithmetic. Switching to naive implementation will slow down the algorithm, but
+#    may be more stable.
+USE_NAIVE_MATH = False
+
+
+def inprod(x, y):
+    if not USE_NAIVE_MATH:
+        return np.dot(x, y)
+    result = 0
+    for i in range(len(x)):
+        result += x[i] * y[i]
+    return result
+
+
+def matprod12(x, y):
+    result = np.zeros(y.shape[1])
+    for i in range(y.shape[1]):
+        result[i] = inprod(x, y[:, i])
+    return result
+
+
+def matprod21(x, y):
+    result = np.zeros(x.shape[0])
+    for i in range(x.shape[1]):
+        result += x[:, i] * y[i]
+    return result
+
+
+def matprod22(x, y):
+    result = np.zeros((x.shape[0], y.shape[1]))
+    for i in range(y.shape[1]):
+        for j in range(x.shape[1]):
+            result[:, j] += x[:, i] * y[i, j]
+    return result
+
+
+def matprod(x, y):
+    if not USE_NAIVE_MATH:
+        return x@y
+    if len(x.shape) == 1 and len(y.shape) == 1:
+        return inprod(x, y)
+    elif len(x.shape) == 1 and len(y.shape) == 2:
+        return matprod12(x, y)
+    elif len(x.shape) == 2 and len(y.shape) == 1:
+        return matprod21(x, y)
+    elif len(x.shape) == 2 and len(y.shape) == 2:
+        return matprod22(x, y)
+    else:
+        raise ValueError(f'Invalid shapes for x and y: {x.shape} and {y.shape}')
+
+
+def outprod(x, y):
+    if not USE_NAIVE_MATH:
+        return np.outer(x, y)
+    result = np.zeros((len(x), len(y)))
+    for i in range(len(x)):
+            result[:, i] = x * y[i]
+    return result
+
+
+def lsqr(A, b, Q, Rdiag):
+    if not USE_NAIVE_MATH:
+        return np.linalg.lstsq(A, b, rcond=None)[0]
+
+    m = A.shape[0]
+    n = A.shape[1]
+
+    rank = min(m, n)
+
+    x = np.zeros(n)
+    y = b.copy()
+
+    for i in range(rank - 1, -1, -1):
+        yq = inprod(y, Q[:, i])
+        yqa = inprod(np.abs(y), np.abs(Q[:, i]))
+        if isminor(yq, yqa):
+            x[i] = 0
+        else:
+            x[i] = yq / Rdiag[i]
+            y = y - x[i] * A[:, i]
+    return x
+
+
+def hypot(x1, x2):
+    if not USE_NAIVE_MATH:
+        return np.hypot(x1, x2)
+    if not np.isfinite(x1):
+        r = abs(x1)
+    elif not np.isfinite(x2):
+        r = abs(x2)
+    else:
+        y = abs(np.array([x1, x2]))
+        y = np.array([min(y), max(y)])
+        if y[0] > np.sqrt(REALMIN) and y[1] < np.sqrt(REALMAX/2.1):
+            r = np.sqrt(sum(y*y))
+        elif y[1] > 0:
+            r = y[1] * np.sqrt((y[0]/y[1])*(y[0]/y[1]) + 1)
+        else:
+            r = 0
+    return r
+
+
+def norm(x):
+    if not USE_NAIVE_MATH:
+        return np.linalg.norm(x)
+    # NOTE: Avoid np.pow! And exponentiation in general!
+    # It appears that in Fortran, x*x and x**2 are the same, but in Python they are not!
+    # Try it with x = 5 - 1e-15
+    result = np.sqrt(sum([xi*xi for xi in x]))
+    return result
+
+
+def istril(A, tol=0):
+    return primasum(abs(A) - np.tril(abs(A))) <= tol
+
+def istriu(A, tol=0):
+    return primasum(abs(A) - np.triu(abs(A))) <= tol
+
+
+def inv(A):
+    if not USE_NAIVE_MATH:
+        return np.linalg.inv(A)
+    A = A.copy()
+    n = A.shape[0]
+    if istril(A):
+        # This case is invoked in COBYLA.
+        R = A.T
+        B = np.zeros((n, n))
+        for i in range(n):
+            B[i, i] = 1 / R[i, i]
+            B[:i, i] = -matprod(B[:i, :i], R[:i, i]) / R[i, i]
+        return B.T
+    elif istriu(A):
+        B = np.zeros((n, n))
+        for i in range(n):
+            B[i, i] = 1 / A[i, i]
+            B[:i, i] = -matprod(B[:i, :i], A[:i, i]) / A[i, i]
+    else:
+        # This is NOT the best algorithm for the inverse, but since the QR subroutine is available ...
+        Q, R, P = qr(A)
+        R = R.T
+        B = np.zeros((n, n))
+        for i in range(n - 1, -1, -1):
+            B[:, i] = (Q[:, i] - matprod(B[:, i + 1:n], R[i + 1:n, i])) / R[i, i]
+        InvP = np.zeros(n, dtype=int)
+        InvP[P] = np.linspace(0, n-1, n)
+        B = B[:, InvP].T
+    return B
+
+
+def qr(A):
+    m = A.shape[0]
+    n = A.shape[1]
+
+    Q = np.eye(m)
+    T = A.T
+    P = np.linspace(0, n-1, n, dtype=int)
+
+    for j in range(n):
+        k = np.argmax(primasum(primapow2(T[j:n+1, j:m+1]), axis=1), axis=0)
+        if k > 0 and k <= n - j - 1:
+            k += j
+            P[j], P[k] = P[k], P[j]
+            T[[j, k], :] = T[[k, j], :]
+        for i in range(m-1, j, -1):
+            G = planerot(T[j, [j, i]]).T
+            T[j, [j, i]] = np.append(hypot(T[j, j], T[j, i]), 0)
+            T[j + 1:n + 1, [j, i]] = matprod(T[j + 1:n + 1, [j, i]], G)
+            Q[:, [j, i]] = matprod(Q[:, [j, i]], G)
+
+    R = T.T
+
+    return Q, R, P
+
+
+def primasum(x, axis=None):
+    '''
+    According to its documentation, np.sum will sometimes do partial pairwise summation.
+    For our purposes, when comparing, we want don't want to do anything fancy, and we
+    just want to add things up one at a time.
+    '''
+    if not USE_NAIVE_MATH:
+        return np.sum(x, axis=axis)
+    if axis is None:
+        if x.ndim == 2:
+            # Sum columns first, then sum the result
+            return sum(primasum(x, axis=0))
+        else:
+            return sum(x)
+    elif axis == 0:
+        result = np.zeros(x.shape[1])
+        for i in range(x.shape[1]):
+            result[i] = sum(x[:, i])
+        return result
+    elif axis == 1:
+        result = np.zeros(x.shape[0])
+        for i in range(x.shape[0]):
+            result[i] = sum(x[i, :])
+        return result
+
+
+def primapow2(x):
+    '''
+    Believe it or now, x**2 is not always the same as x*x in Python. In Fortran they
+    appear to be identical. Here's a quick one-line to find an example on your system
+    (well, two liner after importing numpy):
+    list(filter(lambda x: x[1], [(x:=np.random.random(), x**2 - x*x != 0) for _ in range(10000)]))
+    '''
+    return x*x
+
+
+def planerot(x):
+    '''
+    As in MATLAB, planerot(x) returns a 2x2 Givens matrix G for x in R2 so that Y=G@x has Y[1] = 0.
+    Roughly speaking, G = np.array([[x[0]/R, x[1]/R], [-x[1]/R, x[0]/R]]), where R = np.linalg.norm(x).
+    0. We need to take care of the possibilities of R=0, Inf, NaN, and over/underflow.
+    1. The G defined above is continuous with respect to X except at 0. Following this definition,
+    G = np.array([[np.sign(x[0]), 0], [0, np.sign(x[0])]]) if x[1] == 0,
+    G = np.array([[0, np.sign(x[1])], [np.sign(x[1]), 0]]) if x[0] == 0
+    Yet some implementations ignore the signs, leading to discontinuity and numerical instability.
+    2. Difference from MATLAB: if x contains NaN of consists of only Inf, MATLAB returns a NaN matrix,
+    but we return an identity matrix or a matrix of +/-np.sqrt(2). We intend to keep G always orthogonal.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert len(x) == 2, "x must be a 2-vector"
+
+    # ==================
+    # Calculation starts
+    # ==================
+
+    # Define C = X(1) / R and S = X(2) / R with R = HYPOT(X(1), X(2)). Handle Inf/NaN, over/underflow.
+    if (any(np.isnan(x))):
+        # In this case, MATLAB sets G to NaN(2, 2). We refrain from doing so to keep G orthogonal.
+        c = 1
+        s = 0
+    elif (all(np.isinf(x))):
+        # In this case, MATLAB sets G to NaN(2, 2). We refrain from doing so to keep G orthogonal.
+        c = 1 / np.sqrt(2) * np.sign(x[0])
+        s = 1 / np.sqrt(2) * np.sign(x[1])
+    elif (abs(x[0]) <= 0 and abs(x[1]) <= 0): # X(1) == 0 == X(2).
+        c = 1
+        s = 0
+    elif (abs(x[1]) <= EPS * abs(x[0])):
+        # N.B.:
+        # 0. With <= instead of <, this case covers X(1) == 0 == X(2), which is treated above separately
+        # to avoid the confusing SIGN(., 0) (see 1).
+        # 1. SIGN(A, 0) = ABS(A) in Fortran but sign(0) = 0 in MATLAB, Python, Julia, and R#
+        # 2. Taking SIGN(X(1)) into account ensures the continuity of G with respect to X except at 0.
+        c = np.sign(x[0])
+        s = 0
+    elif (abs(x[0]) <= EPS * abs(x[1])):
+        # N.B.: SIGN(A, X) = ABS(A) * sign of X /= A * sign of X # Therefore, it is WRONG to define G
+        # as SIGN(RESHAPE([ZERO, -ONE, ONE, ZERO], [2, 2]), X(2)). This mistake was committed on
+        # 20211206 and took a whole day to debug! NEVER use SIGN on arrays unless you are really sure.
+        c = 0
+        s = np.sign(x[1])
+    else:
+        # Here is the normal case. It implements the Givens rotation in a stable & continuous way as in:
+        # Bindel, D., Demmel, J., Kahan, W., and Marques, O. (2002). On computing Givens rotations
+        # reliably and efficiently. ACM Transactions on Mathematical Software (TOMS), 28(2), 206-238.
+        # N.B.: 1. Modern compilers compute SQRT(REALMIN) and SQRT(REALMAX/2.1) at compilation time.
+        # 2. The direct calculation without involving T and U seems to work better; use it if possible.
+        if (all(np.logical_and(np.sqrt(REALMIN) < np.abs(x), np.abs(x) < np.sqrt(REALMAX / 2.1)))):
+            # Do NOT use HYPOTENUSE here; the best implementation for one may be suboptimal for the other
+            r = norm(x)
+            c = x[0] / r
+            s = x[1] / r
+        elif (abs(x[0]) > abs(x[1])):
+            t = x[1] / x[0]
+            u = max(1, abs(t), np.sqrt(1 + t*t))  # MAXVAL: precaution against rounding error.
+            u *= np.sign(x[0]) ##MATLAB: u = sign(x(1))*sqrt(1 + t**2)
+            c = 1 / u
+            s = t / u
+        else:
+            t = x[0] / x[1]
+            u = max([1, abs(t), np.sqrt(1 + t*t)])  # MAXVAL: precaution against rounding error.
+            u *= np.sign(x[1]) ##MATLAB: u = sign(x(2))*sqrt(1 + t**2)
+            c = t / u
+            s = 1 / u
+
+    G = np.array([[c, s], [-s, c]]) #  MATLAB: G = [c, s; -s, c]
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert G.shape == (2,2)
+        assert np.all(np.isfinite(G))
+        assert abs(G[0, 0] - G[1, 1]) + abs(G[0, 1] + G[1, 0]) <= 0
+        tol = np.maximum(1.0E-10, np.minimum(1.0E-1, 1.0E6 * EPS))
+        assert isorth(G, tol)
+        if all(np.logical_and(np.isfinite(x), np.abs(x) < np.sqrt(REALMAX / 2.1))):
+            r = np.linalg.norm(x)
+            assert max(abs(G@x - [r, 0])) <= max(tol, tol * r), 'G @ X = [||X||, 0]'
+
+    return G
+
+
+def isminor(x, ref):
+    '''
+    This function tests whether x is minor compared to ref. It is used by Powell, e.g., in COBYLA.
+    In precise arithmetic, isminor(x, ref) is true if and only if x == 0; in floating point
+    arithmetic, isminor(x, ref) is true if x is 0 or its nonzero value can be attributed to
+    computer rounding errors according to ref.
+    Larger sensitivity means the function is more strict/precise, the value 0.1 being due to Powell.
+
+    For example:
+    isminor(1e-20, 1e300) -> True, because in floating point arithmetic 1e-20 cannot be added to
+    1e300 without being rounded to 1e300.
+    isminor(1e300, 1e-20) -> False, because in floating point arithmetic adding 1e300 to 1e-20
+    dominates the latter number.
+    isminor(3, 4) -> False, because 3 can be added to 4 without being rounded off
+    '''
+
+    sensitivity = 0.1
+    refa = abs(ref) + sensitivity * abs(x)
+    refb = abs(ref) + 2 * sensitivity * abs(x)
+    return np.logical_or(abs(ref) >= refa, refa >= refb)
+
+
+def isinv(A, B, tol=None):
+    '''
+    This procedure tests whether A = B^{-1} up to the tolerance TOL.
+    '''
+
+    # Sizes
+    n = np.size(A, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert np.size(A, 0) == np.size(A, 1)
+        assert np.size(B, 0) == np.size(B, 1)
+        assert np.size(A, 0) == np.size(B, 0)
+        if present(tol):
+            assert tol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    tol = tol if present(tol) else np.minimum(1e-3, 1e2 * EPS * np.maximum(np.size(A, 0), np.size(A, 1)))
+    tol = np.max([tol, tol * np.max(abs(A)), tol * np.max(abs(B))])
+    is_inv = ((abs(matprod(A, B)) - np.eye(n)) <= tol).all() or ((abs(matprod(B, A) - np.eye(n))) <= tol).all()
+
+    #===================#
+    #  Calculation ends #
+    #===================#
+    return is_inv
+
+
+def isorth(A, tol=None):
+    '''
+    This function tests whether the matrix A has orthonormal columns up to the tolerance TOL.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        if present(tol):
+            assert tol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    num_vars = np.size(A, 1)
+
+    if num_vars > np.size(A, 0):
+        is_orth = False
+    elif (np.isnan(primasum(abs(A)))):
+        is_orth = False
+    else:
+        if present(tol):
+            is_orth = (abs(matprod(A.T, A) - np.eye(num_vars)) <= np.maximum(tol, tol * np.max(abs(A)))).all()
+        else:
+            is_orth = (abs(matprod(A.T, A) - np.eye(num_vars)) <= 0).all()
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+    return is_orth
+
+
+def get_arrays_tol(*arrays):
+    """
+    Get a relative tolerance for a set of arrays. Borrowed from COBYQA
+
+    Parameters
+    ----------
+    *arrays: tuple
+        Set of `numpy.ndarray` to get the tolerance for.
+
+    Returns
+    -------
+    float
+        Relative tolerance for the set of arrays.
+
+    Raises
+    ------
+    ValueError
+        If no array is provided.
+    """
+    if len(arrays) == 0:
+        raise ValueError("At least one array must be provided.")
+    size = max(array.size for array in arrays)
+    weight = max(
+        np.max(np.abs(array[np.isfinite(array)]), initial=1.0)
+        for array in arrays
+    )
+    return 10.0 * EPS * max(size, 1.0) * weight
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/message.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/message.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb098c04847a4fd57a11700093390ba9f4cf21be
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/message.py
@@ -0,0 +1,290 @@
+'''
+This module provides some functions that print messages to terminal/files.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+
+N.B.:
+1. In case parallelism is desirable (especially during initialization), the functions may
+have to be modified or disabled due to the IO operations.
+2. IPRINT indicates the level of verbosity, which increases with the absolute value of IPRINT.
+IPRINT = +/-3 can be expensive due to high IO operations.
+'''
+
+from .consts import DEBUGGING
+from .infos import FTARGET_ACHIEVED, MAXFUN_REACHED, MAXTR_REACHED, \
+    SMALL_TR_RADIUS, TRSUBP_FAILED, NAN_INF_F, NAN_INF_X, NAN_INF_MODEL, DAMAGING_ROUNDING, \
+    NO_SPACE_BETWEEN_BOUNDS, ZERO_LINEAR_CONSTRAINT, CALLBACK_TERMINATE
+from .present import present
+import numpy as np
+
+spaces = '   '
+
+
+def get_info_string(solver, info):
+    if info == FTARGET_ACHIEVED:
+        reason = 'the target function value is achieved.'
+    elif info == MAXFUN_REACHED:
+        reason = 'the objective function has been evaluated MAXFUN times.'
+    elif info == MAXTR_REACHED:
+        reason = 'the maximal number of trust region iterations has been reached.'
+    elif info == SMALL_TR_RADIUS:
+        reason = 'the trust region radius reaches its lower bound.'
+    elif info == TRSUBP_FAILED:
+        reason = 'a trust region step has failed to reduce the quadratic model.'
+    elif info == NAN_INF_X:
+        reason = 'NaN or Inf occurs in x.'
+    elif info == NAN_INF_F:
+        reason = 'the objective function returns NaN/+Inf.'
+    elif info == NAN_INF_MODEL:
+        reason = 'NaN or Inf occurs in the models.'
+    elif info == DAMAGING_ROUNDING:
+        reason = 'rounding errors are becoming damaging.'
+    elif info == NO_SPACE_BETWEEN_BOUNDS:
+        reason = 'there is no space between the lower and upper bounds of variable.'
+    elif info == ZERO_LINEAR_CONSTRAINT:
+        reason = 'one of the linear constraints has a zero gradient'
+    elif info == CALLBACK_TERMINATE:
+        reason = 'the callback function requested termination'
+    else:
+        reason = 'UNKNOWN EXIT FLAG'
+    ret_message = f'Return from {solver} because {reason.strip()}'
+    return ret_message
+
+
+def retmsg(solver, info, iprint, nf, f, x, cstrv=None, constr=None):
+    '''
+    This function prints messages at return.
+    '''
+    # Local variables
+    valid_exit_codes = [FTARGET_ACHIEVED, MAXFUN_REACHED, MAXTR_REACHED,
+        SMALL_TR_RADIUS, TRSUBP_FAILED, NAN_INF_F, NAN_INF_X, NAN_INF_MODEL, DAMAGING_ROUNDING,
+        NO_SPACE_BETWEEN_BOUNDS, ZERO_LINEAR_CONSTRAINT, CALLBACK_TERMINATE]
+
+    # Preconditions
+    if DEBUGGING:
+        assert info in valid_exit_codes
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 1:  # No printing (iprint == 0)
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver}_output.txt'
+
+    # Decide whether the problem is truly constrained.
+    if present(constr):
+        is_constrained = (np.size(constr) > 0)
+    else:
+        is_constrained = present(cstrv)
+
+    # Decide the constraint violation.
+    if present(cstrv):
+        cstrv_loc = cstrv
+    elif present(constr):
+        cstrv_loc = np.max(np.append(0, -constr))  # N.B.: We assume that the constraint is CONSTR >= 0.
+    else:
+        cstrv_loc = 0
+
+    # Decide the return message.
+    ret_message = get_info_string(solver, info)
+
+    if np.size(x) <= 2:
+        x_message = f'\nThe corresponding X is: {x}'  # Printed in one line
+    else:
+        x_message = f'\nThe corresponding X is:\n{x}'
+
+    if is_constrained:
+        nf_message = (f'\nNumber of function values = {nf}{spaces}'
+            f'Least value of F = {f}{spaces}Constraint violation = {cstrv_loc}')
+    else:
+        nf_message = f'\nNumber of function values = {nf}{spaces}Least value of F = {f}'
+
+    if is_constrained and present(constr):
+        if np.size(constr) <= 2:
+            constr_message = f'\nThe constraint value is: {constr}'  # Printed in one line
+        else:
+            constr_message = f'\nThe constraint value is:\n{constr}'
+    else:
+        constr_message = ''
+
+    # Print the message.
+    if abs(iprint) >= 2:
+        message = f'\n{ret_message}{nf_message}{x_message}{constr_message}\n'
+    else:
+        message = f'{ret_message}{nf_message}{x_message}{constr_message}\n'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+
+def rhomsg(solver, iprint, nf, delta, f, rho, x, cstrv=None, constr=None, cpen=None):
+    '''
+    This function prints messages when RHO is updated.
+    '''
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 2:  # No printing
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver.strip()}_output.txt'
+
+    # Decide whether the problem is truly constrained.
+    if present(constr):
+        is_constrained = (np.size(constr) > 0)
+    else:
+        is_constrained = present(cstrv)
+
+    # Decide the constraint violation.
+    if present(cstrv):
+        cstrv_loc = cstrv
+    elif present(constr):
+        cstrv_loc = np.max(np.append(0, -constr))  # N.B.: We assume that the constraint is CONSTR >= 0.
+    else:
+        cstrv_loc = 0
+
+    if present(cpen):
+        rho_message = (f'\nNew RHO = {rho}{spaces}Delta = {delta}{spaces}'
+            f'CPEN = {cpen}')
+    else:
+        rho_message = f'\nNew RHO = {rho}{spaces}Delta = {delta}'
+
+    if np.size(x) <= 2:
+        x_message = f'\nThe corresponding X is: {x}'  # Printed in one line
+    else:
+        x_message = f'\nThe corresponding X is:\n{x}'
+
+    if is_constrained:
+        nf_message = (f'\nNumber of function values = {nf}{spaces}'
+            f'Least value of F = {f}{spaces}Constraint violation = {cstrv_loc}')
+    else:
+        nf_message = f'\nNumber of function values = {nf}{spaces}Least value of F = {f}'
+
+    if is_constrained and present(constr):
+        if np.size(constr) <= 2:
+            constr_message = f'\nThe constraint value is: {constr}'  # Printed in one line
+        else:
+            constr_message = f'\nThe constraint value is:\n{constr}'
+    else:
+        constr_message = ''
+
+    # Print the message.
+    if abs(iprint) >= 3:
+        message = f'\n{rho_message}{nf_message}{x_message}{constr_message}'
+    else:
+        message = f'{rho_message}{nf_message}{x_message}{constr_message}'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+
+def cpenmsg(solver, iprint, cpen):
+    '''
+    This function prints a message when CPEN is updated.
+    '''
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 2:  # No printing
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver.strip()}_output.txt'
+
+    # Print the message.
+    if abs(iprint) >= 3:
+        message = f'\nSet CPEN to {cpen}'
+    else:
+        message = f'\n\nSet CPEN to {cpen}'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+
+def fmsg(solver, state, iprint, nf, delta, f, x, cstrv=None, constr=None):
+    '''
+    This subroutine prints messages for each evaluation of the objective function.
+    '''
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 2:  # No printing
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver.strip()}_output.txt'
+
+    # Decide whether the problem is truly constrained.
+    if present(constr):
+        is_constrained = (np.size(constr) > 0)
+    else:
+        is_constrained = present(cstrv)
+
+    # Decide the constraint violation.
+    if present(cstrv):
+        cstrv_loc = cstrv
+    elif present(constr):
+        cstrv_loc = np.max(np.append(0, -constr))  # N.B.: We assume that the constraint is CONSTR >= 0.
+    else:
+        cstrv_loc = 0
+
+    delta_message = f'\n{state} step with radius = {delta}'
+
+    if is_constrained:
+        nf_message = (f'\nNumber of function values = {nf}{spaces}'
+            f'Least value of F = {f}{spaces}Constraint violation = {cstrv_loc}')
+    else:
+        nf_message = f'\nNumber of function values = {nf}{spaces}Least value of F = {f}'
+
+    if np.size(x) <= 2:
+        x_message = f'\nThe corresponding X is: {x}'  # Printed in one line
+    else:
+        x_message = f'\nThe corresponding X is:\n{x}'
+
+    if is_constrained and present(constr):
+        if np.size(constr) <= 2:
+            constr_message = f'\nThe constraint value is: {constr}'  # Printed in one line
+        else:
+            constr_message = f'\nThe constraint value is:\n{constr}'
+    else:
+        constr_message = ''
+
+    # Print the message.
+    message = f'{delta_message}{nf_message}{x_message}{constr_message}'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/powalg.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/powalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..2987b4da89f43d39cc7f80a95ce0d40a7bbdeecb
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/powalg.py
@@ -0,0 +1,131 @@
+'''
+This module provides some Powell-style linear algebra procedures.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from .linalg import isminor, planerot, matprod, inprod, hypot
+from .consts import DEBUGGING, EPS
+
+
+def qradd_Rdiag(c, Q, Rdiag, n):
+    '''
+    This function updates the QR factorization of an MxN matrix A of full column rank, attempting to
+    add a new column C to this matrix as the LAST column while maintaining the full-rankness.
+    Case 1. If C is not in range(A) (theoretically, it implies N < M), then the new matrix is np.hstack([A, C])
+    Case 2. If C is in range(A), then the new matrix is np.hstack([A[:, :n-1], C])
+    N.B.:
+    0. Instead of R, this subroutine updates Rdiag, which is np.diag(R), with a size at most M and at
+    least min(m, n+1). The number is min(m, n+1) rather than min(m, n) as n may be augmented by 1 in
+    the function.
+    1. With the two cases specified as above, this function does not need A as an input.
+    2. The function changes only Q[:, nsave:m] (nsave is the original value of n) and
+    R[:, n-1] (n takes the updated value)
+    3. Indeed, when C is in range(A), Powell wrote in comments that "set iOUT to the index of the
+    constraint (here, column of A --- Zaikun) to be deleted, but branch if no suitable index can be
+    found". The idea is to replace a column of A by C so that the new matrix still has full rank
+    (such a column must exist unless C = 0). But his code essentially sets iout=n always. Maybe he
+    found this worked well enough in practice. Meanwhile, Powell's code includes a snippet that can
+    never be reached, which was probably intended to deal with the case that IOUT != n
+    '''
+    m = Q.shape[1]
+    nsave = n  # Needed for debugging (only)
+
+    # As in Powell's COBYLA, CQ is set to 0 at the positions with CQ being negligible as per ISMINOR.
+    # This may not be the best choice if the subroutine is used in other contexts, e.g. LINCOA.
+    cq = matprod(c, Q)
+    cqa = matprod(abs(c), abs(Q))
+    # The line below basically makes an element of cq 0 if adding it to the corresponding element of
+    # cqa does not change the latter.
+    cq = np.array([0 if isminor(cqi, cqai) else cqi for cqi, cqai in zip(cq, cqa)])
+
+    # Update Q so that the columns of Q[:, n+1:m] are orthogonal to C. This is done by applying a 2D
+    # Givens rotation to Q[:, [k, k+1]] from the right to zero C' @ Q[:, k+1] out for K=n+1, ... m-1.
+    # Nothing will be done if n >= m-1
+    for k in range(m-2, n-1, -1):
+        if abs(cq[k+1]) > 0:
+            # Powell wrote cq[k+1] != 0 instead of abs. The two differ if cq[k+1] is NaN.
+            # If we apply the rotation below when cq[k+1] = 0, then cq[k] will get updated to |cq[k]|.
+            G = planerot(cq[k:k+2])
+            Q[:, [k, k+1]] = matprod(Q[:, [k, k+1]], G.T)
+            cq[k] = hypot(*cq[k:k+2])
+
+    # Augment n by 1 if C is not in range(A)
+    if n < m:
+        # Powell's condition for the following if: cq[n+1] != 0
+        if abs(cq[n]) > EPS**2 and not isminor(cq[n], cqa[n]):
+            n += 1
+
+    # Update Rdiag so that Rdiag[n] = cq[n] = np.dot(c, q[:, n]). Note that N may be been augmented.
+    if n - 1 >= 0 and n - 1 < m:  # n >= m should not happen unless the input is wrong
+        Rdiag[n - 1] = cq[n - 1]
+
+    if DEBUGGING:
+        assert nsave <= n <= min(nsave + 1, m)
+        assert n <= len(Rdiag) <= m
+        assert Q.shape == (m, m)
+
+    return Q, Rdiag, n
+
+
+def qrexc_Rdiag(A, Q, Rdiag, i):  # Used in COBYLA
+    '''
+    This function updates the QR factorization for an MxN matrix A=Q@R so that the updated Q and
+    R form a QR factorization of [A_0, ..., A_{I-1}, A_{I+1}, ..., A_{N-1}, A_I] which is the matrix
+    obtained by rearranging columns [I, I+1, ... N-1] of A to [I+1, ..., N-1, I]. Here A is ASSUMED TO
+    BE OF FULL COLUMN RANK, Q is a matrix whose columns are orthogonal, and R, which is not present,
+    is an upper triangular matrix whose diagonal entries are nonzero. Q and R need not be square.
+    N.B.:
+    0. Instead of R, this function updates Rdiag, which is np.diag(R), the size being n.
+    1. With L = Q.shape[1] = R.shape[0], we have M >= L >= N. Most often L = M or N.
+    2. This function changes only Q[:, i:] and Rdiag[i:]
+    3. (NDB 20230919) In Python, i is either icon or nact - 2, whereas in FORTRAN it is either icon or nact - 1.
+    '''
+
+    # Sizes
+    m, n = A.shape
+
+    # Preconditions
+    assert n >= 1 and n <= m
+    assert i >= 0 and i < n
+    assert len(Rdiag) == n
+    assert Q.shape[0] == m and Q.shape[1] >= n and Q.shape[1] <= m
+    # tol = max(1.0E-8, min(1.0E-1, 1.0E8 * EPS * m + 1))
+    # assert isorth(Q, tol)  # Costly!
+
+
+    if i < 0 or i >= n:
+        return Q, Rdiag
+
+    # Let R be the upper triangular matrix in the QR factorization, namely R = Q.T@A.
+    # For each k, find the Givens rotation G with G@(R[k:k+2, :]) = [hypt, 0], and update Q[:, k:k+2]
+    # to Q[:, k:k+2]@(G.T). Then R = Q.T@A is an upper triangular matrix as long as A[:, [k, k+1]] is
+    # updated to A[:, [k+1, k]]. Indeed, this new upper triangular matrix can be obtained by first
+    # updating R[[k, k+1], :] to G@(R[[k, k+1], :]) and then exchanging its columns K and K+1; at the same
+    # time, entries k and k+1 of R's diagonal Rdiag become [hypt, -(Rdiag[k+1]/hypt)*RDiag[k]].
+    # After this is done for each k = 0, ..., n-2, we obtain the QR factorization of the matrix that
+    # rearranges columns [i, i+1, ... n-1] of A as [i+1, ..., n-1, i].
+    # Powell's code, however, is slightly different: before everything, he first exchanged columns k and
+    # k+1 of Q (as well as rows k and k+1 of R). This makes sure that the entries of the update Rdiag
+    # are all positive if it is the case for the original Rdiag.
+    for k in range(i, n-1):
+        G = planerot([Rdiag[k+1], inprod(Q[:, k], A[:, k+1])])
+        Q[:, [k, k+1]] = matprod(Q[:, [k+1, k]], (G.T))
+        # Powell's code updates Rdiag in the following way:
+        # hypt = np.sqrt(Rdiag[k+1]**2 + np.dot(Q[:, k], A[:, k+1])**2)
+        # Rdiag[[k, k+1]] = [hypt, (Rdiag[k+1]/hypt)*Rdiag[k]]
+        # Note that Rdiag[n-1] inherits all rounding in Rdiag[i:n-1] and Q[:, i:n-1] and hence contains
+        # significant errors. Thus we may modify Powell's code to set only Rdiag[k] = hypt here and then
+        # calculate Rdiag[n] by an inner product after the loop. Nevertheless, we simple calculate RDiag
+        # from scratch below.
+
+    # Calculate Rdiag(i:n) from scratch
+    Rdiag[i:n-1] = [inprod(Q[:, k], A[:, k+1]) for k in range(i, n-1)]
+    Rdiag[n-1] = inprod(Q[:, n-1], A[:, i])
+
+    return Q, Rdiag
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/preproc.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/preproc.py
new file mode 100644
index 0000000000000000000000000000000000000000..8104cd8fd80878e9546a4fef21ccc1c08fc1a004
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/preproc.py
@@ -0,0 +1,277 @@
+'''
+This is a module that preprocesses the inputs.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .consts import DEBUGGING, EPS, IPRINT_DEFAULT, FTARGET_DEFAULT, \
+    MIN_MAXFILT, MAXFILT_DEFAULT, MAXHISTMEM, ETA1_DEFAULT, ETA2_DEFAULT, \
+    GAMMA1_DEFAULT, GAMMA2_DEFAULT, RHOBEG_DEFAULT, RHOEND_DEFAULT, \
+    CTOL_DEFAULT, CWEIGHT_DEFAULT
+from .present import present
+from warnings import warn
+import numpy as np
+
+
+def preproc(solver, num_vars, iprint, maxfun, maxhist, ftarget, rhobeg, rhoend,
+            num_constraints=None, npt=None, maxfilt=None, ctol=None, cweight=None,
+            eta1=None, eta2=None, gamma1=None, gamma2=None, is_constrained=None, has_rhobeg=None,
+            honour_x0=None, xl=None, xu=None, x0=None):
+    '''
+    This subroutine preprocesses the inputs. It does nothing to the inputs that are valid.
+    '''
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        if present(num_constraints):
+            assert num_constraints >= 0
+            assert num_constraints == 0 or solver.lower() == 'cobyla'
+        if solver.lower() == 'cobyla' and present(num_constraints) and present(is_constrained):
+            assert num_constraints == 0 or is_constrained
+        if solver.lower() == 'bobyqa':
+            assert present(xl) and present(xu)
+            assert all(xu - xl >= 2 * EPS)
+        if present(honour_x0):
+            assert solver.lower() == 'bobyqa' and present(has_rhobeg) and present(xl) and present(xu) and present(x0)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Read num_constraints, if necessary
+    num_constraints = num_constraints if (present(num_constraints) and solver.lower() == 'cobyla') else 0
+
+    # Decide whether the problem is truly constrained
+    is_constrained = is_constrained if (present(is_constrained)) else num_constraints > 0
+
+    # Validate IPRINT
+    if np.abs(iprint) > 3:
+        iprint = IPRINT_DEFAULT
+        warn(f'{solver}: Invalid IPRINT; it should be 0, 1, -1, 2, -2, 3, or -3; it is set to {iprint}')
+
+    # Validate MAXFUN
+    if solver.lower() == 'uobyqa':
+        min_maxfun = (num_vars + 1) * (num_vars + 2) / 2 + 1
+        min_maxfun_str = '(N+1)(N+2)/2 + 1'
+    elif solver.lower() == 'cobyla':
+        min_maxfun = num_vars + 2
+        min_maxfun_str = 'num_vars + 2'
+    else:  # CASE ('NEWUOA', 'BOBYQA', 'LINCOA')
+        min_maxfun = num_vars + 3
+        min_maxfun_str = 'num_vars + 3'
+    if maxfun < min_maxfun:
+        maxfun = min_maxfun
+        warn(f'{solver}: Invalid MAXFUN; it should be at least {min_maxfun_str}; it is set to {maxfun}')
+
+    # Validate MAXHIST
+    if maxhist < 0:
+        maxhist = maxfun
+        warn(f'{solver}: Invalid MAXHIST; it should be a nonnegative integer; it is set to {maxhist}')
+    maxhist = min(maxhist, maxfun)  # MAXHIST > MAXFUN is never needed.
+
+    # Validate FTARGET
+    if np.isnan(ftarget):
+        ftarget = FTARGET_DEFAULT
+        warn(f'{solver}: Invalid FTARGET; it should be a real number; it is set to {ftarget}')
+
+    # Validate NPT
+    if (solver.lower() == 'newuoa' or solver.lower() == 'bobyqa' or solver.lower() == 'lincoa') and present(npt):
+        if (npt < num_vars + 2 or npt > min(maxfun - 1, ((num_vars + 2) * (num_vars + 1)) / 2)):
+            npt = int(min(maxfun - 1, 2 * num_vars + 1))
+            warn(f'{solver}: Invalid NPT; it should be an integer in the interval [N+2, (N+1)(N+2)/2] and less than MAXFUN; it is set to {npt}')
+
+    # Validate MAXFILT
+    if present(maxfilt) and (solver.lower() == 'lincoa' or solver.lower() == 'cobyla'):
+        maxfilt_in = maxfilt
+        if maxfilt < 1:
+            maxfilt = MAXFILT_DEFAULT  # The inputted MAXFILT is obviously wrong.
+        else:
+            maxfilt = max(MIN_MAXFILT, maxfilt)  # The inputted MAXFILT is too small.
+        # Further revise MAXFILT according to MAXHISTMEM.
+        if solver.lower() == 'lincoa':
+            unit_memo = (num_vars + 2) * np.dtype(float).itemsize
+        elif solver.lower() == 'cobyla':
+            unit_memo = (num_constraints + num_vars + 2) * np.dtype(float).itemsize
+        else:
+            unit_memo = 1
+        # We cannot simply set MAXFILT = MIN(MAXFILT, MAXHISTMEM/...), as they may not have
+        # the same kind, and compilers may complain. We may convert them, but overflow may occur.
+        if maxfilt > MAXHISTMEM / unit_memo:
+            maxfilt = int(MAXHISTMEM / unit_memo)  # Integer division.
+        maxfilt = min(maxfun, max(MIN_MAXFILT, maxfilt))
+        if is_constrained:
+            if maxfilt_in < 1:
+                warn(f'{solver}: Invalid MAXFILT; it should be a positive integer; it is set to  {maxfilt}')
+            elif maxfilt_in < min(maxfun, MIN_MAXFILT):
+                warn(f'{solver}: MAXFILT is too small; it is set to {maxfilt}')
+            elif maxfilt < min(maxfilt_in, maxfun):
+                warn(f'{solver}: MAXFILT is set to {maxfilt} due to memory limit')
+
+    # Validate ETA1 and ETA2
+    eta1_local = eta1 if present(eta1) else ETA1_DEFAULT
+    eta2_local = eta2 if present(eta2) else ETA2_DEFAULT
+
+    # When the difference between ETA1 and ETA2 is tiny, we force them to equal.
+    # See the explanation around RHOBEG and RHOEND for the reason.
+    if present(eta1) and present(eta2):
+        if np.abs(eta1 - eta2) < 1.0E2 * EPS * max(np.abs(eta1), 1):
+            eta2 = eta1
+
+    if present(eta1):
+        if np.isnan(eta1):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            eta1 = ETA1_DEFAULT
+        elif eta1 < 0 or eta1 >= 1:
+            # Take ETA2 into account if it has a valid value.
+            if present(eta2) and eta2_local > 0 and eta2_local <= 1:
+                eta1 = max(EPS, eta2 / 7.0)
+            else:
+                eta1 = ETA1_DEFAULT
+            warn(f'{solver}: Invalid ETA1; it should be in the interval [0, 1) and not more than ETA2; it is set to {eta1}')
+
+    if present(eta2):
+        if np.isnan(eta2):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            eta2 = ETA2_DEFAULT
+        elif present(eta1) and (eta2 < eta1_local or eta2 > 1):
+            eta2 = (eta1 + 2) / 3.0
+            warn(f'{solver}: Invalid ETA2; it should be in the interval [0, 1) and not less than ETA1; it is set to {eta2}')
+
+    # Validate GAMMA1 and GAMMA2
+    if present(gamma1):
+        if np.isnan(gamma1):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            gamma1 = GAMMA1_DEFAULT
+        elif gamma1 <= 0 or gamma1 >= 1:
+            gamma1 = GAMMA1_DEFAULT
+            warn(f'{solver}: Invalid GAMMA1; it should in the interval (0, 1); it is set to {gamma1}')
+
+    if present(gamma2):
+        if np.isnan(gamma2):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            gamma2 = GAMMA2_DEFAULT
+        elif gamma2 < 1 or np.isinf(gamma2):
+            gamma2 = GAMMA2_DEFAULT
+            warn(f'{solver}: Invalid GAMMA2; it should be a real number not less than 1; it is set to {gamma2}')
+
+    # Validate RHOBEG and RHOEND
+
+    if np.abs(rhobeg - rhoend) < 1.0e2 * EPS * np.maximum(np.abs(rhobeg), 1):
+        # When the data is passed from the interfaces (e.g., MEX) to the Fortran code, RHOBEG, and RHOEND
+        # may change a bit. It was observed in a MATLAB test that MEX passed 1 to Fortran as
+        # 0.99999999999999978. Therefore, if we set RHOEND = RHOBEG in the interfaces, then it may happen
+        # that RHOEND > RHOBEG, which is considered as an invalid input. To avoid this situation, we
+        # force RHOBEG and RHOEND to equal when the difference is tiny.
+        rhoend = rhobeg
+
+    # Revise the default values for RHOBEG/RHOEND according to the solver.
+    if solver.lower() == 'bobyqa':
+        rhobeg_default = np.maximum(EPS, np.min(RHOBEG_DEFAULT, np.min(xu - xl) / 4.0))
+        rhoend_default = np.maximum(EPS, np.min(0.1 * rhobeg_default, RHOEND_DEFAULT))
+    else:
+        rhobeg_default = RHOBEG_DEFAULT
+        rhoend_default = RHOEND_DEFAULT
+
+    if solver.lower() == 'bobyqa':
+        # Do NOT merge the IF below into the ELIF above! Otherwise, XU and XL may be accessed even if
+        # the solver is not BOBYQA, because the logical evaluation is not short-circuit.
+        if rhobeg > np.min(xu - xl) / 2:
+            # Do NOT make this revision if RHOBEG not positive or not finite, because otherwise RHOBEG
+            # will get a huge value when XU or XL contains huge values that indicate unbounded variables.
+            rhobeg = np.min(xu - xl) / 4.0  # Here, we do not take RHOBEG_DEFAULT.
+            warn(f'{solver}: Invalid RHOBEG; {solver} requires 0 < RHOBEG <= np.min(XU-XL)/2; it is set to np.min(XU-XL)/4')
+    if rhobeg <= 0 or np.isnan(rhobeg) or np.isinf(rhobeg):
+        # Take RHOEND into account if it has a valid value. We do not do this if the solver is BOBYQA,
+        # which requires that RHOBEG <= (XU-XL)/2.
+        if np.isfinite(rhoend) and rhoend > 0 and solver.lower() != 'bobyqa':
+            rhobeg = max(10 * rhoend, rhobeg_default)
+        else:
+            rhobeg = rhobeg_default
+        warn(f'{solver}: Invalid RHOBEG; it should be a positive number; it is set to {rhobeg}')
+
+    if rhoend <= 0 or rhobeg < rhoend or np.isnan(rhoend) or np.isinf(rhoend):
+        rhoend = max(EPS, min(0.1 * rhobeg, rhoend_default))
+        warn(f'{solver}: Invalid RHOEND; it should be a positive number and RHOEND <= RHOBEG; it is set to {rhoend}')
+
+    # For BOBYQA, revise X0 or RHOBEG so that the distance between X0 and the inactive bounds is at
+    # least RHOBEG. If HONOUR_X0 == TRUE, revise RHOBEG if needed; otherwise, revise HONOUR_X0 if needed.
+    if present(honour_x0):
+        if honour_x0:
+            rhobeg_old = rhobeg;
+            lbx = np.isfinite(xl) & (x0 - xl <= EPS * np.maximum(1, np.abs(xl))) # X0 essentially equals XL
+            ubx = np.isfinite(xu) & (x0 - xu >= -EPS * np.maximum(1, np.abs(xu))) # X0 essentially equals XU
+            x0[lbx] = xl[lbx]
+            x0[ubx] = xu[ubx]
+            rhobeg = max(EPS, np.min([rhobeg, x0[~lbx] - xl[~lbx], xu[~ubx] - x0[~ubx]]))
+            if rhobeg_old - rhobeg > EPS * max(1, rhobeg_old):
+                rhoend = max(EPS, min(0.1 * rhobeg, rhoend)) # We do not revise RHOEND unless RHOBEG is truly revised.
+                if has_rhobeg:
+                    warn(f'{solver}: RHOBEG is revised to {rhobeg} and RHOEND to at most 0.1*RHOBEG so that the distance between X0 and the inactive bounds is at least RHOBEG')
+            else:
+                rhoend = np.minimum(rhoend, rhobeg)  # This may update RHOEND slightly.
+        else:
+            x0_old = x0  # Recorded to see whether X0 is really revised.
+            # N.B.: The following revision is valid only if XL <= X0 <= XU and RHOBEG <= MINVAL(XU-XL)/2,
+            # which should hold at this point due to the revision of RHOBEG and moderation of X0.
+            # The cases below are mutually exclusive in precise arithmetic as MINVAL(XU-XL) >= 2*RHOBEG.
+            lbx = x0 <= xl + 0.5 * rhobeg
+            lbx_plus = (x0 > xl + 0.5 * rhobeg) & (x0 < xl + rhobeg)
+            ubx = x0 >= xu - 0.5 * rhobeg
+            ubx_minus = (x0 < xu - 0.5 * rhobeg) & (x0 > xu - rhobeg)
+            x0[lbx] = xl[lbx]
+            x0[lbx_plus] = xl[lbx_plus] + rhobeg
+            x0[ubx] = xu[ubx]
+            x0[ubx_minus] = xu[ubx_minus] - rhobeg
+
+            if (any(np.abs(x0_old - x0) > 0)):
+                warn(f'{solver}: X0 is revised so that the distance between X0 and the inactive bounds is at least RHOBEG set HONOUR_X0 to .TRUE. if you prefer to keep X0 unchanged')
+
+    # Validate CTOL (it can be 0)
+    if (present(ctol)):
+        if (np.isnan(ctol) or ctol < 0):
+            ctol = CTOL_DEFAULT
+            if (is_constrained):
+                warn(f'{solver}: Invalid CTOL; it should be a nonnegative number; it is set to {ctol}')
+
+    # Validate CWEIGHT (it can be +Inf)
+    if (present(cweight)):
+        if (np.isnan(cweight) or cweight < 0):
+            cweight = CWEIGHT_DEFAULT
+            if (is_constrained):
+                warn(f'{solver}: Invalid CWEIGHT; it should be a nonnegative number; it is set to {cweight}')
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert abs(iprint) <= 3
+        assert maxhist >= 0 and maxhist <= maxfun
+        if present(npt):
+            assert maxfun >= npt + 1
+            assert npt >= 3
+        if present(maxfilt):
+            assert maxfilt >= np.minimum(MIN_MAXFILT, maxfun) and maxfilt <= maxfun
+        if present(eta1) and present(eta2):
+            assert eta1 >= 0 and eta1 <= eta2 and eta2 < 1
+        if present(gamma1) and present(gamma2):
+            assert gamma1 > 0 and gamma1 < 1 and gamma2 > 1
+        assert rhobeg >= rhoend and rhoend > 0
+        if solver.lower() == 'bobyqa':
+            assert all(rhobeg <= (xu - xl) / 2)
+            assert all(np.isfinite(x0))
+            assert all(x0 >= xl and (x0 <= xl or x0 >= xl + rhobeg))
+            assert all(x0 <= xu and (x0 >= xu or x0 <= xu - rhobeg))
+        if present(ctol):
+            assert ctol >= 0
+
+    return iprint, maxfun, maxhist, ftarget, rhobeg, rhoend, npt, maxfilt, ctol, cweight, eta1, eta2, gamma1, gamma2, x0
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/present.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/present.py
new file mode 100644
index 0000000000000000000000000000000000000000..de3cda35ffe69b688c55abb74a059d46dba1655f
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/present.py
@@ -0,0 +1,5 @@
+def present(x):
+    '''
+    This is a Python equivalent of the Fortran 'present' function for optional arguments.
+    '''
+    return x is not None
\ No newline at end of file
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/ratio.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/ratio.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a45bc7b057485564e4f5a655fe250f329a22e9
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/ratio.py
@@ -0,0 +1,54 @@
+'''
+This module calculates the reduction ratio for trust-region methods.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .consts import DEBUGGING, REALMAX
+import numpy as np
+
+def redrat(ared, pred, rshrink):
+    '''
+    This function evaluates the reduction ratio of a trust-region step, handling inf/nan properly.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert rshrink >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if np.isnan(ared):
+        # This should not happen in unconstrained problems due to the moderated extreme barrier.
+        ratio = -REALMAX
+    elif np.isnan(pred) or pred <= 0:
+        # The trust-region subproblem solver fails in this rare case. Instead of terminating as Powell's
+        # original code does, we set ratio as follows so that the solver may continue to progress.
+        if ared > 0:
+            # The trial point will be accepted, but the trust-region radius will be shrunk if rshrink>0
+            ratio = rshrink/2
+        else:
+            # Set the ration to a large negative number to signify a bad trust-region step, so that the
+            # solver will check whether to take a geometry step or reduce rho.
+            ratio = -REALMAX
+    elif np.isposinf(pred) and np.isposinf(ared):
+        ratio = 1  # ared/pred = NaN if calculated directly
+    elif np.isposinf(pred) and np.isneginf(ared):
+        ratio = -REALMAX  # ared/pred = NaN if calculated directly
+    else:
+        ratio = ared/pred
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert not np.isnan(ratio)
+    return ratio
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/redrho.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/redrho.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1048e03b7a3c32e53c2a49d86da7f9cf312e4e4
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/redrho.py
@@ -0,0 +1,47 @@
+'''
+This module provides a function that calculates RHO when it needs to be reduced.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .consts import DEBUGGING
+import numpy as np
+
+def redrho(rho_in, rhoend):
+    '''
+    This function calculates RHO when it needs to be reduced.
+    The scheme is shared by UOBYQA, NEWUOA, BOBYQA, LINCOA. For COBYLA, Powell's code reduces RHO by
+    'RHO *= 0.5; if RHO <= 1.5 * RHOEND: RHO = RHOEND' as specified in (11) of the COBYLA
+    paper. However, this scheme seems to work better, especially after we introduce DELTA.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert rho_in > rhoend > 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    rho_ratio = rho_in / rhoend
+
+    if rho_ratio > 250:
+        rho = 0.1 * rho_in
+    elif rho_ratio <= 16:
+        rho = rhoend
+    else:
+        rho = np.sqrt(rho_ratio) * rhoend  # rho = np.sqrt(rho * rhoend)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert rho_in > rho >= rhoend
+
+    return rho
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/selectx.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/selectx.py
new file mode 100644
index 0000000000000000000000000000000000000000..a03be9aa8469a3357518136b05a371b5c61341d1
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/pyprima/common/selectx.py
@@ -0,0 +1,296 @@
+'''
+This module provides subroutines that ensure the returned X is optimal among all the calculated
+points in the sense that no other point achieves both lower function value and lower constraint
+violation at the same time. This module is needed only in the constrained case.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+import numpy.typing as npt
+from .consts import DEBUGGING, EPS, CONSTRMAX, REALMAX, FUNCMAX
+from .present import present
+
+def isbetter(f1: float, c1: float, f2: float, c2: float, ctol: float) -> bool:
+    '''
+    This function compares whether FC1 = (F1, C1) is (strictly) better than FC2 = (F2, C2), which
+    basically means that (F1 < F2 and C1 <= C2) or (F1 <= F2 and C1 < C2).
+    It takes care of the cases where some of these values are NaN or Inf, even though some cases
+    should never happen due to the moderated extreme barrier.
+    At return, BETTER = TRUE if and only if (F1, C1) is better than (F2, C2).
+    Here, C means constraint violation, which is a nonnegative number.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert not any(np.isnan([f1, c1]) | np.isposinf([f2, c2]))
+        assert not any(np.isnan([f2, c2]) | np.isposinf([f2, c2]))
+        assert c1 >= 0 and c2 >= 0
+        assert ctol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    is_better = False
+    # Even though NaN/+Inf should not occur in FC1 or FC2 due to the moderated extreme barrier, for
+    # security and robustness, the code below does not make this assumption.
+    is_better = is_better or (any(np.isnan([f1, c1]) | np.isposinf([f1, c1])) and not any(np.isnan([f2, c2]) | np.isposinf([f2, c2])))
+
+    is_better = is_better or (f1 < f2 and c1 <= c2)
+    is_better = is_better or (f1 <= f2 and c1 < c2)
+
+    # If C1 <= CTOL and C2 is significantly larger/worse than CTOL, i.e., C2 > MAX(CTOL,CREF),
+    # then FC1 is better than FC2 as long as F1 < REALMAX. Normally CREF >= CTOL so MAX(CTOL, CREF)
+    # is indeed CREF. However, this may not be true if CTOL > 1E-1*CONSTRMAX.
+    cref = 10 * max(EPS, min(ctol, 1.0E-2 * CONSTRMAX))  # The MIN avoids overflow.
+    is_better = is_better or (f1 < REALMAX and c1 <= ctol and (c2 > max(ctol, cref) or np.isnan(c2)))
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert not (is_better and f1 >= f2 and c1 >= c2)
+        assert is_better or not (f1 <= f2 and c1 < c2)
+        assert is_better or not (f1 < f2 and c1 <= c2)
+
+    return is_better
+
+
+def savefilt(cstrv, ctol, cweight, f, x, nfilt, cfilt, ffilt, xfilt, constr=None, confilt=None):
+    '''
+    This subroutine saves X, F, and CSTRV in XFILT, FFILT, and CFILT (and CONSTR in CONFILT
+    if they are present), unless a vector in XFILT[:, :NFILT] is better than X.
+    If X is better than some vectors in XFILT[:, :NFILT] then these vectors will be
+    removed. If X is not better than any of XFILT[:, :NFILT], but NFILT == MAXFILT,
+    then we remove a column from XFILT according to the merit function
+    PHI = FFILT + CWEIGHT * max(CFILT - CTOL, 0)
+    N.B.:
+    1. Only XFILT[:, :NFILT] and FFILT[:, :NFILT] etc contains valid information,
+    while XFILT[:, NFILT+1:MAXFILT] and FFILT[:, NFILT+1:MAXFILT] etc are not
+    initialized yet.
+    2. We decide whether and X is better than another by the ISBETTER function
+    '''
+
+    # Sizes
+    if present(constr):
+        num_constraints = len(constr)
+    else:
+        num_constraints = 0
+    num_vars = len(x)
+    maxfilt = len(ffilt)
+
+    # Preconditions
+    if DEBUGGING:
+        # Check the size of X.
+        assert num_vars >= 1
+        # Check CWEIGHT and CTOL
+        assert cweight >= 0
+        assert ctol >= 0
+        # Check NFILT
+        assert nfilt >= 0 and nfilt <= maxfilt
+        # Check the sizes of XFILT, FFILT, CFILT.
+        assert maxfilt >= 1
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert np.size(cfilt) == maxfilt
+        # Check the values of XFILT, FFILT, CFILT.
+        assert not (np.isnan(xfilt[:, :nfilt])).any()
+        assert not any(np.isnan(ffilt[:nfilt]) | np.isposinf(ffilt[:nfilt]))
+        assert not any(cfilt[:nfilt] < 0 | np.isnan(cfilt[:nfilt]) | np.isposinf(cfilt[:nfilt]))
+        # Check the values of X, F, CSTRV.
+        # X does not contain NaN if X0 does not and the trust-region/geometry steps are proper.
+        assert not any(np.isnan(x))
+        # F cannot be NaN/+Inf due to the moderated extreme barrier.
+        assert not (np.isnan(f) | np.isposinf(f))
+        # CSTRV cannot be NaN/+Inf due to the moderated extreme barrier.
+        assert not (cstrv < 0 | np.isnan(cstrv) | np.isposinf(cstrv))
+        # Check CONSTR and CONFILT.
+        assert present(constr) == present(confilt)
+        if present(constr):
+            # CONSTR cannot contain NaN/-Inf due to the moderated extreme barrier.
+            assert not any(np.isnan(constr) | np.isneginf(constr))
+            assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+            assert not (np.isnan(confilt[:, :nfilt]) | np.isneginf(confilt[:, :nfilt])).any()
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Return immediately if any column of XFILT is better than X.
+    if any((isbetter(ffilt_i, cfilt_i, f, cstrv, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt]))) or \
+        any(np.logical_and(ffilt[:nfilt] <= f, cfilt[:nfilt] <= cstrv)):
+        return nfilt, cfilt, ffilt, xfilt, confilt
+
+    # Decide which columns of XFILT to keep.
+    keep = np.logical_not([isbetter(f, cstrv, ffilt_i, cfilt_i, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt])])
+
+    # If NFILT == MAXFILT and X is not better than any column of XFILT, then we remove the worst column
+    # of XFILT according to the merit function PHI = FFILT + CWEIGHT * MAX(CFILT - CTOL, ZERO).
+    if sum(keep) == maxfilt:  # In this case, NFILT = SIZE(KEEP) = COUNT(KEEP) = MAXFILT > 0.
+        cfilt_shifted = np.maximum(cfilt - ctol, 0)
+        if cweight <= 0:
+            phi = ffilt
+        elif np.isposinf(cweight):
+            phi = cfilt_shifted
+            # We should not use CFILT here; if MAX(CFILT_SHIFTED) is attained at multiple indices, then
+            # we will check FFILT to exhaust the remaining degree of freedom.
+        else:
+            phi = np.maximum(ffilt, -REALMAX)
+            phi = np.nan_to_num(phi, nan=-REALMAX)  # Replace NaN with -REALMAX and +/- inf with large numbers
+            phi += cweight * cfilt_shifted
+        # We select X to maximize PHI. In case there are multiple maximizers, we take the one with the
+        # largest CSTRV_SHIFTED; if there are more than one choices, we take the one with the largest F;
+        # if there are several candidates, we take the one with the largest CSTRV; if the last comparison
+        # still leads to more than one possibilities, then they are equally bad and we choose the first.
+        # N.B.:
+        # 1. This process is the opposite of selecting KOPT in SELECTX.
+        # 2. In finite-precision arithmetic, PHI_1 == PHI_2 and CSTRV_SHIFTED_1 == CSTRV_SHIFTED_2 do
+        # not ensure that F_1 == F_2!
+        phimax = max(phi)
+        cref = max(cfilt_shifted[phi >= phimax])
+        fref = max(ffilt[cfilt_shifted >= cref])
+        kworst = np.ma.array(cfilt, mask=(ffilt > fref)).argmax()
+        if kworst < 0 or kworst >= len(keep):  #  For security. Should not happen.
+            kworst = 0
+        keep[kworst] = False
+
+    # Keep the good xfilt values and remove all the ones that are strictly worse than the new x.
+    nfilt = sum(keep)
+    index_to_keep = np.where(keep)[0]
+    xfilt[:, :nfilt] = xfilt[:, index_to_keep]
+    ffilt[:nfilt] = ffilt[index_to_keep]
+    cfilt[:nfilt] = cfilt[index_to_keep]
+    if confilt is not None and constr is not None:
+        confilt[:, :nfilt] = confilt[:, index_to_keep]
+
+    # Once we have removed all the vectors that are strictly worse than x,
+    # we add x to the filter.
+    xfilt[:, nfilt] = x
+    ffilt[nfilt] = f
+    cfilt[nfilt] = cstrv
+    if confilt is not None and constr is not None:
+        confilt[:, nfilt] = constr
+    nfilt += 1  # In Python we need to increment the index afterwards
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        # Check NFILT and the sizes of XFILT, FFILT, CFILT.
+        assert nfilt >= 1 and nfilt <= maxfilt
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert np.size(ffilt) == maxfilt
+        assert np.size(cfilt) == maxfilt
+        # Check the values of XFILT, FFILT, CFILT.
+        assert not (np.isnan(xfilt[:, :nfilt])).any()
+        assert not any(np.isnan(ffilt[:nfilt]) | np.isposinf(ffilt[:nfilt]))
+        assert not any(cfilt[:nfilt] < 0 | np.isnan(cfilt[:nfilt]) | np.isposinf(cfilt[:nfilt]))
+        # Check that no point in the filter is better than X, and X is better than no point.
+        assert not any([isbetter(ffilt_i, cfilt_i, f, cstrv, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt])])
+        assert not any([isbetter(f, cstrv, ffilt_i, cfilt_i, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt])])
+        # Check CONFILT.
+        if present(confilt):
+            assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+            assert not (np.isnan(confilt[:, :nfilt]) | np.isneginf(confilt[:, :nfilt])).any()
+
+
+    return nfilt, cfilt, ffilt, xfilt, confilt
+
+
+def selectx(fhist: npt.NDArray, chist: npt.NDArray, cweight: float, ctol: float):
+    '''
+    This subroutine selects X according to FHIST and CHIST, which represents (a part of) history
+    of F and CSTRV. Normally, FHIST and CHIST are not the full history but only a filter, e.g. ffilt
+    and CFILT generated by SAVEFILT. However, we name them as FHIST and CHIST because the [F, CSTRV]
+    in a filter should not dominate each other, but this subroutine does NOT assume such a property.
+    N.B.: CTOL is the tolerance of the constraint violation (CSTRV). A point is considered feasible if
+    its constraint violation is at most CTOL. Not that CTOL is absolute, not relative.
+    '''
+
+    # Sizes
+    nhist = len(fhist)
+
+    # Preconditions
+    if DEBUGGING:
+        assert nhist >= 1
+        assert np.size(chist) == nhist
+        assert not any(np.isnan(fhist) | np.isposinf(fhist))
+        assert not any(chist < 0 | np.isnan(chist) | np.isposinf(chist))
+        assert cweight >= 0
+        assert ctol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # We select X among the points with F < FREF and CSTRV < CREF.
+    # Do NOT use F <= FREF, because F == FREF (FUNCMAX or REALMAX) may mean F == INF in practice!
+    if any(np.logical_and(fhist < FUNCMAX, chist < CONSTRMAX)):
+        fref = FUNCMAX
+        cref = CONSTRMAX
+    elif any(np.logical_and(fhist < REALMAX, chist < CONSTRMAX)):
+        fref = REALMAX
+        cref = CONSTRMAX
+    elif any(np.logical_and(fhist < FUNCMAX, chist < REALMAX)):
+        fref = FUNCMAX
+        cref = REALMAX
+    else:
+        fref = REALMAX
+        cref = REALMAX
+
+    if not any(np.logical_and(fhist < fref, chist < cref)):
+        kopt = nhist - 1
+    else:
+        # Shift the constraint violations by ctol, so that cstrv <= ctol is regarded as no violation.
+        chist_shifted = np.maximum(chist - ctol, 0)
+        # cmin is the minimal shift constraint violation attained in the history.
+        cmin = np.min(chist_shifted[fhist < fref])
+        # We consider only the points whose shifted constraint violations are at most the cref below.
+        # N.B.: Without taking np.maximum(EPS, .), cref would be 0 if cmin = 0. In that case, asking for
+        # cstrv_shift < cref would be WRONG!
+        cref = np.maximum(EPS, 2*cmin)
+        # We use the following phi as our merit function to select X.
+        if cweight <= 0:
+            phi = fhist
+        elif np.isposinf(cweight):
+            phi = chist_shifted
+            # We should not use chist here; if np.minimum(chist_shifted) is attained at multiple indices, then
+            # we will check fhist to exhaust the remaining degree of freedom.
+        else:
+            phi = np.maximum(fhist, -REALMAX) + cweight * chist_shifted
+            # np.maximum(fhist, -REALMAX) makes sure that phi will not contain NaN (unless there is a bug).
+
+        # We select X to minimize phi subject to f < fref and cstrv_shift <= cref (see the comments
+        # above for the reason of taking "<" and "<=" in these two constraints). In case there are
+        # multiple minimizers, we take the one with the least cstrv_shift; if there is more than one
+        # choice, we take the one with the least f; if there are several candidates, we take the one
+        # with the least cstrv; if the last comparison still leads to more than one possibility, then
+        # they are equally good and we choose the first.
+        # N.B.:
+        # 1. This process is the opposite of selecting kworst in savefilt
+        # 2. In finite-precision arithmetic, phi_2 == phi_2 and cstrv_shift_1 == cstrv_shifted_2 do
+        # not ensure thatn f_1 == f_2!
+        phimin = np.min(phi[np.logical_and(fhist < fref, chist_shifted <= cref)])
+        cref = np.min(chist_shifted[np.logical_and(fhist < fref, phi <= phimin)])
+        fref = np.min(fhist[chist_shifted <= cref])
+        # Can't use argmin here because using it with a mask throws off the index
+        kopt = np.ma.array(chist, mask=(fhist > fref)).argmin()
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert kopt >= 0 and kopt < nhist
+        assert not any([isbetter(fhisti, chisti, fhist[kopt], chist[kopt], ctol) for fhisti, chisti in zip(fhist[:nhist], chist[:nhist])])
+
+    return kopt
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__gcutils.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__gcutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ae5fc46af5853cb67dc57d5e682f6bd9983ac40
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__pep440.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__pep440.py
new file mode 100644
index 0000000000000000000000000000000000000000..995876a4db918e49739f4bdf644721d3cbfa7252
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__testutils.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..56e88b49c8179d8fa4009c37a08503afe2670af6
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__util.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__util.py
new file mode 100644
index 0000000000000000000000000000000000000000..be6112d19c7fce576c5a1a732116dd618bb9d621
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test__util.py
@@ -0,0 +1,638 @@
+from multiprocessing import Pool
+from multiprocessing.pool import Pool as PWL
+import re
+import math
+import functools
+from fractions import Fraction
+
+import numpy as np
+from numpy.testing import assert_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+from scipy.conftest import skip_xp_invalid_arg
+
+from scipy._lib._array_api import xp_assert_equal
+from scipy._lib._util import (_aligned_zeros, check_random_state, MapWrapper,
+                              getfullargspec_no_self, FullArgSpec,
+                              rng_integers, _validate_int, _rename_parameter,
+                              _contains_nan, _rng_html_rewrite, _workers_wrapper)
+import scipy._lib.array_api_extra as xpx
+from scipy._lib.array_api_extra.testing import lazy_xp_function
+from scipy import cluster, interpolate, linalg, optimize, sparse, spatial, stats
+
+
+lazy_xp_function(_contains_nan)
+
+
+@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)
+
+
+@_workers_wrapper
+def user_of_workers(x, b=1, workers=None):
+    assert workers is not None
+    assert isinstance(workers, MapWrapper)
+    return np.array(list(workers(np.sin, x * b)))
+
+
+def test__workers_wrapper():
+    arr = np.linspace(0, np.pi)
+    req = np.sin(arr * 2.0)
+
+    with Pool(2) as p:
+        v = user_of_workers(arr, workers=p.map, b=2)
+        assert_equal(v, req)
+
+    v = user_of_workers(arr, workers=None, b=2)
+    assert_equal(v, req)
+
+    v = user_of_workers(arr, workers=2, b=2)
+    assert_equal(v, req)
+
+    # assess if decorator works with partial functions
+    part_f = functools.partial(user_of_workers, b=2)
+    assert_equal(part_f(arr), req)
+
+    with Pool(2) as p:
+        part_f = functools.partial(user_of_workers, b=2, workers=p.map)
+        assert_equal(part_f(arr), req)
+
+
+def test_rng_integers():
+    rng = np.random.RandomState()
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # now try with np.random.Generator
+    try:
+        rng = np.random.default_rng()
+    except AttributeError:
+        return
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+
+class TestValidateInt:
+
+    @pytest.mark.parametrize('n', [4, np.uint8(4), np.int16(4), np.array(4)])
+    def test_validate_int(self, n):
+        n = _validate_int(n, 'n')
+        assert n == 4
+
+    @pytest.mark.parametrize('n', [4.0, np.array([4]), Fraction(4, 1)])
+    def test_validate_int_bad(self, n):
+        with pytest.raises(TypeError, match='n must be an integer'):
+            _validate_int(n, 'n')
+
+    def test_validate_int_below_min(self):
+        with pytest.raises(ValueError, match='n must be an integer not '
+                                             'less than 0'):
+            _validate_int(-1, 'n', 0)
+
+
+class TestRenameParameter:
+    # check that wrapper `_rename_parameter` for backward-compatible
+    # keyword renaming works correctly
+
+    # Example method/function that still accepts keyword `old`
+    @_rename_parameter("old", "new")
+    def old_keyword_still_accepted(self, new):
+        return new
+
+    # Example method/function for which keyword `old` is deprecated
+    @_rename_parameter("old", "new", dep_version="1.9.0")
+    def old_keyword_deprecated(self, new):
+        return new
+
+    def test_old_keyword_still_accepted(self):
+        # positional argument and both keyword work identically
+        res1 = self.old_keyword_still_accepted(10)
+        res2 = self.old_keyword_still_accepted(new=10)
+        res3 = self.old_keyword_still_accepted(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_still_accepted() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(unexpected=10)
+
+        # multiple values for the same parameter raises an error
+        message = re.escape("old_keyword_still_accepted() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, new=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, old=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(new=10, old=10)
+
+    @pytest.fixture
+    def kwarg_lock(self):
+        from threading import Lock
+        return Lock()
+
+    def test_old_keyword_deprecated(self, kwarg_lock):
+        # positional argument and both keyword work identically,
+        # but use of old keyword results in DeprecationWarning
+        dep_msg = "Use of keyword argument `old` is deprecated"
+        res1 = self.old_keyword_deprecated(10)
+        res2 = self.old_keyword_deprecated(new=10)
+        # pytest warning filter is not thread-safe, enforce serialization
+        with kwarg_lock:
+            with pytest.warns(DeprecationWarning, match=dep_msg):
+                    res3 = self.old_keyword_deprecated(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_deprecated() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(unexpected=10)
+
+        # multiple values for the same parameter raises an error and,
+        # if old keyword is used, results in DeprecationWarning
+        message = re.escape("old_keyword_deprecated() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(10, new=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    # breakpoint()
+                    self.old_keyword_deprecated(10, old=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    self.old_keyword_deprecated(new=10, old=10)
+
+
+class TestContainsNaN:
+    def test_policy(self):
+        data = np.array([1, 2, 3, np.nan])
+
+        assert _contains_nan(data)  # default policy is "propagate"
+        assert _contains_nan(data, nan_policy="propagate")
+        assert _contains_nan(data, nan_policy="omit")
+        assert not _contains_nan(data[:3])
+        assert not _contains_nan(data[:3], nan_policy="propagate")
+        assert not _contains_nan(data[:3], nan_policy="omit")
+
+        with pytest.raises(ValueError, match="The input contains nan values"):
+            _contains_nan(data, nan_policy="raise")
+        assert not _contains_nan(data[:3], nan_policy="raise")
+
+        with pytest.raises(ValueError, match="nan_policy must be one of"):
+            _contains_nan(data, nan_policy="nan")
+
+    def test_contains_nan(self):
+        # Special case: empty array
+        assert not _contains_nan(np.array([], dtype=float))
+
+        # Integer arrays cannot contain NaN
+        assert not _contains_nan(np.array([1, 2, 3]))
+        assert not _contains_nan(np.array([[1, 2], [3, 4]]))
+
+        assert not _contains_nan(np.array([1., 2., 3.]))
+        assert not _contains_nan(np.array([1., 2.j, 3.]))
+        assert _contains_nan(np.array([1., 2.j, np.nan]))
+        assert _contains_nan(np.array([1., 2., np.nan]))
+        assert _contains_nan(np.array([np.nan, 2., np.nan]))
+        assert not _contains_nan(np.array([[1., 2.], [3., 4.]]))
+        assert _contains_nan(np.array([[1., 2.], [3., np.nan]]))
+
+    @skip_xp_invalid_arg
+    def test_contains_nan_with_strings(self):
+        data1 = np.array([1, 2, "3", np.nan])  # converted to string "nan"
+        assert not _contains_nan(data1)
+
+        data2 = np.array([1, 2, "3", np.nan], dtype='object')
+        assert _contains_nan(data2)
+
+        data3 = np.array([["1", 2], [3, np.nan]])  # converted to string "nan"
+        assert not _contains_nan(data3)
+
+        data4 = np.array([["1", 2], [3, np.nan]], dtype='object')
+        assert _contains_nan(data4)
+
+    @pytest.mark.skip_xp_backends(eager_only=True,
+                                  reason="lazy backends tested separately")
+    @pytest.mark.parametrize("nan_policy", ['propagate', 'omit', 'raise'])
+    def test_array_api(self, xp, nan_policy):
+        rng = np.random.default_rng(932347235892482)
+        x0 = rng.random(size=(2, 3, 4))
+        x = xp.asarray(x0)
+        assert not _contains_nan(x, nan_policy)
+
+        x = xpx.at(x)[1, 2, 1].set(xp.nan)
+
+        if nan_policy == 'raise':
+            with pytest.raises(ValueError, match="The input contains nan values"):
+                _contains_nan(x, nan_policy)
+        elif nan_policy == 'omit':
+            assert _contains_nan(x, nan_policy, xp_omit_okay=True)
+        elif nan_policy == 'propagate':
+            assert _contains_nan(x, nan_policy)
+
+    @pytest.mark.skip_xp_backends("numpy", reason="lazy backends only")
+    @pytest.mark.skip_xp_backends("cupy", reason="lazy backends only")
+    @pytest.mark.skip_xp_backends("array_api_strict", reason="lazy backends only")
+    @pytest.mark.skip_xp_backends("torch", reason="lazy backends only")
+    def test_array_api_lazy(self, xp):
+        rng = np.random.default_rng(932347235892482)
+        x0 = rng.random(size=(2, 3, 4))
+        x = xp.asarray(x0)
+
+        xp_assert_equal(_contains_nan(x), xp.asarray(False))
+        xp_assert_equal(_contains_nan(x, "propagate"), xp.asarray(False))
+        xp_assert_equal(_contains_nan(x, "omit", xp_omit_okay=True), xp.asarray(False))
+        # Lazy arrays don't support "omit" and "raise" policies
+        match = "not supported for lazy arrays"
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "omit")
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "raise")
+
+        x = xpx.at(x)[1, 2, 1].set(np.nan)
+
+        xp_assert_equal(_contains_nan(x), xp.asarray(True))
+        xp_assert_equal(_contains_nan(x, "propagate"), xp.asarray(True))
+        xp_assert_equal(_contains_nan(x, "omit", xp_omit_okay=True), xp.asarray(True))
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "omit")
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "raise")
+
+
+def test__rng_html_rewrite():
+    def mock_str():
+        lines = [
+            'np.random.default_rng(8989843)',
+            'np.random.default_rng(seed)',
+            'np.random.default_rng(0x9a71b21474694f919882289dc1559ca)',
+            ' bob ',
+        ]
+        return lines
+
+    res = _rng_html_rewrite(mock_str)()
+    ref = [
+        'np.random.default_rng()',
+        'np.random.default_rng(seed)',
+        'np.random.default_rng()',
+        ' bob ',
+    ]
+
+    assert res == ref
+
+
+class TestTransitionToRNG:
+    def kmeans(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def kmeans2(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def barycentric(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x1, x2, y1 = rng.random((3, 10))
+        f = interpolate.BarycentricInterpolator(x1, y1, **kwargs)
+        return f(x2)
+
+    def clarkson_woodruff_transform(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return linalg.clarkson_woodruff_transform(rng.random((10, 10)), 3, **kwargs)
+
+    def basinhopping(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return optimize.basinhopping(optimize.rosen, rng.random(3), **kwargs).x
+
+    def opt(self, fun, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        bounds = optimize.Bounds(-rng.random(3) * 10, rng.random(3) * 10)
+        return fun(optimize.rosen, bounds, **kwargs).x
+
+    def differential_evolution(self, **kwargs):
+        return self.opt(optimize.differential_evolution, **kwargs)
+
+    def dual_annealing(self, **kwargs):
+        return self.opt(optimize.dual_annealing, **kwargs)
+
+    def check_grad(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x = rng.random(3)
+        return optimize.check_grad(optimize.rosen, optimize.rosen_der, x,
+                                   direction='random', **kwargs)
+
+    def random_array(self, **kwargs):
+        return sparse.random_array((10, 10), density=1.0, **kwargs).toarray()
+
+    def random(self, **kwargs):
+        return sparse.random(10, 10, density=1.0, **kwargs).toarray()
+
+    def rand(self, **kwargs):
+        return sparse.rand(10, 10, density=1.0, **kwargs).toarray()
+
+    def svds(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        A = rng.random((10, 10))
+        return sparse.linalg.svds(A, **kwargs)
+
+    def random_rotation(self, **kwargs):
+        return spatial.transform.Rotation.random(3, **kwargs).as_matrix()
+
+    def goodness_of_fit(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = rng.random(100)
+        return stats.goodness_of_fit(stats.laplace, data, **kwargs).pvalue
+
+    def permutation_test(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        def statistic(x, y, axis): return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+        return stats.permutation_test(data, statistic, **kwargs).pvalue
+
+    def bootstrap(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = (rng.random(100),)
+        return stats.bootstrap(data, np.mean, **kwargs).confidence_interval
+
+    def dunnett(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x, y, control = rng.random((3, 100))
+        return stats.dunnett(x, y, control=control, **kwargs).pvalue
+
+    def sobol_indices(self, **kwargs):
+        def f_ishigami(x): return (np.sin(x[0]) + 7 * np.sin(x[1]) ** 2
+                                   + 0.1 * (x[2] ** 4) * np.sin(x[0]))
+        dists = [stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi)]
+        res = stats.sobol_indices(func=f_ishigami, n=1024, dists=dists, **kwargs)
+        return res.first_order
+
+    def qmc_engine(self, engine, **kwargs):
+        qrng = engine(d=1, **kwargs)
+        return qrng.random(4)
+
+    def halton(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Halton, **kwargs)
+
+    def sobol(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Sobol, **kwargs)
+
+    def latin_hypercube(self, **kwargs):
+        return self.qmc_engine(stats.qmc.LatinHypercube, **kwargs)
+
+    def poisson_disk(self, **kwargs):
+        return self.qmc_engine(stats.qmc.PoissonDisk, **kwargs)
+
+    def multivariate_normal_qmc(self, **kwargs):
+        X = stats.qmc.MultivariateNormalQMC([0], **kwargs)
+        return X.random(4)
+
+    def multinomial_qmc(self, **kwargs):
+        X = stats.qmc.MultinomialQMC([0.5, 0.5], 4, **kwargs)
+        return X.random(4)
+
+    def permutation_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        method = stats.PermutationMethod(**kwargs)
+        return stats.pearsonr(*data, method=method).pvalue
+
+    def bootstrap_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        res = stats.pearsonr(*data)
+        method = stats.BootstrapMethod(**kwargs)
+        return res.confidence_interval(method=method)
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow
+    @pytest.mark.parametrize("method, arg_name", [
+        (kmeans, "seed"),
+        (kmeans2, "seed"),
+        (barycentric, "random_state"),
+        (clarkson_woodruff_transform, "seed"),
+        (basinhopping, "seed"),
+        (differential_evolution, "seed"),
+        (dual_annealing, "seed"),
+        (check_grad, "seed"),
+        (random_array, 'random_state'),
+        (random, 'random_state'),
+        (rand, 'random_state'),
+        (random_rotation, "random_state"),
+        (goodness_of_fit, "random_state"),
+        (permutation_test, "random_state"),
+        (bootstrap, "random_state"),
+        (permutation_method, "random_state"),
+        (bootstrap_method, "random_state"),
+        (dunnett, "random_state"),
+        (sobol_indices, "random_state"),
+        (halton, "seed"),
+        (sobol, "seed"),
+        (latin_hypercube, "seed"),
+        (poisson_disk, "seed"),
+        (multivariate_normal_qmc, "seed"),
+        (multinomial_qmc, "seed"),
+    ])
+    def test_rng_deterministic(self, method, arg_name):
+        np.random.seed(None)
+        seed = 2949672964
+
+        rng = np.random.default_rng(seed)
+        message = "got multiple values for argument now known as `rng`"
+        with pytest.raises(TypeError, match=message):
+            method(self, **{'rng': rng, arg_name: seed})
+
+        rng = np.random.default_rng(seed)
+        res1 = method(self, rng=rng)
+        res2 = method(self, rng=seed)
+        assert_equal(res2, res1)
+
+        if method.__name__ in {"dunnett", "sobol_indices"}:
+            # the two kwargs have essentially the same behavior for these functions
+            res3 = method(self, **{arg_name: seed})
+            assert_equal(res3, res1)
+            return
+
+        rng = np.random.RandomState(seed)
+        res1 = method(self, **{arg_name: rng})
+        res2 = method(self, **{arg_name: seed})
+
+        if method.__name__ in {"halton", "sobol", "latin_hypercube", "poisson_disk",
+                               "multivariate_normal_qmc", "multinomial_qmc"}:
+            # For these, passing `random_state=RandomState(seed)` is not the same as
+            # passing integer `seed`.
+            res1b = method(self, **{arg_name: np.random.RandomState(seed)})
+            assert_equal(res1b, res1)
+            res2b = method(self, **{arg_name: seed})
+            assert_equal(res2b, res2)
+            return
+
+        np.random.seed(seed)
+        res3 = method(self, **{arg_name: None})
+        assert_equal(res2, res1)
+        assert_equal(res3, res1)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_array_api.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..52c6a401d5923e88003a920c0a86c60182d06364
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_array_api.py
@@ -0,0 +1,400 @@
+import re
+
+import numpy as np
+import pytest
+
+from importlib import import_module
+
+from scipy._lib._array_api import (
+    SCIPY_ARRAY_API, array_namespace, _asarray, xp_copy, xp_assert_equal, is_numpy,
+    np_compat, xp_default_dtype, xp_result_type, is_torch,
+    xp_capabilities_table, _xp_copy_to_numpy
+)
+from scipy._lib._array_api_docs_tables import is_named_function_like_object
+from scipy._lib import array_api_extra as xpx
+from scipy._lib._array_api_no_0d import xp_assert_equal as xp_assert_equal_no_0d
+from scipy._lib.array_api_extra.testing import lazy_xp_function
+
+# Run all tests in this module in the Array API CI,
+# including those without the `xp` fixture
+pytestmark = pytest.mark.array_api_backends
+
+lazy_xp_function(_asarray)
+lazy_xp_function(xp_copy)
+
+
+@pytest.mark.skipif(not SCIPY_ARRAY_API,
+        reason="Array API test; set environment variable SCIPY_ARRAY_API=1 to run it")
+class TestArrayAPI:
+
+    def test_array_namespace(self):
+        x, y = np.array([0, 1, 2]), np.array([0, 1, 2])
+        xp = array_namespace(x, y)
+        assert 'array_api_compat.numpy' in xp.__name__
+
+    def test_asarray(self, xp):
+        x, y = _asarray([0, 1, 2], xp=xp), _asarray(np.arange(3), xp=xp)
+        ref = xp.asarray([0, 1, 2])
+        xp_assert_equal(x, ref)
+        xp_assert_equal(y, ref)
+
+    @pytest.mark.filterwarnings("ignore: the matrix subclass")
+    def test_raises(self):
+        msg = "of type `numpy.ma.MaskedArray` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.ma.array(1), np.array(1))
+
+        msg = "of type `numpy.matrix` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.array(1), np.matrix(1))
+
+        msg = "only boolean and numerical dtypes are supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace([object()])
+        with pytest.raises(TypeError, match=msg):
+            array_namespace('abc')
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason="Array-likes")
+    def test_array_likes(self, xp):
+        """Test that if all parameters of array_namespace are Array-likes,
+        the output is array_api_compat.numpy
+        """
+        assert array_namespace([0, 1, 2]) is xp
+        assert array_namespace((0, 1, 2)) is xp
+        assert array_namespace(1, 2, 3) is xp
+        assert array_namespace(1) is xp
+        assert array_namespace(np.int64(1)) is xp
+        assert array_namespace([0, 1, 2], 3) is xp
+        assert array_namespace() is xp
+        assert array_namespace(None) is xp
+        assert array_namespace(1, None) is xp
+        assert array_namespace(None, 1) is xp
+
+        # This only works when xp is numpy!
+        assert array_namespace(np.asarray([1, 2]), [3, 4]) is xp
+        assert array_namespace(np.int64(1), [3, 4]) is xp
+
+    def test_array_and_array_likes_mix(self, xp):
+        """Test that if there is at least one Array API object among
+        the parameters of array_namespace, and all other parameters
+        are scalars, the output is its namespace.
+
+        If there are non-scalar Array-Likes, raise as in array-api-compat.
+        """
+        x = xp.asarray(1)
+        assert array_namespace(x) is xp
+        assert array_namespace(x, 1) is xp
+        assert array_namespace(1, x) is xp
+        assert array_namespace(None, x) is xp
+
+        if is_numpy(xp):
+            assert array_namespace(x, [1, 2]) is xp
+        else:
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                array_namespace(x, [1, 2])
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                array_namespace(x, np.int64(1))
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                 # Subclass of float; matches array_api_compat behavior
+                array_namespace(x, np.float64(1))
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                # Subclass of complex; matches array_api_compat behavior
+                array_namespace(x, np.complex128(1))
+
+    def test_array_api_extra_hook(self):
+        """Test that the `array_namespace` function used by
+        array-api-extra has been overridden by scipy
+        """
+        msg = "only boolean and numerical dtypes are supported"
+        with pytest.raises(TypeError, match=msg):
+            xpx.atleast_nd("abc", ndim=0)
+
+    def test_jax_zero_gradient_array(self):
+        """Test array_namespace special case for JAX zero-gradient arrays, which are
+        numpy arrays but must be treated as JAX arrays.
+        See matching code and tests in array_api_compat.
+        """
+        jax = pytest.importorskip("jax")
+        xp = pytest.importorskip("jax.numpy")
+        # Create numpy array with dtype=jax.float0
+        jax_zero = jax.vmap(jax.grad(xp.float32, allow_int=True))(xp.arange(4))
+        assert array_namespace(jax_zero) is xp
+
+    def test_void_but_not_jax_zero_gradient_array(self):
+        """A void dtype that is not a jax.float0 must not be caught in the
+        special case for JAX zero-gradient arrays.
+        """
+        void = np.empty(0, dtype=np.dtype([]))
+        with pytest.raises(TypeError, match="only boolean and numerical dtypes"):
+            array_namespace(void)
+        with pytest.raises(TypeError, match="only boolean and numerical dtypes"):
+            array_namespace([void, void])
+
+    def test_copy(self, xp):
+        for _xp in [xp, None]:
+            x = xp.asarray([1, 2, 3])
+            y = xp_copy(x, xp=_xp)
+            # with numpy we'd want to use np.shared_memory, but that's not specified
+            # in the array-api
+            assert id(x) != id(y)
+            try:
+                y[0] = 10
+            except (TypeError, ValueError):
+                pass
+            else:
+                assert x[0] != y[0]
+
+    @pytest.mark.parametrize(
+        "dtype",
+        ["float32", "float64", "complex64", "complex128", "int32", "int64"],
+    )
+    @pytest.mark.parametrize(
+        "data", [[], 1, [1, 2, 3], [[1, 2], [2, 3]]],
+    )
+    def test_copy_to_numpy(self, xp, data, dtype):
+        xp_dtype = getattr(xp, dtype)
+        np_dtype = getattr(np, dtype)
+        x = xp.asarray(data, dtype=xp_dtype)
+        y = _xp_copy_to_numpy(x)
+        assert isinstance(y, np.ndarray)
+        assert y.dtype == np_dtype
+        assert x.shape == y.shape
+        np.testing.assert_equal(y, np.asarray(data, dtype=np_dtype))
+        if is_numpy(xp):
+            # Ensure y is a copy when xp is numpy.
+            assert id(x) != id(y)
+
+    
+    @pytest.mark.parametrize('dtype', ['int32', 'int64', 'float32', 'float64'])
+    @pytest.mark.parametrize('shape', [(), (3,)])
+    def test_strict_checks(self, xp, dtype, shape):
+        # Check that `_strict_check` behaves as expected
+        dtype = getattr(xp, dtype)
+        x = xp.broadcast_to(xp.asarray(1, dtype=dtype), shape)
+        x = x if shape else x[()]
+        y = np_compat.asarray(1)[()]
+
+        kwarg_names = ["check_namespace", "check_dtype", "check_shape", "check_0d"]
+        options = dict(zip(kwarg_names, [True, False, False, False]))
+        if is_numpy(xp):
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(
+                AssertionError,
+                match="Namespace of desired array does not match",
+            ):
+                xp_assert_equal(x, y, **options)
+            with pytest.raises(
+                AssertionError,
+                match="Namespace of actual and desired arrays do not match",
+            ):
+                xp_assert_equal(y, x, **options)
+
+        options = dict(zip(kwarg_names, [False, True, False, False]))
+        if y.dtype.name in str(x.dtype):
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="dtypes do not match."):
+                xp_assert_equal(x, y, **options)
+
+        options = dict(zip(kwarg_names, [False, False, True, False]))
+        if x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="Shapes do not match."):
+                xp_assert_equal(x, xp.asarray(y), **options)
+
+        options = dict(zip(kwarg_names, [False, False, False, True]))
+        if is_numpy(xp) and x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        elif is_numpy(xp):
+            with pytest.raises(AssertionError, match="Array-ness does not match."):
+                xp_assert_equal(x, y, **options)
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason="Scalars only exist in NumPy")
+    def test_check_scalar(self, xp):
+        # identity always passes
+        xp_assert_equal(xp.float64(0), xp.float64(0))
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.))
+        xp_assert_equal(xp.float64(0), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.), check_0d=False)
+
+        # Check default convention: 0d-arrays are distinguished from scalars
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.float64(0), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(42), xp.int64(42))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.int64(42), xp.asarray(42))
+
+        # with `check_0d=False`, scalars-vs-0d passes (if values match)
+        xp_assert_equal(xp.asarray(0.), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.float64(0), xp.asarray(0.), check_0d=False)
+        # also with regular python objects
+        xp_assert_equal(xp.asarray(0.), 0., check_0d=False)
+        xp_assert_equal(0., xp.asarray(0.), check_0d=False)
+        xp_assert_equal(xp.asarray(42), 42, check_0d=False)
+        xp_assert_equal(42, xp.asarray(42), check_0d=False)
+
+        # as an alternative to `check_0d=False`, explicitly expect scalar
+        xp_assert_equal(xp.float64(0), xp.asarray(0.)[()])
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason="Scalars only exist in NumPy")
+    def test_check_scalar_no_0d(self, xp):
+        # identity passes, if first argument is not 0d (or check_0d=True)
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0))
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0), check_0d=True)
+        xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.), check_0d=True)
+
+        # by default, 0d values are forbidden as the first argument
+        message = "Result is a NumPy 0d-array.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(42))
+
+        # Check default convention: 0d-arrays are NOT distinguished from scalars
+        xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.))
+        xp_assert_equal_no_0d(xp.int64(42), xp.asarray(42))
+
+        # opt in to 0d-check remains possible
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.int64(0), xp.asarray(42), check_0d=True)
+
+        # scalars-vs-0d passes (if values match) also with regular python objects
+        xp_assert_equal_no_0d(0., xp.asarray(0.))
+        xp_assert_equal_no_0d(42, xp.asarray(42))
+
+    def test_default_dtype(self, xp):
+        assert xp_default_dtype(xp) == xp.asarray(1.).dtype
+
+
+scalars = [1, 1., 1. + 1j]
+lists = [[1], [1.], [1. + 1j]]
+types = ('int8 int16 int32 int64 '
+         'uint8 uint16 uint32 uint64 '
+         'float32 float64 complex64 complex128').split()
+arrays = [np.asarray([1], dtype=getattr(np, t)) for t in types]
+
+
+def convert_type(x, xp):
+    # Convert NumPy array to xp-array
+    # Convert string to indicated dtype from xp
+    # Return Python scalars unchanged
+    if isinstance(x, np.ndarray):
+        return xp.asarray(x)
+    elif isinstance(x, str):
+        return getattr(xp, x)
+    return x
+
+
+def is_inexact(x, xp):
+    # Determine whether `x` is of inexact (real of complex floating) dtype
+    x = xp.asarray(x) if np.isscalar(x) or isinstance(x, list) else x
+    dtype = getattr(x, 'dtype', x)
+    return xp.isdtype(dtype, ('real floating', 'complex floating'))
+
+
+@pytest.mark.parametrize('x', scalars + lists + types + arrays)
+@pytest.mark.parametrize('y', scalars + lists + types + arrays)
+def test_xp_result_type_no_force(x, y, xp):
+    # When force_floating==False (default), behavior of `xp_result_type`
+    # should match that of `xp.result_type` on the same arguments after
+    # converting lists to arrays of type `xp`.
+    x = convert_type(x, xp)
+    y = convert_type(y, xp)
+    x_ref = xp.asarray(x) if isinstance(x, list) else x
+    y_ref = xp.asarray(y) if isinstance(y, list) else y
+
+    try:
+        dtype_ref = xp.result_type(x_ref, y_ref)
+        expected_error = None
+    except Exception as e:
+        expected_error = (type(e), str(e))
+
+    if expected_error is not None:
+        with pytest.raises(expected_error[0], match=re.escape(expected_error[1])):
+            xp_result_type(x, y, xp=xp)
+        return
+
+    dtype_res = xp_result_type(x, y, xp=xp)
+    assert dtype_res == dtype_ref
+
+
+@pytest.mark.parametrize('x', scalars + lists + types + arrays)
+@pytest.mark.parametrize('y', scalars + lists + types + arrays)
+def test_xp_result_type_force_floating(x, y, xp):
+    # When `force_floating==True`, behavior of `xp_result_type`
+    # should match that of `xp.result_type` with `1.0` appended to the set of
+    # arguments (after converting lists to arrays of type `xp`).
+    # If this raises a `TypeError`, which is the case when the result
+    # type is not defined by the standard, the result type should be
+    # the result type of any inexact (real or complex floating) arguments
+    # and the default floating point type.
+    if (is_torch(xp) and not(isinstance(x, str) or isinstance(y, str))
+            and np.isscalar(x) and np.isscalar(y)):
+        pytest.skip("See 3/27/2024 comment at  data-apis/array-api-compat#277")
+
+    x = convert_type(x, xp)
+    y = convert_type(y, xp)
+    x_ref = xp.asarray(x) if isinstance(x, list) else x
+    y_ref = xp.asarray(y) if isinstance(y, list) else y
+
+    expected_error = None
+    try:
+        dtype_ref = xp.result_type(x_ref, y_ref, 1.0)
+    except TypeError:
+        args = []
+        if is_inexact(x_ref, xp):
+            args.append(x_ref)
+        if is_inexact(y_ref, xp):
+            args.append(y_ref)
+        dtype_ref = xp.result_type(*args, xp.asarray(1.0))
+    except Exception as e:
+        expected_error = (type(e), str(e))
+
+    if expected_error is not None:
+        with pytest.raises(expected_error[0], match=expected_error[1]):
+            xp_result_type(x, y, xp=xp)
+        return
+
+    dtype_res = xp_result_type(x, y, force_floating=True, xp=xp)
+    assert dtype_res == dtype_ref
+
+# Test that the xp_capabilities decorator has been applied to all
+# functions and function-likes in the public API. Modules will be
+# added to the list of tested_modules below as decorator coverage
+# is added on a module by module basis. It remains for future work
+# to offer similar functionality to xp_capabilities for classes in
+# the public API.
+
+tested_modules = ["scipy.stats"]
+
+
+def collect_public_functions():
+    functions = []
+    for module_name in tested_modules:
+        module = import_module(module_name)
+        for name in module.__all__:
+            obj = getattr(module, name)
+            if not is_named_function_like_object(obj):
+                continue
+            functions.append(pytest.param(obj, id=f"{module_name}.{name}"))
+    return functions
+
+
+@pytest.mark.parametrize("func", collect_public_functions())
+def test_xp_capabilities_coverage(func):
+    assert func in xp_capabilities_table
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_bunch.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_bunch.py
new file mode 100644
index 0000000000000000000000000000000000000000..954a3240970d32fb9290e3189b6c9dcdae0033bf
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_bunch.py
@@ -0,0 +1,169 @@
+import pytest
+import pickle
+from numpy.testing import assert_equal
+from scipy._lib._bunch import _make_tuple_bunch
+
+
+# `Result` is defined at the top level of the module so it can be
+# used to test pickling.
+Result = _make_tuple_bunch('Result', ['x', 'y', 'z'], ['w', 'beta'])
+
+
+class TestMakeTupleBunch:
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Tests with Result
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def setup_method(self):
+        # Set up an instance of Result.
+        self.result = Result(x=1, y=2, z=3, w=99, beta=0.5)
+
+    def test_attribute_access(self):
+        assert_equal(self.result.x, 1)
+        assert_equal(self.result.y, 2)
+        assert_equal(self.result.z, 3)
+        assert_equal(self.result.w, 99)
+        assert_equal(self.result.beta, 0.5)
+
+    def test_indexing(self):
+        assert_equal(self.result[0], 1)
+        assert_equal(self.result[1], 2)
+        assert_equal(self.result[2], 3)
+        assert_equal(self.result[-1], 3)
+        with pytest.raises(IndexError, match='index out of range'):
+            self.result[3]
+
+    def test_unpacking(self):
+        x0, y0, z0 = self.result
+        assert_equal((x0, y0, z0), (1, 2, 3))
+        assert_equal(self.result, (1, 2, 3))
+
+    def test_slice(self):
+        assert_equal(self.result[1:], (2, 3))
+        assert_equal(self.result[::2], (1, 3))
+        assert_equal(self.result[::-1], (3, 2, 1))
+
+    def test_len(self):
+        assert_equal(len(self.result), 3)
+
+    def test_repr(self):
+        s = repr(self.result)
+        assert_equal(s, 'Result(x=1, y=2, z=3, w=99, beta=0.5)')
+
+    def test_hash(self):
+        assert_equal(hash(self.result), hash((1, 2, 3)))
+
+    def test_pickle(self):
+        s = pickle.dumps(self.result)
+        obj = pickle.loads(s)
+        assert isinstance(obj, Result)
+        assert_equal(obj.x, self.result.x)
+        assert_equal(obj.y, self.result.y)
+        assert_equal(obj.z, self.result.z)
+        assert_equal(obj.w, self.result.w)
+        assert_equal(obj.beta, self.result.beta)
+
+    def test_read_only_existing(self):
+        with pytest.raises(AttributeError, match="can't set attribute"):
+            self.result.x = -1
+
+    def test_read_only_new(self):
+        self.result.plate_of_shrimp = "lattice of coincidence"
+        assert self.result.plate_of_shrimp == "lattice of coincidence"
+
+    def test_constructor_missing_parameter(self):
+        with pytest.raises(TypeError, match='missing'):
+            # `w` is missing.
+            Result(x=1, y=2, z=3, beta=0.75)
+
+    def test_constructor_incorrect_parameter(self):
+        with pytest.raises(TypeError, match='unexpected'):
+            # `foo` is not an existing field.
+            Result(x=1, y=2, z=3, w=123, beta=0.75, foo=999)
+
+    def test_module(self):
+        m = 'scipy._lib.tests.test_bunch'
+        assert_equal(Result.__module__, m)
+        assert_equal(self.result.__module__, m)
+
+    def test_extra_fields_per_instance(self):
+        # This test exists to ensure that instances of the same class
+        # store their own values for the extra fields. That is, the values
+        # are stored per instance and not in the class.
+        result1 = Result(x=1, y=2, z=3, w=-1, beta=0.0)
+        result2 = Result(x=4, y=5, z=6, w=99, beta=1.0)
+        assert_equal(result1.w, -1)
+        assert_equal(result1.beta, 0.0)
+        # The rest of these checks aren't essential, but let's check
+        # them anyway.
+        assert_equal(result1[:], (1, 2, 3))
+        assert_equal(result2.w, 99)
+        assert_equal(result2.beta, 1.0)
+        assert_equal(result2[:], (4, 5, 6))
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Other tests
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def test_extra_field_names_is_optional(self):
+        Square = _make_tuple_bunch('Square', ['width', 'height'])
+        sq = Square(width=1, height=2)
+        assert_equal(sq.width, 1)
+        assert_equal(sq.height, 2)
+        s = repr(sq)
+        assert_equal(s, 'Square(width=1, height=2)')
+
+    def test_tuple_like(self):
+        Tup = _make_tuple_bunch('Tup', ['a', 'b'])
+        tu = Tup(a=1, b=2)
+        assert isinstance(tu, tuple)
+        assert isinstance(tu + (1,), tuple)
+
+    def test_explicit_module(self):
+        m = 'some.module.name'
+        Foo = _make_tuple_bunch('Foo', ['x'], ['a', 'b'], module=m)
+        foo = Foo(x=1, a=355, b=113)
+        assert_equal(Foo.__module__, m)
+        assert_equal(foo.__module__, m)
+
+    def test_passes_polars_checks(self):
+        # gh-22450
+        Square = _make_tuple_bunch('Square', ['width', 'height'])
+        assert hasattr(Square, '_replace')
+        assert hasattr(Square, '_field_defaults')
+
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Argument validation
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    @pytest.mark.parametrize('args', [('123', ['a'], ['b']),
+                                      ('Foo', ['-3'], ['x']),
+                                      ('Foo', ['a'], ['+-*/'])])
+    def test_identifiers_not_allowed(self, args):
+        with pytest.raises(ValueError, match='identifiers'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['a', 'b', 'a'], ['x']),
+                                      ('Foo', ['a', 'b'], ['b', 'x'])])
+    def test_repeated_field_names(self, args):
+        with pytest.raises(ValueError, match='Duplicate'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['_a'], ['x']),
+                                      ('Foo', ['a'], ['_x'])])
+    def test_leading_underscore_not_allowed(self, args):
+        with pytest.raises(ValueError, match='underscore'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['def'], ['x']),
+                                      ('Foo', ['a'], ['or']),
+                                      ('and', ['a'], ['x'])])
+    def test_keyword_not_allowed_in_fields(self, args):
+        with pytest.raises(ValueError, match='keyword'):
+            _make_tuple_bunch(*args)
+
+    def test_at_least_one_field_name_required(self):
+        with pytest.raises(ValueError, match='at least one name'):
+            _make_tuple_bunch('Qwerty', [], ['a', 'b'])
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_ccallback.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_ccallback.py
new file mode 100644
index 0000000000000000000000000000000000000000..37bfa84e522dbf3df01abef73ea973e038f781ca
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_ccallback.py
@@ -0,0 +1,196 @@
+from numpy.testing import assert_equal, assert_
+from pytest import raises as assert_raises
+
+import time
+import pytest
+import ctypes
+import threading
+from scipy._lib import _ccallback_c as _test_ccallback_cython
+from scipy._lib import _test_ccallback
+from scipy._lib._ccallback import LowLevelCallable
+
+
+ERROR_VALUE = 2.0
+
+
+def callback_python(a, user_data=None):
+    if a == ERROR_VALUE:
+        raise ValueError("bad value")
+
+    if user_data is None:
+        return a + 1
+    else:
+        return a + user_data
+
+def _get_cffi_func(base, signature):
+    cffi = pytest.importorskip("cffi")
+
+    # Get function address
+    voidp = ctypes.cast(base, ctypes.c_void_p)
+    address = voidp.value
+
+    # Create corresponding cffi handle
+    ffi = cffi.FFI()
+    func = ffi.cast(signature, address)
+    return func
+
+
+def _get_ctypes_data():
+    value = ctypes.c_double(2.0)
+    return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp)
+
+
+def _get_cffi_data():
+    cffi = pytest.importorskip("cffi")
+    ffi = cffi.FFI()
+    return ffi.new('double *', 2.0)
+
+
+CALLERS = {
+    'simple': _test_ccallback.test_call_simple,
+    'nodata': _test_ccallback.test_call_nodata,
+    'nonlocal': _test_ccallback.test_call_nonlocal,
+    'cython': _test_ccallback_cython.test_call_cython,
+}
+
+# These functions have signatures known to the callers
+FUNCS = {
+    'python': lambda: callback_python,
+    'capsule': lambda: _test_ccallback.test_get_plus1_capsule(),
+    'cython': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                   "plus1_cython"),
+    'ctypes': lambda: _test_ccallback_cython.plus1_ctypes,
+    'cffi': lambda: _get_cffi_func(_test_ccallback_cython.plus1_ctypes,
+                                   'double (*)(double, int *, void *)'),
+    'capsule_b': lambda: _test_ccallback.test_get_plus1b_capsule(),
+    'cython_b': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                     "plus1b_cython"),
+    'ctypes_b': lambda: _test_ccallback_cython.plus1b_ctypes,
+    'cffi_b': lambda: _get_cffi_func(_test_ccallback_cython.plus1b_ctypes,
+                                     'double (*)(double, double, int *, void *)'),
+}
+
+# These functions have signatures the callers don't know
+BAD_FUNCS = {
+    'capsule_bc': lambda: _test_ccallback.test_get_plus1bc_capsule(),
+    'cython_bc': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                      "plus1bc_cython"),
+    'ctypes_bc': lambda: _test_ccallback_cython.plus1bc_ctypes,
+    'cffi_bc': lambda: _get_cffi_func(
+        _test_ccallback_cython.plus1bc_ctypes,
+        'double (*)(double, double, double, int *, void *)'
+    ),
+}
+
+USER_DATAS = {
+    'ctypes': _get_ctypes_data,
+    'cffi': _get_cffi_data,
+    'capsule': _test_ccallback.test_get_data_capsule,
+}
+
+
+def test_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        func = FUNCS[func]()
+        user_data = USER_DATAS[user_data]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test basic call
+        assert_equal(caller(func, 1.0), 2.0)
+
+        # Test 'bad' value resulting to an error
+        assert_raises(ValueError, caller, func, ERROR_VALUE)
+
+        # Test passing in user_data
+        assert_equal(caller(func2, 1.0), 3.0)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_bad_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        user_data = USER_DATAS[user_data]()
+        func = BAD_FUNCS[func]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test that basic call fails
+        assert_raises(ValueError, caller, LowLevelCallable(func), 1.0)
+
+        # Test that passing in user_data also fails
+        assert_raises(ValueError, caller, func2, 1.0)
+
+        # Test error message
+        llfunc = LowLevelCallable(func)
+        try:
+            caller(llfunc, 1.0)
+        except ValueError as err:
+            msg = str(err)
+            assert_(llfunc.signature in msg, msg)
+            assert_('double (double, double, int *, void *)' in msg, msg)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(BAD_FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_signature_override():
+    caller = _test_ccallback.test_call_simple
+    func = _test_ccallback.test_get_plus1_capsule()
+
+    llcallable = LowLevelCallable(func, signature="bad signature")
+    assert_equal(llcallable.signature, "bad signature")
+    assert_raises(ValueError, caller, llcallable, 3)
+
+    llcallable = LowLevelCallable(func, signature="double (double, int *, void *)")
+    assert_equal(llcallable.signature, "double (double, int *, void *)")
+    assert_equal(caller(llcallable, 3), 4)
+
+
+def test_threadsafety():
+    def callback(a, caller):
+        if a <= 0:
+            return 1
+        else:
+            res = caller(lambda x: callback(x, caller), a - 1)
+            return 2*res
+
+    def check(caller):
+        caller = CALLERS[caller]
+
+        results = []
+
+        count = 10
+
+        def run():
+            time.sleep(0.01)
+            r = caller(lambda x: callback(x, caller), count)
+            results.append(r)
+
+        threads = [threading.Thread(target=run) for j in range(20)]
+        for thread in threads:
+            thread.start()
+        for thread in threads:
+            thread.join()
+
+        assert_equal(results, [2.0**count]*len(threads))
+
+    for caller in CALLERS.keys():
+        check(caller)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_config.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..777f44bead4ef8ff3cf82aa7da1ede37fd86cd20
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_config.py
@@ -0,0 +1,44 @@
+"""
+Check the SciPy config is valid.
+"""
+import scipy
+import pytest
+from unittest.mock import patch
+
+pytestmark = pytest.mark.skipif(
+    not hasattr(scipy.__config__, "_built_with_meson"),
+    reason="Requires Meson builds",
+)
+
+
+class TestSciPyConfigs:
+    REQUIRED_CONFIG_KEYS = [
+        "Compilers",
+        "Machine Information",
+        "Python Information",
+    ]
+
+    @patch("scipy.__config__._check_pyyaml")
+    def test_pyyaml_not_found(self, mock_yaml_importer):
+        mock_yaml_importer.side_effect = ModuleNotFoundError()
+        with pytest.warns(UserWarning):
+            scipy.show_config()
+
+    def test_dict_mode(self):
+        config = scipy.show_config(mode="dicts")
+
+        assert isinstance(config, dict)
+        assert all([key in config for key in self.REQUIRED_CONFIG_KEYS]), (
+            "Required key missing,"
+            " see index of `False` with `REQUIRED_CONFIG_KEYS`"
+        )
+
+    def test_invalid_mode(self):
+        with pytest.raises(AttributeError):
+            scipy.show_config(mode="foo")
+
+    def test_warn_to_add_tests(self):
+        assert len(scipy.__config__.DisplayModes) == 2, (
+            "New mode detected,"
+            " please add UT if applicable and increment this count"
+        )
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_deprecation.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a52c68e5516c4e88934868b6d1daf7398ec4f9c9
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_deprecation.py
@@ -0,0 +1,10 @@
+import pytest
+
+@pytest.mark.thread_unsafe(reason="deprecate_cython_api is not thread-safe")
+def test_cython_api_deprecation():
+    match = ("`scipy._lib._test_deprecation_def.foo_deprecated` "
+             "is deprecated, use `foo` instead!\n"
+             "Deprecated in Scipy 42.0.0")
+    with pytest.warns(DeprecationWarning, match=match):
+        from .. import _test_deprecation_call
+    assert _test_deprecation_call.call() == (1, 1)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_doccer.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f47827e191df498d92f01628de5d34718b3c09c
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_doccer.py
@@ -0,0 +1,144 @@
+''' Some tests for the documenting decorator and support functions '''
+
+import sys
+import warnings
+import pytest
+from numpy.testing import assert_equal
+
+from scipy._lib import doccer
+
+# python -OO strips docstrings
+DOCSTRINGS_STRIPPED = sys.flags.optimize > 1
+
+docstring = \
+"""Docstring
+    %(strtest1)s
+        %(strtest2)s
+     %(strtest3)s
+"""
+param_doc1 = \
+"""Another test
+   with some indent"""
+
+param_doc2 = \
+"""Another test, one line"""
+
+param_doc3 = \
+"""    Another test
+       with some indent"""
+
+doc_dict = {'strtest1':param_doc1,
+            'strtest2':param_doc2,
+            'strtest3':param_doc3}
+
+filled_docstring = \
+"""Docstring
+    Another test
+       with some indent
+        Another test, one line
+     Another test
+       with some indent
+"""
+
+
+def test_unindent():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        assert_equal(doccer.unindent_string(param_doc1), param_doc1)
+        assert_equal(doccer.unindent_string(param_doc2), param_doc2)
+        assert_equal(doccer.unindent_string(param_doc3), param_doc1)
+
+
+def test_unindent_dict():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        d2 = doccer.unindent_dict(doc_dict)
+    assert_equal(d2['strtest1'], doc_dict['strtest1'])
+    assert_equal(d2['strtest2'], doc_dict['strtest2'])
+    assert_equal(d2['strtest3'], doc_dict['strtest1'])
+
+
+def test_docformat():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        udd = doccer.unindent_dict(doc_dict)
+        formatted = doccer.docformat(docstring, udd)
+        assert_equal(formatted, filled_docstring)
+        single_doc = 'Single line doc %(strtest1)s'
+        formatted = doccer.docformat(single_doc, doc_dict)
+        # Note - initial indent of format string does not
+        # affect subsequent indent of inserted parameter
+        assert_equal(formatted, """Single line doc Another test
+   with some indent""")
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_decorator():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        # with unindentation of parameters
+        decorator = doccer.filldoc(doc_dict, True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+
+        def expected():
+            """ Docstring
+            Another test
+               with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+        # without unindentation of parameters
+
+        # The docstring should be unindented for Python 3.13+
+        # because of https://github.com/python/cpython/issues/81283
+        decorator = doccer.filldoc(doc_dict, False if \
+                                   sys.version_info < (3, 13) else True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+        def expected():
+            """ Docstring
+                Another test
+                   with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_inherit_docstring_from():
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+
+        class Foo:
+            def func(self):
+                '''Do something useful.'''
+                return
+
+            def func2(self):
+                '''Something else.'''
+
+        class Bar(Foo):
+            @doccer.inherit_docstring_from(Foo)
+            def func(self):
+                '''%(super)sABC'''
+                return
+
+            @doccer.inherit_docstring_from(Foo)
+            def func2(self):
+                # No docstring.
+                return
+
+    assert_equal(Bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(Bar.func2.__doc__, Foo.func2.__doc__)
+    bar = Bar()
+    assert_equal(bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(bar.func2.__doc__, Foo.func2.__doc__)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_import_cycles.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_import_cycles.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f2b1ded9799b25d2aaef373b8676f9536aef8e7
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_import_cycles.py
@@ -0,0 +1,26 @@
+import multiprocessing
+import subprocess
+import sys
+
+import pytest
+
+from .test_public_api import PUBLIC_MODULES
+
+# Regression tests for gh-6793.
+# Check that all modules are importable in a new Python process.
+# This is not necessarily true if there are import cycles present.
+
+
+def _check_single_module(module):
+    pid = subprocess.Popen([sys.executable, '-X', 'faulthandler', '-c',
+                            f'import {module}'])
+    assert pid.wait() == 0, f'Failed to import {module}'
+
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+def test_public_modules_importable_2():
+    # Ensure we use max 6 processes, to limit peak resource usage (memory, file handles)
+    # on resource-constrained systems (e.g., RISC-V - see gh-24163).
+    with multiprocessing.Pool(processes=6) as pool:
+        pool.map(_check_single_module, PUBLIC_MODULES)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_public_api.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_public_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..cba7b8d9a9edcfa79b709e9dcb66f9264e5a21fe
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_public_api.py
@@ -0,0 +1,433 @@
+"""
+This test script is adopted from:
+    https://github.com/numpy/numpy/blob/main/numpy/tests/test_public_api.py
+"""
+
+import pkgutil
+import types
+import importlib
+import warnings
+from importlib import import_module
+
+import pytest
+
+import scipy
+
+from scipy._lib._public_api import PUBLIC_MODULES
+from scipy.conftest import xp_available_backends
+
+
+def test_dir_testing():
+    """Assert that output of dir has only one "testing/tester"
+    attribute without duplicate"""
+    assert len(dir(scipy)) == len(set(dir(scipy)))
+
+
+# The PRIVATE_BUT_PRESENT_MODULES list contains modules that lacked underscores
+# in their name and hence looked public, but weren't meant to be. All these
+# namespace were deprecated in the 1.8.0 release - see "clear split between
+# public and private API" in the 1.8.0 release notes.
+# These private modules support will be removed in SciPy v2.0.0, as the
+# deprecation messages emitted by each of these modules say.
+PRIVATE_BUT_PRESENT_MODULES = [
+    'scipy.constants.codata',
+    'scipy.constants.constants',
+    'scipy.fftpack.basic',
+    'scipy.fftpack.convolve',
+    'scipy.fftpack.helper',
+    'scipy.fftpack.pseudo_diffs',
+    'scipy.fftpack.realtransforms',
+    'scipy.integrate.dop',
+    'scipy.integrate.odepack',
+    'scipy.integrate.quadpack',
+    'scipy.integrate.vode',
+    'scipy.interpolate.dfitpack',
+    'scipy.interpolate.fitpack',
+    'scipy.interpolate.fitpack2',
+    'scipy.interpolate.interpnd',
+    'scipy.interpolate.interpolate',
+    'scipy.interpolate.ndgriddata',
+    'scipy.interpolate.polyint',
+    'scipy.interpolate.rbf',
+    'scipy.io.arff.arffread',
+    'scipy.io.harwell_boeing',
+    'scipy.io.idl',
+    'scipy.io.matlab.byteordercodes',
+    'scipy.io.matlab.mio',
+    'scipy.io.matlab.mio4',
+    'scipy.io.matlab.mio5',
+    'scipy.io.matlab.mio5_params',
+    'scipy.io.matlab.mio5_utils',
+    'scipy.io.matlab.mio_utils',
+    'scipy.io.matlab.miobase',
+    'scipy.io.matlab.streams',
+    'scipy.io.mmio',
+    'scipy.io.netcdf',
+    'scipy.linalg.basic',
+    'scipy.linalg.decomp',
+    'scipy.linalg.decomp_cholesky',
+    'scipy.linalg.decomp_lu',
+    'scipy.linalg.decomp_qr',
+    'scipy.linalg.decomp_schur',
+    'scipy.linalg.decomp_svd',
+    'scipy.linalg.matfuncs',
+    'scipy.linalg.misc',
+    'scipy.linalg.special_matrices',
+    'scipy.misc',
+    'scipy.misc.common',
+    'scipy.misc.doccer',
+    'scipy.ndimage.filters',
+    'scipy.ndimage.fourier',
+    'scipy.ndimage.interpolation',
+    'scipy.ndimage.measurements',
+    'scipy.ndimage.morphology',
+    'scipy.odr.models',
+    'scipy.odr.odrpack',
+    'scipy.optimize.cobyla',
+    'scipy.optimize.cython_optimize',
+    'scipy.optimize.lbfgsb',
+    'scipy.optimize.linesearch',
+    'scipy.optimize.minpack',
+    'scipy.optimize.minpack2',
+    'scipy.optimize.moduleTNC',
+    'scipy.optimize.nonlin',
+    'scipy.optimize.optimize',
+    'scipy.optimize.slsqp',
+    'scipy.optimize.tnc',
+    'scipy.optimize.zeros',
+    'scipy.signal.bsplines',
+    'scipy.signal.filter_design',
+    'scipy.signal.fir_filter_design',
+    'scipy.signal.lti_conversion',
+    'scipy.signal.ltisys',
+    'scipy.signal.signaltools',
+    'scipy.signal.spectral',
+    'scipy.signal.spline',
+    'scipy.signal.waveforms',
+    'scipy.signal.wavelets',
+    'scipy.signal.windows.windows',
+    'scipy.sparse.base',
+    'scipy.sparse.bsr',
+    'scipy.sparse.compressed',
+    'scipy.sparse.construct',
+    'scipy.sparse.coo',
+    'scipy.sparse.csc',
+    'scipy.sparse.csr',
+    'scipy.sparse.data',
+    'scipy.sparse.dia',
+    'scipy.sparse.dok',
+    'scipy.sparse.extract',
+    'scipy.sparse.lil',
+    'scipy.sparse.linalg.dsolve',
+    'scipy.sparse.linalg.eigen',
+    'scipy.sparse.linalg.interface',
+    'scipy.sparse.linalg.isolve',
+    'scipy.sparse.linalg.matfuncs',
+    'scipy.sparse.sparsetools',
+    'scipy.sparse.spfuncs',
+    'scipy.sparse.sputils',
+    'scipy.spatial.ckdtree',
+    'scipy.spatial.kdtree',
+    'scipy.spatial.qhull',
+    'scipy.spatial.transform.rotation',
+    'scipy.special.add_newdocs',
+    'scipy.special.basic',
+    'scipy.special.cython_special',
+    'scipy.special.orthogonal',
+    'scipy.special.sf_error',
+    'scipy.special.specfun',
+    'scipy.special.spfun_stats',
+    'scipy.stats.biasedurn',
+    'scipy.stats.kde',
+    'scipy.stats.morestats',
+    'scipy.stats.mstats_basic',
+    'scipy.stats.mstats_extras',
+    'scipy.stats.mvn',
+    'scipy.stats.stats',
+]
+
+
+def is_unexpected(name):
+    """Check if this needs to be considered."""
+    if '._' in name or '.tests' in name or '.setup' in name:
+        return False
+
+    if name in PUBLIC_MODULES:
+        return False
+
+    if name in PRIVATE_BUT_PRESENT_MODULES:
+        return False
+
+    return True
+
+
+SKIP_LIST = [
+    'scipy.conftest',
+    'scipy.version',
+    'scipy.special.libsf_error_state',
+    'scipy.integrate.lsoda'
+]
+
+
+# XXX: this test does more than it says on the tin - in using `pkgutil.walk_packages`,
+# it will raise if it encounters any exceptions which are not handled by `ignore_errors`
+# while attempting to import each discovered package.
+# For now, `ignore_errors` only ignores what is necessary, but this could be expanded -
+# for example, to all errors from private modules or git subpackages - if desired.
+@pytest.mark.thread_unsafe(
+    reason=("crashes in pkgutil.walk_packages, see "
+            "https://github.com/data-apis/array-api-compat/issues/343"))
+def test_all_modules_are_expected():
+    """
+    Test that we don't add anything that looks like a new public module by
+    accident.  Check is based on filenames.
+    """
+
+    def ignore_errors(name):
+        # if versions of other array libraries are installed which are incompatible
+        # with the installed NumPy version, there can be errors on importing
+        # `array_api_compat`. This should only raise if SciPy is configured with
+        # that library as an available backend.
+        backends = {'cupy', 'torch', 'dask.array'}
+        for backend in backends:
+            path = f'array_api_compat.{backend}'
+            if path in name and backend not in xp_available_backends:
+                return
+        raise
+
+    modnames = []
+
+    with warnings.catch_warnings():
+        warnings.filterwarnings("ignore", "scipy.misc", DeprecationWarning)
+        for _, modname, _ in pkgutil.walk_packages(path=scipy.__path__,
+                                                   prefix=scipy.__name__ + '.',
+                                                   onerror=ignore_errors):
+            if is_unexpected(modname) and modname not in SKIP_LIST:
+                # We have a name that is new.  If that's on purpose, add it to
+                # PUBLIC_MODULES.  We don't expect to have to add anything to
+                # PRIVATE_BUT_PRESENT_MODULES.  Use an underscore in the name!
+                modnames.append(modname)
+
+    if modnames:
+        raise AssertionError(f'Found unexpected modules: {modnames}')
+
+
+# Stuff that clearly shouldn't be in the API and is detected by the next test
+# below
+SKIP_LIST_2 = [
+    'scipy.char',
+    'scipy.rec',
+    'scipy.emath',
+    'scipy.math',
+    'scipy.random',
+    'scipy.ctypeslib',
+    'scipy.ma',
+    'scipy.integrate.lsoda'
+]
+
+
+def test_all_modules_are_expected_2():
+    """
+    Method checking all objects. The pkgutil-based method in
+    `test_all_modules_are_expected` does not catch imports into a namespace,
+    only filenames.
+    """
+
+    def find_unexpected_members(mod_name):
+        members = []
+        module = importlib.import_module(mod_name)
+        if hasattr(module, '__all__'):
+            objnames = module.__all__
+        else:
+            objnames = dir(module)
+
+        for objname in objnames:
+            if not objname.startswith('_'):
+                fullobjname = mod_name + '.' + objname
+                if isinstance(getattr(module, objname), types.ModuleType):
+                    if is_unexpected(fullobjname) and fullobjname not in SKIP_LIST_2:
+                        members.append(fullobjname)
+
+        return members
+    with warnings.catch_warnings():
+        warnings.filterwarnings("ignore",  "scipy.misc", DeprecationWarning)
+        unexpected_members = find_unexpected_members("scipy")
+
+    for modname in PUBLIC_MODULES:
+        unexpected_members.extend(find_unexpected_members(modname))
+
+    if unexpected_members:
+        raise AssertionError("Found unexpected object(s) that look like "
+                             f"modules: {unexpected_members}")
+
+
+def test_api_importable():
+    """
+    Check that all submodules listed higher up in this file can be imported
+    Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
+    simply need to be removed from the list (deprecation may or may not be
+    needed - apply common sense).
+    """
+    def check_importable(module_name):
+        try:
+            importlib.import_module(module_name)
+        except (ImportError, AttributeError):
+            return False
+
+        return True
+
+    module_names = []
+    for module_name in PUBLIC_MODULES:
+        if not check_importable(module_name):
+            module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules in the public API that cannot be "
+                             f"imported: {module_names}")
+
+    with warnings.catch_warnings(record=True):
+        warnings.simplefilter('always', category=DeprecationWarning)
+        warnings.simplefilter('always', category=ImportWarning)
+        for module_name in PRIVATE_BUT_PRESENT_MODULES:
+            if not check_importable(module_name):
+                module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules that are not really public but looked "
+                             "public and can not be imported: "
+                             f"{module_names}")
+
+
+@pytest.mark.parametrize(("module_name", "correct_module"),
+                         [('scipy.constants.codata', None),
+                          ('scipy.constants.constants', None),
+                          ('scipy.fftpack.basic', None),
+                          ('scipy.fftpack.helper', None),
+                          ('scipy.fftpack.pseudo_diffs', None),
+                          ('scipy.fftpack.realtransforms', None),
+                          ('scipy.integrate.dop', None),
+                          ('scipy.integrate.odepack', None),
+                          ('scipy.integrate.quadpack', None),
+                          ('scipy.integrate.vode', None),
+                          ('scipy.interpolate.dfitpack', None),
+                          ('scipy.interpolate.fitpack', None),
+                          ('scipy.interpolate.fitpack2', None),
+                          ('scipy.interpolate.interpnd', None),
+                          ('scipy.interpolate.interpolate', None),
+                          ('scipy.interpolate.ndgriddata', None),
+                          ('scipy.interpolate.polyint', None),
+                          ('scipy.interpolate.rbf', None),
+                          ('scipy.io.harwell_boeing', None),
+                          ('scipy.io.idl', None),
+                          ('scipy.io.mmio', None),
+                          ('scipy.io.netcdf', None),
+                          ('scipy.io.arff.arffread', 'arff'),
+                          ('scipy.io.matlab.byteordercodes', 'matlab'),
+                          ('scipy.io.matlab.mio_utils', 'matlab'),
+                          ('scipy.io.matlab.mio', 'matlab'),
+                          ('scipy.io.matlab.mio4', 'matlab'),
+                          ('scipy.io.matlab.mio5_params', 'matlab'),
+                          ('scipy.io.matlab.mio5_utils', 'matlab'),
+                          ('scipy.io.matlab.mio5', 'matlab'),
+                          ('scipy.io.matlab.miobase', 'matlab'),
+                          ('scipy.io.matlab.streams', 'matlab'),
+                          ('scipy.linalg.basic', None),
+                          ('scipy.linalg.decomp', None),
+                          ('scipy.linalg.decomp_cholesky', None),
+                          ('scipy.linalg.decomp_lu', None),
+                          ('scipy.linalg.decomp_qr', None),
+                          ('scipy.linalg.decomp_schur', None),
+                          ('scipy.linalg.decomp_svd', None),
+                          ('scipy.linalg.matfuncs', None),
+                          ('scipy.linalg.misc', None),
+                          ('scipy.linalg.special_matrices', None),
+                          ('scipy.ndimage.filters', None),
+                          ('scipy.ndimage.fourier', None),
+                          ('scipy.ndimage.interpolation', None),
+                          ('scipy.ndimage.measurements', None),
+                          ('scipy.ndimage.morphology', None),
+                          ('scipy.optimize.cobyla', None),
+                          ('scipy.optimize.lbfgsb', None),
+                          ('scipy.optimize.linesearch', None),
+                          ('scipy.optimize.minpack', None),
+                          ('scipy.optimize.minpack2', None),
+                          ('scipy.optimize.moduleTNC', None),
+                          ('scipy.optimize.nonlin', None),
+                          ('scipy.optimize.optimize', None),
+                          ('scipy.optimize.slsqp', None),
+                          ('scipy.optimize.tnc', None),
+                          ('scipy.optimize.zeros', None),
+                          ('scipy.signal.bsplines', None),
+                          ('scipy.signal.filter_design', None),
+                          ('scipy.signal.fir_filter_design', None),
+                          ('scipy.signal.lti_conversion', None),
+                          ('scipy.signal.ltisys', None),
+                          ('scipy.signal.signaltools', None),
+                          ('scipy.signal.spectral', None),
+                          ('scipy.signal.spline', None),
+                          ('scipy.signal.waveforms', None),
+                          ('scipy.signal.wavelets', None),
+                          ('scipy.signal.windows.windows', 'windows'),
+                          ('scipy.sparse.base', None),
+                          ('scipy.sparse.bsr', None),
+                          ('scipy.sparse.compressed', None),
+                          ('scipy.sparse.construct', None),
+                          ('scipy.sparse.coo', None),
+                          ('scipy.sparse.csc', None),
+                          ('scipy.sparse.csr', None),
+                          ('scipy.sparse.data', None),
+                          ('scipy.sparse.dia', None),
+                          ('scipy.sparse.dok', None),
+                          ('scipy.sparse.extract', None),
+                          ('scipy.sparse.lil', None),
+                          ('scipy.sparse.linalg.dsolve', 'linalg'),
+                          ('scipy.sparse.linalg.eigen', 'linalg'),
+                          ('scipy.sparse.linalg.interface', 'linalg'),
+                          ('scipy.sparse.linalg.isolve', 'linalg'),
+                          ('scipy.sparse.linalg.matfuncs', 'linalg'),
+                          ('scipy.sparse.sparsetools', None),
+                          ('scipy.sparse.spfuncs', None),
+                          ('scipy.sparse.sputils', None),
+                          ('scipy.spatial.ckdtree', None),
+                          ('scipy.spatial.kdtree', None),
+                          ('scipy.spatial.qhull', None),
+                          ('scipy.spatial.transform.rotation', 'transform'),
+                          ('scipy.special.add_newdocs', None),
+                          ('scipy.special.basic', None),
+                          ('scipy.special.orthogonal', None),
+                          ('scipy.special.sf_error', None),
+                          ('scipy.special.specfun', None),
+                          ('scipy.special.spfun_stats', None),
+                          ('scipy.stats.biasedurn', None),
+                          ('scipy.stats.kde', None),
+                          ('scipy.stats.morestats', None),
+                          ('scipy.stats.mstats_basic', 'mstats'),
+                          ('scipy.stats.mstats_extras', 'mstats'),
+                          ('scipy.stats.mvn', None),
+                          ('scipy.stats.stats', None)])
+def test_private_but_present_deprecation(module_name, correct_module):
+    # gh-18279, gh-17572, gh-17771 noted that deprecation warnings
+    # for imports from private modules
+    # were misleading. Check that this is resolved.
+    module = import_module(module_name)
+    if correct_module is None:
+        import_name = f'scipy.{module_name.split(".")[1]}'
+    else:
+        import_name = f'scipy.{module_name.split(".")[1]}.{correct_module}'
+
+    correct_import = import_module(import_name)
+
+    # Attributes that were formerly in `module_name` can still be imported from
+    # `module_name`, albeit with a deprecation warning.
+    for attr_name in module.__all__:
+        # ensure attribute is present where the warning is pointing
+        assert getattr(correct_import, attr_name, None) is not None
+        message = f"Please import `{attr_name}` from the `{import_name}`..."
+        with pytest.deprecated_call(match=message):
+            getattr(module, attr_name)
+
+    # Attributes that were not in `module_name` get an error notifying the user
+    # that the attribute is not in `module_name` and that `module_name` is deprecated.
+    message = f"`{module_name}` is deprecated..."
+    with pytest.raises(AttributeError, match=message):
+        getattr(module, "ekki")
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_scipy_version.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_scipy_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..f124f1ae9548f47e67d670840ece88c2ed583b01
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_tmpdirs.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..447929a351d363aa6b9cd0f56f8e0a2bb5d3833f
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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(reason="tempdir is not thread-safe")
+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(reason="in_tempdir is not thread-safe")
+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(reason="in_dir is not thread-safe")
+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/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_warnings.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/tests/test_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd0172b8045cf772302cdcec8c8dd30c7d9dfd6a
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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 outside of test code
+            if argtext == "ignore" and "tests" not in self.__filename.parts:
+                self.bad_filters.append(
+                    f"{self.__filename}:{node.lineno}")
+
+        if p.ls[-1] == 'warn' and (
+                len(p.ls) == 1 or p.ls[-2] == 'warnings'):
+
+            if self.__filename == "_lib/tests/test_warnings.py":
+                # This file
+                return
+
+            # See if stacklevel exists:
+            if len(node.args) == 3:
+                return
+            args = {kw.arg for kw in node.keywords}
+            if "stacklevel" not in args:
+                self.bad_stacklevels.append(
+                    f"{self.__filename}:{node.lineno}")
+
+
+@pytest.fixture(scope="session")
+def warning_calls():
+    # combined "ignore" and stacklevel error
+    base = Path(scipy.__file__).parent
+
+    bad_filters = []
+    bad_stacklevels = []
+
+    for path in base.rglob("*.py"):
+        # use tokenize to auto-detect encoding on systems where no
+        # default encoding is defined (e.g., LANG='C')
+        with tokenize.open(str(path)) as file:
+            tree = ast.parse(file.read(), filename=str(path))
+            finder = FindFuncs(path.relative_to(base))
+            finder.visit(tree)
+            bad_filters.extend(finder.bad_filters)
+            bad_stacklevels.extend(finder.bad_stacklevels)
+
+    return bad_filters, bad_stacklevels
+
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+def test_warning_calls_filters(warning_calls):
+    bad_filters, bad_stacklevels = warning_calls
+
+    # We try not to add filters in the code base, because those filters aren't
+    # thread-safe. We aim to only filter in tests with
+    # warnings.catch_warnings. However, in some cases it may prove
+    # necessary to filter out warnings, because we can't (easily) fix the root
+    # cause for them and we don't want users to see some warnings when they use
+    # SciPy correctly. So we list exceptions here.  Add new entries only if
+    # there's a good reason.
+    allowed_filters = (
+        os.path.join('datasets', '_fetchers.py'),
+        os.path.join('datasets', '__init__.py'),
+        os.path.join('optimize', '_optimize.py'),
+        os.path.join('optimize', '_constraints.py'),
+        os.path.join('optimize', '_nnls.py'),
+        os.path.join('signal', '_ltisys.py'),
+        os.path.join('sparse', '__init__.py'),  # np.matrix pending-deprecation
+        os.path.join('special', '_basic.py'),  # gh-21801
+        os.path.join('stats', '_discrete_distns.py'),  # gh-14901
+        os.path.join('stats', '_continuous_distns.py'),
+        os.path.join('stats', '_binned_statistic.py'),  # gh-19345
+        os.path.join('stats', '_stats_py.py'),  # gh-20743
+        os.path.join('stats', '_variation.py'),  # gh-22827
+        os.path.join('stats', 'tests', 'test_axis_nan_policy.py'),  # gh-20694
+        os.path.join('_lib', '_util.py'),  # gh-19341
+        os.path.join('sparse', 'linalg', '_dsolve', 'linsolve.py'),  # gh-17924
+        "conftest.py",
+    )
+    bad_filters = [item for item in bad_filters if item.split(':')[0] not in
+                   allowed_filters]
+
+    if bad_filters:
+        raise AssertionError(
+            "Warning ignore filters should not be used outside of tests.\n"
+            "Found in:\n    {}".format(
+                "\n    ".join(bad_filters)))
+
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/uarray.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/uarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1d37be3ff9a7817de00bfa557f7a01c78440510
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..93a68daf892e865a9d949a77d8857b1d1b68c1f3
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/__init__.py
@@ -0,0 +1,31 @@
+"""
+=========================================
+Clustering package (:mod:`scipy.cluster`)
+=========================================
+
+.. currentmodule:: scipy.cluster
+
+Clustering algorithms are useful in information theory, target detection,
+communications, compression, and other areas. The `vq` module only
+supports vector quantization and the k-means algorithms.
+
+The `hierarchy` module provides functions for hierarchical and
+agglomerative clustering.  Its features include generating hierarchical
+clusters from distance matrices,
+calculating statistics on clusters, cutting linkages
+to generate flat clusters, and visualizing clusters with dendrograms.
+
+.. toctree::
+   :maxdepth: 1
+
+   cluster.vq
+   cluster.hierarchy
+
+"""
+__all__ = ['vq', 'hierarchy']
+
+from . import vq, hierarchy
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..30bb9ab7c4f3d9e8d766d60ddaa38dc4d00d8966
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..057531361c5882cc61a1af196870c50275e9b192
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.pyd
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d0f3ecaf076a4dd76f565fea77a48902c52c0017f801ebcca9559bd8bbb41f13
+size 245760
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..374c7eae6141fbe306ed24c15bedcfe4fac1d070
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..6312890bedc0c55d6ef444895b4e087d407779e4
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.pyd
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b04f540816f40caf0516c1487cae2eca92cec792145f96a4bd38bbce5d2f597f
+size 173056
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..9d9f9be618474fffb1bd4f29d01e87c6183bff4c
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.pyd b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..ab15d61575d77cc5b179b7a73c4ee4b323d77512
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.pyd
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3dfe9c54f9b339d73c884907616d8dc63bed2bea49256c443fb81f0d49769013
+size 110080
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/hierarchy.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e0476073cd5d30bce109a424a6d97382bc6ef24
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/hierarchy.py
@@ -0,0 +1,4338 @@
+"""
+Hierarchical clustering (:mod:`scipy.cluster.hierarchy`)
+========================================================
+
+.. currentmodule:: scipy.cluster.hierarchy
+
+These functions cut hierarchical clusterings into flat clusterings
+or find the roots of the forest formed by a cut by providing the flat
+cluster ids of each observation.
+
+.. autosummary::
+   :toctree: generated/
+
+   fcluster
+   fclusterdata
+   leaders
+
+These are routines for agglomerative clustering.
+
+.. autosummary::
+   :toctree: generated/
+
+   linkage
+   single
+   complete
+   average
+   weighted
+   centroid
+   median
+   ward
+
+These routines compute statistics on hierarchies.
+
+.. autosummary::
+   :toctree: generated/
+
+   cophenet
+   from_mlab_linkage
+   inconsistent
+   maxinconsts
+   maxdists
+   maxRstat
+   to_mlab_linkage
+
+Routines for visualizing flat clusters.
+
+.. autosummary::
+   :toctree: generated/
+
+   dendrogram
+
+These are data structures and routines for representing hierarchies as
+tree objects.
+
+.. autosummary::
+   :toctree: generated/
+
+   ClusterNode
+   leaves_list
+   to_tree
+   cut_tree
+   optimal_leaf_ordering
+
+These are predicates for checking the validity of linkage and
+inconsistency matrices as well as for checking isomorphism of two
+flat cluster assignments.
+
+.. autosummary::
+   :toctree: generated/
+
+   is_valid_im
+   is_valid_linkage
+   is_isomorphic
+   is_monotonic
+   correspond
+   num_obs_linkage
+
+Utility routines for plotting:
+
+.. autosummary::
+   :toctree: generated/
+
+   set_link_color_palette
+
+Utility classes:
+
+.. autosummary::
+   :toctree: generated/
+
+   DisjointSet -- data structure for incremental connectivity queries
+
+"""
+# Copyright (C) Damian Eads, 2007-2008. New BSD License.
+
+# hierarchy.py (derived from cluster.py, http://scipy-cluster.googlecode.com)
+#
+# Author: Damian Eads
+# Date:   September 22, 2007
+#
+# Copyright (c) 2007, 2008, Damian Eads
+#
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#   - Redistributions of source code must retain the above
+#     copyright notice, this list of conditions and the
+#     following disclaimer.
+#   - Redistributions in binary form must reproduce the above copyright
+#     notice, this list of conditions and the following disclaimer
+#     in the documentation and/or other materials provided with the
+#     distribution.
+#   - Neither the name of the author nor the names of its
+#     contributors may be used to endorse or promote products derived
+#     from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import warnings
+import bisect
+from collections import deque
+
+import numpy as np
+from . import _hierarchy, _optimal_leaf_ordering
+import scipy.spatial.distance as distance
+from scipy._lib._array_api import (_asarray, array_namespace, is_dask,
+                                   is_lazy_array, xp_capabilities, xp_copy)
+from scipy._lib._disjoint_set import DisjointSet
+import scipy._lib.array_api_extra as xpx
+
+
+_LINKAGE_METHODS = {'single': 0, 'complete': 1, 'average': 2, 'centroid': 3,
+                    'median': 4, 'ward': 5, 'weighted': 6}
+_EUCLIDEAN_METHODS = ('centroid', 'median', 'ward')
+
+__all__ = ['ClusterNode', 'DisjointSet', 'average', 'centroid', 'complete',
+           'cophenet', 'correspond', 'cut_tree', 'dendrogram', 'fcluster',
+           'fclusterdata', 'from_mlab_linkage', 'inconsistent',
+           'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage',
+           'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists',
+           'maxinconsts', 'median', 'num_obs_linkage', 'optimal_leaf_ordering',
+           'set_link_color_palette', 'single', 'to_mlab_linkage', 'to_tree',
+           'ward', 'weighted']
+
+
+class ClusterWarning(UserWarning):
+    pass
+
+
+def _warning(s):
+    warnings.warn(f'scipy.cluster: {s}', ClusterWarning, stacklevel=3)
+
+
+def int_floor(arr, xp):
+    # array_api_strict is strict about not allowing `int()` on a float array.
+    # That's typically not needed, here it is - so explicitly convert
+    return int(xp.asarray(arr, dtype=xp.int64))
+
+
+lazy_cython = xp_capabilities(
+    cpu_only=True, reason="Cython code",
+    warnings=[("dask.array", "merges chunks")])
+
+
+@lazy_cython
+def single(y):
+    """
+    Perform single/min/nearest linkage on the condensed distance matrix ``y``.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        The linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = single(y)
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  4,  5,  6,  1,  2,  3], dtype=int32)
+    >>> fcluster(Z, 1, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='single', metric='euclidean')
+
+
+@lazy_cython
+def complete(y):
+    """
+    Perform complete/max/farthest point linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import complete, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = complete(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.41421356,  3.        ],
+           [ 5.        , 13.        ,  1.41421356,  3.        ],
+           [ 8.        , 14.        ,  1.41421356,  3.        ],
+           [11.        , 15.        ,  1.41421356,  3.        ],
+           [16.        , 17.        ,  4.12310563,  6.        ],
+           [18.        , 19.        ,  4.12310563,  6.        ],
+           [20.        , 21.        ,  5.65685425, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4.5, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='complete', metric='euclidean')
+
+
+@lazy_cython
+def average(y):
+    """
+    Perform average/UPGMA linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import average, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = average(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 5.        , 13.        ,  1.20710678,  3.        ],
+           [ 8.        , 14.        ,  1.20710678,  3.        ],
+           [11.        , 15.        ,  1.20710678,  3.        ],
+           [16.        , 17.        ,  3.39675184,  6.        ],
+           [18.        , 19.        ,  3.39675184,  6.        ],
+           [20.        , 21.        ,  4.09206523, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='average', metric='euclidean')
+
+
+@lazy_cython
+def weighted(y):
+    """
+    Perform weighted/WPGMA linkage on the condensed distance matrix.
+
+    See `linkage` for more information on the return
+    structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import weighted, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = weighted(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 11.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 8.        , 13.        ,  1.20710678,  3.        ],
+           [ 5.        , 14.        ,  1.20710678,  3.        ],
+           [10.        , 15.        ,  1.20710678,  3.        ],
+           [18.        , 19.        ,  3.05595762,  6.        ],
+           [16.        , 17.        ,  3.32379407,  6.        ],
+           [20.        , 21.        ,  4.06357713, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9,  1,  2,  3, 10, 11, 12,  4,  6,  5], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([3, 3, 3, 1, 1, 1, 4, 4, 4, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='weighted', metric='euclidean')
+
+
+@lazy_cython
+def centroid(y):
+    """
+    Perform centroid/UPGMC linkage.
+
+    See `linkage` for more information on the input matrix,
+    return structure, and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = centroid(y)``
+
+       Performs centroid/UPGMC linkage on the condensed distance
+       matrix ``y``.
+
+    2. ``Z = centroid(X)``
+
+       Performs centroid/UPGMC linkage on the observation matrix ``X``
+       using Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns. Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import centroid, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = centroid(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.33333333,  6.        ],
+           [16.        , 17.        ,  3.33333333,  6.        ],
+           [20.        , 21.        ,  3.33333333, 12.        ]]) # may vary
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32) # may vary
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32) # may vary
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32) # may vary
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='centroid', metric='euclidean')
+
+
+@lazy_cython
+def median(y):
+    """
+    Perform median/WPGMC linkage.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+     The following are common calling conventions:
+
+     1. ``Z = median(y)``
+
+        Performs median/WPGMC linkage on the condensed distance matrix
+        ``y``.  See ``linkage`` for more information on the return
+        structure and algorithm.
+
+     2. ``Z = median(X)``
+
+        Performs median/WPGMC linkage on the observation matrix ``X``
+        using Euclidean distance as the distance metric. See `linkage`
+        for more information on the return structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = median(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='median', metric='euclidean')
+
+
+@lazy_cython
+def ward(y):
+    """
+    Perform Ward's linkage on a condensed distance matrix.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = ward(y)``
+       Performs Ward's linkage on the condensed distance matrix ``y``.
+
+    2. ``Z = ward(X)``
+       Performs Ward's linkage on the observation matrix ``X`` using
+       Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = ward(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+    >>> fcluster(Z, 3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='ward', metric='euclidean')
+
+
+@lazy_cython
+def linkage(y, method='single', metric='euclidean', optimal_ordering=False):
+    """
+    Perform hierarchical/agglomerative clustering.
+
+    The input y may be either a 1-D condensed distance matrix
+    or a 2-D array of observation vectors.
+
+    If y is a 1-D condensed distance matrix,
+    then y must be a :math:`\\binom{n}{2}` sized
+    vector, where n is the number of original observations paired
+    in the distance matrix. The behavior of this function is very
+    similar to the MATLAB linkage function.
+
+    A :math:`(n-1)` by 4 matrix ``Z`` is returned. At the
+    :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and
+    ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A
+    cluster with an index less than :math:`n` corresponds to one of
+    the :math:`n` original observations. The distance between
+    clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The
+    fourth value ``Z[i, 3]`` represents the number of original
+    observations in the newly formed cluster.
+
+    The following linkage methods are used to compute the distance
+    :math:`d(s, t)` between two clusters :math:`s` and
+    :math:`t`. The algorithm begins with a forest of clusters that
+    have yet to be used in the hierarchy being formed. When two
+    clusters :math:`s` and :math:`t` from this forest are combined
+    into a single cluster :math:`u`, :math:`s` and :math:`t` are
+    removed from the forest, and :math:`u` is added to the
+    forest. When only one cluster remains in the forest, the algorithm
+    stops, and this cluster becomes the root.
+
+    A distance matrix is maintained at each iteration. The ``d[i,j]``
+    entry corresponds to the distance between cluster :math:`i` and
+    :math:`j` in the original forest.
+
+    At each iteration, the algorithm must update the distance matrix
+    to reflect the distance of the newly formed cluster u with the
+    remaining clusters in the forest.
+
+    Suppose there are :math:`|u|` original observations
+    :math:`u[0], \\ldots, u[|u|-1]` in cluster :math:`u` and
+    :math:`|v|` original objects :math:`v[0], \\ldots, v[|v|-1]` in
+    cluster :math:`v`. Recall, :math:`s` and :math:`t` are
+    combined to form cluster :math:`u`. Let :math:`v` be any
+    remaining cluster in the forest that is not :math:`u`.
+
+    The following are methods for calculating the distance between the
+    newly formed cluster :math:`u` and each :math:`v`.
+
+      * method='single' assigns
+
+        .. math::
+           d(u,v) = \\min(dist(u[i],v[j]))
+
+        for all points :math:`i` in cluster :math:`u` and
+        :math:`j` in cluster :math:`v`. This is also known as the
+        Nearest Point Algorithm.
+
+      * method='complete' assigns
+
+        .. math::
+           d(u, v) = \\max(dist(u[i],v[j]))
+
+        for all points :math:`i` in cluster u and :math:`j` in
+        cluster :math:`v`. This is also known by the Farthest Point
+        Algorithm or Voor Hees Algorithm.
+
+      * method='average' assigns
+
+        .. math::
+           d(u,v) = \\sum_{ij} \\frac{d(u[i], v[j])}
+                                   {(|u|*|v|)}
+
+        for all points :math:`i` and :math:`j` where :math:`|u|`
+        and :math:`|v|` are the cardinalities of clusters :math:`u`
+        and :math:`v`, respectively. This is also called the UPGMA
+        algorithm.
+
+      * method='weighted' assigns
+
+        .. math::
+           d(u,v) = (dist(s,v) + dist(t,v))/2
+
+        where cluster u was formed with cluster s and t and v
+        is a remaining cluster in the forest (also called WPGMA).
+
+      * method='centroid' assigns
+
+        .. math::
+           dist(s,t) = ||c_s-c_t||_2
+
+        where :math:`c_s` and :math:`c_t` are the centroids of
+        clusters :math:`s` and :math:`t`, respectively. When two
+        clusters :math:`s` and :math:`t` are combined into a new
+        cluster :math:`u`, the new centroid is computed over all the
+        original objects in clusters :math:`s` and :math:`t`. The
+        distance then becomes the Euclidean distance between the
+        centroid of :math:`u` and the centroid of a remaining cluster
+        :math:`v` in the forest. This is also known as the UPGMC
+        algorithm.
+
+      * method='median' assigns :math:`d(s,t)` like the ``centroid``
+        method. When two clusters :math:`s` and :math:`t` are combined
+        into a new cluster :math:`u`, the average of centroids s and t
+        give the new centroid :math:`u`. This is also known as the
+        WPGMC algorithm.
+
+      * method='ward' uses the Ward variance minimization algorithm.
+        The new entry :math:`d(u,v)` is computed as follows,
+
+        .. math::
+
+           d(u,v) = \\sqrt{\\frac{|v|+|s|}
+                               {T}d(v,s)^2
+                        + \\frac{|v|+|t|}
+                               {T}d(v,t)^2
+                        - \\frac{|v|}
+                               {T}d(s,t)^2}
+
+        where :math:`u` is the newly joined cluster consisting of
+        clusters :math:`s` and :math:`t`, :math:`v` is an unused
+        cluster in the forest, :math:`T=|v|+|s|+|t|`, and
+        :math:`|*|` is the cardinality of its argument. This is also
+        known as the incremental algorithm.
+
+    Warning: When the minimum distance pair in the forest is chosen, there
+    may be two or more pairs with the same minimum distance. This
+    implementation may choose a different minimum than the MATLAB
+    version.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed distance matrix
+        is a flat array containing the upper triangular of the distance matrix.
+        This is the form that ``pdist`` returns. Alternatively, a collection of
+        :math:`m` observation vectors in :math:`n` dimensions may be passed as
+        an :math:`m` by :math:`n` array. All elements of the condensed distance
+        matrix must be finite, i.e., no NaNs or infs.
+    method : str, optional
+        The linkage algorithm to use. See the ``Linkage Methods`` section below
+        for full descriptions.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+    optimal_ordering : bool, optional
+        If True, the linkage matrix will be reordered so that the distance
+        between successive leaves is minimal. This results in a more intuitive
+        tree structure when the data are visualized. defaults to False, because
+        this algorithm can be slow, particularly on large datasets [2]_. See
+        also the `optimal_leaf_ordering` function.
+
+        .. versionadded:: 1.0.0
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    Notes
+    -----
+    1. For method 'single', an optimized algorithm based on minimum spanning
+       tree is implemented. It has time complexity :math:`O(n^2)`.
+       For methods 'complete', 'average', 'weighted' and 'ward', an algorithm
+       called nearest-neighbors chain is implemented. It also has time
+       complexity :math:`O(n^2)`.
+       For other methods, a naive algorithm is implemented with :math:`O(n^3)`
+       time complexity.
+       All algorithms use :math:`O(n^2)` memory.
+       Refer to [1]_ for details about the algorithms.
+    2. Methods 'centroid', 'median', and 'ward' are correctly defined only if
+       Euclidean pairwise metric is used. If `y` is passed as precomputed
+       pairwise distances, then it is the user's responsibility to assure that
+       these distances are in fact Euclidean, otherwise the produced result
+       will be incorrect.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    References
+    ----------
+    .. [1] Daniel Mullner, "Modern hierarchical, agglomerative clustering
+           algorithms", :arXiv:`1109.2378v1`.
+    .. [2] Ziv Bar-Joseph, David K. Gifford, Tommi S. Jaakkola, "Fast optimal
+           leaf ordering for hierarchical clustering", 2001. Bioinformatics
+           :doi:`10.1093/bioinformatics/17.suppl_1.S22`
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import dendrogram, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+
+    >>> Z = linkage(X, 'ward')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+
+    >>> Z = linkage(X, 'single')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+    lazy = is_lazy_array(y)
+
+    if method not in _LINKAGE_METHODS:
+        raise ValueError(f"Invalid method: {method}")
+
+    if method in _EUCLIDEAN_METHODS and metric != 'euclidean' and y.ndim == 2:
+        msg = f"`method={method}` requires the distance metric to be Euclidean"
+        raise ValueError(msg)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (not lazy and y.shape[0] == y.shape[1]
+            and xp.all(xpx.isclose(xp.linalg.diagonal(y), 0))
+            and xp.all(y >= 0) and xp.all(xpx.isclose(y, y.T))):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+
+    if not lazy and not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    n = distance.num_obs_y(y)
+    method_code = _LINKAGE_METHODS[method]
+
+    def cy_linkage(y, validate):
+        if validate and not np.all(np.isfinite(y)):
+            raise ValueError("The condensed distance matrix must contain only "
+                            "finite values.")            
+
+        if method == 'single':
+            return _hierarchy.mst_single_linkage(y, n)
+        elif method in ('complete', 'average', 'weighted', 'ward'):
+            return _hierarchy.nn_chain(y, n, method_code)
+        else:
+            return _hierarchy.fast_linkage(y, n, method_code)
+
+    result = xpx.lazy_apply(cy_linkage, y, validate=lazy,
+                            shape=(n - 1, 4), dtype=xp.float64,
+                            as_numpy=True, xp=xp)
+
+    if optimal_ordering:
+        return optimal_leaf_ordering(result, y)
+    else:
+        return result
+
+
+class ClusterNode:
+    """
+    A tree node class for representing a cluster.
+
+    Leaf nodes correspond to original observations, while non-leaf nodes
+    correspond to non-singleton clusters.
+
+    The `to_tree` function converts a matrix returned by the linkage
+    function into an easy-to-use tree representation.
+
+    All parameter names are also attributes.
+
+    Parameters
+    ----------
+    id : int
+        The node id.
+    left : ClusterNode instance, optional
+        The left child tree node.
+    right : ClusterNode instance, optional
+        The right child tree node.
+    dist : float, optional
+        Distance for this cluster in the linkage matrix.
+    count : int, optional
+        The number of samples in this cluster.
+
+    See Also
+    --------
+    to_tree : for converting a linkage matrix ``Z`` into a tree object.
+
+    """
+
+    def __init__(self, id, left=None, right=None, dist=0.0, count=1):
+        if id < 0:
+            raise ValueError('The id must be non-negative.')
+        if dist < 0:
+            raise ValueError('The distance must be non-negative.')
+        if (left is None and right is not None) or \
+           (left is not None and right is None):
+            raise ValueError('Only full or proper binary trees are permitted.'
+                             '  This node has one child.')
+        if count < 1:
+            raise ValueError('A cluster must contain at least one original '
+                             'observation.')
+        self.id = id
+        self.left = left
+        self.right = right
+        self.dist = dist
+        if self.left is None:
+            self.count = count
+        else:
+            self.count = left.count + right.count
+
+    def __lt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist < node.dist
+
+    def __gt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist > node.dist
+
+    def __eq__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist == node.dist
+
+    def get_id(self):
+        """
+        The identifier of the target node.
+
+        For ``0 <= i < n``, `i` corresponds to original observation i.
+        For ``n <= i < 2n-1``, `i` corresponds to non-singleton cluster formed
+        at iteration ``i-n``.
+
+        Returns
+        -------
+        id : int
+            The identifier of the target node.
+
+        """
+        return self.id
+
+    def get_count(self):
+        """
+        The number of leaf nodes (original observations) belonging to
+        the cluster node nd. If the target node is a leaf, 1 is
+        returned.
+
+        Returns
+        -------
+        get_count : int
+            The number of leaf nodes below the target node.
+
+        """
+        return self.count
+
+    def get_left(self):
+        """
+        Return a reference to the left child tree object.
+
+        Returns
+        -------
+        left : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.left
+
+    def get_right(self):
+        """
+        Return a reference to the right child tree object.
+
+        Returns
+        -------
+        right : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.right
+
+    def is_leaf(self):
+        """
+        Return True if the target node is a leaf.
+
+        Returns
+        -------
+        leafness : bool
+            True if the target node is a leaf node.
+
+        """
+        return self.left is None
+
+    def pre_order(self, func=(lambda x: x.id)):
+        """
+        Perform pre-order traversal without recursive function calls.
+
+        When a leaf node is first encountered, ``func`` is called with
+        the leaf node as its argument, and its result is appended to
+        the list.
+
+        For example, the statement::
+
+           ids = root.pre_order(lambda x: x.id)
+
+        returns a list of the node ids corresponding to the leaf nodes
+        of the tree as they appear from left to right.
+
+        Parameters
+        ----------
+        func : function
+            Applied to each leaf ClusterNode object in the pre-order traversal.
+            Given the ``i``-th leaf node in the pre-order traversal ``n[i]``,
+            the result of ``func(n[i])`` is stored in ``L[i]``. If not
+            provided, the index of the original observation to which the node
+            corresponds is used.
+
+        Returns
+        -------
+        L : list
+            The pre-order traversal.
+
+        """
+        # Do a preorder traversal, caching the result. To avoid having to do
+        # recursion, we'll store the previous index we've visited in a vector.
+        n = self.count
+
+        curNode = [None] * (2 * n)
+        lvisited = set()
+        rvisited = set()
+        curNode[0] = self
+        k = 0
+        preorder = []
+        while k >= 0:
+            nd = curNode[k]
+            ndid = nd.id
+            if nd.is_leaf():
+                preorder.append(func(nd))
+                k = k - 1
+            else:
+                if ndid not in lvisited:
+                    curNode[k + 1] = nd.left
+                    lvisited.add(ndid)
+                    k = k + 1
+                elif ndid not in rvisited:
+                    curNode[k + 1] = nd.right
+                    rvisited.add(ndid)
+                    k = k + 1
+                # If we've visited the left and right of this non-leaf
+                # node already, go up in the tree.
+                else:
+                    k = k - 1
+
+        return preorder
+
+
+_cnode_bare = ClusterNode(0)
+_cnode_type = type(ClusterNode)
+
+
+def _order_cluster_tree(Z):
+    """
+    Return clustering nodes in bottom-up order by distance.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+
+    Returns
+    -------
+    nodes : list
+        A list of ClusterNode objects.
+    """
+    q = deque()
+    tree = to_tree(Z)
+    q.append(tree)
+    nodes = []
+
+    while q:
+        node = q.popleft()
+        if not node.is_leaf():
+            bisect.insort_left(nodes, node)
+            q.append(node.get_right())
+            q.append(node.get_left())
+    return nodes
+
+
+@xp_capabilities(np_only=True, reason="non-standard indexing")
+def cut_tree(Z, n_clusters=None, height=None):
+    """
+    Given a linkage matrix Z, return the cut tree.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+    n_clusters : array_like, optional
+        Number of clusters in the tree at the cut point.
+    height : array_like, optional
+        The height at which to cut the tree. Only possible for ultrametric
+        trees.
+
+    Returns
+    -------
+    cutree : array
+        An array indicating group membership at each agglomeration step. I.e.,
+        for a full cut tree, in the first column each data point is in its own
+        cluster. At the next step, two nodes are merged. Finally, all
+        singleton and non-singleton clusters are in one group. If `n_clusters`
+        or `height` are given, the columns correspond to the columns of
+        `n_clusters` or `height`.
+
+    Examples
+    --------
+    >>> from scipy import cluster
+    >>> import numpy as np
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+    >>> X = rng.random((50, 4))
+    >>> Z = cluster.hierarchy.ward(X)
+    >>> cutree = cluster.hierarchy.cut_tree(Z, n_clusters=[5, 10])
+    >>> cutree[:10]
+    array([[0, 0],
+           [1, 1],
+           [2, 2],
+           [3, 3],
+           [3, 4],
+           [2, 2],
+           [0, 0],
+           [1, 5],
+           [3, 6],
+           [4, 7]])  # random
+
+    """
+    xp = array_namespace(Z)
+    nobs = num_obs_linkage(Z)
+    nodes = _order_cluster_tree(Z)
+
+    if height is not None and n_clusters is not None:
+        raise ValueError("At least one of either height or n_clusters "
+                         "must be None")
+    elif height is None and n_clusters is None:  # return the full cut tree
+        cols_idx = xp.arange(nobs)
+    elif height is not None:
+        height = xp.asarray(height)
+        heights = xp.asarray([x.dist for x in nodes])
+        cols_idx = xp.searchsorted(heights, height)
+    else:
+        n_clusters = xp.asarray(n_clusters)
+        cols_idx = nobs - xp.searchsorted(xp.arange(nobs), n_clusters)
+
+    try:
+        n_cols = len(cols_idx)
+    except TypeError:  # scalar
+        n_cols = 1
+        cols_idx = xp.asarray([cols_idx])
+
+    groups = xp.zeros((n_cols, nobs), dtype=xp.int64)
+    last_group = xp.arange(nobs)
+    if 0 in cols_idx:
+        groups[0] = last_group
+
+    for i, node in enumerate(nodes):
+        idx = node.pre_order()
+        this_group = xp_copy(last_group, xp=xp)
+        # TODO ARRAY_API complex indexing not supported
+        this_group[idx] = xp.min(last_group[idx])
+        this_group[this_group > xp.max(last_group[idx])] -= 1
+        if i + 1 in cols_idx:
+            groups[np.nonzero(i + 1 == cols_idx)[0]] = this_group
+        last_group = this_group
+
+    return groups.T
+
+
+@xp_capabilities(jax_jit=False, allow_dask_compute=True)
+def to_tree(Z, rd=False):
+    """
+    Convert a linkage matrix into an easy-to-use tree object.
+
+    The reference to the root `ClusterNode` object is returned (by default).
+
+    Each `ClusterNode` object has a ``left``, ``right``, ``dist``, ``id``,
+    and ``count`` attribute. The left and right attributes point to
+    ClusterNode objects that were combined to generate the cluster.
+    If both are None then the `ClusterNode` object is a leaf node, its count
+    must be 1, and its distance is meaningless but set to 0.
+
+    *Note: This function is provided for the convenience of the library
+    user. ClusterNodes are not used as input to any of the functions in this
+    library.*
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix in proper form (see the `linkage`
+        function documentation).
+    rd : bool, optional
+        When False (default), a reference to the root `ClusterNode` object is
+        returned.  Otherwise, a tuple ``(r, d)`` is returned. ``r`` is a
+        reference to the root node while ``d`` is a list of `ClusterNode`
+        objects - one per original entry in the linkage matrix plus entries
+        for all clustering steps. If a cluster id is
+        less than the number of samples ``n`` in the data that the linkage
+        matrix describes, then it corresponds to a singleton cluster (leaf
+        node).
+        See `linkage` for more information on the assignment of cluster ids
+        to clusters.
+
+    Returns
+    -------
+    tree : ClusterNode or tuple (ClusterNode, list of ClusterNode)
+        If ``rd`` is False, a `ClusterNode`.
+        If ``rd`` is True, a list of length ``2*n - 1``, with ``n`` the number
+        of samples.  See the description of `rd` above for more details.
+
+    See Also
+    --------
+    linkage, is_valid_linkage, ClusterNode
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random((5, 2))
+    >>> Z = hierarchy.linkage(x)
+    >>> hierarchy.to_tree(Z)
+    >> rootnode, nodelist = hierarchy.to_tree(Z, rd=True)
+    >>> rootnode
+    >> len(nodelist)
+    9
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+
+    # Number of original objects is equal to the number of rows plus 1.
+    n = Z.shape[0] + 1
+
+    # Create a list full of None's to store the node objects
+    d = [None] * (n * 2 - 1)
+
+    # Create the nodes corresponding to the n original objects.
+    for i in range(0, n):
+        d[i] = ClusterNode(i)
+
+    nd = None
+
+    for i in range(Z.shape[0]):
+        row = Z[i, :]
+
+        fi = int_floor(row[0], xp)
+        fj = int_floor(row[1], xp)
+        if fi > i + n:
+            raise ValueError('Corrupt matrix Z. Index to derivative cluster '
+                              f'is used before it is formed. See row {fi}, '
+                              'column 0')
+        if fj > i + n:
+            raise ValueError('Corrupt matrix Z. Index to derivative cluster '
+                              f'is used before it is formed. See row {fj}, '
+                              'column 1')
+
+        nd = ClusterNode(i + n, d[fi], d[fj], row[2])
+        #                ^ id   ^ left ^ right ^ dist
+        if row[3] != nd.count:
+            raise ValueError(f'Corrupt matrix Z. The count Z[{i},3] is '
+                              'incorrect.')
+        d[n + i] = nd
+
+    if rd:
+        return (nd, d)
+    else:
+        return nd
+
+
+@lazy_cython
+def optimal_leaf_ordering(Z, y, metric='euclidean'):
+    """
+    Given a linkage matrix Z and distance, reorder the cut tree.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+    y : ndarray
+        The condensed distance matrix from which Z was generated.
+        Alternatively, a collection of m observation vectors in n
+        dimensions may be passed as an m by n array.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+
+    Returns
+    -------
+    Z_ordered : ndarray
+        A copy of the linkage matrix Z, reordered to minimize the distance
+        between adjacent leaves.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> X = rng.standard_normal((10, 10))
+    >>> Z = hierarchy.ward(X)
+    >>> hierarchy.leaves_list(Z)
+    array([0, 3, 1, 9, 2, 5, 7, 4, 6, 8], dtype=int32)
+    >>> hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, X))
+    array([3, 0, 2, 5, 7, 4, 8, 6, 9, 1], dtype=int32)
+
+    """
+    xp = array_namespace(Z, y)
+    Z = _asarray(Z, order='C', xp=xp)
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+    lazy = is_lazy_array(Z)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (not lazy and y.shape[0] == y.shape[1]
+            and xp.all(xpx.isclose(xp.linalg.diagonal(y), 0))
+            and xp.all(y >= 0) and xp.all(xpx.isclose(y, y.T))):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+    if not lazy and not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    # The function name is prominently visible on the user-facing Dask dashboard;
+    # make sure it is meaningful.
+    def cy_optimal_leaf_ordering(Z, y, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            if not np.all(np.isfinite(y)):
+                raise ValueError("The condensed distance matrix must contain only "
+                                 "finite values.")
+        return _optimal_leaf_ordering.optimal_leaf_ordering(Z, y)
+
+    return xpx.lazy_apply(cy_optimal_leaf_ordering, Z, y, validate=lazy,
+                          shape=Z.shape, dtype=Z.dtype, as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def cophenet(Z, Y=None):
+    """
+    Calculate the cophenetic distances between each observation in
+    the hierarchical clustering defined by the linkage ``Z``.
+
+    Suppose ``p`` and ``q`` are original observations in
+    disjoint clusters ``s`` and ``t``, respectively and
+    ``s`` and ``t`` are joined by a direct parent cluster
+    ``u``. The cophenetic distance between observations
+    ``i`` and ``j`` is simply the distance between
+    clusters ``s`` and ``t``.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as an array
+        (see `linkage` function).
+    Y : ndarray (optional)
+        Calculates the cophenetic correlation coefficient ``c`` of a
+        hierarchical clustering defined by the linkage matrix `Z`
+        of a set of :math:`n` observations in :math:`m`
+        dimensions. `Y` is the condensed distance matrix from which
+        `Z` was generated.
+
+    Returns
+    -------
+    c : ndarray
+        The cophentic correlation distance (if ``Y`` is passed).
+    d : ndarray
+        The cophenetic distance matrix in condensed form. The
+        :math:`ij` th entry is the cophenetic distance between
+        original observations :math:`i` and :math:`j`.
+
+    See Also
+    --------
+    linkage :
+        for a description of what a linkage matrix is.
+    scipy.spatial.distance.squareform :
+        transforming condensed matrices into square ones.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, cophenet
+    >>> from scipy.spatial.distance import pdist, squareform
+
+    Given a dataset ``X`` and a linkage matrix ``Z``, the cophenetic distance
+    between two points of ``X`` is the distance between the largest two
+    distinct clusters that each of the points:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    ``X`` corresponds to this dataset ::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> Z = single(pdist(X))
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+    >>> cophenet(Z)
+    array([1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 2., 2., 2., 2., 2.,
+           2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 2., 2.,
+           2., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
+           1., 1., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 1., 1., 1.])
+
+    The output of the `scipy.cluster.hierarchy.cophenet` method is
+    represented in condensed form. We can use
+    `scipy.spatial.distance.squareform` to see the output as a
+    regular matrix (where each element ``ij`` denotes the cophenetic distance
+    between each ``i``, ``j`` pair of points in ``X``):
+
+    >>> squareform(cophenet(Z))
+    array([[0., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 0., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 1., 0., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 0., 1., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 0., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 1., 0., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 0., 1., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 0., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 1., 0., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 0., 1., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 0., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 0.]])
+
+    In this example, the cophenetic distance between points on ``X`` that are
+    very close (i.e., in the same corner) is 1. For other pairs of points is 2,
+    because the points will be located in clusters at different
+    corners - thus, the distance between these clusters will be larger.
+
+    """
+    xp = array_namespace(Z, Y)
+    # Ensure float64 C-contiguous array. Cython code doesn't deal with striding.
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_cophenet(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n = Z.shape[0] + 1
+        zz = np.zeros((n * (n-1)) // 2, dtype=np.float64)
+        _hierarchy.cophenetic_distances(Z, zz, n)
+        return zz
+    
+    n = Z.shape[0] + 1
+    zz = xpx.lazy_apply(cy_cophenet, Z, validate=is_lazy_array(Z),
+                        shape=((n * (n-1)) // 2, ), dtype=xp.float64,
+                        as_numpy=True, xp=xp)
+                        
+    if Y is None:
+        return zz
+
+    Y = _asarray(Y, order='C', xp=xp)
+    distance.is_valid_y(Y, throw=True, name='Y')
+
+    z = xp.mean(zz)
+    y = xp.mean(Y)
+    Yy = Y - y
+    Zz = zz - z
+    numerator = (Yy * Zz)
+    denomA = Yy**2
+    denomB = Zz**2
+    c = xp.sum(numerator) / xp.sqrt(xp.sum(denomA) * xp.sum(denomB))
+    return (c, zz)
+
+
+@lazy_cython
+def inconsistent(Z, d=2):
+    r"""
+    Calculate inconsistency statistics on a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical
+        clustering).  See `linkage` documentation for more information on its
+        form.
+    d : int, optional
+        The number of links up to `d` levels below each non-singleton cluster.
+
+    Returns
+    -------
+    R : ndarray
+        A :math:`(n-1)` by 4 matrix where the ``i``'th row contains the link
+        statistics for the non-singleton cluster ``i``. The link statistics are
+        computed over the link heights for links :math:`d` levels below the
+        cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard
+        deviation of the link heights, respectively; ``R[i,2]`` is the number
+        of links included in the calculation; and ``R[i,3]`` is the
+        inconsistency coefficient,
+
+        .. math:: \frac{\mathtt{Z[i,2]} - \mathtt{R[i,0]}} {R[i,1]}
+
+    Notes
+    -----
+    This function behaves similarly to the MATLAB(TM) ``inconsistent``
+    function.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import inconsistent, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+    >>> Z = linkage(X, 'ward')
+    >>> print(Z)
+    [[ 5.          6.          0.          2.        ]
+     [ 2.          7.          0.          2.        ]
+     [ 0.          4.          1.          2.        ]
+     [ 1.          8.          1.15470054  3.        ]
+     [ 9.         10.          2.12132034  4.        ]
+     [ 3.         12.          4.11096096  5.        ]
+     [11.         13.         14.07183949  8.        ]]
+    >>> inconsistent(Z)
+    array([[ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 1.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.57735027,  0.81649658,  2.        ,  0.70710678],
+           [ 1.04044011,  1.06123822,  3.        ,  1.01850858],
+           [ 3.11614065,  1.40688837,  2.        ,  0.70710678],
+           [ 6.44583366,  6.76770586,  3.        ,  1.12682288]])
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if d != np.floor(d) or d < 0:
+        raise ValueError('The second argument d must be a nonnegative '
+                         'integer value.')
+
+    def cy_inconsistent(Z, d, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        R = np.zeros((Z.shape[0], 4), dtype=np.float64)
+        n = Z.shape[0] + 1
+        _hierarchy.inconsistent(Z, R, n, d)
+        return R
+
+    return xpx.lazy_apply(cy_inconsistent, Z, d=int(d), validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], 4), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def from_mlab_linkage(Z):
+    """
+    Convert a linkage matrix generated by MATLAB(TM) to a new
+    linkage matrix compatible with this module.
+
+    The conversion does two things:
+
+     * the indices are converted from ``1..N`` to ``0..(N-1)`` form,
+       and
+
+     * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the
+       number of original observations (leaves) in the non-singleton
+       cluster ``i``.
+
+    This function is useful when loading in linkages from legacy data
+    files generated by MATLAB.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by MATLAB(TM).
+
+    Returns
+    -------
+    ZS : ndarray
+        A linkage matrix compatible with ``scipy.cluster.hierarchy``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    to_mlab_linkage : transform from SciPy to MATLAB format.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.hierarchy import ward, from_mlab_linkage
+
+    Given a linkage matrix in MATLAB format ``mZ``, we can use
+    `scipy.cluster.hierarchy.from_mlab_linkage` to import
+    it into SciPy format:
+
+    >>> mZ = np.array([[1, 2, 1], [4, 5, 1], [7, 8, 1],
+    ...                [10, 11, 1], [3, 13, 1.29099445],
+    ...                [6, 14, 1.29099445],
+    ...                [9, 15, 1.29099445],
+    ...                [12, 16, 1.29099445],
+    ...                [17, 18, 5.77350269],
+    ...                [19, 20, 5.77350269],
+    ...                [21, 22,  8.16496581]])
+
+    >>> Z = from_mlab_linkage(mZ)
+    >>> Z
+    array([[  0.        ,   1.        ,   1.        ,   2.        ],
+           [  3.        ,   4.        ,   1.        ,   2.        ],
+           [  6.        ,   7.        ,   1.        ,   2.        ],
+           [  9.        ,  10.        ,   1.        ,   2.        ],
+           [  2.        ,  12.        ,   1.29099445,   3.        ],
+           [  5.        ,  13.        ,   1.29099445,   3.        ],
+           [  8.        ,  14.        ,   1.29099445,   3.        ],
+           [ 11.        ,  15.        ,   1.29099445,   3.        ],
+           [ 16.        ,  17.        ,   5.77350269,   6.        ],
+           [ 18.        ,  19.        ,   5.77350269,   6.        ],
+           [ 20.        ,  21.        ,   8.16496581,  12.        ]])
+
+    As expected, the linkage matrix ``Z`` returned includes an
+    additional column counting the number of original samples in
+    each cluster. Also, all cluster indices are reduced by 1
+    (MATLAB format uses 1-indexing, whereas SciPy uses 0-indexing).
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, dtype=xp.float64, order='C', xp=xp)
+
+    # If it's empty, return it.
+    if Z.shape in ((), (0, )):
+        return xp_copy(Z, xp=xp)
+
+    if Z.ndim != 2:
+        raise ValueError("The linkage array must be rectangular.")
+
+    # If it contains no rows, return it.
+    n = Z.shape[0]
+    if n == 0:
+        return xp_copy(Z, xp=xp)
+
+    lazy = is_lazy_array(Z)
+
+    if not lazy and xp.min(Z[:, :2]) != 1.0 and xp.max(Z[:, :2]) != 2 * n:
+        raise ValueError('The format of the indices is not 1..N')
+
+    res = xp.empty((Z.shape[0], Z.shape[1] + 1), dtype=Z.dtype)
+    res = xpx.at(res)[:, :2].set(Z[:, :2] - 1.0)
+    res = xpx.at(res)[:, 2:-1].set(Z[:, 2:])
+
+    def cy_from_mlab_linkage(Zpart, validate):
+        n = Zpart.shape[0]
+        if validate and np.min(Zpart[:, :2]) != 0.0 and np.max(Zpart[:, :2]) != 2 * n:
+            raise ValueError('The format of the indices is not 1..N')
+
+        if not Zpart.flags.writeable:
+            Zpart = Zpart.copy()  # xp=jax.numpy
+
+        CS = np.zeros((n,))
+        _hierarchy.calculate_cluster_sizes(Zpart, CS, n + 1)
+        return CS
+
+    CS = xpx.lazy_apply(cy_from_mlab_linkage, res[:, :-1], validate=lazy,
+                        shape=(res.shape[0],), dtype=xp.float64,
+                        as_numpy=True, xp=xp)
+
+    return xpx.at(res)[:, -1].set(CS)
+
+
+@xp_capabilities()
+def to_mlab_linkage(Z):
+    """
+    Convert a linkage matrix to a MATLAB(TM) compatible one.
+
+    Converts a linkage matrix ``Z`` generated by the linkage function
+    of this module to a MATLAB(TM) compatible one. The return linkage
+    matrix has the last column removed and the cluster indices are
+    converted to ``1..N`` indexing.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by ``scipy.cluster.hierarchy``.
+
+    Returns
+    -------
+    to_mlab_linkage : ndarray
+        A linkage matrix compatible with MATLAB(TM)'s hierarchical
+        clustering functions.
+
+        The return linkage matrix has the last column removed
+        and the cluster indices are converted to ``1..N`` indexing.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    from_mlab_linkage : transform from Matlab to SciPy format.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, to_mlab_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    After a linkage matrix ``Z`` has been created, we can use
+    `scipy.cluster.hierarchy.to_mlab_linkage` to convert it
+    into MATLAB format:
+
+    >>> mZ = to_mlab_linkage(Z)
+    >>> mZ
+    array([[  1.        ,   2.        ,   1.        ],
+           [  4.        ,   5.        ,   1.        ],
+           [  7.        ,   8.        ,   1.        ],
+           [ 10.        ,  11.        ,   1.        ],
+           [  3.        ,  13.        ,   1.29099445],
+           [  6.        ,  14.        ,   1.29099445],
+           [  9.        ,  15.        ,   1.29099445],
+           [ 12.        ,  16.        ,   1.29099445],
+           [ 17.        ,  18.        ,   5.77350269],
+           [ 19.        ,  20.        ,   5.77350269],
+           [ 21.        ,  22.        ,   8.16496581]])
+
+    The new linkage matrix ``mZ`` uses 1-indexing for all the
+    clusters (instead of 0-indexing). Also, the last column of
+    the original linkage matrix has been dropped.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, dtype=xp.float64, xp=xp)
+    if Z.shape in ((), (0, )):
+        return xp_copy(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    return xp.concat((Z[:, :2] + 1.0, Z[:, 2:3]), axis=1)
+
+
+@xp_capabilities()
+def is_monotonic(Z):
+    """
+    Return True if the linkage passed is monotonic.
+
+    The linkage is monotonic if for every cluster :math:`s` and :math:`t`
+    joined, the distance between them is no less than the distance
+    between any previously joined clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix to check for monotonicity.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage is monotonic.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, ward, is_monotonic
+    >>> from scipy.spatial.distance import pdist
+
+    By definition, some hierarchical clustering algorithms - such as
+    `scipy.cluster.hierarchy.ward` - produce monotonic assignments of
+    samples to clusters; however, this is not always true for other
+    hierarchical methods - e.g. `scipy.cluster.hierarchy.median`.
+
+    Given a linkage matrix ``Z`` (as the result of a hierarchical clustering
+    method) we can test programmatically whether it has the monotonicity
+    property or not, using `scipy.cluster.hierarchy.is_monotonic`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_monotonic(Z)
+    True
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> is_monotonic(Z)
+    False
+
+    Note that this method is equivalent to just verifying that the distances
+    in the third column of the linkage matrix appear in a monotonically
+    increasing order.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    # We expect the i'th value to be greater than its successor.
+    return xp.all(Z[1:, 2] >= Z[:-1, 2])
+
+
+@xp_capabilities(warnings=[("dask.array", "see notes"), ("jax.numpy", "see notes")])
+def is_valid_im(R, warning=False, throw=False, name=None):
+    """Return True if the inconsistency matrix passed is valid.
+
+    It must be a :math:`n` by 4 array of doubles. The standard
+    deviations ``R[:,1]`` must be nonnegative. The link counts
+    ``R[:,2]`` must be positive and no greater than :math:`n-1`.
+
+    Parameters
+    ----------
+    R : ndarray
+        The inconsistency matrix to check for validity.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid; False otherwise.
+
+    Notes
+    -----
+    *Array API support (experimental):* If the input is a lazy Array (e.g. Dask
+    or JAX), the return value may be a 0-dimensional bool Array. When warning=True
+    or throw=True, calling this function materializes the array.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, inconsistent, is_valid_im
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [6.57065706, 1.38071187, 3.        , 1.15470054]])
+
+    Now we can use `scipy.cluster.hierarchy.is_valid_im` to verify that
+    ``R`` is correct:
+
+    >>> is_valid_im(R)
+    True
+
+    However, if ``R`` is wrongly constructed (e.g., one of the standard
+    deviations is set to a negative value), then the check will fail:
+
+    >>> R[-1,1] = R[-1,1] * -1
+    >>> is_valid_im(R)
+    False
+
+    """
+    xp = array_namespace(R)
+    R = _asarray(R, xp=xp)
+    return _is_valid_im(R, warning=warning, throw=throw, name=name,
+                        materialize=True, xp=xp)
+
+
+def _is_valid_im(R, warning=False, throw=False, name=None, materialize=False, *, xp):
+    """Variant of `is_valid_im` to be called internally by other scipy functions,
+    which by default does not materialize lazy input arrays (Dask, JAX, etc.) when
+    warning=True or throw=True.
+    """
+    name_str = f"{name!r} " if name else ''
+    try:
+        if R.dtype != xp.float64:
+            raise TypeError(f'Inconsistency matrix {name_str}must contain doubles '
+                            '(double).')
+        if len(R.shape) != 2:
+            raise ValueError(f'Inconsistency matrix {name_str}must have shape=2 (i.e. '
+                             'be two-dimensional).')
+        if R.shape[1] != 4:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have 4 columns.')
+        if R.shape[0] < 1:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have at least one row.')
+    except (TypeError, ValueError) as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        return False
+
+    return _lazy_valid_checks(
+        (xp.any(R[:, 0] < 0),
+         f'Inconsistency matrix {name_str} contains negative link height means.'),
+        (xp.any(R[:, 1] < 0),
+         f'Inconsistency matrix {name_str} contains negative link height standard '
+         'deviations.'),
+        (xp.any(R[:, 2] < 0),
+         f'Inconsistency matrix {name_str} contains negative link counts.'),
+        throw=throw, warning=warning, materialize=materialize, xp=xp
+    )
+
+
+@xp_capabilities(warnings=[("dask.array", "see notes"), ("jax.numpy", "see notes")])
+def is_valid_linkage(Z, warning=False, throw=False, name=None):
+    """
+    Check the validity of a linkage matrix.
+
+    A linkage matrix is valid if it is a 2-D array (type double)
+    with :math:`n` rows and 4 columns. The first two columns must contain
+    indices between 0 and :math:`2n-1`. For a given row ``i``, the following
+    two expressions have to hold:
+
+    .. math::
+
+        0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1
+        0 \\leq Z[i,1] \\leq i+n-1
+
+    I.e., a cluster cannot join another cluster unless the cluster being joined
+    has been generated.
+
+    The fourth column of `Z` represents the number of original observations
+    in a cluster, so a valid ``Z[i, 3]`` value may not exceed the number of
+    original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        Linkage matrix.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid; False otherwise.
+
+    Notes
+    -----
+    *Array API support (experimental):* If the input is a lazy Array (e.g. Dask
+    or JAX), the return value may be a 0-dimensional bool Array. When warning=True
+    or throw=True, calling this function materializes the array.
+
+    See Also
+    --------
+    linkage: for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, is_valid_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    All linkage matrices generated by the clustering methods in this module
+    will be valid (i.e., they will have the appropriate dimensions and the two
+    required expressions will hold for all the rows).
+
+    We can check this using `scipy.cluster.hierarchy.is_valid_linkage`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_valid_linkage(Z)
+    True
+
+    However, if we create a linkage matrix in a wrong way - or if we modify
+    a valid one in a way that any of the required expressions don't hold
+    anymore, then the check will fail:
+
+    >>> Z[3][1] = 20    # the cluster number 20 is not defined at this point
+    >>> is_valid_linkage(Z)
+    False
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    return _is_valid_linkage(Z, warning=warning, throw=throw,
+                             name=name, materialize=True, xp=xp)
+
+
+def _is_valid_linkage(Z, warning=False, throw=False, name=None,
+                      materialize=False, *, xp):
+    """Variant of `is_valid_linkage` to be called internally by other scipy functions,
+    which by default does not materialize lazy input arrays (Dask, JAX, etc.) when
+    warning=True or throw=True.
+    """
+    name_str = f"{name!r} " if name else ''
+    try:
+        if Z.dtype != xp.float64:
+            raise TypeError(f'Linkage matrix {name_str}must contain doubles.')
+        if len(Z.shape) != 2:
+            raise ValueError(f'Linkage matrix {name_str}must have shape=2 (i.e. be'
+                             ' two-dimensional).')
+        if Z.shape[1] != 4:
+            raise ValueError(f'Linkage matrix {name_str}must have 4 columns.')
+        if Z.shape[0] == 0:
+            raise ValueError('Linkage must be computed on at least two '
+                             'observations.')
+    except (TypeError, ValueError) as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        return False
+
+    n = Z.shape[0]
+    if n < 2:
+        return True
+
+    return _lazy_valid_checks(
+        (xp.any(Z[:, :2] < 0),
+         f'Linkage {name_str}contains negative indices.'),
+        (xp.any(Z[:, 2] < 0),
+         f'Linkage {name_str}contains negative distances.'),
+        (xp.any(Z[:, 3] < 0),
+         f'Linkage {name_str}contains negative counts.'),
+        (xp.any(Z[:, 3] > n + 1),
+         f'Linkage {name_str}contains excessive observations in a cluster'),
+        (xp.any(xp.max(Z[:, :2], axis=1) >= xp.arange(n + 1, 2 * n + 1, dtype=Z.dtype)),
+         f'Linkage {name_str}uses non-singleton cluster before it is formed.'),
+        (xpx.nunique(Z[:, :2]) < n * 2,
+         f'Linkage {name_str}uses the same cluster more than once.'),
+        throw=throw, warning=warning, materialize=materialize, xp=xp
+    )
+
+
+def _lazy_valid_checks(*args, throw=False, warning=False, materialize=False, xp):
+    """Validate a set of conditions on the contents of possibly lazy arrays.
+
+    Parameters
+    ----------
+    args : tuples of (Array, str)
+        The first element of each tuple must be a 0-dimensional Array
+        that evaluates to bool; the second element must be the message to convey
+        if the  first element evaluates to True.
+    throw: bool
+        Set to True to `raise ValueError(args[i][1])` if `args[i][0]` is True.
+    warning: bool
+        Set to True to issue a warning with message `args[i][1]` if `args[i][0]`
+        is True.
+    materialize: bool
+        Set to True to force materialization of lazy arrays when throw=True or
+        warning=True. If the inputs are lazy and materialize=False, ignore the
+        `throw` and `warning` flags.
+    xp: module
+        Array API namespace
+
+    Returns
+    -------
+    If xp is an eager backend (e.g. numpy) and all conditions are False, return True.
+    If throw is True, raise. Otherwise, return False.
+
+    If xp is a lazy backend (e.g. Dask or JAX), return a 0-dimensional bool Array.
+    """
+    conds = xp.concat([xp.reshape(cond, (1, )) for cond, _ in args])
+
+    lazy = is_lazy_array(conds)
+    if not throw and not warning or (lazy and not materialize):
+        out = ~xp.any(conds)
+        return out if lazy else bool(out)
+
+    if is_dask(xp):
+        # Only materialize the graph once, instead of once per check
+        conds = conds.compute()
+
+    # Don't call np.asarray(conds), as it would be blocked by the device transfer
+    # guard on CuPy and PyTorch and the densification guard on Sparse, whereas
+    # bool() will not.
+    conds = [bool(cond) for cond in conds]
+
+    for cond, (_, msg) in zip(conds, args):
+        if throw and cond:
+            raise ValueError(msg)
+        elif warning and cond:
+            warnings.warn(msg, ClusterWarning, stacklevel=3)
+
+    return not any(conds)
+
+
+@xp_capabilities()
+def num_obs_linkage(Z):
+    """
+    Return the number of original observations of the linkage matrix passed.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix on which to perform the operation.
+
+    Returns
+    -------
+    n : int
+        The number of original observations in the linkage.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, num_obs_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    ``Z`` is a linkage matrix obtained after using the Ward clustering method
+    with ``X``, a dataset with 12 data points.
+
+    >>> num_obs_linkage(Z)
+    12
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    return Z.shape[0] + 1
+
+
+@xp_capabilities()
+def correspond(Z, Y):
+    """
+    Check for correspondence between linkage and condensed distance matrices.
+
+    They must have the same number of original observations for
+    the check to succeed.
+
+    This function is useful as a sanity check in algorithms that make
+    extensive use of linkage and distance matrices that must
+    correspond to the same set of original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        The linkage matrix to check for correspondence.
+    Y : array_like
+        The condensed distance matrix to check for correspondence.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage matrix and distance
+        matrix could possibly correspond to one another.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, correspond
+    >>> from scipy.spatial.distance import pdist
+
+    This method can be used to check if a given linkage matrix ``Z`` has been
+    obtained from the application of a cluster method over a dataset ``X``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+    >>> X_condensed = pdist(X)
+    >>> Z = ward(X_condensed)
+
+    Here, we can compare ``Z`` and ``X`` (in condensed form):
+
+    >>> correspond(Z, X_condensed)
+    True
+
+    """
+    xp = array_namespace(Z, Y)
+    Z = _asarray(Z, xp=xp)
+    Y = _asarray(Y, xp=xp)
+    _is_valid_linkage(Z, throw=True, xp=xp)
+    distance.is_valid_y(Y, throw=True)
+    return distance.num_obs_y(Y) == num_obs_linkage(Z)
+
+
+@xp_capabilities(cpu_only=True, reason="Cython code",
+                 jax_jit=False, allow_dask_compute=True)
+def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None):
+    """
+    Form flat clusters from the hierarchical clustering defined by
+    the given linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded with the matrix returned
+        by the `linkage` function.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        The criterion to use in forming flat clusters. This can
+        be any of the following values:
+
+          ``inconsistent`` :
+              If a cluster node and all its
+              descendants have an inconsistent value less than or equal
+              to `t`, then all its leaf descendants belong to the
+              same flat cluster. When no non-singleton cluster meets
+              this criterion, every node is assigned to its own
+              cluster. (Default)
+
+          ``distance`` :
+              Forms flat clusters so that the original
+              observations in each flat cluster have no greater a
+              cophenetic distance than `t`.
+
+          ``maxclust`` :
+              Finds a minimum threshold ``r`` so that
+              the cophenetic distance between any two original
+              observations in the same flat cluster is no more than
+              ``r`` and no more than `t` flat clusters are formed.
+
+          ``monocrit`` :
+              Forms a flat cluster from a cluster node c
+              with index i when ``monocrit[j] <= t``.
+
+              For example, to threshold on the maximum mean distance
+              as computed in the inconsistency matrix R with a
+              threshold of 0.8 do::
+
+                  MR = maxRstat(Z, R, 3)
+                  fcluster(Z, t=0.8, criterion='monocrit', monocrit=MR)
+
+          ``maxclust_monocrit`` :
+              Forms a flat cluster from a
+              non-singleton cluster node ``c`` when ``monocrit[i] <=
+              r`` for all cluster indices ``i`` below and including
+              ``c``. ``r`` is minimized such that no more than ``t``
+              flat clusters are formed. monocrit must be
+              monotonic. For example, to minimize the threshold t on
+              maximum inconsistency values so that no more than 3 flat
+              clusters are formed, do::
+
+                  MI = maxinconsts(Z, R)
+                  fcluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI)
+    depth : int, optional
+        The maximum depth to perform the inconsistency calculation.
+        It has no meaning for the other criteria. Default is 2.
+    R : ndarray, optional
+        The inconsistency matrix to use for the ``'inconsistent'``
+        criterion. This matrix is computed if not provided.
+    monocrit : ndarray, optional
+        An array of length n-1. `monocrit[i]` is the
+        statistics upon which non-singleton i is thresholded. The
+        monocrit vector must be monotonic, i.e., given a node c with
+        index i, for all node indices j corresponding to nodes
+        below c, ``monocrit[i] >= monocrit[j]``.
+
+    Returns
+    -------
+    fcluster : ndarray
+        An array of length ``n``. ``T[i]`` is the flat cluster number to
+        which original observation ``i`` belongs.
+
+    See Also
+    --------
+    linkage : for information about hierarchical clustering methods work.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    All cluster linkage methods - e.g., `scipy.cluster.hierarchy.ward`
+    generate a linkage matrix ``Z`` as their output:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    This matrix represents a dendrogram, where the first and second elements
+    are the two clusters merged at each step, the third element is the
+    distance between these clusters, and the fourth element is the size of
+    the new cluster - the number of original data points included.
+
+    `scipy.cluster.hierarchy.fcluster` can be used to flatten the
+    dendrogram, obtaining as a result an assignation of the original data
+    points to single clusters.
+
+    This assignation mostly depends on a distance threshold ``t`` - the maximum
+    inter-cluster distance allowed:
+
+    >>> fcluster(Z, t=0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+
+    >>> fcluster(Z, t=1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+
+    >>> fcluster(Z, t=3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    >>> fcluster(Z, t=9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    In the first case, the threshold ``t`` is too small to allow any two
+    samples in the data to form a cluster, so 12 different clusters are
+    returned.
+
+    In the second case, the threshold is large enough to allow the first
+    4 points to be merged with their nearest neighbors. So, here, only 8
+    clusters are returned.
+
+    The third case, with a much higher threshold, allows for up to 8 data
+    points to be connected - so 4 clusters are returned here.
+
+    Lastly, the threshold of the fourth case is large enough to allow for
+    all data points to be merged together - so a single cluster is returned.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+
+    n = Z.shape[0] + 1
+    T = np.zeros((n,), dtype='i')
+
+    if monocrit is not None:
+        monocrit = np.asarray(monocrit, order='C', dtype=np.float64)
+
+    Z = np.asarray(Z)
+    monocrit = np.asarray(monocrit)
+    if criterion == 'inconsistent':
+        if R is None:
+            R = inconsistent(Z, depth)
+        else:
+            R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+            _is_valid_im(R, throw=True, name='R', materialize=True, xp=xp)
+            # Since the C code does not support striding using strides.
+            # The dimensions are used instead.
+            R = np.asarray(R)
+        _hierarchy.cluster_in(Z, R, T, float(t), int(n))
+    elif criterion == 'distance':
+        _hierarchy.cluster_dist(Z, T, float(t), int(n))
+    elif criterion == 'maxclust':
+        _hierarchy.cluster_maxclust_dist(Z, T, int(n), t)
+    elif criterion == 'monocrit':
+        _hierarchy.cluster_monocrit(Z, monocrit, T, float(t), int(n))
+    elif criterion == 'maxclust_monocrit':
+        _hierarchy.cluster_maxclust_monocrit(Z, monocrit, T, int(n), int(t))
+    else:
+        raise ValueError(f'Invalid cluster formation criterion: {str(criterion)}')
+    return xp.asarray(T)
+
+
+@xp_capabilities(cpu_only=True, reason="Cython code",
+                 jax_jit=False, allow_dask_compute=True)
+def fclusterdata(X, t, criterion='inconsistent',
+                 metric='euclidean', depth=2, method='single', R=None):
+    """
+    Cluster observation data using a given metric.
+
+    Clusters the original observations in the n-by-m data
+    matrix X (n observations in m dimensions), using the euclidean
+    distance metric to calculate distances between original observations,
+    performs hierarchical clustering using the single linkage algorithm,
+    and forms flat clusters using the inconsistency method with `t` as the
+    cut-off threshold.
+
+    A 1-D array ``T`` of length ``n`` is returned. ``T[i]`` is
+    the index of the flat cluster to which the original observation ``i``
+    belongs.
+
+    Parameters
+    ----------
+    X : (N, M) ndarray
+        N by M data matrix with N observations in M dimensions.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        Specifies the criterion for forming flat clusters. Valid
+        values are 'inconsistent' (default), 'distance', or 'maxclust'
+        cluster formation algorithms. See `fcluster` for descriptions.
+    metric : str or function, optional
+        The distance metric for calculating pairwise distances. See
+        ``distance.pdist`` for descriptions and linkage to verify
+        compatibility with the linkage method.
+    depth : int, optional
+        The maximum depth for the inconsistency calculation. See
+        `inconsistent` for more information.
+    method : str, optional
+        The linkage method to use (single, complete, average,
+        weighted, median centroid, ward). See `linkage` for more
+        information. Default is "single".
+    R : ndarray, optional
+        The inconsistency matrix. It will be computed if necessary
+        if it is not passed.
+
+    Returns
+    -------
+    fclusterdata : ndarray
+        A vector of length n. T[i] is the flat cluster number to
+        which original observation i belongs.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Notes
+    -----
+    This function is similar to the MATLAB function ``clusterdata``.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fclusterdata
+
+    This is a convenience method that abstracts all the steps to perform in a
+    typical SciPy's hierarchical clustering workflow.
+
+    * Transform the input data into a condensed matrix with
+      `scipy.spatial.distance.pdist`.
+
+    * Apply a clustering method.
+
+    * Obtain flat clusters at a user defined distance threshold ``t`` using
+      `scipy.cluster.hierarchy.fcluster`.
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> fclusterdata(X, t=1)
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    The output here (for the dataset ``X``, distance threshold ``t``, and the
+    default settings) is four clusters with three data points each.
+
+    """
+    xp = array_namespace(X)
+    X = _asarray(X, order='C', dtype=xp.float64, xp=xp)
+
+    if X.ndim != 2:
+        raise TypeError('The observation matrix X must be an n by m array.')
+
+    Y = distance.pdist(X, metric=metric)
+    Z = linkage(Y, method=method)
+    if R is None:
+        R = inconsistent(Z, d=depth)
+    else:
+        R = _asarray(R, order='C', xp=xp)
+    T = fcluster(Z, criterion=criterion, depth=depth, R=R, t=t)
+    return T
+
+
+@lazy_cython
+def leaves_list(Z):
+    """
+    Return a list of leaf node ids.
+
+    The return corresponds to the observation vector index as it appears
+    in the tree from left to right. Z is a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix.  `Z` is
+        a linkage matrix.  See `linkage` for more information.
+
+    Returns
+    -------
+    leaves_list : ndarray
+        The list of leaf node ids.
+
+    See Also
+    --------
+    dendrogram : for information about dendrogram structure.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, dendrogram, leaves_list
+    >>> from scipy.spatial.distance import pdist
+    >>> from matplotlib import pyplot as plt
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    The linkage matrix ``Z`` represents a dendrogram, that is, a tree that
+    encodes the structure of the clustering performed.
+    `scipy.cluster.hierarchy.leaves_list` shows the mapping between
+    indices in the ``X`` dataset and leaves in the dendrogram:
+
+    >>> leaves_list(Z)
+    array([ 2,  0,  1,  5,  3,  4,  8,  6,  7, 11,  9, 10], dtype=int32)
+
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_leaves_list(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n = Z.shape[0] + 1
+        ML = np.zeros((n,), dtype=np.int32)
+        _hierarchy.prelist(Z, ML, n)
+        return ML
+
+    n = Z.shape[0] + 1
+    return xpx.lazy_apply(cy_leaves_list, Z, validate=is_lazy_array(Z),
+                          shape=(n, ), dtype=xp.int32,
+                          as_numpy=True, xp=xp)
+
+
+# Maps number of leaves to text size.
+#
+# p <= 20, size="12"
+# 20 < p <= 30, size="10"
+# 30 < p <= 50, size="8"
+# 50 < p <= np.inf, size="6"
+
+_dtextsizes = {20: 12, 30: 10, 50: 8, 85: 6, np.inf: 5}
+_drotation = {20: 0, 40: 45, np.inf: 90}
+_dtextsortedkeys = list(_dtextsizes.keys())
+_dtextsortedkeys.sort()
+_drotationsortedkeys = list(_drotation.keys())
+_drotationsortedkeys.sort()
+
+
+def _remove_dups(L):
+    """
+    Remove duplicates AND preserve the original order of the elements.
+
+    The set class is not guaranteed to do this.
+    """
+    seen_before = set()
+    L2 = []
+    for i in L:
+        if i not in seen_before:
+            seen_before.add(i)
+            L2.append(i)
+    return L2
+
+
+def _get_tick_text_size(p):
+    for k in _dtextsortedkeys:
+        if p <= k:
+            return _dtextsizes[k]
+
+
+def _get_tick_rotation(p):
+    for k in _drotationsortedkeys:
+        if p <= k:
+            return _drotation[k]
+
+
+def _plot_dendrogram(icoords, dcoords, ivl, p, n, mh, orientation,
+                     no_labels, color_list, leaf_font_size=None,
+                     leaf_rotation=None, contraction_marks=None,
+                     ax=None, above_threshold_color='C0'):
+    # Import matplotlib here so that it's not imported unless dendrograms
+    # are plotted. Raise an informative error if importing fails.
+    try:
+        # if an axis is provided, don't use pylab at all
+        if ax is None:
+            import matplotlib.pylab
+        import matplotlib.patches
+        import matplotlib.collections
+    except ImportError as e:
+        raise ImportError("You must install the matplotlib library to plot "
+                          "the dendrogram. Use no_plot=True to calculate the "
+                          "dendrogram without plotting.") from e
+
+    if ax is None:
+        ax = matplotlib.pylab.gca()
+        # if we're using pylab, we want to trigger a draw at the end
+        trigger_redraw = True
+    else:
+        trigger_redraw = False
+
+    # Independent variable plot width
+    ivw = len(ivl) * 10
+    # Dependent variable plot height
+    dvw = mh + mh * 0.05
+
+    iv_ticks = np.arange(5, len(ivl) * 10 + 5, 10)
+    if orientation in ('top', 'bottom'):
+        if orientation == 'top':
+            ax.set_ylim([0, dvw])
+            ax.set_xlim([0, ivw])
+        else:
+            ax.set_ylim([dvw, 0])
+            ax.set_xlim([0, ivw])
+
+        xlines = icoords
+        ylines = dcoords
+        if no_labels:
+            ax.set_xticks([])
+            ax.set_xticklabels([])
+        else:
+            ax.set_xticks(iv_ticks)
+
+            if orientation == 'top':
+                ax.xaxis.set_ticks_position('bottom')
+            else:
+                ax.xaxis.set_ticks_position('top')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_xticklines():
+                line.set_visible(False)
+
+            leaf_rot = (float(_get_tick_rotation(len(ivl)))
+                        if (leaf_rotation is None) else leaf_rotation)
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+            ax.set_xticklabels(ivl, rotation=leaf_rot, size=leaf_font)
+
+    elif orientation in ('left', 'right'):
+        if orientation == 'left':
+            ax.set_xlim([dvw, 0])
+            ax.set_ylim([0, ivw])
+        else:
+            ax.set_xlim([0, dvw])
+            ax.set_ylim([0, ivw])
+
+        xlines = dcoords
+        ylines = icoords
+        if no_labels:
+            ax.set_yticks([])
+            ax.set_yticklabels([])
+        else:
+            ax.set_yticks(iv_ticks)
+
+            if orientation == 'left':
+                ax.yaxis.set_ticks_position('right')
+            else:
+                ax.yaxis.set_ticks_position('left')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_yticklines():
+                line.set_visible(False)
+
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+
+            if leaf_rotation is not None:
+                ax.set_yticklabels(ivl, rotation=leaf_rotation, size=leaf_font)
+            else:
+                ax.set_yticklabels(ivl, size=leaf_font)
+
+    # Let's use collections instead. This way there is a separate legend item
+    # for each tree grouping, rather than stupidly one for each line segment.
+    colors_used = _remove_dups(color_list)
+    color_to_lines = {}
+    for color in colors_used:
+        color_to_lines[color] = []
+    for (xline, yline, color) in zip(xlines, ylines, color_list):
+        color_to_lines[color].append(list(zip(xline, yline)))
+
+    colors_to_collections = {}
+    # Construct the collections.
+    for color in colors_used:
+        coll = matplotlib.collections.LineCollection(color_to_lines[color],
+                                                     colors=(color,))
+        colors_to_collections[color] = coll
+
+    # Add all the groupings below the color threshold.
+    for color in colors_used:
+        if color != above_threshold_color:
+            ax.add_collection(colors_to_collections[color])
+    # If there's a grouping of links above the color threshold, it goes last.
+    if above_threshold_color in colors_to_collections:
+        ax.add_collection(colors_to_collections[above_threshold_color])
+
+    if contraction_marks is not None:
+        Ellipse = matplotlib.patches.Ellipse
+        for (x, y) in contraction_marks:
+            if orientation in ('left', 'right'):
+                e = Ellipse((y, x), width=dvw / 100, height=1.0)
+            else:
+                e = Ellipse((x, y), width=1.0, height=dvw / 100)
+            ax.add_artist(e)
+            e.set_clip_box(ax.bbox)
+            e.set_alpha(0.5)
+            e.set_facecolor('k')
+
+    if trigger_redraw:
+        matplotlib.pylab.draw_if_interactive()
+
+
+# C0  is used for above threshold color
+_link_line_colors_default = ('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9')
+_link_line_colors = list(_link_line_colors_default)
+
+
+@xp_capabilities(out_of_scope=True)
+def set_link_color_palette(palette):
+    """
+    Set list of matplotlib color codes for use by dendrogram.
+
+    Note that this palette is global (i.e., setting it once changes the colors
+    for all subsequent calls to `dendrogram`) and that it affects only the
+    the colors below ``color_threshold``.
+
+    Note that `dendrogram` also accepts a custom coloring function through its
+    ``link_color_func`` keyword, which is more flexible and non-global.
+
+    Parameters
+    ----------
+    palette : list of str or None
+        A list of matplotlib color codes.  The order of the color codes is the
+        order in which the colors are cycled through when color thresholding in
+        the dendrogram.
+
+        If ``None``, resets the palette to its default (which are matplotlib
+        default colors C1 to C9).
+
+    Returns
+    -------
+    None
+
+    See Also
+    --------
+    dendrogram
+
+    Notes
+    -----
+    Ability to reset the palette with ``None`` added in SciPy 0.17.0.
+
+    Thread safety: using this function in a multi-threaded fashion may
+    result in `dendrogram` producing plots with unexpected colors.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True)
+    >>> dn['color_list']
+    ['C1', 'C0', 'C0', 'C0', 'C0']
+    >>> hierarchy.set_link_color_palette(['c', 'm', 'y', 'k'])
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, above_threshold_color='b')
+    >>> dn['color_list']
+    ['c', 'b', 'b', 'b', 'b']
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, color_threshold=267,
+    ...                           above_threshold_color='k')
+    >>> dn['color_list']
+    ['c', 'm', 'm', 'k', 'k']
+
+    Now, reset the color palette to its default:
+
+    >>> hierarchy.set_link_color_palette(None)
+
+    """
+    if palette is None:
+        # reset to its default
+        palette = _link_line_colors_default
+    elif not isinstance(palette, list | tuple):
+        raise TypeError("palette must be a list or tuple")
+    _ptypes = [isinstance(p, str) for p in palette]
+
+    if False in _ptypes:
+        raise TypeError("all palette list elements must be color strings")
+
+    global _link_line_colors
+    _link_line_colors = palette
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def dendrogram(Z, p=30, truncate_mode=None, color_threshold=None,
+               get_leaves=True, orientation='top', labels=None,
+               count_sort=False, distance_sort=False, show_leaf_counts=True,
+               no_plot=False, no_labels=False, leaf_font_size=None,
+               leaf_rotation=None, leaf_label_func=None,
+               show_contracted=False, link_color_func=None, ax=None,
+               above_threshold_color='C0'):
+    """
+    Plot the hierarchical clustering as a dendrogram.
+
+    The dendrogram illustrates how each cluster is
+    composed by drawing a U-shaped link between a non-singleton
+    cluster and its children. The top of the U-link indicates a
+    cluster merge. The two legs of the U-link indicate which clusters
+    were merged. The length of the two legs of the U-link represents
+    the distance between the child clusters. It is also the
+    cophenetic distance between original observations in the two
+    children clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix encoding the hierarchical clustering to
+        render as a dendrogram. See the ``linkage`` function for more
+        information on the format of ``Z``.
+    p : int, optional
+        The ``p`` parameter for ``truncate_mode``.
+    truncate_mode : str, optional
+        The dendrogram can be hard to read when the original
+        observation matrix from which the linkage is derived is
+        large. Truncation is used to condense the dendrogram. There
+        are several modes:
+
+        ``None``
+          No truncation is performed (default).
+          Note: ``'none'`` is an alias for ``None`` that's kept for
+          backward compatibility.
+
+        ``'lastp'``
+          The last ``p`` non-singleton clusters formed in the linkage are the
+          only non-leaf nodes in the linkage; they correspond to rows
+          ``Z[n-p-2:end]`` in ``Z``. All other non-singleton clusters are
+          contracted into leaf nodes.
+
+        ``'level'``
+          No more than ``p`` levels of the dendrogram tree are displayed.
+          A "level" includes all nodes with ``p`` merges from the final merge.
+
+          Note: ``'mtica'`` is an alias for ``'level'`` that's kept for
+          backward compatibility.
+
+    color_threshold : double, optional
+        For brevity, let :math:`t` be the ``color_threshold``.
+        Colors all the descendent links below a cluster node
+        :math:`k` the same color if :math:`k` is the first node below
+        the cut threshold :math:`t`. All links connecting nodes with
+        distances greater than or equal to the threshold are colored
+        with de default matplotlib color ``'C0'``. If :math:`t` is less
+        than or equal to zero, all nodes are colored ``'C0'``.
+        If ``color_threshold`` is None or 'default',
+        corresponding with MATLAB(TM) behavior, the threshold is set to
+        ``0.7*max(Z[:,2])``.
+
+    get_leaves : bool, optional
+        Includes a list ``R['leaves']=H`` in the result
+        dictionary. For each :math:`i`, ``H[i] == j``, cluster node
+        ``j`` appears in position ``i`` in the left-to-right traversal
+        of the leaves, where :math:`j < 2n-1` and :math:`i < n`.
+    orientation : str, optional
+        The direction to plot the dendrogram, which can be any
+        of the following strings:
+
+        ``'top'``
+          Plots the root at the top, and plot descendent links going downwards.
+          (default).
+
+        ``'bottom'``
+          Plots the root at the bottom, and plot descendent links going
+          upwards.
+
+        ``'left'``
+          Plots the root at the left, and plot descendent links going right.
+
+        ``'right'``
+          Plots the root at the right, and plot descendent links going left.
+
+    labels : ndarray, optional
+        By default, ``labels`` is None so the index of the original observation
+        is used to label the leaf nodes.  Otherwise, this is an :math:`n`-sized
+        sequence, with ``n == Z.shape[0] + 1``. The ``labels[i]`` value is the
+        text to put under the :math:`i` th leaf node only if it corresponds to
+        an original observation and not a non-singleton cluster.
+    count_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum number of original objects in its cluster
+          is plotted first.
+
+        ``'descending'``
+          The child with the maximum number of original objects in its cluster
+          is plotted first.
+
+        Note, ``distance_sort`` and ``count_sort`` cannot both be True.
+    distance_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum distance between its direct descendents is
+          plotted first.
+
+        ``'descending'``
+          The child with the maximum distance between its direct descendents is
+          plotted first.
+
+        Note ``distance_sort`` and ``count_sort`` cannot both be True.
+    show_leaf_counts : bool, optional
+         When True, leaf nodes representing :math:`k>1` original
+         observation are labeled with the number of observations they
+         contain in parentheses.
+    no_plot : bool, optional
+        When True, the final rendering is not performed. This is
+        useful if only the data structures computed for the rendering
+        are needed or if matplotlib is not available.
+    no_labels : bool, optional
+        When True, no labels appear next to the leaf nodes in the
+        rendering of the dendrogram.
+    leaf_rotation : double, optional
+        Specifies the angle (in degrees) to rotate the leaf
+        labels. When unspecified, the rotation is based on the number of
+        nodes in the dendrogram (default is 0).
+    leaf_font_size : int, optional
+        Specifies the font size (in points) of the leaf labels. When
+        unspecified, the size based on the number of nodes in the
+        dendrogram.
+    leaf_label_func : lambda or function, optional
+        When ``leaf_label_func`` is a callable function, for each
+        leaf with cluster index :math:`k < 2n-1`. The function
+        is expected to return a string with the label for the
+        leaf.
+
+        Indices :math:`k < n` correspond to original observations
+        while indices :math:`k \\geq n` correspond to non-singleton
+        clusters.
+
+        For example, to label singletons with their node id and
+        non-singletons with their id, count, and inconsistency
+        coefficient, simply do::
+
+            # First define the leaf label function.
+            def llf(id):
+                if id < n:
+                    return str(id)
+                else:
+                    return '[%d %d %1.2f]' % (id, count, R[n-id,3])
+
+            # The text for the leaf nodes is going to be big so force
+            # a rotation of 90 degrees.
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90)
+
+            # leaf_label_func can also be used together with ``truncate_mode``,
+            # in which case you will get your leaves labeled after truncation:
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90,
+                       truncate_mode='level', p=2)
+
+    show_contracted : bool, optional
+        When True the heights of non-singleton nodes contracted
+        into a leaf node are plotted as crosses along the link
+        connecting that leaf node.  This really is only useful when
+        truncation is used (see ``truncate_mode`` parameter).
+    link_color_func : callable, optional
+        If given, `link_color_function` is called with each non-singleton id
+        corresponding to each U-shaped link it will paint. The function is
+        expected to return the color to paint the link, encoded as a matplotlib
+        color string code. For example::
+
+            dendrogram(Z, link_color_func=lambda k: colors[k])
+
+        colors the direct links below each untruncated non-singleton node
+        ``k`` using ``colors[k]``.
+    ax : matplotlib Axes instance, optional
+        If None and `no_plot` is not True, the dendrogram will be plotted
+        on the current axes.  Otherwise if `no_plot` is not True the
+        dendrogram will be plotted on the given ``Axes`` instance. This can be
+        useful if the dendrogram is part of a more complex figure.
+    above_threshold_color : str, optional
+        This matplotlib color string sets the color of the links above the
+        color_threshold. The default is ``'C0'``.
+
+    Returns
+    -------
+    R : dict
+        A dictionary of data structures computed to render the
+        dendrogram. Its has the following keys:
+
+        ``'color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th link.
+
+        ``'icoord'`` and ``'dcoord'``
+          Each of them is a list of lists. Let ``icoord = [I1, I2, ..., Ip]``
+          where ``Ik = [xk1, xk2, xk3, xk4]`` and ``dcoord = [D1, D2, ..., Dp]``
+          where ``Dk = [yk1, yk2, yk3, yk4]``, then the k'th link painted is
+          ``(xk1, yk1)`` - ``(xk2, yk2)`` - ``(xk3, yk3)`` - ``(xk4, yk4)``.
+
+        ``'ivl'``
+          A list of labels corresponding to the leaf nodes.
+
+        ``'leaves'``
+          For each i, ``H[i] == j``, cluster node ``j`` appears in position
+          ``i`` in the left-to-right traversal of the leaves, where
+          :math:`j < 2n-1` and :math:`i < n`. If ``j`` is less than ``n``, the
+          ``i``-th leaf node corresponds to an original observation.
+          Otherwise, it corresponds to a non-singleton cluster.
+
+        ``'leaves_color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th leaf.
+
+    See Also
+    --------
+    linkage, set_link_color_palette
+
+    Notes
+    -----
+    It is expected that the distances in ``Z[:,2]`` be monotonic, otherwise
+    crossings appear in the dendrogram.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> import matplotlib.pyplot as plt
+
+    A very basic example:
+
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> plt.figure()
+    >>> dn = hierarchy.dendrogram(Z)
+
+    Now, plot in given axes, improve the color scheme and use both vertical and
+    horizontal orientations:
+
+    >>> hierarchy.set_link_color_palette(['m', 'c', 'y', 'k'])
+    >>> fig, axes = plt.subplots(1, 2, figsize=(8, 3))
+    >>> dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y',
+    ...                            orientation='top')
+    >>> dn2 = hierarchy.dendrogram(Z, ax=axes[1],
+    ...                            above_threshold_color='#bcbddc',
+    ...                            orientation='right')
+    >>> hierarchy.set_link_color_palette(None)  # reset to default after use
+    >>> plt.show()
+
+    """
+    # This feature was thought about but never implemented (still useful?):
+    #
+    #         ... = dendrogram(..., leaves_order=None)
+    #
+    #         Plots the leaves in the order specified by a vector of
+    #         original observation indices. If the vector contains duplicates
+    #         or results in a crossing, an exception will be thrown. Passing
+    #         None orders leaf nodes based on the order they appear in the
+    #         pre-order traversal.
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+
+    if orientation not in ["top", "left", "bottom", "right"]:
+        raise ValueError("orientation must be one of 'top', 'left', "
+                         "'bottom', or 'right'")
+
+    if labels is not None:
+        try:
+            len_labels = len(labels)
+        except (TypeError, AttributeError):
+            len_labels = labels.shape[0]
+        if Z.shape[0] + 1 != len_labels:
+            raise ValueError("Dimensions of Z and labels must be consistent.")
+
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+    Zs = Z.shape
+    n = Zs[0] + 1
+    if isinstance(p, int | float):
+        p = int(p)
+    else:
+        raise TypeError('The second argument must be a number')
+
+    if truncate_mode not in ('lastp', 'mtica', 'level', 'none', None):
+        # 'mtica' is kept working for backwards compat.
+        raise ValueError('Invalid truncation mode.')
+
+    if truncate_mode == 'lastp':
+        if p > n or p == 0:
+            p = n
+
+    if truncate_mode == 'mtica':
+        # 'mtica' is an alias
+        truncate_mode = 'level'
+
+    if truncate_mode == 'level':
+        if p <= 0:
+            p = np.inf
+
+    if get_leaves:
+        lvs = []
+    else:
+        lvs = None
+
+    icoord_list = []
+    dcoord_list = []
+    color_list = []
+    current_color = [0]
+    currently_below_threshold = [False]
+    ivl = []  # list of leaves
+
+    if color_threshold is None or (isinstance(color_threshold, str) and
+                                   color_threshold == 'default'):
+        color_threshold = xp.max(Z[:, 2]) * 0.7
+
+    R = {'icoord': icoord_list, 'dcoord': dcoord_list, 'ivl': ivl,
+         'leaves': lvs, 'color_list': color_list}
+
+    # Empty list will be filled in _dendrogram_calculate_info
+    contraction_marks = [] if show_contracted else None
+
+    _dendrogram_calculate_info(
+        Z=Z, p=p,
+        truncate_mode=truncate_mode,
+        color_threshold=color_threshold,
+        get_leaves=get_leaves,
+        orientation=orientation,
+        labels=labels,
+        count_sort=count_sort,
+        distance_sort=distance_sort,
+        show_leaf_counts=show_leaf_counts,
+        i=2*n - 2,
+        iv=0.0,
+        ivl=ivl,
+        n=n,
+        icoord_list=icoord_list,
+        dcoord_list=dcoord_list,
+        lvs=lvs,
+        current_color=current_color,
+        color_list=color_list,
+        currently_below_threshold=currently_below_threshold,
+        leaf_label_func=leaf_label_func,
+        contraction_marks=contraction_marks,
+        link_color_func=link_color_func,
+        above_threshold_color=above_threshold_color)
+
+    if not no_plot:
+        mh = xp.max(Z[:, 2])
+        _plot_dendrogram(icoord_list, dcoord_list, ivl, p, n, mh, orientation,
+                         no_labels, color_list,
+                         leaf_font_size=leaf_font_size,
+                         leaf_rotation=leaf_rotation,
+                         contraction_marks=contraction_marks,
+                         ax=ax,
+                         above_threshold_color=above_threshold_color)
+
+    R["leaves_color_list"] = _get_leaves_color_list(R)
+
+    return R
+
+
+def _get_leaves_color_list(R):
+    leaves_color_list = [None] * len(R['leaves'])
+    for link_x, link_y, link_color in zip(R['icoord'],
+                                          R['dcoord'],
+                                          R['color_list']):
+        for (xi, yi) in zip(link_x, link_y):
+            if yi == 0.0 and (xi % 5 == 0 and xi % 2 == 1):
+                # if yi is 0.0 and xi is divisible by 5 and odd,
+                # the point is a leaf
+                # xi of leaves are      5, 15, 25, 35, ... (see `iv_ticks`)
+                # index of leaves are   0,  1,  2,  3, ... as below
+                leaf_index = (int(xi) - 5) // 10
+                # each leaf has a same color of its link.
+                leaves_color_list[leaf_index] = link_color
+    return leaves_color_list
+
+
+def _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                i, labels):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+
+    # If leaf node labels are to be displayed...
+    if ivl is not None:
+        # If a leaf_label_func has been provided, the label comes from the
+        # string returned from the leaf_label_func, which is a function
+        # passed to dendrogram.
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            # Otherwise, if the dendrogram caller has passed a labels list
+            # for the leaf nodes, use it.
+            if labels is not None:
+                ivl.append(labels[int(i - n)])
+            else:
+                # Otherwise, use the id as the label for the leaf.x
+                ivl.append(str(int(i)))
+
+
+def _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                   i, labels, show_leaf_counts):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+    if ivl is not None:
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            if show_leaf_counts:
+                ivl.append("(" + str(np.asarray(Z[i - n, 3], dtype=np.int64)) + ")")
+            else:
+                ivl.append("")
+
+
+def _append_contraction_marks(Z, iv, i, n, contraction_marks, xp):
+    _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp),
+                                  n, contraction_marks, xp)
+    _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp),
+                                  n, contraction_marks, xp)
+
+
+def _append_contraction_marks_sub(Z, iv, i, n, contraction_marks, xp):
+    if i >= n:
+        contraction_marks.append((iv, Z[i - n, 2]))
+        _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp),
+                                      n, contraction_marks, xp)
+        _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp),
+                                      n, contraction_marks, xp)
+
+
+def _dendrogram_calculate_info(Z, p, truncate_mode,
+                               color_threshold=np.inf, get_leaves=True,
+                               orientation='top', labels=None,
+                               count_sort=False, distance_sort=False,
+                               show_leaf_counts=False, i=-1, iv=0.0,
+                               ivl=None, n=0, icoord_list=None, dcoord_list=None,
+                               lvs=None, mhr=False,
+                               current_color=None, color_list=None,
+                               currently_below_threshold=None,
+                               leaf_label_func=None, level=0,
+                               contraction_marks=None,
+                               link_color_func=None,
+                               above_threshold_color='C0'):
+    """
+    Calculate the endpoints of the links as well as the labels for the
+    the dendrogram rooted at the node with index i. iv is the independent
+    variable value to plot the left-most leaf node below the root node i
+    (if orientation='top', this would be the left-most x value where the
+    plotting of this root node i and its descendents should begin).
+
+    ivl is a list to store the labels of the leaf nodes. The leaf_label_func
+    is called whenever ivl != None, labels == None, and
+    leaf_label_func != None. When ivl != None and labels != None, the
+    labels list is used only for labeling the leaf nodes. When
+    ivl == None, no labels are generated for leaf nodes.
+
+    When get_leaves==True, a list of leaves is built as they are visited
+    in the dendrogram.
+
+    Returns a tuple with l being the independent variable coordinate that
+    corresponds to the midpoint of cluster to the left of cluster i if
+    i is non-singleton, otherwise the independent coordinate of the leaf
+    node if i is a leaf node.
+
+    Returns
+    -------
+    A tuple (left, w, h, md), where:
+        * left is the independent variable coordinate of the center of the
+          the U of the subtree
+
+        * w is the amount of space used for the subtree (in independent
+          variable units)
+
+        * h is the height of the subtree in dependent variable units
+
+        * md is the ``max(Z[*,2]``) for all nodes ``*`` below and including
+          the target node.
+
+    """
+    xp = array_namespace(Z)
+    if n == 0:
+        raise ValueError("Invalid singleton cluster count n.")
+
+    if i == -1:
+        raise ValueError("Invalid root cluster index i.")
+
+    if truncate_mode == 'lastp':
+        # If the node is a leaf node but corresponds to a non-singleton
+        # cluster, its label is either the empty string or the number of
+        # original observations belonging to cluster i.
+        if 2*n - p > i >= n:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+    elif truncate_mode == 'level':
+        if i > n and level > p:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # Otherwise, only truncate if we have a leaf node.
+    #
+    # Only place leaves if they correspond to original observations.
+    if i < n:
+        _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                    leaf_label_func, i, labels)
+        return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # !!! Otherwise, we don't have a leaf node, so work on plotting a
+    # non-leaf node.
+    # Actual indices of a and b
+    aa = int_floor(Z[i - n, 0], xp)
+    ab = int_floor(Z[i - n, 1], xp)
+    if aa >= n:
+        # The number of singletons below cluster a
+        na = Z[aa - n, 3]
+        # The distance between a's two direct children.
+        da = Z[aa - n, 2]
+    else:
+        na = 1
+        da = 0.0
+    if ab >= n:
+        nb = Z[ab - n, 3]
+        db = Z[ab - n, 2]
+    else:
+        nb = 1
+        db = 0.0
+
+    if count_sort == 'ascending' or count_sort is True:
+        # If a has a count greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if na > nb:
+            # The cluster index to draw to the left (ua) will be ab
+            # and the one to draw to the right (ub) will be aa
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif count_sort == 'descending':
+        # If a has a count less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if na > nb:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    elif distance_sort == 'ascending' or distance_sort is True:
+        # If a has a distance greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if da > db:
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif distance_sort == 'descending':
+        # If a has a distance less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if da > db:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    else:
+        ua = aa
+        ub = ab
+
+    # Updated iv variable and the amount of space used.
+    (uiva, uwa, uah, uamd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ua, iv=iv, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    h = Z[i - n, 2]
+    if h >= color_threshold or color_threshold <= 0:
+        c = above_threshold_color
+
+        if currently_below_threshold[0]:
+            current_color[0] = (current_color[0] + 1) % len(_link_line_colors)
+        currently_below_threshold[0] = False
+    else:
+        currently_below_threshold[0] = True
+        c = _link_line_colors[current_color[0]]
+
+    (uivb, uwb, ubh, ubmd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ub, iv=iv + uwa, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    max_dist = max(uamd, ubmd, h)
+
+    icoord_list.append([uiva, uiva, uivb, uivb])
+    dcoord_list.append([uah, h, h, ubh])
+    if link_color_func is not None:
+        v = link_color_func(int(i))
+        if not isinstance(v, str):
+            raise TypeError("link_color_func must return a matplotlib "
+                            "color string!")
+        color_list.append(v)
+    else:
+        color_list.append(c)
+
+    return (((uiva + uivb) / 2), uwa + uwb, h, max_dist)
+
+
+@xp_capabilities()
+def is_isomorphic(T1, T2):
+    """
+    Determine if two different cluster assignments are equivalent.
+
+    Parameters
+    ----------
+    T1 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+    T2 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+
+    Returns
+    -------
+    b : bool
+        Whether the flat cluster assignments `T1` and `T2` are
+        equivalent.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fcluster, is_isomorphic
+    >>> from scipy.cluster.hierarchy import single, complete
+    >>> from scipy.spatial.distance import pdist
+
+    Two flat cluster assignments can be isomorphic if they represent the same
+    cluster assignment, with different labels.
+
+    For example, we can use the `scipy.cluster.hierarchy.single` method
+    and flatten the output to four clusters:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = single(pdist(X))
+    >>> T = fcluster(Z, 1, criterion='distance')
+    >>> T
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    We can then do the same using the
+    `scipy.cluster.hierarchy.complete`: method:
+
+    >>> Z = complete(pdist(X))
+    >>> T_ = fcluster(Z, 1.5, criterion='distance')
+    >>> T_
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    As we can see, in both cases we obtain four clusters and all the data
+    points are distributed in the same way - the only thing that changes
+    are the flat cluster labels (3 => 1, 4 =>2, 2 =>3 and 4 =>1), so both
+    cluster assignments are isomorphic:
+
+    >>> is_isomorphic(T, T_)
+    True
+
+    """
+    xp = array_namespace(T1, T2)
+    T1 = _asarray(T1, xp=xp)
+    T2 = _asarray(T2, xp=xp)
+
+    if T1.ndim != 1:
+        raise ValueError('T1 must be one-dimensional.')
+    if T2.ndim != 1:
+        raise ValueError('T2 must be one-dimensional.')
+    if T1.shape != T2.shape:
+        raise ValueError('T1 and T2 must have the same number of elements.')
+
+    # For each pair of (i, j) indices, test that
+    # T1[i] == T1[j] <--> T2[i] == T2[j]
+    # In other words, if the same symbol appears multiple times in T1,
+    # then a potentially different symbol must also be repeated in the same
+    # positions in T2, and vice versa.
+
+    # O(n*log(n)) algorithm.
+    # It is also possible to write a O(n) algorithm on top of unique_all(),
+    # but in practice it's much slower even for large clusters.
+    idx = xp.argsort(T1)
+    T1 = xp.take(T1, idx)
+    T2 = xp.take(T2, idx)
+    changes1 = T1 != xp.roll(T1, -1)
+    changes2 = T2 != xp.roll(T2, -1)
+    return xp.all(changes1 == changes2)
+
+
+@lazy_cython
+def maxdists(Z):
+    """
+    Return the maximum distance between any non-singleton cluster.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        ``linkage`` for more information.
+
+    Returns
+    -------
+    maxdists : ndarray
+        A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents
+        the maximum distance between any cluster (including
+        singletons) below and including the node with index i. More
+        specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the
+        set of all node indices below and including node i.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    is_monotonic : for testing for monotonicity of a linkage matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, maxdists
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z``, `scipy.cluster.hierarchy.maxdists`
+    computes for each new cluster generated (i.e., for each row of the linkage
+    matrix) what is the maximum distance between any two child clusters.
+
+    Due to the nature of hierarchical clustering, in many cases this is going
+    to be just the distance between the two child clusters that were merged
+    to form the current one - that is, Z[:,2].
+
+    However, for non-monotonic cluster assignments such as
+    `scipy.cluster.hierarchy.median` clustering this is not always the
+    case: There may be cluster formations were the distance between the two
+    clusters merged is smaller than the distance between their children.
+
+    We can see this in an example:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> maxdists(Z)
+    array([1.        , 1.        , 1.        , 1.        , 1.11803399,
+           1.11803399, 1.11803399, 1.11803399, 3.        , 3.5       ,
+           3.5       ])
+
+    Note that while the distance between the two clusters merged when creating the
+    last cluster is 3.25, there are two children (clusters 16 and 17) whose distance
+    is larger (3.5). Thus, `scipy.cluster.hierarchy.maxdists` returns 3.5 in
+    this case.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_maxdists(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        MD = np.zeros((Z.shape[0],))
+        _hierarchy.get_max_dist_for_each_cluster(Z, MD, Z.shape[0] + 1)
+        return MD
+
+    return xpx.lazy_apply(cy_maxdists, Z, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def maxinconsts(Z, R):
+    """
+    Return the maximum inconsistency coefficient for each
+    non-singleton cluster and its children.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    R : ndarray
+        The inconsistency matrix.
+
+    Returns
+    -------
+    MI : ndarray
+        A monotonic ``(n-1)``-sized numpy array of doubles.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxinconsts
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    Here, `scipy.cluster.hierarchy.maxinconsts` can be used to compute
+    the maximum value of the inconsistency statistic (the last column of
+    ``R``) for each non-singleton cluster and its children:
+
+    >>> maxinconsts(Z, R)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    _is_valid_im(R, throw=True, name='R', xp=xp)
+
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+    
+    def cy_maxinconsts(Z, R, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            _is_valid_im(R, throw=True, name='R', xp=np)
+        n = Z.shape[0] + 1
+        MI = np.zeros((n - 1,))
+        _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, n, 3)
+        return MI
+
+    return xpx.lazy_apply(cy_maxinconsts, Z, R, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def maxRstat(Z, R, i):
+    """
+    Return the maximum statistic for each non-singleton cluster and its
+    children.
+
+    Parameters
+    ----------
+    Z : array_like
+        The hierarchical clustering encoded as a matrix. See `linkage` for more
+        information.
+    R : array_like
+        The inconsistency matrix.
+    i : int
+        The column of `R` to use as the statistic.
+
+    Returns
+    -------
+    MR : ndarray
+        Calculates the maximum statistic for the i'th column of the
+        inconsistency matrix `R` for each non-singleton cluster
+        node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]``, where
+        ``Q(j)`` the set of all node ids corresponding to nodes below
+        and including ``j``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxRstat
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    `scipy.cluster.hierarchy.maxRstat` can be used to compute
+    the maximum value of each column of ``R``, for each non-singleton
+    cluster and its children:
+
+    >>> maxRstat(Z, R, 0)
+    array([1.        , 1.        , 1.        , 1.        , 1.05901699,
+           1.05901699, 1.05901699, 1.05901699, 1.74535599, 1.91202266,
+           3.25      ])
+    >>> maxRstat(Z, R, 1)
+    array([0.        , 0.        , 0.        , 0.        , 0.08346263,
+           0.08346263, 0.08346263, 0.08346263, 1.08655358, 1.37522872,
+           1.37522872])
+    >>> maxRstat(Z, R, 3)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    _is_valid_im(R, throw=True, name='R', xp=xp)
+
+    if not isinstance(i, int):
+        raise TypeError('The third argument must be an integer.')
+
+    if i < 0 or i > 3:
+        raise ValueError('i must be an integer between 0 and 3 inclusive.')
+
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+
+    def cy_maxRstat(Z, R, i, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            _is_valid_im(R, throw=True, name='R', xp=np)
+        MR = np.zeros((Z.shape[0],))
+        n = Z.shape[0] + 1
+        _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MR, n, i)
+        return MR
+
+    return xpx.lazy_apply(cy_maxRstat, Z, R, i=i, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+# Data-dependent output shape makes it impossible to use jax.jit
+@xp_capabilities(cpu_only=True, reason="Cython code", jax_jit=False,
+                 warnings=[("dask.array", "merges chunks")])
+def leaders(Z, T):
+    """
+    Return the root nodes in a hierarchical clustering.
+
+    Returns the root nodes in a hierarchical clustering corresponding
+    to a cut defined by a flat cluster assignment vector ``T``. See
+    the ``fcluster`` function for more information on the format of ``T``.
+
+    For each flat cluster :math:`j` of the :math:`k` flat clusters
+    represented in the n-sized flat cluster assignment vector ``T``,
+    this function finds the lowest cluster node :math:`i` in the linkage
+    tree Z, such that:
+
+      * leaf descendants belong only to flat cluster j
+        (i.e., ``T[p]==j`` for all :math:`p` in :math:`S(i)`, where
+        :math:`S(i)` is the set of leaf ids of descendant leaf nodes
+        with cluster node :math:`i`)
+
+      * there does not exist a leaf that is not a descendant with
+        :math:`i` that also belongs to cluster :math:`j`
+        (i.e., ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`). If
+        this condition is violated, ``T`` is not a valid cluster
+        assignment vector, and an exception will be thrown.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    T : ndarray
+        The flat cluster assignment vector.
+
+    Returns
+    -------
+    L : ndarray
+        The leader linkage node id's stored as a k-element 1-D array,
+        where ``k`` is the number of flat clusters found in ``T``.
+
+        ``L[j]=i`` is the linkage cluster node id that is the
+        leader of flat cluster with id M[j]. If ``i < n``, ``i``
+        corresponds to an original observation, otherwise it
+        corresponds to a non-singleton cluster.
+    M : ndarray
+        The leader linkage node id's stored as a k-element 1-D array, where
+        ``k`` is the number of flat clusters found in ``T``. This allows the
+        set of flat cluster ids to be any arbitrary set of ``k`` integers.
+
+        For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with
+        id 8's leader is linkage node 2.
+
+    See Also
+    --------
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster, leaders
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z`` - obtained after apply a clustering method
+    to a dataset ``X`` - and a flat cluster assignment array ``T``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    >>> T = fcluster(Z, 3, criterion='distance')
+    >>> T
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    `scipy.cluster.hierarchy.leaders` returns the indices of the nodes
+    in the dendrogram that are the leaders of each flat cluster:
+
+    >>> L, M = leaders(Z, T)
+    >>> L
+    array([16, 17, 18, 19], dtype=int32)
+
+    (remember that indices 0-11 point to the 12 data points in ``X``,
+    whereas indices 12-22 point to the 11 rows of ``Z``)
+
+    `scipy.cluster.hierarchy.leaders` also returns the indices of
+    the flat clusters in ``T``:
+
+    >>> M
+    array([1, 2, 3, 4], dtype=int32)
+
+    Notes
+    -----
+    *Array API support (experimental):* This function returns arrays
+    with data-dependent shape. In JAX, at the moment of writing this makes it
+    impossible to execute it inside `@jax.jit`.
+    """
+    xp = array_namespace(Z, T)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    T = _asarray(T, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if T.dtype != xp.int32:
+        raise TypeError('T must be a 1-D array of dtype int32.')
+
+    if T.shape[0] != Z.shape[0] + 1:
+        raise ValueError('Mismatch: len(T)!=Z.shape[0] + 1.')
+
+    n_obs = Z.shape[0] + 1
+
+    def cy_leaders(Z, T, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n_clusters = int(xpx.nunique(T))
+        L = np.zeros(n_clusters, dtype=np.int32)
+        M = np.zeros(n_clusters, dtype=np.int32)
+        s = _hierarchy.leaders(Z, T, L, M, n_clusters, n_obs)
+        if s >= 0:
+            raise ValueError('T is not a valid assignment vector. Error found '
+                             f'when examining linkage node {s} (< 2n-1).')
+        return L, M
+
+    return xpx.lazy_apply(cy_leaders, Z, T, validate=is_lazy_array(Z),
+                          shape=((None,), (None, )), dtype=(xp.int32, xp.int32),
+                          as_numpy=True, xp=xp)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ad7da3af7fa3acf8f399c9eedb149a1420d5a17
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py
@@ -0,0 +1,145 @@
+from numpy import array
+
+
+Q_X = array([[5.26563660e-01, 3.14160190e-01, 8.00656370e-02],
+             [7.50205180e-01, 4.60299830e-01, 8.98696460e-01],
+             [6.65461230e-01, 6.94011420e-01, 9.10465700e-01],
+             [9.64047590e-01, 1.43082200e-03, 7.39874220e-01],
+             [1.08159060e-01, 5.53028790e-01, 6.63804780e-02],
+             [9.31359130e-01, 8.25424910e-01, 9.52315440e-01],
+             [6.78086960e-01, 3.41903970e-01, 5.61481950e-01],
+             [9.82730940e-01, 7.04605210e-01, 8.70978630e-02],
+             [6.14691610e-01, 4.69989230e-02, 6.02406450e-01],
+             [5.80161260e-01, 9.17354970e-01, 5.88163850e-01],
+             [1.38246310e+00, 1.96358160e+00, 1.94437880e+00],
+             [2.10675860e+00, 1.67148730e+00, 1.34854480e+00],
+             [1.39880070e+00, 1.66142050e+00, 1.32224550e+00],
+             [1.71410460e+00, 1.49176380e+00, 1.45432170e+00],
+             [1.54102340e+00, 1.84374950e+00, 1.64658950e+00],
+             [2.08512480e+00, 1.84524350e+00, 2.17340850e+00],
+             [1.30748740e+00, 1.53801650e+00, 2.16007740e+00],
+             [1.41447700e+00, 1.99329070e+00, 1.99107420e+00],
+             [1.61943490e+00, 1.47703280e+00, 1.89788160e+00],
+             [1.59880600e+00, 1.54988980e+00, 1.57563350e+00],
+             [3.37247380e+00, 2.69635310e+00, 3.39981700e+00],
+             [3.13705120e+00, 3.36528090e+00, 3.06089070e+00],
+             [3.29413250e+00, 3.19619500e+00, 2.90700170e+00],
+             [2.65510510e+00, 3.06785900e+00, 2.97198540e+00],
+             [3.30941040e+00, 2.59283970e+00, 2.57714110e+00],
+             [2.59557220e+00, 3.33477370e+00, 3.08793190e+00],
+             [2.58206180e+00, 3.41615670e+00, 3.26441990e+00],
+             [2.71127000e+00, 2.77032450e+00, 2.63466500e+00],
+             [2.79617850e+00, 3.25473720e+00, 3.41801560e+00],
+             [2.64741750e+00, 2.54538040e+00, 3.25354110e+00]])
+
+ytdist = array([662., 877., 255., 412., 996., 295., 468., 268., 400., 754.,
+                564., 138., 219., 869., 669.])
+
+linkage_ytdist_single = array([[2., 5., 138., 2.],
+                               [3., 4., 219., 2.],
+                               [0., 7., 255., 3.],
+                               [1., 8., 268., 4.],
+                               [6., 9., 295., 6.]])
+
+linkage_ytdist_complete = array([[2., 5., 138., 2.],
+                                 [3., 4., 219., 2.],
+                                 [1., 6., 400., 3.],
+                                 [0., 7., 412., 3.],
+                                 [8., 9., 996., 6.]])
+
+linkage_ytdist_average = array([[2., 5., 138., 2.],
+                                [3., 4., 219., 2.],
+                                [0., 7., 333.5, 3.],
+                                [1., 6., 347.5, 3.],
+                                [8., 9., 680.77777778, 6.]])
+
+linkage_ytdist_weighted = array([[2., 5., 138., 2.],
+                                 [3., 4., 219., 2.],
+                                 [0., 7., 333.5, 3.],
+                                 [1., 6., 347.5, 3.],
+                                 [8., 9., 670.125, 6.]])
+
+# the optimal leaf ordering of linkage_ytdist_single
+linkage_ytdist_single_olo = array([[5., 2., 138., 2.],
+                                   [4., 3., 219., 2.],
+                                   [7., 0., 255., 3.],
+                                   [1., 8., 268., 4.],
+                                   [6., 9., 295., 6.]])
+
+X = array([[1.43054825, -7.5693489],
+           [6.95887839, 6.82293382],
+           [2.87137846, -9.68248579],
+           [7.87974764, -6.05485803],
+           [8.24018364, -6.09495602],
+           [7.39020262, 8.54004355]])
+ 
+linkage_X_centroid = array([[3., 4., 0.36265956, 2.],
+                            [1., 5., 1.77045373, 2.],
+                            [0., 2., 2.55760419, 2.],
+                            [6., 8., 6.43614494, 4.],
+                            [7., 9., 15.17363237, 6.]])
+
+linkage_X_median = array([[3., 4., 0.36265956, 2.],
+                          [1., 5., 1.77045373, 2.],
+                          [0., 2., 2.55760419, 2.],
+                          [6., 8., 6.43614494, 4.],
+                          [7., 9., 15.17363237, 6.]])
+
+linkage_X_ward = array([[3., 4., 0.36265956, 2.],
+                        [1., 5., 1.77045373, 2.],
+                        [0., 2., 2.55760419, 2.],
+                        [6., 8., 9.10208346, 4.],
+                        [7., 9., 24.7784379, 6.]])
+
+# the optimal leaf ordering of linkage_X_ward
+linkage_X_ward_olo = array([[4., 3., 0.36265956, 2.],
+                            [5., 1., 1.77045373, 2.],
+                            [2., 0., 2.55760419, 2.],
+                            [6., 8., 9.10208346, 4.],
+                            [7., 9., 24.7784379, 6.]])
+
+inconsistent_ytdist = {
+    1: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [255., 0., 1., 0.],
+              [268., 0., 1., 0.],
+              [295., 0., 1., 0.]]),
+    2: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [261.5, 9.19238816, 2., 0.70710678],
+              [233.66666667, 83.9424406, 3., 0.7306594]]),
+    3: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [247.33333333, 25.38372182, 3., 0.81417007],
+              [239., 69.36377537, 4., 0.80733783]]),
+    4: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [247.33333333, 25.38372182, 3., 0.81417007],
+              [235., 60.73302232, 5., 0.98793042]])}
+
+fcluster_inconsistent = {
+    0.8: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    1.0: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1])}
+
+fcluster_distance = {
+    0.6: array([4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 3,
+                1, 1, 1, 2, 1, 1, 1, 1, 1]),
+    1.0: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1])}
+
+fcluster_maxclust = {
+    8.0: array([5, 5, 5, 5, 5, 5, 5, 6, 5, 5, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 4,
+                1, 1, 1, 3, 1, 1, 1, 1, 2]),
+    4.0: array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    1.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1])}
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9518ea1af28df04d811f46ff114d5cf58e594d7
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py
@@ -0,0 +1,202 @@
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from scipy.cluster.hierarchy import DisjointSet
+import string
+
+
+def generate_random_token():
+    k = len(string.ascii_letters)
+    tokens = list(np.arange(k, dtype=int))
+    tokens += list(np.arange(k, dtype=float))
+    tokens += list(string.ascii_letters)
+    tokens += [None for i in range(k)]
+    tokens = np.array(tokens, dtype=object)
+    rng = np.random.RandomState(seed=0)
+
+    while 1:
+        size = rng.randint(1, 3)
+        element = rng.choice(tokens, size)
+        if size == 1:
+            yield element[0]
+        else:
+            yield tuple(element)
+
+
+def get_elements(n):
+    # dict is deterministic without difficulty of comparing numpy ints
+    elements = {}
+    for element in generate_random_token():
+        if element not in elements:
+            elements[element] = len(elements)
+            if len(elements) >= n:
+                break
+    return list(elements.keys())
+
+
+def test_init():
+    n = 10
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert dis.n_subsets == n
+    assert list(dis) == elements
+
+
+def test_len():
+    n = 10
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert len(dis) == n
+
+    dis.add("dummy")
+    assert len(dis) == n + 1
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_contains(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    for x in elements:
+        assert x in dis
+
+    assert "dummy" not in dis
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_add(n):
+    elements = get_elements(n)
+    dis1 = DisjointSet(elements)
+
+    dis2 = DisjointSet()
+    for i, x in enumerate(elements):
+        dis2.add(x)
+        assert len(dis2) == i + 1
+
+        # test idempotency by adding element again
+        dis2.add(x)
+        assert len(dis2) == i + 1
+
+    assert list(dis1) == list(dis2)
+
+
+def test_element_not_present():
+    elements = get_elements(n=10)
+    dis = DisjointSet(elements)
+
+    with assert_raises(KeyError):
+        dis["dummy"]
+
+    with assert_raises(KeyError):
+        dis.merge(elements[0], "dummy")
+
+    with assert_raises(KeyError):
+        dis.connected(elements[0], "dummy")
+
+
+@pytest.mark.parametrize("direction", ["forwards", "backwards"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_linear_union_sequence(n, direction):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert elements == list(dis)
+
+    indices = list(range(n - 1))
+    if direction == "backwards":
+        indices = indices[::-1]
+
+    for it, i in enumerate(indices):
+        assert not dis.connected(elements[i], elements[i + 1])
+        assert dis.merge(elements[i], elements[i + 1])
+        assert dis.connected(elements[i], elements[i + 1])
+        assert dis.n_subsets == n - 1 - it
+
+    roots = [dis[i] for i in elements]
+    if direction == "forwards":
+        assert all(elements[0] == r for r in roots)
+    else:
+        assert all(elements[-2] == r for r in roots)
+    assert not dis.merge(elements[0], elements[-1])
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_self_unions(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    for x in elements:
+        assert dis.connected(x, x)
+        assert not dis.merge(x, x)
+        assert dis.connected(x, x)
+    assert dis.n_subsets == len(elements)
+
+    assert elements == list(dis)
+    roots = [dis[x] for x in elements]
+    assert elements == roots
+
+
+@pytest.mark.parametrize("order", ["ab", "ba"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_equal_size_ordering(n, order):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    rng = np.random.RandomState(seed=0)
+    indices = np.arange(n)
+    rng.shuffle(indices)
+
+    for i in range(0, len(indices), 2):
+        a, b = elements[indices[i]], elements[indices[i + 1]]
+        if order == "ab":
+            assert dis.merge(a, b)
+        else:
+            assert dis.merge(b, a)
+
+        expected = elements[min(indices[i], indices[i + 1])]
+        assert dis[a] == expected
+        assert dis[b] == expected
+
+
+@pytest.mark.parametrize("kmax", [5, 10])
+def test_binary_tree(kmax):
+    n = 2**kmax
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    rng = np.random.RandomState(seed=0)
+
+    for k in 2**np.arange(kmax):
+        for i in range(0, n, 2 * k):
+            r1, r2 = rng.randint(0, k, size=2)
+            a, b = elements[i + r1], elements[i + k + r2]
+            assert not dis.connected(a, b)
+            assert dis.merge(a, b)
+            assert dis.connected(a, b)
+
+        assert elements == list(dis)
+        roots = [dis[i] for i in elements]
+        expected_indices = np.arange(n) - np.arange(n) % (2 * k)
+        expected = [elements[i] for i in expected_indices]
+        assert roots == expected
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_subsets(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    rng = np.random.RandomState(seed=0)
+    for i, j in rng.randint(0, n, (n, 2)):
+        x = elements[i]
+        y = elements[j]
+
+        expected = {element for element in dis if {dis[element]} == {dis[x]}}
+        assert dis.subset_size(x) == len(dis.subset(x))
+        assert expected == dis.subset(x)
+
+        expected = {dis[element]: set() for element in dis}
+        for element in dis:
+            expected[dis[element]].add(element)
+        expected = list(expected.values())
+        assert expected == dis.subsets()
+
+        dis.merge(x, y)
+        assert dis.subset(x) == dis.subset(y)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..21c1817efdc020e45d647400b98ac85a42c562b2
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py
@@ -0,0 +1,1237 @@
+#
+# Author: Damian Eads
+# Date: April 17, 2008
+#
+# Copyright (C) 2008 Damian Eads
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_array_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.cluster.hierarchy import (
+    ClusterWarning, linkage, from_mlab_linkage, to_mlab_linkage,
+    num_obs_linkage, inconsistent, cophenet, fclusterdata, fcluster,
+    is_isomorphic, single, ward, leaders,
+    correspond, is_monotonic, maxdists, maxinconsts, maxRstat,
+    is_valid_linkage, is_valid_im, to_tree, leaves_list, dendrogram,
+    set_link_color_palette, cut_tree, optimal_leaf_ordering,
+    _order_cluster_tree, _hierarchy, _EUCLIDEAN_METHODS, _LINKAGE_METHODS)
+from scipy.cluster._hierarchy import Heap
+from scipy.spatial.distance import pdist
+from scipy._lib._array_api import (eager_warns, make_xp_test_case,
+                                   xp_assert_close, xp_assert_equal)
+import scipy._lib.array_api_extra as xpx
+
+from threading import Lock
+
+from . import hierarchy_test_data
+
+class eager:
+    # Bypass xpx.testing.lazy_xp_function when calling
+    # these functions from this namespace
+    is_valid_im = is_valid_im
+    is_valid_linkage = is_valid_linkage
+
+
+# Matplotlib is not a scipy dependency but is optionally used in dendrogram, so
+# check if it's available
+try:
+    import matplotlib
+    # and set the backend to be Agg (no gui)
+    matplotlib.use('Agg')
+    # before importing pyplot
+    import matplotlib.pyplot as plt
+    have_matplotlib = True
+except Exception:
+    have_matplotlib = False
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@make_xp_test_case(linkage)
+class TestLinkage:
+
+    @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback")
+    def test_linkage_non_finite_elements_in_distance_matrix(self, xp):
+        # Tests linkage(Y) where Y contains a non-finite element (e.g. NaN or Inf).
+        # Exception expected.
+        y = xp.asarray([xp.nan] + [0.0]*5)
+        assert_raises(ValueError, linkage, y)
+
+    def test_linkage_empty_distance_matrix(self, xp):
+        # Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected.
+        y = xp.zeros((0,))
+        assert_raises(ValueError, linkage, y)
+
+    def test_linkage_tdist(self, xp):
+        for method in ['single', 'complete', 'average', 'weighted']:
+            self.check_linkage_tdist(method, xp)
+
+    def check_linkage_tdist(self, method, xp):
+        # Tests linkage(Y, method) on the tdist data set.
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), method)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_' + method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    def test_linkage_X(self, xp):
+        for method in ['centroid', 'median', 'ward']:
+            self.check_linkage_q(method, xp)
+
+    def check_linkage_q(self, method, xp):
+        # Tests linkage(Y, method) on the Q data set.
+        Z = linkage(xp.asarray(hierarchy_test_data.X), method)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_X_' + method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+        X = xp.asarray(hierarchy_test_data.X)
+        y = pdist(X, metric="euclidean")
+        Z = linkage(y, method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+    def test_compare_with_trivial(self, xp):
+        rng = np.random.RandomState(0)
+        n = 20
+        X = rng.rand(n, 2)
+        d = pdist(X)
+
+        for method, code in _LINKAGE_METHODS.items():
+            Z_trivial = _hierarchy.linkage(d, n, code)
+            Z = linkage(xp.asarray(d), method)
+            xp_assert_close(Z, xp.asarray(Z_trivial), rtol=1e-14, atol=1e-15)
+
+    def test_optimal_leaf_ordering(self, xp):
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), optimal_ordering=True)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_single_olo')
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    @pytest.mark.parametrize("method,expect", [
+        ('single',   [[0, 1, 1.41421356, 2],
+                      [2, 3, 1.41421356, 3]]),
+        ('complete', [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.82842712, 3]]),
+        ('average',  [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('weighted', [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('centroid', [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('median',   [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('ward',     [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.44948974, 3]]),
+    ])
+    def test_linkage_ties(self, method, expect, xp):
+        X = xp.asarray([[-1, -1], [0, 0], [1, 1]])
+        Z = linkage(X, method=method)
+        expect = xp.asarray(expect, dtype=xp.float64)
+        xp_assert_close(Z, expect, atol=1e-06)
+
+    def test_unsupported_uncondensed_distance_matrix_linkage_warning(self, xp):
+        X = xp.asarray([[0, 1], [1, 0]])
+        with eager_warns(ClusterWarning, xp=xp):
+            linkage(X)
+
+    @pytest.mark.parametrize("method", _EUCLIDEAN_METHODS)
+    def test_euclidean_linkage_value_error(self, method, xp):
+        X = xp.asarray([[1, 1], [1, 1]])
+        with pytest.raises(ValueError):
+            linkage(X, method=method, metric='cityblock')
+
+    def test_2x2_linkage(self, xp):
+        Z1 = linkage(xp.asarray([1]), method='single', metric='euclidean')
+        Z2 = linkage(xp.asarray([[0, 1], [0, 0]]), method='single', metric='euclidean')
+        xp_assert_close(Z1, Z2, rtol=1e-15)
+
+    @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback")
+    def test_centroid_neg_distance(self, xp):
+        # gh-21011
+        values = xp.asarray([0, 0, -1])
+        with pytest.raises(ValueError):
+            # This is just checking that this doesn't crash
+            linkage(values, method='centroid')
+
+
+@make_xp_test_case(inconsistent)
+class TestInconsistent:
+
+    def test_inconsistent_tdist(self, xp):
+        for depth in hierarchy_test_data.inconsistent_ytdist:
+            self.check_inconsistent_tdist(depth, xp)
+
+    def check_inconsistent_tdist(self, depth, xp):
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        xp_assert_close(inconsistent(Z, depth),
+                        xp.asarray(hierarchy_test_data.inconsistent_ytdist[depth]))
+
+
+@make_xp_test_case(cophenet)
+class TestCopheneticDistance:
+
+    def test_linkage_cophenet_tdist_Z(self, xp):
+        # Tests cophenet(Z) on tdist data set.
+        expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+                                295, 138, 219, 295, 295])
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        M = cophenet(Z)
+        xp_assert_close(M, xp.asarray(expectedM, dtype=xp.float64), atol=1e-10)
+
+    def test_linkage_cophenet_tdist_Z_Y(self, xp):
+        # Tests cophenet(Z, Y) on tdist data set.
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        (c, M) = cophenet(Z, xp.asarray(hierarchy_test_data.ytdist))
+        expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+                                295, 138, 219, 295, 295], dtype=xp.float64)
+        expectedc = xp.asarray(0.639931296433393415057366837573, dtype=xp.float64)[()]
+        xp_assert_close(c, expectedc, atol=1e-10)
+        xp_assert_close(M, expectedM, atol=1e-10)
+
+    @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback")
+    def test_gh_22183(self, xp):
+        # check for lack of segfault
+        # (out of bounds memory access)
+        # and correct interception of
+        # invalid linkage matrix
+        arr=[[0.0, 1.0, 1.0, 2.0],
+             [2.0, 12.0, 1.0, 3.0],
+             [3.0, 4.0, 1.0, 2.0],
+             [5.0, 14.0, 1.0, 3.0],
+             [6.0, 7.0, 1.0, 2.0],
+             [8.0, 16.0, 1.0, 3.0],
+             [9.0, 10.0, 1.0, 2.0],
+             [11.0, 18.0, 1.0, 3.0],
+             [13.0, 15.0, 2.0, 6.0],
+             [17.0, 20.0, 2.0, 32.0],
+             [19.0, 21.0, 2.0, 12.0]]
+        with pytest.raises(ValueError, match="excessive observations"):
+            cophenet(xp.asarray(arr))
+
+
+@make_xp_test_case(from_mlab_linkage, to_mlab_linkage)
+class TestMLabLinkageConversion:
+
+    def test_mlab_linkage_conversion_empty(self, xp):
+        # Tests from/to_mlab_linkage on empty linkage array.
+        X = xp.asarray([], dtype=xp.float64)
+        xp_assert_equal(from_mlab_linkage(X), X)
+        xp_assert_equal(to_mlab_linkage(X), X)
+
+    def test_mlab_linkage_conversion_single_row(self, xp):
+        # Tests from/to_mlab_linkage on linkage array with single row.
+        Z = xp.asarray([[0., 1., 3., 2.]])
+        Zm = xp.asarray([[1, 2, 3]])
+        xp_assert_close(from_mlab_linkage(Zm), xp.asarray(Z, dtype=xp.float64),
+                        rtol=1e-15)
+        xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+                        rtol=1e-15)
+
+    def test_mlab_linkage_conversion_multiple_rows(self, xp):
+        # Tests from/to_mlab_linkage on linkage array with multiple rows.
+        Zm = xp.asarray([[3, 6, 138], [4, 5, 219],
+                         [1, 8, 255], [2, 9, 268], [7, 10, 295]])
+        Z = xp.asarray([[2., 5., 138., 2.],
+                        [3., 4., 219., 2.],
+                        [0., 7., 255., 3.],
+                        [1., 8., 268., 4.],
+                        [6., 9., 295., 6.]],
+                       dtype=xp.float64)
+        xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15)
+        xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+                        rtol=1e-15)
+
+
+@make_xp_test_case(fclusterdata)
+class TestFclusterData:
+
+    @make_xp_test_case(is_isomorphic)
+    @pytest.mark.parametrize("criterion,t",
+        [("inconsistent", t) for t in hierarchy_test_data.fcluster_inconsistent]
+        + [("distance", t) for t in hierarchy_test_data.fcluster_distance]
+        + [("maxclust", t) for t in hierarchy_test_data.fcluster_maxclust]
+    )
+    def test_fclusterdata(self, t, criterion, xp):
+        # Tests fclusterdata(X, criterion=criterion, t=t) on a random 3-cluster data set
+        expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        T = fclusterdata(X, criterion=criterion, t=t)
+        assert is_isomorphic(T, expectedT)
+
+
+@make_xp_test_case(fcluster)
+class TestFcluster:
+
+    @make_xp_test_case(single, is_isomorphic)
+    @pytest.mark.parametrize("criterion,t",
+        [("inconsistent", t) for t in hierarchy_test_data.fcluster_inconsistent]
+        + [("distance", t) for t in hierarchy_test_data.fcluster_distance]
+        + [("maxclust", t) for t in hierarchy_test_data.fcluster_maxclust]
+    )
+    def test_fcluster(self, t, criterion, xp):
+        # Tests fcluster(Z, criterion=criterion, t=t) on a random 3-cluster data set.
+        expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, criterion=criterion, t=t)
+        assert_(is_isomorphic(T, expectedT))
+
+    @make_xp_test_case(single, is_isomorphic, maxdists)
+    @pytest.mark.parametrize("t", hierarchy_test_data.fcluster_distance)
+    def test_fcluster_monocrit(self, t, xp):
+        expectedT = xp.asarray(hierarchy_test_data.fcluster_distance[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, t, criterion='monocrit', monocrit=maxdists(Z))
+        assert_(is_isomorphic(T, expectedT))
+
+    @make_xp_test_case(single, is_isomorphic, maxdists)
+    @pytest.mark.parametrize("t", hierarchy_test_data.fcluster_maxclust)
+    def test_fcluster_maxclust_monocrit(self, t, xp):
+        expectedT = xp.asarray(hierarchy_test_data.fcluster_maxclust[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, t, criterion='maxclust_monocrit', monocrit=maxdists(Z))
+        assert_(is_isomorphic(T, expectedT))
+
+    @make_xp_test_case(single)
+    def test_fcluster_maxclust_gh_12651(self, xp):
+        y = xp.asarray([[1], [4], [5]])
+        Z = single(y)
+        assert_array_equal(fcluster(Z, t=1, criterion="maxclust"),
+                           xp.asarray([1, 1, 1]))
+        assert_array_equal(fcluster(Z, t=2, criterion="maxclust"),
+                           xp.asarray([2, 1, 1]))
+        assert_array_equal(fcluster(Z, t=3, criterion="maxclust"),
+                           xp.asarray([1, 2, 3]))
+        assert_array_equal(fcluster(Z, t=5, criterion="maxclust"),
+                           xp.asarray([1, 2, 3]))
+
+
+@make_xp_test_case(leaders)
+class TestLeaders:
+
+    def test_leaders_single(self, xp):
+        # Tests leaders using a flat clustering generated by single linkage.
+        X = hierarchy_test_data.Q_X
+        Y = pdist(X)
+        Z = linkage(Y)
+        T = fcluster(Z, criterion='maxclust', t=3)
+        Z = xp.asarray(Z)
+        T = xp.asarray(T, dtype=xp.int32)
+        L = leaders(Z, T)
+        expect = xp.asarray([53, 55, 56, 2, 3, 1], dtype=xp.int32)
+        xp_assert_close(xp.concat(L), expect, rtol=1e-15)
+
+
+@make_xp_test_case(is_isomorphic)
+class TestIsIsomorphic:
+
+    def test_array_like(self):
+        assert is_isomorphic([1, 1, 1], [2, 2, 2])
+        assert is_isomorphic([], [])
+
+    def test_is_isomorphic_1(self, xp):
+        # Tests is_isomorphic on test case #1 (one flat cluster, different labellings)
+        a = xp.asarray([1, 1, 1])
+        b = xp.asarray([2, 2, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_2(self, xp):
+        # Tests is_isomorphic on test case #2 (two flat clusters, different labelings)
+        a = xp.asarray([1, 7, 1])
+        b = xp.asarray([2, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_3(self, xp):
+        # Tests is_isomorphic on test case #3 (no flat clusters)
+        a = xp.asarray([])
+        b = xp.asarray([])
+        assert is_isomorphic(a, b)
+
+    def test_is_isomorphic_4A(self, xp):
+        # Tests is_isomorphic on test case #4A
+        # (3 flat clusters, different labelings, isomorphic)
+        a = xp.asarray([1, 2, 3])
+        b = xp.asarray([1, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_4B(self, xp):
+        # Tests is_isomorphic on test case #4B
+        # (3 flat clusters, different labelings, nonisomorphic)
+        a = xp.asarray([1, 2, 3, 3])
+        b = xp.asarray([1, 3, 2, 3])
+        assert not is_isomorphic(a, b)
+        assert not is_isomorphic(b, a)
+
+    def test_is_isomorphic_4C(self, xp):
+        # Tests is_isomorphic on test case #4C
+        # (3 flat clusters, different labelings, isomorphic)
+        a = xp.asarray([7, 2, 3])
+        b = xp.asarray([6, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    @pytest.mark.parametrize("nclusters", [2, 3, 5])
+    def test_is_isomorphic_5(self, nclusters, xp):
+        # Tests is_isomorphic on test case #5 (1000 observations, 2/3/5 random
+        # clusters, random permutation of the labeling).
+        self.is_isomorphic_randperm(1000, nclusters, xp=xp)
+
+    @pytest.mark.parametrize("nclusters", [2, 3, 5])
+    def test_is_isomorphic_6(self, nclusters, xp):
+        # Tests is_isomorphic on test case #5A (1000 observations, 2/3/5 random
+        # clusters, random permutation of the labeling, slightly
+        # nonisomorphic.)
+        self.is_isomorphic_randperm(1000, nclusters, True, 5, xp=xp)
+
+    def test_is_isomorphic_7(self, xp):
+        # Regression test for gh-6271
+        a = xp.asarray([1, 2, 3])
+        b = xp.asarray([1, 1, 1])
+        assert not is_isomorphic(a, b)
+
+    def is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0, *, xp):
+        rng = np.random.default_rng()
+        for _ in range(3):
+            a = rng.integers(0, nclusters, size=nobs)
+            p = rng.permutation(nclusters)
+            b = p.take(a.astype(np.intp))
+            if noniso:
+                q = rng.permutation(nobs)
+                b[q[0:nerrors]] += 1
+                b[q[0:nerrors]] %= nclusters
+            a = xp.asarray(a)
+            b = xp.asarray(b)
+            assert is_isomorphic(a, b) == (not noniso)
+            assert is_isomorphic(b, a) == (not noniso)
+
+
+@make_xp_test_case(is_valid_linkage)
+class TestIsValidLinkage:
+
+    @pytest.mark.parametrize("nrow, ncol, valid", [(2, 5, False), (2, 3, False),
+                                                  (1, 4, True), (2, 4, True)])
+    def test_is_valid_linkage_various_size(self, nrow, ncol, valid, xp):
+        # Tests is_valid_linkage(Z) with linkage matrices of various sizes
+        Z = xp.asarray([[0, 1, 3.0, 2, 5],
+                        [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+        Z = Z[:nrow, :ncol]
+        xp_assert_equal(is_valid_linkage(Z), valid, check_namespace=False)
+        if not valid:
+            assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_int_type(self, xp):
+        # Tests is_valid_linkage(Z) with integer type.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.int64)
+        xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+        assert_raises(TypeError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_empty(self, xp):
+        # Tests is_valid_linkage(Z) with empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+        assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            xp_assert_equal(is_valid_linkage(Z), True, check_namespace=False)
+
+    def test_is_valid_linkage_4_and_up_neg_index_left(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative indices (left).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 0].set(-2)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up_neg_index_right(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative indices (right).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 1].set(-2)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up_neg_dist(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative distances.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 2].set(-0.5)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up_neg_counts(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative counts.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 3].set(-2)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+
+@make_xp_test_case(is_valid_im)
+class TestIsValidInconsistent:
+
+    def test_is_valid_im_int_type(self, xp):
+        # Tests is_valid_im(R) with integer type.
+        R = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.int64)
+        xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+        assert_raises(TypeError, is_valid_im, R, throw=True)
+
+    @pytest.mark.parametrize("nrow, ncol, valid", [(2, 5, False), (2, 3, False),
+                                                  (1, 4, True), (2, 4, True)])
+    def test_is_valid_im_various_size(self, nrow, ncol, valid, xp):
+        # Tests is_valid_im(R) with linkage matrices of various sizes
+        R = xp.asarray([[0, 1, 3.0, 2, 5],
+                        [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+        R = R[:nrow, :ncol]
+        xp_assert_equal(is_valid_im(R), valid, check_namespace=False)
+        if not valid:
+            assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    def test_is_valid_im_empty(self, xp):
+        # Tests is_valid_im(R) with empty inconsistency matrix.
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+        assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    def test_is_valid_im_4_and_up(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), True, check_namespace=False)
+
+    def test_is_valid_im_4_and_up_neg_index_left(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link height means.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xpx.at(R)[i//2 , 0].set(-2.0)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_im(R, throw=True)
+
+    def test_is_valid_im_4_and_up_neg_index_right(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link height standard deviations.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xpx.at(R)[i//2 , 1].set(-2.0)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_im(R, throw=True)
+
+    def test_is_valid_im_4_and_up_neg_dist(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link counts.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xpx.at(R)[i//2, 2].set(-0.5)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_im(R, throw=True)
+
+
+class TestNumObsLinkage:
+
+    def test_num_obs_linkage_empty(self, xp):
+        # Tests num_obs_linkage(Z) with empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, num_obs_linkage, Z)
+
+    def test_num_obs_linkage_1x4(self, xp):
+        # Tests num_obs_linkage(Z) on linkage over 2 observations.
+        Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+        assert num_obs_linkage(Z) == 2
+
+    def test_num_obs_linkage_2x4(self, xp):
+        # Tests num_obs_linkage(Z) on linkage over 3 observations.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.float64)
+        assert num_obs_linkage(Z) == 3
+
+    def test_num_obs_linkage_4_and_up(self, xp):
+        # Tests num_obs_linkage(Z) on linkage on observation sets between sizes
+        # 4 and 15 (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            assert num_obs_linkage(Z) == i
+
+    def test_num_obs_linkage_multi_matrix(self, xp):
+        # Tests num_obs_linkage with observation matrices of multiple sizes.
+        for n in range(2, 10):
+            X = np.random.rand(n, 4)
+            Y = pdist(X)
+            Z = xp.asarray(linkage(Y))
+            assert num_obs_linkage(Z) == n
+
+
+@make_xp_test_case(leaves_list, to_tree)
+class TestLeavesList:
+
+    def test_leaves_list_1x4(self, xp):
+        # Tests leaves_list(Z) on a 1x4 linkage.
+        Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+        to_tree(Z)
+        assert_allclose(leaves_list(Z), [0, 1], rtol=1e-15)
+
+    def test_leaves_list_2x4(self, xp):
+        # Tests leaves_list(Z) on a 2x4 linkage.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.float64)
+        to_tree(Z)
+        assert_allclose(leaves_list(Z), [0, 1, 2], rtol=1e-15)
+
+    @pytest.mark.parametrize("method",
+        ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward'])
+    def test_leaves_list_Q(self, method, xp):
+        # Tests leaves_list(Z) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, method))
+        node = to_tree(Z)
+        assert_allclose(node.pre_order(), leaves_list(Z), rtol=1e-15)
+
+    def test_Q_subtree_pre_order(self, xp):
+        # Tests that pre_order() works when called on sub-trees.
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, 'single'))
+        node = to_tree(Z)
+        assert_allclose(node.pre_order(),
+                        (node.get_left().pre_order() + node.get_right().pre_order()),
+                        rtol=1e-15)
+
+
+@make_xp_test_case(correspond)
+class TestCorrespond:
+
+    def test_correspond_empty(self, xp):
+        # Tests correspond(Z, y) with empty linkage and condensed distance matrix.
+        y = xp.zeros((0,), dtype=xp.float64)
+        Z = xp.zeros((0,4), dtype=xp.float64)
+        assert_raises(ValueError, correspond, Z, y)
+
+    def test_correspond_2_and_up(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes.
+        for i in range(2, 4):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            assert_(correspond(Z, y))
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            assert_(correspond(Z, y))
+
+    def test_correspond_4_and_up(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes. Correspondence should be false.
+        for (i, j) in (list(zip(list(range(2, 4)), list(range(3, 5)))) +
+                       list(zip(list(range(3, 5)), list(range(2, 4))))):
+            y = np.random.rand(i*(i-1)//2)
+            y2 = np.random.rand(j*(j-1)//2)
+            Z = xp.asarray(linkage(y))
+            Z2 = xp.asarray(linkage(y2))
+            y = xp.asarray(y)
+            y2 = xp.asarray(y2)
+            assert not correspond(Z, y2)
+            assert not correspond(Z2, y)
+
+    def test_correspond_4_and_up_2(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes. Correspondence should be false.
+        for (i, j) in (list(zip(list(range(2, 7)), list(range(16, 21)))) +
+                       list(zip(list(range(2, 7)), list(range(16, 21))))):
+            y = np.random.rand(i*(i-1)//2)
+            y2 = np.random.rand(j*(j-1)//2)
+            Z = xp.asarray(linkage(y))
+            Z2 = xp.asarray(linkage(y2))
+            y = xp.asarray(y)
+            y2 = xp.asarray(y2)
+            assert not correspond(Z, y2)
+            assert not correspond(Z2, y)
+
+
+@make_xp_test_case(is_monotonic)
+class TestIsMonotonic:
+
+    def test_is_monotonic_empty(self, xp):
+        # Tests is_monotonic(Z) on an empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, is_monotonic, Z)
+
+    def test_is_monotonic_1x4(self, xp):
+        # Tests is_monotonic(Z) on 1x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_2x4_T(self, xp):
+        # Tests is_monotonic(Z) on 2x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 3]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_2x4_F(self, xp):
+        # Tests is_monotonic(Z) on 2x4 linkage. Expecting False.
+        Z = xp.asarray([[0, 1, 0.4, 2],
+                        [2, 3, 0.3, 3]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_T(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F1(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.2, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F2(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False.
+        Z = xp.asarray([[0, 1, 0.8, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F3(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.2, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_tdist_linkage1(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # tdist data set. Expecting True.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_tdist_linkage2(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # tdist data set. Perturbing. Expecting False.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        Z = xpx.at(Z)[2, 2].set(0.0)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_Q_linkage(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # Q data set. Expecting True.
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, 'single'))
+        assert is_monotonic(Z)
+
+
+@make_xp_test_case(maxdists)
+class TestMaxDists:
+
+    def test_maxdists_empty_linkage(self, xp):
+        # Tests maxdists(Z) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxdists, Z)
+
+    def test_maxdists_one_cluster_linkage(self, xp):
+        # Tests maxdists(Z) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        MD = maxdists(Z)
+        expectedMD = calculate_maximum_distances(Z, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        "method", ['single', 'complete', 'ward', 'centroid', 'median'])
+    def test_maxdists_Q_linkage(self, method, xp):
+        # Tests maxdists(Z) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, method))
+        MD = maxdists(Z)
+        expectedMD = calculate_maximum_distances(Z, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@make_xp_test_case(maxinconsts)
+class TestMaxInconsts:
+
+    def test_maxinconsts_empty_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxinconsts, Z, R)
+
+    def test_maxinconsts_difrow_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on linkage and inconsistency matrices with
+        # different numbers of clusters. Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = np.random.rand(2, 4)
+        R = xp.asarray(R)
+        assert_raises(ValueError, maxinconsts, Z, R)
+
+    def test_maxinconsts_one_cluster_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        MD = maxinconsts(Z, R)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        "method", ['single', 'complete', 'ward', 'centroid', 'median'])
+    def test_maxinconsts_Q_linkage(self, method, xp):
+        # Tests maxinconsts(Z, R) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = linkage(X, method)
+        R = xp.asarray(inconsistent(Z))
+        Z = xp.asarray(Z)
+        MD = maxinconsts(Z, R)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@make_xp_test_case(maxRstat)
+class TestMaxRStat:
+
+    def test_maxRstat_invalid_index(self, xp):
+        # Tests maxRstat(Z, R, i). Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        with pytest.raises(TypeError):
+            maxRstat(Z, R, 3.3)
+        with pytest.raises(ValueError):
+            maxRstat(Z, R, -1)
+        with pytest.raises(ValueError):
+            maxRstat(Z, R, 4)
+
+    @pytest.mark.parametrize("i", range(4))
+    def test_maxRstat_empty_linkage(self, i, xp):
+        # Tests maxRstat(Z, R, i) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxRstat, Z, R, i)
+
+    @pytest.mark.parametrize("i", range(4))
+    def test_maxRstat_difrow_linkage(self, i, xp):
+        # Tests maxRstat(Z, R, i) on linkage and inconsistency matrices with
+        # different numbers of clusters. Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = np.random.rand(2, 4)
+        R = xp.asarray(R)
+        assert_raises(ValueError, maxRstat, Z, R, i)
+
+    def test_maxRstat_one_cluster_linkage(self, xp):
+        # Tests maxRstat(Z, R, i) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        MD = maxRstat(Z, R, 1)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        "method", ['single', 'complete', 'ward', 'centroid', 'median'])
+    def test_maxRstat_Q_linkage(self, method, xp):
+        # Tests maxRstat(Z, R, 1) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = linkage(X, method)
+        R = xp.asarray(inconsistent(Z))
+        Z = xp.asarray(Z)
+        MD = maxRstat(Z, R, 1)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@make_xp_test_case(dendrogram)
+class TestDendrogram:
+
+    def test_dendrogram_single_linkage_tdist(self, xp):
+        # Tests dendrogram calculation on single linkage of the tdist data set.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        R = dendrogram(Z, no_plot=True)
+        leaves = R["leaves"]
+        assert_equal(leaves, [2, 5, 1, 0, 3, 4])
+
+    def test_valid_orientation(self, xp):
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        assert_raises(ValueError, dendrogram, Z, orientation="foo")
+
+    def test_labels_as_array_or_list(self, xp):
+        # test for gh-12418
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        labels = [1, 3, 2, 6, 4, 5]
+        result1 = dendrogram(Z, labels=xp.asarray(labels), no_plot=True)
+        result2 = dendrogram(Z, labels=labels, no_plot=True)
+        assert result1 == result2
+
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_valid_label_size(self, xp):
+        link = xp.asarray([
+            [0, 1, 1.0, 4],
+            [2, 3, 1.0, 5],
+            [4, 5, 2.0, 6],
+        ])
+        plt.figure()
+        with pytest.raises(ValueError) as exc_info:
+            dendrogram(link, labels=list(range(100)))
+        assert "Dimensions of Z and labels must be consistent."\
+               in str(exc_info.value)
+
+        with pytest.raises(
+                ValueError,
+                match="Dimensions of Z and labels must be consistent."):
+            dendrogram(link, labels=[])
+
+        plt.close()
+
+    @skip_xp_backends('torch',
+         reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+                ' and NumPy 2.0'
+    )
+    @skip_xp_backends('dask.array',
+         reason='dask.array has bad interaction with matplotlib'
+    )
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    @pytest.mark.parametrize("orientation", ['top', 'bottom', 'left', 'right'])
+    def test_dendrogram_plot(self, orientation, xp):
+        # Tests dendrogram plotting.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        expected = {'color_list': ['C1', 'C0', 'C0', 'C0', 'C0'],
+                    'dcoord': [[0.0, 138.0, 138.0, 0.0],
+                               [0.0, 219.0, 219.0, 0.0],
+                               [0.0, 255.0, 255.0, 219.0],
+                               [0.0, 268.0, 268.0, 255.0],
+                               [138.0, 295.0, 295.0, 268.0]],
+                    'icoord': [[5.0, 5.0, 15.0, 15.0],
+                               [45.0, 45.0, 55.0, 55.0],
+                               [35.0, 35.0, 50.0, 50.0],
+                               [25.0, 25.0, 42.5, 42.5],
+                               [10.0, 10.0, 33.75, 33.75]],
+                    'ivl': ['2', '5', '1', '0', '3', '4'],
+                    'leaves': [2, 5, 1, 0, 3, 4],
+                    'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0', 'C0'],
+                    }
+
+        fig = plt.figure()
+        ax = fig.add_subplot(221)
+
+        # test that dendrogram accepts ax keyword
+        R1 = dendrogram(Z, ax=ax, orientation=orientation)
+        R1['dcoord'] = np.asarray(R1['dcoord'])
+        assert_equal(R1, expected)
+
+        # test that dendrogram accepts and handle the leaf_font_size and
+        # leaf_rotation keywords
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_font_size=20, leaf_rotation=90)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_rotation(), 90)
+        assert_equal(testlabel.get_size(), 20)
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_rotation=90)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_rotation(), 90)
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_font_size=20)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_size(), 20)
+        plt.close()
+
+        # test plotting to gca (will import pylab)
+        R2 = dendrogram(Z, orientation=orientation)
+        plt.close()
+        R2['dcoord'] = np.asarray(R2['dcoord'])
+        assert_equal(R2, expected)
+
+    @skip_xp_backends('torch',
+          reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+                 ' and NumPy 2.0'
+     )
+    @skip_xp_backends('dask.array',
+         reason='dask.array has bad interaction with matplotlib'
+    )
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_dendrogram_truncate_mode(self, xp):
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+
+        R = dendrogram(Z, 2, 'lastp', show_contracted=True)
+        plt.close()
+        R['dcoord'] = np.asarray(R['dcoord'])
+        assert_equal(R, {'color_list': ['C0'],
+                         'dcoord': [[0.0, 295.0, 295.0, 0.0]],
+                         'icoord': [[5.0, 5.0, 15.0, 15.0]],
+                         'ivl': ['(2)', '(4)'],
+                         'leaves': [6, 9],
+                         'leaves_color_list': ['C0', 'C0'],
+                         })
+
+        R = dendrogram(Z, 2, 'mtica', show_contracted=True)
+        plt.close()
+        R['dcoord'] = np.asarray(R['dcoord'])
+        assert_equal(R, {'color_list': ['C1', 'C0', 'C0', 'C0'],
+                         'dcoord': [[0.0, 138.0, 138.0, 0.0],
+                                    [0.0, 255.0, 255.0, 0.0],
+                                    [0.0, 268.0, 268.0, 255.0],
+                                    [138.0, 295.0, 295.0, 268.0]],
+                         'icoord': [[5.0, 5.0, 15.0, 15.0],
+                                    [35.0, 35.0, 45.0, 45.0],
+                                    [25.0, 25.0, 40.0, 40.0],
+                                    [10.0, 10.0, 32.5, 32.5]],
+                         'ivl': ['2', '5', '1', '0', '(2)'],
+                         'leaves': [2, 5, 1, 0, 7],
+                         'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0'],
+                         })
+
+    @pytest.fixture
+    def dendrogram_lock(self):
+        return Lock()
+
+    def test_dendrogram_colors(self, xp, dendrogram_lock):
+        # Tests dendrogram plots with alternate colors
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+
+        with dendrogram_lock:
+            # Global color palette might be changed concurrently
+            set_link_color_palette(['c', 'm', 'y', 'k'])
+            R = dendrogram(Z, no_plot=True,
+                           above_threshold_color='g', color_threshold=250)
+            set_link_color_palette(['g', 'r', 'c', 'm', 'y', 'k'])
+
+            color_list = R['color_list']
+            assert_equal(color_list, ['c', 'm', 'g', 'g', 'g'])
+
+            # reset color palette (global list)
+            set_link_color_palette(None)
+
+    def test_dendrogram_leaf_colors_zero_dist(self, xp):
+        # tests that the colors of leafs are correct for tree
+        # with two identical points
+        X = np.asarray([[1, 0, 0],
+                        [0, 0, 1],
+                        [0, 2, 0],
+                        [0, 0, 1],
+                        [0, 1, 0],
+                        [0, 1, 0]])
+        Z = xp.asarray(linkage(X, "single"))
+        d = dendrogram(Z, no_plot=True)
+        exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+        colors = d["leaves_color_list"]
+        assert_equal(colors, exp_colors)
+
+    def test_dendrogram_leaf_colors(self, xp):
+        # tests that the colors are correct for a tree
+        # with two near points ((0, 0, 1.1) and (0, 0, 1))
+        X = np.asarray([[1, 0, 0],
+                        [0, 0, 1.1],
+                        [0, 2, 0],
+                        [0, 0, 1],
+                        [0, 1, 0],
+                        [0, 1, 0]])
+        Z = xp.asarray(linkage(X, "single"))
+        d = dendrogram(Z, no_plot=True)
+        exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+        colors = d["leaves_color_list"]
+        assert_equal(colors, exp_colors)
+
+
+def calculate_maximum_distances(Z, xp):
+    # Used for testing correctness of maxdists.
+    n = Z.shape[0] + 1
+    B = xp.zeros((n-1,), dtype=Z.dtype)
+    for i in range(0, n - 1):
+        q = xp.zeros((3,))
+        left = Z[i, 0]
+        right = Z[i, 1]
+        if left >= n:
+            b_left = B[xp.asarray(left, dtype=xp.int64) - n]
+            q = xpx.at(q, 0).set(b_left)
+        if right >= n:
+            b_right = B[xp.asarray(right, dtype=xp.int64) - n]
+            q = xpx.at(q, 1).set(b_right)
+        q = xpx.at(q, 2).set(Z[i, 2])
+        B = xpx.at(B, i).set(xp.max(q))
+    return B
+
+
+def calculate_maximum_inconsistencies(Z, R, k=3, xp=np):
+    # Used for testing correctness of maxinconsts.
+    n = Z.shape[0] + 1
+    dtype = xp.result_type(Z, R)
+    B = xp.zeros((n-1,), dtype=dtype)
+    for i in range(0, n - 1):
+        q = xp.zeros((3,))
+        left = Z[i, 0]
+        right = Z[i, 1]
+        if left >= n:
+            b_left = B[xp.asarray(left, dtype=xp.int64) - n]
+            q = xpx.at(q, 0).set(b_left)
+        if right >= n:
+            b_right = B[xp.asarray(right, dtype=xp.int64) - n]
+            q = xpx.at(q, 1).set(b_right)
+        q = xpx.at(q, 2).set(R[i, k])
+        B = xpx.at(B, i).set(xp.max(q))
+    return B
+
+
+@make_xp_test_case(to_tree)
+def test_node_compare(xp):
+    np.random.seed(23)
+    nobs = 50
+    X = np.random.randn(nobs, 4)
+    Z = xp.asarray(ward(X))
+    tree = to_tree(Z)
+    assert_(tree > tree.get_left())
+    assert_(tree.get_right() > tree.get_left())
+    assert_(tree.get_right() == tree.get_right())
+    assert_(tree.get_right() != tree.get_left())
+
+
+@make_xp_test_case(cut_tree)
+def test_cut_tree(xp):
+    np.random.seed(23)
+    nobs = 50
+    X = np.random.randn(nobs, 4)
+    Z = xp.asarray(ward(X))
+    cutree = cut_tree(Z)
+
+    # cutree.dtype varies between int32 and int64 over platforms
+    xp_assert_close(cutree[:, 0], xp.arange(nobs), rtol=1e-15, check_dtype=False)
+    xp_assert_close(cutree[:, -1], xp.zeros(nobs), rtol=1e-15, check_dtype=False)
+    assert_equal(np.asarray(cutree).max(0), np.arange(nobs - 1, -1, -1))
+
+    xp_assert_close(cutree[:, [-5]], cut_tree(Z, n_clusters=5), rtol=1e-15)
+    xp_assert_close(cutree[:, [-5, -10]], cut_tree(Z, n_clusters=[5, 10]), rtol=1e-15)
+    xp_assert_close(cutree[:, [-10, -5]], cut_tree(Z, n_clusters=[10, 5]), rtol=1e-15)
+
+    nodes = _order_cluster_tree(Z)
+    heights = xp.asarray([node.dist for node in nodes])
+
+    xp_assert_close(cutree[:, np.searchsorted(heights, [5])],
+                    cut_tree(Z, height=5), rtol=1e-15)
+    xp_assert_close(cutree[:, np.searchsorted(heights, [5, 10])],
+                    cut_tree(Z, height=[5, 10]), rtol=1e-15)
+    xp_assert_close(cutree[:, np.searchsorted(heights, [10, 5])],
+                    cut_tree(Z, height=[10, 5]), rtol=1e-15)
+
+
+@make_xp_test_case(optimal_leaf_ordering)
+def test_optimal_leaf_ordering(xp):
+    # test with the distance vector y
+    Z = optimal_leaf_ordering(xp.asarray(linkage(hierarchy_test_data.ytdist)),
+                              xp.asarray(hierarchy_test_data.ytdist))
+    expectedZ = hierarchy_test_data.linkage_ytdist_single_olo
+    xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    # test with the observation matrix X
+    Z = optimal_leaf_ordering(xp.asarray(linkage(hierarchy_test_data.X, 'ward')),
+                              xp.asarray(hierarchy_test_data.X))
+    expectedZ = hierarchy_test_data.linkage_X_ward_olo
+    xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+
+@skip_xp_backends(np_only=True, reason='`Heap` only supports NumPy backend')
+def test_Heap(xp):
+    values = xp.asarray([2, -1, 0, -1.5, 3])
+    heap = Heap(values)
+
+    pair = heap.get_min()
+    assert_equal(pair['key'], 3)
+    assert_equal(pair['value'], -1.5)
+
+    heap.remove_min()
+    pair = heap.get_min()
+    assert_equal(pair['key'], 1)
+    assert_equal(pair['value'], -1)
+
+    heap.change_value(1, 2.5)
+    pair = heap.get_min()
+    assert_equal(pair['key'], 2)
+    assert_equal(pair['value'], 0)
+
+    heap.remove_min()
+    heap.remove_min()
+
+    heap.change_value(1, 10)
+    pair = heap.get_min()
+    assert_equal(pair['key'], 4)
+    assert_equal(pair['value'], 3)
+
+    heap.remove_min()
+    pair = heap.get_min()
+    assert_equal(pair['key'], 1)
+    assert_equal(pair['value'], 10)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_vq.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b1a1c81e49a3e16305e2d4402f3d539d6507b08
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/tests/test_vq.py
@@ -0,0 +1,437 @@
+import math
+import sys
+import warnings
+from copy import deepcopy
+from threading import Lock
+
+import numpy as np
+from numpy.testing import assert_array_equal
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.cluster.vq import (kmeans, kmeans2, py_vq, vq, whiten,
+                              ClusterError, _krandinit)
+from scipy.cluster import _vq
+from scipy.sparse._sputils import matrix
+
+from scipy._lib import array_api_extra as xpx
+from scipy._lib._array_api import (
+    SCIPY_ARRAY_API, eager_warns, is_lazy_array, make_xp_test_case,
+    xp_copy, xp_assert_close, xp_assert_equal
+)
+
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+TESTDATA_2D = np.array([
+    -2.2, 1.17, -1.63, 1.69, -2.04, 4.38, -3.09, 0.95, -1.7, 4.79, -1.68, 0.68,
+    -2.26, 3.34, -2.29, 2.55, -1.72, -0.72, -1.99, 2.34, -2.75, 3.43, -2.45,
+    2.41, -4.26, 3.65, -1.57, 1.87, -1.96, 4.03, -3.01, 3.86, -2.53, 1.28,
+    -4.0, 3.95, -1.62, 1.25, -3.42, 3.17, -1.17, 0.12, -3.03, -0.27, -2.07,
+    -0.55, -1.17, 1.34, -2.82, 3.08, -2.44, 0.24, -1.71, 2.48, -5.23, 4.29,
+    -2.08, 3.69, -1.89, 3.62, -2.09, 0.26, -0.92, 1.07, -2.25, 0.88, -2.25,
+    2.02, -4.31, 3.86, -2.03, 3.42, -2.76, 0.3, -2.48, -0.29, -3.42, 3.21,
+    -2.3, 1.73, -2.84, 0.69, -1.81, 2.48, -5.24, 4.52, -2.8, 1.31, -1.67,
+    -2.34, -1.18, 2.17, -2.17, 2.82, -1.85, 2.25, -2.45, 1.86, -6.79, 3.94,
+    -2.33, 1.89, -1.55, 2.08, -1.36, 0.93, -2.51, 2.74, -2.39, 3.92, -3.33,
+    2.99, -2.06, -0.9, -2.83, 3.35, -2.59, 3.05, -2.36, 1.85, -1.69, 1.8,
+    -1.39, 0.66, -2.06, 0.38, -1.47, 0.44, -4.68, 3.77, -5.58, 3.44, -2.29,
+    2.24, -1.04, -0.38, -1.85, 4.23, -2.88, 0.73, -2.59, 1.39, -1.34, 1.75,
+    -1.95, 1.3, -2.45, 3.09, -1.99, 3.41, -5.55, 5.21, -1.73, 2.52, -2.17,
+    0.85, -2.06, 0.49, -2.54, 2.07, -2.03, 1.3, -3.23, 3.09, -1.55, 1.44,
+    -0.81, 1.1, -2.99, 2.92, -1.59, 2.18, -2.45, -0.73, -3.12, -1.3, -2.83,
+    0.2, -2.77, 3.24, -1.98, 1.6, -4.59, 3.39, -4.85, 3.75, -2.25, 1.71, -3.28,
+    3.38, -1.74, 0.88, -2.41, 1.92, -2.24, 1.19, -2.48, 1.06, -1.68, -0.62,
+    -1.3, 0.39, -1.78, 2.35, -3.54, 2.44, -1.32, 0.66, -2.38, 2.76, -2.35,
+    3.95, -1.86, 4.32, -2.01, -1.23, -1.79, 2.76, -2.13, -0.13, -5.25, 3.84,
+    -2.24, 1.59, -4.85, 2.96, -2.41, 0.01, -0.43, 0.13, -3.92, 2.91, -1.75,
+    -0.53, -1.69, 1.69, -1.09, 0.15, -2.11, 2.17, -1.53, 1.22, -2.1, -0.86,
+    -2.56, 2.28, -3.02, 3.33, -1.12, 3.86, -2.18, -1.19, -3.03, 0.79, -0.83,
+    0.97, -3.19, 1.45, -1.34, 1.28, -2.52, 4.22, -4.53, 3.22, -1.97, 1.75,
+    -2.36, 3.19, -0.83, 1.53, -1.59, 1.86, -2.17, 2.3, -1.63, 2.71, -2.03,
+    3.75, -2.57, -0.6, -1.47, 1.33, -1.95, 0.7, -1.65, 1.27, -1.42, 1.09, -3.0,
+    3.87, -2.51, 3.06, -2.6, 0.74, -1.08, -0.03, -2.44, 1.31, -2.65, 2.99,
+    -1.84, 1.65, -4.76, 3.75, -2.07, 3.98, -2.4, 2.67, -2.21, 1.49, -1.21,
+    1.22, -5.29, 2.38, -2.85, 2.28, -5.6, 3.78, -2.7, 0.8, -1.81, 3.5, -3.75,
+    4.17, -1.29, 2.99, -5.92, 3.43, -1.83, 1.23, -1.24, -1.04, -2.56, 2.37,
+    -3.26, 0.39, -4.63, 2.51, -4.52, 3.04, -1.7, 0.36, -1.41, 0.04, -2.1, 1.0,
+    -1.87, 3.78, -4.32, 3.59, -2.24, 1.38, -1.99, -0.22, -1.87, 1.95, -0.84,
+    2.17, -5.38, 3.56, -1.27, 2.9, -1.79, 3.31, -5.47, 3.85, -1.44, 3.69,
+    -2.02, 0.37, -1.29, 0.33, -2.34, 2.56, -1.74, -1.27, -1.97, 1.22, -2.51,
+    -0.16, -1.64, -0.96, -2.99, 1.4, -1.53, 3.31, -2.24, 0.45, -2.46, 1.71,
+    -2.88, 1.56, -1.63, 1.46, -1.41, 0.68, -1.96, 2.76, -1.61,
+    2.11]).reshape((200, 2))
+
+
+# Global data
+X = np.array([[3.0, 3], [4, 3], [4, 2],
+              [9, 2], [5, 1], [6, 2], [9, 4],
+              [5, 2], [5, 4], [7, 4], [6, 5]])
+
+CODET1 = np.array([[3.0000, 3.0000],
+                   [6.2000, 4.0000],
+                   [5.8000, 1.8000]])
+
+CODET2 = np.array([[11.0/3, 8.0/3],
+                   [6.7500, 4.2500],
+                   [6.2500, 1.7500]])
+
+LABEL1 = np.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1])
+
+
+@make_xp_test_case(whiten)
+class TestWhiten:
+
+    def test_whiten(self, xp):
+        desired = xp.asarray([[5.08738849, 2.97091878],
+                            [3.19909255, 0.69660580],
+                            [4.51041982, 0.02640918],
+                            [4.38567074, 0.95120889],
+                            [2.32191480, 1.63195503]])
+
+        obs = xp.asarray([[0.98744510, 0.82766775],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+        xp_assert_close(whiten(obs), desired, rtol=1e-5)
+
+    def test_whiten_zero_std(self, xp):
+        desired = xp.asarray([[0., 1.0, 2.86666544],
+                              [0., 1.0, 1.32460034],
+                              [0., 1.0, 3.74382172]])
+
+        obs = xp.asarray([[0., 1., 0.74109533],
+                          [0., 1., 0.34243798],
+                          [0., 1., 0.96785929]])
+
+        with eager_warns(RuntimeWarning, match="Some columns have standard...", xp=xp):
+            actual = whiten(obs)
+        xp_assert_close(actual, desired, rtol=1e-5)
+
+    @pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning:dask")
+    @pytest.mark.parametrize("bad_value", [math.nan, math.inf, -math.inf])
+    def test_whiten_not_finite(self, bad_value, xp):
+        obs = xp.asarray([[0.98744510, bad_value],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+
+        if is_lazy_array(obs):
+            desired = xp.asarray([[5.08738849, math.nan],
+                                  [3.19909255, math.nan],
+                                  [4.51041982, math.nan],
+                                  [4.38567074, math.nan],
+                                  [2.32191480, math.nan]])
+            xp_assert_close(whiten(obs), desired, rtol=1e-5)
+        else:
+            assert_raises(ValueError, whiten, obs)
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_whiten_not_finite_matrix(self):
+        for bad_value in np.nan, np.inf, -np.inf:
+            obs = matrix([[0.98744510, bad_value],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+            assert_raises(ValueError, whiten, obs)
+
+
+@make_xp_test_case(vq)
+class TestVq:
+
+    def test_py_vq(self, xp):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        # label1.dtype varies between int32 and int64 over platforms
+        label1 = py_vq(xp.asarray(X), xp.asarray(initc))[0]
+        xp_assert_equal(label1, xp.asarray(LABEL1, dtype=xp.int64),
+                        check_dtype=False)
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_py_vq_matrix(self):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        # label1.dtype varies between int32 and int64 over platforms
+        label1 = py_vq(matrix(X), matrix(initc))[0]
+        assert_array_equal(label1, LABEL1)
+
+    def test_vq(self, xp):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        label1, _ = _vq.vq(X, initc)
+        assert_array_equal(label1, LABEL1)
+        _, _ = vq(xp.asarray(X), xp.asarray(initc))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_vq_matrix(self):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        label1, _ = _vq.vq(matrix(X), matrix(initc))
+        assert_array_equal(label1, LABEL1)
+        _, _ = vq(matrix(X), matrix(initc))
+
+    def test_vq_1d(self, xp):
+        # Test special rank 1 vq algo, python implementation.
+        data = X[:, 0]
+        initc = data[:3]
+        a, b = _vq.vq(data, initc)
+        data = xp.asarray(data)
+        initc = xp.asarray(initc)
+        ta, tb = py_vq(data[:, np.newaxis], initc[:, np.newaxis])
+        # ta.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(ta, xp.asarray(a, dtype=xp.int64), check_dtype=False)
+        xp_assert_equal(tb, xp.asarray(b))
+
+    def test__vq_sametype(self):
+        a = np.asarray([1.0, 2.0])
+        b = a.astype(np.float32)
+        assert_raises(TypeError, _vq.vq, a, b)
+
+    def test__vq_invalid_type(self):
+        a = np.asarray([1, 2], dtype=int)
+        assert_raises(TypeError, _vq.vq, a, a)
+
+    def test_vq_large_nfeat(self, xp):
+        X = np.random.rand(20, 20)
+        code_book = np.random.rand(3, 20)
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+        X = X.astype(np.float32)
+        code_book = code_book.astype(np.float32)
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0, dtype=xp.float64), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+    def test_vq_large_features(self, xp):
+        X = np.random.rand(10, 5) * 1000000
+        code_book = np.random.rand(2, 5) * 1000000
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+
+# Whole class skipped on GPU for now;
+# once pdist/cdist are hooked up for CuPy, more tests will work
+@make_xp_test_case(kmeans, kmeans2)
+class TestKMeans:
+
+    def test_large_features(self, xp):
+        # Generate a data set with large values, and run kmeans on it to
+        # (regression for 1077).
+        d = 300
+        n = 100
+
+        m1 = np.random.randn(d)
+        m2 = np.random.randn(d)
+        x = 10000 * np.random.randn(n, d) - 20000 * m1
+        y = 10000 * np.random.randn(n, d) + 20000 * m2
+
+        data = np.empty((x.shape[0] + y.shape[0], d), np.float64)
+        data[:x.shape[0]] = x
+        data[x.shape[0]:] = y
+
+        # use `seed` to ensure backwards compatibility after SPEC7
+        kmeans(xp.asarray(data), 2, seed=1)
+
+    def test_kmeans_simple(self, xp):
+        rng = np.random.default_rng(54321)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans(xp.asarray(X), xp.asarray(initc), iter=1, rng=rng)[0]
+        xp_assert_close(code1, xp.asarray(CODET2))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_kmeans_simple_matrix(self):
+        rng = np.random.default_rng(54321)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+        xp_assert_close(code1, CODET2)
+
+    def test_kmeans_lost_cluster(self, xp):
+        # This will cause kmeans to have a cluster with no points.
+        data = xp.asarray(TESTDATA_2D)
+        initk = xp.asarray([[-1.8127404, -0.67128041],
+                            [2.04621601, 0.07401111],
+                            [-2.31149087, -0.05160469]])
+
+        kmeans(data, initk)
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                ("One of the clusters is empty. Re-run kmeans with a different "
+                 "initialization"),
+                UserWarning,
+            )
+            kmeans2(data, initk, missing='warn')
+
+        assert_raises(ClusterError, kmeans2, data, initk, missing='raise')
+
+    def test_kmeans2_simple(self, xp):
+        rng = np.random.default_rng(12345678)
+        initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]]))
+        arrays = [xp.asarray] if SCIPY_ARRAY_API else [np.asarray, matrix]
+        for tp in arrays:
+            code1 = kmeans2(tp(X), tp(initc), iter=1, rng=rng)[0]
+            code2 = kmeans2(tp(X), tp(initc), iter=2, rng=rng)[0]
+
+            xp_assert_close(code1, xp.asarray(CODET1))
+            xp_assert_close(code2, xp.asarray(CODET2))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_kmeans2_simple_matrix(self):
+        rng = np.random.default_rng(12345678)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans2(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+        code2 = kmeans2(matrix(X), matrix(initc), iter=2, rng=rng)[0]
+
+        xp_assert_close(code1, CODET1)
+        xp_assert_close(code2, CODET2)
+
+    def test_kmeans2_rank1(self, xp):
+        data = xp.asarray(TESTDATA_2D)
+        data1 = data[:, 0]
+
+        initc = data1[:3]
+        code = xp_copy(initc, xp=xp)
+
+        # use `seed` to ensure backwards compatibility after SPEC7
+        kmeans2(data1, code, iter=1, seed=1)[0]
+        kmeans2(data1, code, iter=2)[0]
+
+    def test_kmeans2_rank1_2(self, xp):
+        data = xp.asarray(TESTDATA_2D)
+        data1 = data[:, 0]
+        kmeans2(data1, 2, iter=1)
+
+    def test_kmeans2_high_dim(self, xp):
+        # test kmeans2 when the number of dimensions exceeds the number
+        # of input points
+        data = xp.asarray(TESTDATA_2D)
+        data = xp.reshape(data, (20, 20))[:10, :]
+        kmeans2(data, 2)
+
+    def test_kmeans2_init(self, xp):
+        rng = np.random.default_rng(12345678)
+        data = xp.asarray(TESTDATA_2D)
+        k = 3
+
+        kmeans2(data, k, minit='points', rng=rng)
+        kmeans2(data[:, 1], k, minit='points', rng=rng)  # special case (1-D)
+
+        kmeans2(data, k, minit='++', rng=rng)
+        kmeans2(data[:, 1], k, minit='++', rng=rng)  # special case (1-D)
+
+        # minit='random' can give warnings, filter those
+        with warnings.catch_warnings():
+            warnings.filterwarnings("ignore", "One of the clusters is empty. Re-run.")
+            kmeans2(data, k, minit='random', rng=rng)
+            kmeans2(data[:, 1], k, minit='random', rng=rng)  # special case (1-D)
+
+    @pytest.fixture
+    def krand_lock(self):
+        return Lock()
+
+    @xfail_xp_backends('dask.array', reason="Wrong answer")
+    @pytest.mark.skipif(sys.platform == 'win32',
+                        reason='Fails with MemoryError in Wine.')
+    def test_krandinit(self, xp, krand_lock):
+        data = xp.asarray(TESTDATA_2D)
+        datas = [xp.reshape(data, (200, 2)),
+                 xp.reshape(data, (20, 20))[:10, :]]
+        k = int(1e6)
+        with krand_lock:
+            for data in datas:
+                rng = np.random.default_rng(1234)
+                init = _krandinit(data, k, rng, xp)
+                orig_cov = xpx.cov(data.T, xp=xp)
+                init_cov = xpx.cov(init.T, xp=xp)
+                xp_assert_close(orig_cov, init_cov, atol=1.1e-2)
+
+    def test_kmeans2_empty(self, xp):
+        # Regression test for gh-1032.
+        assert_raises(ValueError, kmeans2, xp.asarray([]), 2)
+
+    def test_kmeans_0k(self, xp):
+        # Regression test for gh-1073: fail when k arg is 0.
+        assert_raises(ValueError, kmeans, xp.asarray(X), 0)
+        assert_raises(ValueError, kmeans2, xp.asarray(X), 0)
+        assert_raises(ValueError, kmeans2, xp.asarray(X), xp.asarray([]))
+
+    def test_kmeans_large_thres(self, xp):
+        # Regression test for gh-1774
+        x = xp.asarray([1, 2, 3, 4, 10], dtype=xp.float64)
+        res = kmeans(x, 1, thresh=1e16)
+        xp_assert_close(res[0], xp.asarray([4.], dtype=xp.float64))
+        xp_assert_close(res[1], xp.asarray(2.3999999999999999, dtype=xp.float64)[()])
+
+    def test_kmeans2_kpp_low_dim(self, xp):
+        # Regression test for gh-11462
+        rng = np.random.default_rng(2358792345678234568)
+        prev_res = xp.asarray([[-1.95266667, 0.898],
+                               [-3.153375, 3.3945]], dtype=xp.float64)
+        res, _ = kmeans2(xp.asarray(TESTDATA_2D), 2, minit='++', rng=rng)
+        xp_assert_close(res, prev_res)
+
+    def test_kmeans2_kpp_high_dim(self, xp):
+        # Regression test for gh-11462
+        rng = np.random.default_rng(23587923456834568)
+        n_dim = 100
+        size = 10
+        centers = np.vstack([5 * np.ones(n_dim),
+                             -5 * np.ones(n_dim)])
+
+        data = np.vstack([
+            rng.multivariate_normal(centers[0], np.eye(n_dim), size=size),
+            rng.multivariate_normal(centers[1], np.eye(n_dim), size=size)
+        ])
+
+        data = xp.asarray(data)
+        res, _ = kmeans2(data, 2, minit='++', rng=rng)
+        xp_assert_equal(xp.sign(res), xp.sign(xp.asarray(centers)))
+
+    def test_kmeans_diff_convergence(self, xp):
+        # Regression test for gh-8727
+        obs = xp.asarray([-3, -1, 0, 1, 1, 8], dtype=xp.float64)
+        res = kmeans(obs, xp.asarray([-3., 0.99]))
+        xp_assert_close(res[0], xp.asarray([-0.4,  8.], dtype=xp.float64))
+        xp_assert_close(res[1], xp.asarray(1.0666666666666667, dtype=xp.float64)[()])
+
+    def test_kmeans_and_kmeans2_random_seed(self, xp):
+
+        seed_list = [
+            1234, np.random.RandomState(1234), np.random.default_rng(1234)
+        ]
+
+        for seed in seed_list:
+            seed1 = deepcopy(seed)
+            seed2 = deepcopy(seed)
+            data = xp.asarray(TESTDATA_2D)
+            # test for kmeans
+            res1, _ = kmeans(data, 2, seed=seed1)
+            res2, _ = kmeans(data, 2, seed=seed2)
+            xp_assert_close(res1, res2)  # should be same results
+            # test for kmeans2
+            for minit in ["random", "points", "++"]:
+                res1, _ = kmeans2(data, 2, minit=minit, seed=seed1)
+                res2, _ = kmeans2(data, 2, minit=minit, seed=seed2)
+                xp_assert_close(res1, res2)  # should be same results
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/vq.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3e238ea44a8855704e47e02f38bacefd132b652
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/vq.py
@@ -0,0 +1,832 @@
+"""
+K-means clustering and vector quantization (:mod:`scipy.cluster.vq`)
+====================================================================
+
+Provides routines for k-means clustering, generating code books
+from k-means models and quantizing vectors by comparing them with
+centroids in a code book.
+
+.. autosummary::
+   :toctree: generated/
+
+   whiten -- Normalize a group of observations so each feature has unit variance
+   vq -- Calculate code book membership of a set of observation vectors
+   kmeans -- Perform k-means on a set of observation vectors forming k clusters
+   kmeans2 -- A different implementation of k-means with more methods
+           -- for initializing centroids
+
+Background information
+----------------------
+The k-means algorithm takes as input the number of clusters to
+generate, k, and a set of observation vectors to cluster. It
+returns a set of centroids, one for each of the k clusters. An
+observation vector is classified with the cluster number or
+centroid index of the centroid closest to it.
+
+A vector v belongs to cluster i if it is closer to centroid i than
+any other centroid. If v belongs to i, we say centroid i is the
+dominating centroid of v. The k-means algorithm tries to
+minimize distortion, which is defined as the sum of the squared distances
+between each observation vector and its dominating centroid.
+The minimization is achieved by iteratively reclassifying
+the observations into clusters and recalculating the centroids until
+a configuration is reached in which the centroids are stable. One can
+also define a maximum number of iterations.
+
+Since vector quantization is a natural application for k-means,
+information theory terminology is often used. The centroid index
+or cluster index is also referred to as a "code" and the table
+mapping codes to centroids and, vice versa, is often referred to as a
+"code book". The result of k-means, a set of centroids, can be
+used to quantize vectors. Quantization aims to find an encoding of
+vectors that reduces the expected distortion.
+
+All routines expect obs to be an M by N array, where the rows are
+the observation vectors. The codebook is a k by N array, where the
+ith row is the centroid of code word i. The observation vectors
+and centroids have the same feature dimension.
+
+As an example, suppose we wish to compress a 24-bit color image
+(each pixel is represented by one byte for red, one for blue, and
+one for green) before sending it over the web. By using a smaller
+8-bit encoding, we can reduce the amount of data by two
+thirds. Ideally, the colors for each of the 256 possible 8-bit
+encoding values should be chosen to minimize distortion of the
+color. Running k-means with k=256 generates a code book of 256
+codes, which fills up all possible 8-bit sequences. Instead of
+sending a 3-byte value for each pixel, the 8-bit centroid index
+(or code word) of the dominating centroid is transmitted. The code
+book is also sent over the wire so each 8-bit code can be
+translated back to a 24-bit pixel value representation. If the
+image of interest was of an ocean, we would expect many 24-bit
+blues to be represented by 8-bit codes. If it was an image of a
+human face, more flesh-tone colors would be represented in the
+code book.
+
+"""
+import warnings
+import numpy as np
+from collections import deque
+from scipy._lib._array_api import (_asarray, array_namespace, is_lazy_array,
+                                   xp_capabilities, xp_copy, xp_size)
+from scipy._lib._util import (check_random_state, rng_integers,
+                              _transition_to_rng)
+from scipy._lib import array_api_extra as xpx
+from scipy.spatial.distance import cdist
+
+from . import _vq
+
+__docformat__ = 'restructuredtext'
+
+__all__ = ['whiten', 'vq', 'kmeans', 'kmeans2']
+
+
+class ClusterError(Exception):
+    pass
+
+
+@xp_capabilities()
+def whiten(obs, check_finite=None):
+    """
+    Normalize a group of observations on a per feature basis.
+
+    Before running k-means, it is beneficial to rescale each feature
+    dimension of the observation set by its standard deviation (i.e. "whiten"
+    it - as in "white noise" where each frequency has equal power).
+    Each feature is divided by its standard deviation across all observations
+    to give it unit variance.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the array is an observation.  The
+        columns are the features seen during each observation::
+
+            #        f0  f1  f2
+            obs = [[ 1., 1., 1.],  #o0
+                   [ 2., 2., 2.],  #o1
+                   [ 3., 3., 3.],  #o2
+                   [ 4., 4., 4.]]  #o3
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True for eager backends and False for lazy ones.
+
+    Returns
+    -------
+    result : ndarray
+        Contains the values in `obs` scaled by the standard deviation
+        of each column.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import whiten
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7,]])
+    >>> whiten(features)
+    array([[ 4.17944278,  2.69811351,  7.21248917],
+           [ 3.29956009,  2.93273208,  9.33380951],
+           [ 1.75976538,  0.7038557 ,  7.21248917]])
+
+    """
+    xp = array_namespace(obs)
+    if check_finite is None:
+        check_finite = not is_lazy_array(obs)
+    obs = _asarray(obs, check_finite=check_finite, xp=xp)
+    std_dev = xp.std(obs, axis=0)
+    zero_std_mask = std_dev == 0
+    std_dev = xpx.at(std_dev, zero_std_mask).set(1.0)
+    if check_finite and xp.any(zero_std_mask):
+        warnings.warn("Some columns have standard deviation zero. "
+                      "The values of these columns will not change.",
+                      RuntimeWarning, stacklevel=2)
+    return obs / std_dev
+
+
+@xp_capabilities(cpu_only=True, reason="uses spatial.distance.cdist",
+                 jax_jit=False, allow_dask_compute=True)
+def vq(obs, code_book, check_finite=True):
+    """
+    Assign codes from a code book to observations.
+
+    Assigns a code from a code book to each observation. Each
+    observation vector in the 'M' by 'N' `obs` array is compared with the
+    centroids in the code book and assigned the code of the closest
+    centroid.
+
+    The features in `obs` should have unit variance, which can be
+    achieved by passing them through the whiten function. The code
+    book can be created with the k-means algorithm or a different
+    encoding algorithm.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the 'M' x 'N' array is an observation. The columns are
+        the "features" seen during each observation. The features must be
+        whitened first using the whiten function or something equivalent.
+    code_book : ndarray
+        The code book is usually generated using the k-means algorithm.
+        Each row of the array holds a different code, and the columns are
+        the features of the code::
+
+            #              f0  f1  f2  f3
+            code_book = [[ 1., 2., 3., 4.],  #c0
+                         [ 1., 2., 3., 4.],  #c1
+                         [ 1., 2., 3., 4.]]  #c2
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        A length M array holding the code book index for each observation.
+    dist : ndarray
+        The distortion (distance) between the observation and its nearest
+        code.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq
+    >>> code_book = np.array([[1., 1., 1.],
+    ...                       [2., 2., 2.]])
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7]])
+    >>> vq(features, code_book)
+    (array([1, 1, 0], dtype=int32), array([0.43588989, 0.73484692, 0.83066239]))
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+    ct = xp.result_type(obs, code_book)
+
+    if xp.isdtype(ct, kind='real floating'):
+        c_obs = xp.astype(obs, ct, copy=False)
+        c_code_book = xp.astype(code_book, ct, copy=False)
+        c_obs = np.asarray(c_obs)
+        c_code_book = np.asarray(c_code_book)
+        result = _vq.vq(c_obs, c_code_book)
+        return xp.asarray(result[0]), xp.asarray(result[1])
+    return py_vq(obs, code_book, check_finite=False)
+
+
+def py_vq(obs, code_book, check_finite=True):
+    """ Python version of vq algorithm.
+
+    The algorithm computes the Euclidean distance between each
+    observation and every frame in the code_book.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Expects a rank 2 array. Each row is one observation.
+    code_book : ndarray
+        Code book to use. Same format than obs. Should have same number of
+        features (e.g., columns) than obs.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        code[i] gives the label of the ith obversation; its code is
+        code_book[code[i]].
+    mind_dist : ndarray
+        min_dist[i] gives the distance between the ith observation and its
+        corresponding code.
+
+    Notes
+    -----
+    This function is slower than the C version but works for
+    all input types. If the inputs have the wrong types for the
+    C versions of the function, this one is called as a last resort.
+
+    It is about 20 times slower than the C version.
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+
+    if obs.ndim != code_book.ndim:
+        raise ValueError("Observation and code_book should have the same rank")
+
+    if obs.ndim == 1:
+        obs = obs[:, xp.newaxis]
+        code_book = code_book[:, xp.newaxis]
+
+    # Once `cdist` has array API support, this `xp.asarray` call can be removed
+    dist = xp.asarray(cdist(obs, code_book))
+    code = xp.argmin(dist, axis=1)
+    min_dist = xp.min(dist, axis=1)
+    return code, min_dist
+
+
+def _kmeans(obs, guess, thresh=1e-5, xp=None):
+    """ "raw" version of k-means.
+
+    Returns
+    -------
+    code_book
+        The lowest distortion codebook found.
+    avg_dist
+        The average distance a observation is from a code in the book.
+        Lower means the code_book matches the data better.
+
+    See Also
+    --------
+    kmeans : wrapper around k-means
+
+    Examples
+    --------
+    Note: not whitened in this example.
+
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import _kmeans
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 1.0,1.0]])
+    >>> book = np.array((features[0],features[2]))
+    >>> _kmeans(features,book)
+    (array([[ 1.7       ,  2.4       ],
+           [ 0.73333333,  1.13333333]]), 0.40563916697728591)
+
+    """
+    xp = np if xp is None else xp
+    code_book = guess
+    diff = xp.inf
+    prev_avg_dists = deque([diff], maxlen=2)
+
+    np_obs = np.asarray(obs)
+    while diff > thresh:
+        # compute membership and distances between obs and code_book
+        obs_code, distort = vq(obs, code_book, check_finite=False)
+        prev_avg_dists.append(xp.mean(distort, axis=-1))
+        # recalc code_book as centroids of associated obs
+        obs_code = np.asarray(obs_code)
+        code_book, has_members = _vq.update_cluster_means(np_obs, obs_code,
+                                                          code_book.shape[0])
+        code_book = code_book[has_members]
+        code_book = xp.asarray(code_book)
+        diff = xp.abs(prev_avg_dists[0] - prev_avg_dists[1])
+
+    return code_book, prev_avg_dists[1]
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+@_transition_to_rng("seed")
+def kmeans(obs, k_or_guess, iter=20, thresh=1e-5, check_finite=True,
+           *, rng=None):
+    """
+    Performs k-means on a set of observation vectors forming k clusters.
+
+    The k-means algorithm adjusts the classification of the observations
+    into clusters and updates the cluster centroids until the position of
+    the centroids is stable over successive iterations. In this
+    implementation of the algorithm, the stability of the centroids is
+    determined by comparing the absolute value of the change in the average
+    Euclidean distance between the observations and their corresponding
+    centroids against a threshold. This yields
+    a code book mapping centroids to codes and vice versa.
+
+    Parameters
+    ----------
+    obs : ndarray
+       Each row of the M by N array is an observation vector. The
+       columns are the features seen during each observation.
+       The features must be whitened first with the `whiten` function.
+
+    k_or_guess : int or ndarray
+       The number of centroids to generate. A code is assigned to
+       each centroid, which is also the row index of the centroid
+       in the code_book matrix generated.
+
+       The initial k centroids are chosen by randomly selecting
+       observations from the observation matrix. Alternatively,
+       passing a k by N array specifies the initial k centroids.
+
+    iter : int, optional
+       The number of times to run k-means, returning the codebook
+       with the lowest distortion. This argument is ignored if
+       initial centroids are specified with an array for the
+       ``k_or_guess`` parameter. This parameter does not represent the
+       number of iterations of the k-means algorithm.
+
+    thresh : float, optional
+       Terminates the k-means algorithm if the change in
+       distortion since the last k-means iteration is less than
+       or equal to threshold.
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    codebook : ndarray
+       A k by N array of k centroids. The ith centroid
+       codebook[i] is represented with the code i. The centroids
+       and codes generated represent the lowest distortion seen,
+       not necessarily the globally minimal distortion.
+       Note that the number of centroids is not necessarily the same as the
+       ``k_or_guess`` parameter, because centroids assigned to no observations
+       are removed during iterations.
+
+    distortion : float
+       The mean (non-squared) Euclidean distance between the observations
+       passed and the centroids generated. Note the difference to the standard
+       definition of distortion in the context of the k-means algorithm, which
+       is the sum of the squared distances.
+
+    See Also
+    --------
+    kmeans2 : a different implementation of k-means clustering
+       with more methods for generating initial centroids but without
+       using a distortion change threshold as a stopping criterion.
+
+    whiten : must be called prior to passing an observation matrix
+       to kmeans.
+
+    Notes
+    -----
+    For more functionalities or optimal performance, you can use
+    `sklearn.cluster.KMeans `_.
+    `This `_
+    is a benchmark result of several implementations.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq, kmeans, whiten
+    >>> import matplotlib.pyplot as plt
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 0.1,0.1],
+    ...                       [ 0.2,1.8],
+    ...                       [ 2.0,0.5],
+    ...                       [ 0.3,1.5],
+    ...                       [ 1.0,1.0]])
+    >>> whitened = whiten(features)
+    >>> book = np.array((whitened[0],whitened[2]))
+    >>> kmeans(whitened,book)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 0.93218041,  1.24398691]]), 0.85684700941625547)
+
+    >>> codes = 3
+    >>> kmeans(whitened,codes)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 1.32544402,  0.65607529],
+           [ 0.40782893,  2.02786907]]), 0.5196582527686241)
+
+    >>> # Create 50 datapoints in two clusters a and b
+    >>> pts = 50
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 0], [[4, 1], [1, 4]], size=pts)
+    >>> b = rng.multivariate_normal([30, 10],
+    ...                             [[10, 2], [2, 1]],
+    ...                             size=pts)
+    >>> features = np.concatenate((a, b))
+    >>> # Whiten data
+    >>> whitened = whiten(features)
+    >>> # Find 2 clusters in the data
+    >>> codebook, distortion = kmeans(whitened, 2)
+    >>> # Plot whitened data and cluster centers in red
+    >>> plt.scatter(whitened[:, 0], whitened[:, 1])
+    >>> plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
+    >>> plt.show()
+
+    """
+    if isinstance(k_or_guess, int):
+        xp = array_namespace(obs)
+    else:
+        xp = array_namespace(obs, k_or_guess)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    guess = _asarray(k_or_guess, xp=xp, check_finite=check_finite)
+    if iter < 1:
+        raise ValueError(f"iter must be at least 1, got {iter}")
+
+    # Determine whether a count (scalar) or an initial guess (array) was passed.
+    if xp_size(guess) != 1:
+        if xp_size(guess) < 1:
+            raise ValueError(f"Asked for 0 clusters. Initial book was {guess}")
+        return _kmeans(obs, guess, thresh=thresh, xp=xp)
+
+    # k_or_guess is a scalar, now verify that it's an integer
+    k = int(guess)
+    if k != guess:
+        raise ValueError("If k_or_guess is a scalar, it must be an integer.")
+    if k < 1:
+        raise ValueError(f"Asked for {k} clusters.")
+
+    rng = check_random_state(rng)
+
+    # initialize best distance value to a large value
+    best_dist = xp.inf
+    for i in range(iter):
+        # the initial code book is randomly selected from observations
+        guess = _kpoints(obs, k, rng, xp)
+        book, dist = _kmeans(obs, guess, thresh=thresh, xp=xp)
+        if dist < best_dist:
+            best_book = book
+            best_dist = dist
+    return best_book, best_dist
+
+
+def _kpoints(data, k, rng, xp):
+    """Pick k points at random in data (one row = one observation).
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 are assumed to describe one
+        dimensional data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    idx = rng.choice(data.shape[0], size=int(k), replace=False)
+    # convert to array with default integer dtype (avoids numpy#25607)
+    idx = xp.asarray(idx, dtype=xp.asarray([1]).dtype)
+    return xp.take(data, idx, axis=0)
+
+
+def _krandinit(data, k, rng, xp):
+    """Returns k samples of a random variable whose parameters depend on data.
+
+    More precisely, it returns k observations sampled from a Gaussian random
+    variable whose mean and covariances are the ones estimated from the data.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    mu = xp.mean(data, axis=0)
+    k = np.asarray(k)
+
+    if data.ndim == 1:
+        _cov = xpx.cov(data, xp=xp)
+        x = rng.standard_normal(size=k)
+        x = xp.asarray(x)
+        x *= xp.sqrt(_cov)
+    elif data.shape[1] > data.shape[0]:
+        # initialize when the covariance matrix is rank deficient
+        _, s, vh = xp.linalg.svd(data - mu, full_matrices=False)
+        x = rng.standard_normal(size=(k, xp_size(s)))
+        x = xp.asarray(x)
+        sVh = s[:, None] * vh / xp.sqrt(data.shape[0] - xp.asarray(1.))
+        x = x @ sVh
+    else:
+        _cov = xpx.atleast_nd(xpx.cov(data.T, xp=xp), ndim=2, xp=xp)
+
+        # k rows, d cols (one row = one obs)
+        # Generate k sample of a random variable ~ Gaussian(mu, cov)
+        x = rng.standard_normal(size=(k, xp_size(mu)))
+        x = xp.asarray(x)
+        x = x @ xp.linalg.cholesky(_cov).T
+
+    x += mu
+    return x
+
+
+def _kpp(data, k, rng, xp):
+    """ Picks k points in the data based on the kmeans++ method.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    init : ndarray
+        A 'k' by 'N' containing the initial centroids.
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+    """
+
+    ndim = len(data.shape)
+    if ndim == 1:
+        data = data[:, None]
+
+    dims = data.shape[1]
+
+    init = xp.empty((int(k), dims))
+
+    for i in range(k):
+        if i == 0:
+            data_idx = rng_integers(rng, data.shape[0])
+        else:
+            D2 = cdist(init[:i,:], data, metric='sqeuclidean').min(axis=0)
+            probs = D2/D2.sum()
+            cumprobs = probs.cumsum()
+            r = rng.uniform()
+            cumprobs = np.asarray(cumprobs)
+            data_idx = int(np.searchsorted(cumprobs, r))
+
+        init = xpx.at(init)[i, :].set(data[data_idx, :])
+
+    if ndim == 1:
+        init = init[:, 0]
+    return init
+
+
+_valid_init_meth = {'random': _krandinit, 'points': _kpoints, '++': _kpp}
+
+
+def _missing_warn():
+    """Print a warning when called."""
+    warnings.warn("One of the clusters is empty. "
+                  "Re-run kmeans with a different initialization.",
+                  stacklevel=3)
+
+
+def _missing_raise():
+    """Raise a ClusterError when called."""
+    raise ClusterError("One of the clusters is empty. "
+                       "Re-run kmeans with a different initialization.")
+
+
+_valid_miss_meth = {'warn': _missing_warn, 'raise': _missing_raise}
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+@_transition_to_rng("seed")
+def kmeans2(data, k, iter=10, thresh=1e-5, minit='random',
+            missing='warn', check_finite=True, *, rng=None):
+    """
+    Classify a set of observations into k clusters using the k-means algorithm.
+
+    The algorithm attempts to minimize the Euclidean distance between
+    observations and centroids. Several initialization methods are
+    included.
+
+    Parameters
+    ----------
+    data : ndarray
+        A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
+        'M' array of 'M' 1-D observations.
+    k : int or ndarray
+        The number of clusters to form as well as the number of
+        centroids to generate. If `minit` initialization string is
+        'matrix', or if a ndarray is given instead, it is
+        interpreted as initial cluster to use instead.
+    iter : int, optional
+        Number of iterations of the k-means algorithm to run. Note
+        that this differs in meaning from the iters parameter to
+        the kmeans function.
+    thresh : float, optional
+        (not used yet)
+    minit : str, optional
+        Method for initialization. Available methods are 'random',
+        'points', '++' and 'matrix':
+
+        'random': generate k centroids from a Gaussian with mean and
+        variance estimated from the data.
+
+        'points': choose k observations (rows) at random from data for
+        the initial centroids.
+
+        '++': choose k observations accordingly to the kmeans++ method
+        (careful seeding)
+
+        'matrix': interpret the k parameter as a k by M (or length k
+        array for 1-D data) array of initial centroids.
+    missing : str, optional
+        Method to deal with empty clusters. Available methods are
+        'warn' and 'raise':
+
+        'warn': give a warning and continue.
+
+        'raise': raise an ClusterError and terminate the algorithm.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    centroid : ndarray
+        A 'k' by 'N' array of centroids found at the last iteration of
+        k-means.
+    label : ndarray
+        label[i] is the code or index of the centroid the
+        ith observation is closest to.
+
+    See Also
+    --------
+    kmeans
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+
+    Examples
+    --------
+    >>> from scipy.cluster.vq import kmeans2
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+
+    Create z, an array with shape (100, 2) containing a mixture of samples
+    from three multivariate normal distributions.
+
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 6], [[2, 1], [1, 1.5]], size=45)
+    >>> b = rng.multivariate_normal([2, 0], [[1, -1], [-1, 3]], size=30)
+    >>> c = rng.multivariate_normal([6, 4], [[5, 0], [0, 1.2]], size=25)
+    >>> z = np.concatenate((a, b, c))
+    >>> rng.shuffle(z)
+
+    Compute three clusters.
+
+    >>> centroid, label = kmeans2(z, 3, minit='points')
+    >>> centroid
+    array([[ 2.22274463, -0.61666946],  # may vary
+           [ 0.54069047,  5.86541444],
+           [ 6.73846769,  4.01991898]])
+
+    How many points are in each cluster?
+
+    >>> counts = np.bincount(label)
+    >>> counts
+    array([29, 51, 20])  # may vary
+
+    Plot the clusters.
+
+    >>> w0 = z[label == 0]
+    >>> w1 = z[label == 1]
+    >>> w2 = z[label == 2]
+    >>> plt.plot(w0[:, 0], w0[:, 1], 'o', alpha=0.5, label='cluster 0')
+    >>> plt.plot(w1[:, 0], w1[:, 1], 'd', alpha=0.5, label='cluster 1')
+    >>> plt.plot(w2[:, 0], w2[:, 1], 's', alpha=0.5, label='cluster 2')
+    >>> plt.plot(centroid[:, 0], centroid[:, 1], 'k*', label='centroids')
+    >>> plt.axis('equal')
+    >>> plt.legend(shadow=True)
+    >>> plt.show()
+
+    """
+    if int(iter) < 1:
+        raise ValueError(f"Invalid iter ({iter}), must be a positive integer.")
+    try:
+        miss_meth = _valid_miss_meth[missing]
+    except KeyError as e:
+        raise ValueError(f"Unknown missing method {missing!r}") from e
+
+    if isinstance(k, int):
+        xp = array_namespace(data)
+    else:
+        xp = array_namespace(data, k)
+    data = _asarray(data, xp=xp, check_finite=check_finite)
+    code_book = xp_copy(k, xp=xp)
+    if data.ndim == 1:
+        d = 1
+    elif data.ndim == 2:
+        d = data.shape[1]
+    else:
+        raise ValueError("Input of rank > 2 is not supported.")
+
+    if xp_size(data) < 1 or xp_size(code_book) < 1:
+        raise ValueError("Empty input is not supported.")
+
+    # If k is not a single value, it should be compatible with data's shape
+    if minit == 'matrix' or xp_size(code_book) > 1:
+        if data.ndim != code_book.ndim:
+            raise ValueError("k array doesn't match data rank")
+        nc = code_book.shape[0]
+        if data.ndim > 1 and code_book.shape[1] != d:
+            raise ValueError("k array doesn't match data dimension")
+    else:
+        nc = int(code_book)
+
+        if nc < 1:
+            raise ValueError(
+                f"Cannot ask kmeans2 for {nc} clusters (k was {code_book})"
+            )
+        elif nc != code_book:
+            warnings.warn("k was not an integer, was converted.", stacklevel=2)
+
+        try:
+            init_meth = _valid_init_meth[minit]
+        except KeyError as e:
+            raise ValueError(f"Unknown init method {minit!r}") from e
+        else:
+            rng = check_random_state(rng)
+            code_book = init_meth(data, code_book, rng, xp)
+
+    data = np.asarray(data)
+    code_book = np.asarray(code_book)
+    for _ in range(iter):
+        # Compute the nearest neighbor for each obs using the current code book
+        label = vq(data, code_book, check_finite=check_finite)[0]
+        # Update the code book by computing centroids
+        new_code_book, has_members = _vq.update_cluster_means(data, label, nc)
+        if not has_members.all():
+            miss_meth()
+            # Set the empty clusters to their previous positions
+            new_code_book[~has_members] = code_book[~has_members]
+        code_book = new_code_book
+
+    return xp.asarray(code_book), xp.asarray(label)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/conftest.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..030049cc66296c87c152c2ae8fdec119f35e935e
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/conftest.py
@@ -0,0 +1,708 @@
+# Pytest customization
+import json
+import multiprocessing
+import os
+import sys
+import warnings
+import tempfile
+from contextlib import contextmanager
+from typing import Literal
+
+import numpy as np
+import pytest
+try:
+    import hypothesis
+    hypothesis_available = True
+except ImportError:
+    hypothesis_available = False
+
+from scipy._lib._fpumode import get_fpu_mode
+from scipy._lib._array_api import (
+    SCIPY_ARRAY_API, SCIPY_DEVICE, array_namespace, default_xp,
+    is_cupy, is_dask, is_jax, is_torch,
+)
+from scipy._lib._testutils import FPUModeChangeWarning
+from scipy._lib.array_api_extra.testing import patch_lazy_xp_functions
+from scipy._lib import _pep440
+
+try:
+    from scipy_doctest.conftest import dt_config
+    HAVE_SCPDT = True
+except ModuleNotFoundError:
+    HAVE_SCPDT = False
+
+try:
+    import pytest_run_parallel  # noqa:F401
+    PARALLEL_RUN_AVAILABLE = True
+except Exception:
+    PARALLEL_RUN_AVAILABLE = False
+
+
+def pytest_configure(config):
+    """
+    Add pytest markers to avoid PytestUnknownMarkWarning
+
+    This needs to contain all markers that are SciPy-specific, as well as
+    dummy fallbacks for markers defined in optional test packages.
+
+    Note that we need both the registration here *and* in `pytest.ini`.
+    """
+    config.addinivalue_line("markers",
+        "slow: Tests that are very slow.")
+    config.addinivalue_line("markers",
+        "xslow: mark test as extremely slow (not run unless explicitly requested)")
+    config.addinivalue_line("markers",
+        "xfail_on_32bit: mark test as failing on 32-bit platforms")
+    config.addinivalue_line("markers",
+        "array_api_backends: test iterates on all array API backends")
+    config.addinivalue_line("markers",
+        ("skip_xp_backends(backends, reason=None, np_only=False, cpu_only=False, " +
+         "eager_only=False, exceptions=None): mark the desired skip configuration " +
+         "for the `skip_xp_backends` fixture"))
+    config.addinivalue_line("markers",
+        ("xfail_xp_backends(backends, reason=None, np_only=False, cpu_only=False, " +
+         "eager_only=False, exceptions=None): mark the desired xfail configuration " +
+         "for the `xfail_xp_backends` fixture"))
+
+    try:
+        import pytest_timeout  # noqa:F401
+    except Exception:
+        config.addinivalue_line(
+            "markers", 'timeout: mark a test for a non-default timeout')
+    try:
+        # This is a more reliable test of whether pytest_fail_slow is installed
+        # When I uninstalled it, `import pytest_fail_slow` didn't fail!
+        from pytest_fail_slow import parse_duration  # type: ignore[import-not-found] # noqa:F401,E501
+    except Exception:
+        config.addinivalue_line(
+            "markers", 'fail_slow: mark a test for a non-default timeout failure')
+
+    if not PARALLEL_RUN_AVAILABLE:
+        config.addinivalue_line(
+            'markers',
+            'parallel_threads_limit(n): run the given test function in parallel '
+            'using `n` threads.')
+        config.addinivalue_line(
+            "markers",
+            "thread_unsafe: mark the test function as single-threaded",
+        )
+        config.addinivalue_line(
+            "markers",
+            "iterations(n): run the given test function `n` times in each thread",
+        )
+
+    if os.name == 'posix' and sys.version_info < (3, 14):
+        # On POSIX, Python 3.13 and older uses the 'fork' context by
+        # default. Calling fork() from multiple threads leads to
+        # deadlocks. This has been changed in 3.14 to 'forkserver'.
+        multiprocessing.set_start_method('forkserver', force=True)
+
+
+def pytest_runtest_setup(item):
+    mark = item.get_closest_marker("xslow")
+    if mark is not None:
+        try:
+            v = int(os.environ.get('SCIPY_XSLOW', '0'))
+        except ValueError:
+            v = False
+        if not v:
+            pytest.skip("very slow test; "
+                        "set environment variable SCIPY_XSLOW=1 to run it")
+    mark = item.get_closest_marker("xfail_on_32bit")
+    if mark is not None and np.intp(0).itemsize < 8:
+        pytest.xfail(f'Fails on our 32-bit test platform(s): {mark.args[0]}')
+
+    # Older versions of threadpoolctl have an issue that may lead to this
+    # warning being emitted, see gh-14441
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", pytest.PytestUnraisableExceptionWarning)
+
+        try:
+            from threadpoolctl import threadpool_limits
+
+            HAS_THREADPOOLCTL = True
+        except Exception:  # observed in gh-14441: (ImportError, AttributeError)
+            # Optional dependency only. All exceptions are caught, for robustness
+            HAS_THREADPOOLCTL = False
+
+        if HAS_THREADPOOLCTL:
+            # Set the number of openmp threads based on the number of workers
+            # xdist is using to prevent oversubscription. Simplified version of what
+            # sklearn does (it can rely on threadpoolctl and its builtin OpenMP helper
+            # functions)
+            try:
+                xdist_worker_count = int(os.environ['PYTEST_XDIST_WORKER_COUNT'])
+            except KeyError:
+                # raises when pytest-xdist is not installed
+                return
+
+            if not os.getenv('OMP_NUM_THREADS'):
+                max_openmp_threads = os.cpu_count() // 2  # use nr of physical cores
+                threads_per_worker = max(max_openmp_threads // xdist_worker_count, 1)
+                try:
+                    threadpool_limits(threads_per_worker, user_api='blas')
+                except Exception:
+                    # May raise AttributeError for older versions of OpenBLAS.
+                    # Catch any error for robustness.
+                    return
+
+
+@pytest.fixture(scope="function", autouse=True)
+def check_fpu_mode(request):
+    """
+    Check FPU mode was not changed during the test.
+    """
+    old_mode = get_fpu_mode()
+    yield
+    new_mode = get_fpu_mode()
+
+    if old_mode != new_mode:
+        warnings.warn(f"FPU mode changed from {old_mode:#x} to {new_mode:#x} during "
+                      "the test",
+                      category=FPUModeChangeWarning, stacklevel=0)
+
+
+if not PARALLEL_RUN_AVAILABLE:
+    @pytest.fixture
+    def num_parallel_threads():
+        return 1
+
+
+# Array API backend handling
+xp_known_backends = {'numpy', 'array_api_strict', 'torch', 'cupy', 'jax.numpy',
+                     'dask.array'}
+xp_available_backends = [
+    pytest.param(np, id='numpy', marks=pytest.mark.array_api_backends)
+]
+xp_skip_cpu_only_backends = set()
+xp_skip_eager_only_backends = set()
+
+if SCIPY_ARRAY_API:
+    # fill the dict of backends with available libraries
+    try:
+        import array_api_strict
+        xp_available_backends.append(
+            pytest.param(array_api_strict, id='array_api_strict',
+                         marks=pytest.mark.array_api_backends))
+        if _pep440.parse(array_api_strict.__version__) < _pep440.Version('2.3'):
+            raise ImportError("array-api-strict must be >= version 2.3")
+        array_api_strict.set_array_api_strict_flags(
+            api_version='2024.12'
+        )
+    except ImportError:
+        pass
+
+    try:
+        import torch  # type: ignore[import-not-found]
+        xp_available_backends.append(
+            pytest.param(torch, id='torch',
+            marks=pytest.mark.array_api_backends))
+        torch.set_default_device(SCIPY_DEVICE)
+        if SCIPY_DEVICE != "cpu":
+            xp_skip_cpu_only_backends.add('torch')
+
+        # default to float64 unless explicitly requested
+        default = os.getenv('SCIPY_DEFAULT_DTYPE', default='float64')
+        if default == 'float64':
+            torch.set_default_dtype(torch.float64)
+        elif default != "float32":
+            raise ValueError(
+                "SCIPY_DEFAULT_DTYPE env var, if set, can only be either 'float64' "
+               f"or 'float32'. Got '{default}' instead."
+            )
+    except ImportError:
+        pass
+
+    try:
+        import cupy  # type: ignore[import-not-found]
+        # Note: cupy disregards SCIPY_DEVICE and always runs on cuda.
+        # It will fail to import if you don't have CUDA hardware and drivers.
+        xp_available_backends.append(
+            pytest.param(cupy, id='cupy',
+            marks=pytest.mark.array_api_backends))
+        xp_skip_cpu_only_backends.add('cupy')
+
+        # this is annoying in CuPy 13.x
+        warnings.filterwarnings(
+            'ignore', 'cupyx.jit.rawkernel is experimental', category=FutureWarning
+        )
+        from cupyx.scipy import signal
+        del signal
+    except ImportError:
+        pass
+
+    try:
+        import jax.numpy  # type: ignore[import-not-found]
+        
+        xp_available_backends.append(
+            pytest.param(jax.numpy, id='jax.numpy',
+            marks=[pytest.mark.array_api_backends,
+                   # Uses xpx.testing.patch_lazy_xp_functions to monkey-patch module
+                   pytest.mark.thread_unsafe]))
+
+        jax.config.update("jax_enable_x64", True)
+        jax.config.update("jax_default_device", jax.devices(SCIPY_DEVICE)[0])
+        if SCIPY_DEVICE != "cpu":
+            xp_skip_cpu_only_backends.add('jax.numpy')
+        # JAX can be eager or lazy (when wrapped in jax.jit). However it is
+        # recommended by upstream devs to assume it's always lazy.
+        xp_skip_eager_only_backends.add('jax.numpy')
+    except ImportError:
+        pass
+
+    try:
+        import dask.array as da
+
+        xp_available_backends.append(
+            pytest.param(da, id='dask.array',
+            marks=[pytest.mark.array_api_backends,
+                   # Uses xpx.testing.patch_lazy_xp_functions to monkey-patch module
+                   pytest.mark.thread_unsafe]))
+
+        # Dask can wrap around cupy. However, this is untested in scipy
+        # (and will almost surely not work as delegation will misbehave).
+
+        # Dask, strictly speaking, can be eager, in the sense that
+        # __array__, __bool__ etc. are implemented and do not raise.
+        # However, calling them triggers an extra computation of the whole graph
+        # until that point, which is highly destructive for performance.
+        xp_skip_eager_only_backends.add('dask.array')
+    except ImportError:
+        pass
+
+    xp_available_backend_ids = {p.id for p in xp_available_backends}
+    assert not xp_available_backend_ids - xp_known_backends
+
+    # by default, use all available backends
+    if (
+        isinstance(SCIPY_ARRAY_API, str)
+        and SCIPY_ARRAY_API.lower() not in ("1", "true", "all")
+    ):
+        SCIPY_ARRAY_API_ = set(json.loads(SCIPY_ARRAY_API))
+        if SCIPY_ARRAY_API_ != {'all'}:
+            if SCIPY_ARRAY_API_ - xp_available_backend_ids:
+                msg = ("'--array-api-backend' must be in "
+                       f"{xp_available_backend_ids}; got {SCIPY_ARRAY_API_}")
+                raise ValueError(msg)
+            # Only select a subset of backends
+            xp_available_backends = [
+                param for param in xp_available_backends
+                if param.id in SCIPY_ARRAY_API_
+            ]
+
+
+@pytest.fixture(params=xp_available_backends)
+def xp(request):
+    """Run the test that uses this fixture on each available array API library.
+
+    You can select all and only the tests that use the `xp` fixture by
+    passing `-m array_api_backends` to pytest.
+
+    You can select where individual tests run through the `@skip_xp_backends`,
+    `@xfail_xp_backends`, and `@skip_xp_invalid_arg` pytest markers.
+
+    Please read: https://docs.scipy.org/doc/scipy/dev/api-dev/array_api.html#adding-tests
+    """
+    # Read all @pytest.marks.skip_xp_backends markers that decorate to the test,
+    # if any, and raise pytest.skip() if the current xp is in the list.
+    skip_or_xfail_xp_backends(request, "skip")
+    # Read all @pytest.marks.xfail_xp_backends markers that decorate the test,
+    # if any, and raise pytest.xfail() if the current xp is in the list.
+    skip_or_xfail_xp_backends(request, "xfail")
+
+    xp = request.param
+    # Potentially wrap namespace with array_api_compat
+    xp = array_namespace(xp.empty(0))
+
+    if SCIPY_ARRAY_API:
+        # If xp==jax.numpy, wrap tested functions in jax.jit
+        # If xp==dask.array, wrap tested functions to test that graph is not computed
+        with patch_lazy_xp_functions(request=request, xp=request.param):
+            # Throughout all calls to assert_almost_equal, assert_array_almost_equal,
+            # and xp_assert_* functions, test that the array namespace is xp in both
+            # the expected and actual arrays. This is to detect the case where both
+            # arrays are erroneously just plain numpy while xp is something else.
+            with default_xp(xp):
+                yield xp
+    else:
+        yield xp
+
+
+skip_xp_invalid_arg = pytest.mark.skipif(SCIPY_ARRAY_API,
+    reason = ('Test involves masked arrays, object arrays, or other types '
+              'that are not valid input when `SCIPY_ARRAY_API` is used.'))
+
+
+def _backends_kwargs_from_request(request, skip_or_xfail):
+    """A helper for {skip,xfail}_xp_backends.
+
+    Return dict of {backend to skip/xfail: top reason to skip/xfail it}
+    """
+    markers = list(request.node.iter_markers(f'{skip_or_xfail}_xp_backends'))
+    reasons = {backend: [] for backend in xp_known_backends}
+
+    for marker in markers:
+        invalid_kwargs = set(marker.kwargs) - {
+            "cpu_only", "np_only", "eager_only", "reason", "exceptions"}
+        if invalid_kwargs:
+            raise TypeError(f"Invalid kwargs: {invalid_kwargs}")
+
+        exceptions = set(marker.kwargs.get('exceptions', []))
+        invalid_exceptions = exceptions - xp_known_backends
+        if (invalid_exceptions := list(exceptions - xp_known_backends)):
+            raise ValueError(f"Unknown backend(s): {invalid_exceptions}; "
+                             f"must be a subset of {list(xp_known_backends)}")
+
+        if marker.kwargs.get('np_only', False):
+            reason = marker.kwargs.get("reason") or "do not run with non-NumPy backends"
+            for backend, backend_reasons in reasons.items():
+                if backend != 'numpy' and backend not in exceptions:
+                    backend_reasons.append(reason)
+
+        elif marker.kwargs.get('cpu_only', False):
+            reason = marker.kwargs.get("reason") or (
+                "no array-agnostic implementation or delegation available "
+                "for this backend and device")
+            for backend in xp_skip_cpu_only_backends - exceptions:
+                reasons[backend].append(reason)
+
+        elif marker.kwargs.get('eager_only', False):
+            reason = marker.kwargs.get("reason") or (
+                "eager checks not executed on lazy backends")
+            for backend in xp_skip_eager_only_backends - exceptions:
+                reasons[backend].append(reason)
+
+        # add backends, if any
+        if len(marker.args) == 1:
+            backend = marker.args[0]
+            if backend not in xp_known_backends:
+                raise ValueError(f"Unknown backend: {backend}; "
+                                 f"must be one of {list(xp_known_backends)}")
+            reason = marker.kwargs.get("reason") or (
+                f"do not run with array API backend: {backend}")
+            # reason overrides the ones from cpu_only, np_only, and eager_only.
+            # This is regardless of order of appearence of the markers.
+            reasons[backend].insert(0, reason)
+
+            for kwarg in ("cpu_only", "np_only", "eager_only", "exceptions"):
+                if kwarg in marker.kwargs:
+                    raise ValueError(f"{kwarg} is mutually exclusive with {backend}")
+
+        elif len(marker.args) > 1:
+            raise ValueError(
+                f"Please specify only one backend per marker: {marker.args}"
+            )
+
+    return {backend: backend_reasons[0]
+            for backend, backend_reasons in reasons.items()
+            if backend_reasons}
+
+
+def skip_or_xfail_xp_backends(request: pytest.FixtureRequest,
+                              skip_or_xfail: Literal['skip', 'xfail']) -> None:
+    """
+    Helper of the `xp` fixture.
+    Skip or xfail based on the ``skip_xp_backends`` or ``xfail_xp_backends`` markers.
+
+    See the "Support for the array API standard" docs page for usage examples.
+
+    Usage
+    -----
+    ::
+        skip_xp_backends = pytest.mark.skip_xp_backends
+        xfail_xp_backends = pytest.mark.xfail_xp_backends
+        ...
+
+        @skip_xp_backends(backend, *, reason=None)
+        @skip_xp_backends(*, cpu_only=True, exceptions=(), reason=None)
+        @skip_xp_backends(*, eager_only=True, exceptions=(), reason=None)
+        @skip_xp_backends(*, np_only=True, exceptions=(), reason=None)
+
+        @xfail_xp_backends(backend, *, reason=None)
+        @xfail_xp_backends(*, cpu_only=True, exceptions=(), reason=None)
+        @xfail_xp_backends(*, eager_only=True, exceptions=(), reason=None)
+        @xfail_xp_backends(*, np_only=True, exceptions=(), reason=None)
+
+    Parameters
+    ----------
+    backend : str, optional
+        Backend to skip/xfail, e.g. ``"torch"``.
+        Mutually exclusive with ``cpu_only``, ``eager_only``, and ``np_only``.
+    cpu_only : bool, optional
+        When ``True``, the test is skipped/xfailed on non-CPU devices,
+        minus exceptions. Mutually exclusive with ``backend``.
+    eager_only : bool, optional
+        When ``True``, the test is skipped/xfailed for lazy backends, e.g. those
+        with major caveats when invoking ``__array__``, ``__bool__``, ``__float__``,
+        or ``__complex__``, minus exceptions. Mutually exclusive with ``backend``.
+    np_only : bool, optional
+        When ``True``, the test is skipped/xfailed for all backends other
+        than the default NumPy backend and the exceptions.
+        Mutually exclusive with ``backend``. Implies ``cpu_only`` and ``eager_only``.
+    reason : str, optional
+        A reason for the skip/xfail. If omitted, a default reason is used.
+    exceptions : list[str], optional
+        A list of exceptions for use with ``cpu_only``, ``eager_only``, or ``np_only``.
+        This should be provided when delegation is implemented for some,
+        but not all, non-CPU/non-NumPy backends.
+    """
+    if f"{skip_or_xfail}_xp_backends" not in request.keywords:
+        return
+
+    skip_xfail_reasons = _backends_kwargs_from_request(
+        request, skip_or_xfail=skip_or_xfail
+    )
+    xp = request.param
+    if xp.__name__ in skip_xfail_reasons:
+        reason = skip_xfail_reasons[xp.__name__]
+        assert reason  # Default reason applied above
+        skip_or_xfail = getattr(pytest, skip_or_xfail)
+        skip_or_xfail(reason=reason)
+
+
+@pytest.fixture
+def devices(xp):
+    """Fixture that returns a list of all devices for the backend, plus None.
+    Used to test input->output device propagation.
+
+    Usage
+    -----
+    from scipy._lib._array_api import xp_device
+
+    def test_device(xp, devices):
+        for d in devices:
+            x = xp.asarray(..., device=d)
+            y = f(x)
+            assert xp_device(y) == xp_device(x)
+    """
+    if is_cupy(xp):
+        # CuPy does not support devices other than the current one
+        # data-apis/array-api-compat#293
+        pytest.xfail(reason="data-apis/array-api-compat#293")
+    if is_dask(xp):
+        # Skip dummy DASK_DEVICE from array-api-compat, which does not propagate
+        return ["cpu", None]
+    if is_jax(xp):
+        # The .device attribute is not accessible inside jax.jit; the consequence
+        # (downstream of array-api-compat hacks) is that a non-default device in
+        # input is not guaranteed to propagate to the output even if the scipy code
+        # states `device=xp_device(arg)`` in all array creation functions.
+        # While this issue is specific to jax.jit, it would be unnecessarily
+        # verbose to skip the test for each jit-capable function and run it for
+        # those that only support eager mode.
+        pytest.xfail(reason="jax-ml/jax#26000")
+    if is_torch(xp):
+        devices = xp.__array_namespace_info__().devices()
+        # open an issue about this - cannot branch based on `any`/`all`?
+        return (device for device in devices if device.type != 'meta')
+
+    return xp.__array_namespace_info__().devices() + [None]
+
+
+if hypothesis_available:
+    # Following the approach of NumPy's conftest.py...
+    # Use a known and persistent tmpdir for hypothesis' caches, which
+    # can be automatically cleared by the OS or user.
+    hypothesis.configuration.set_hypothesis_home_dir(
+        os.path.join(tempfile.gettempdir(), ".hypothesis")
+    )
+
+    # We register two custom profiles for SciPy - for details see
+    # https://hypothesis.readthedocs.io/en/latest/settings.html
+    # The first is designed for our own CI runs; the latter also
+    # forces determinism and is designed for use via scipy.test()
+    hypothesis.settings.register_profile(
+        name="nondeterministic", deadline=None, print_blob=True,
+    )
+    hypothesis.settings.register_profile(
+        name="deterministic",
+        deadline=None, print_blob=True, database=None, derandomize=True,
+        suppress_health_check=list(hypothesis.HealthCheck),
+    )
+
+    # Profile is currently set by environment variable `SCIPY_HYPOTHESIS_PROFILE`
+    # In the future, it would be good to work the choice into `.spin/cmds.py`.
+    SCIPY_HYPOTHESIS_PROFILE = os.environ.get("SCIPY_HYPOTHESIS_PROFILE",
+                                              "deterministic")
+    hypothesis.settings.load_profile(SCIPY_HYPOTHESIS_PROFILE)
+
+
+############################################################################
+# doctesting stuff
+
+if HAVE_SCPDT:
+
+    # FIXME: populate the dict once
+    @contextmanager
+    def warnings_errors_and_rng(test=None):
+        """Temporarily turn (almost) all warnings to errors.
+
+        Filter out known warnings which we allow.
+        """
+        known_warnings = dict()
+
+        # these functions are known to emit "divide by zero" RuntimeWarnings
+        divide_by_zero = [
+            'scipy.linalg.norm', 'scipy.ndimage.center_of_mass',
+        ]
+        for name in divide_by_zero:
+            known_warnings[name] = dict(category=RuntimeWarning,
+                                        message='divide by zero')
+
+        # Deprecated stuff
+        deprecated = []
+        for name in deprecated:
+            known_warnings[name] = dict(category=DeprecationWarning)
+
+        from scipy import integrate
+        # the functions are known to emit IntegrationWarnings
+        integration_w = ['scipy.special.ellip_normal',
+                         'scipy.special.ellip_harm_2',
+        ]
+        for name in integration_w:
+            known_warnings[name] = dict(category=integrate.IntegrationWarning,
+                                        message='The occurrence of roundoff')
+
+        # scipy.stats deliberately emits UserWarnings sometimes
+        user_w = ['scipy.stats.anderson_ksamp', 'scipy.stats.kurtosistest',
+                  'scipy.stats.normaltest', 'scipy.sparse.linalg.norm']
+        for name in user_w:
+            known_warnings[name] = dict(category=UserWarning)
+
+        # additional one-off warnings to filter
+        dct = {
+            'scipy.sparse.linalg.norm':
+                dict(category=UserWarning, message="Exited at iteration"),
+            # tutorials
+            'linalg.rst':
+                dict(message='the matrix subclass is not',
+                     category=PendingDeprecationWarning),
+            'stats.rst':
+                dict(message='The maximum number of subdivisions',
+                     category=integrate.IntegrationWarning),
+        }
+        known_warnings.update(dct)
+
+        # these legitimately emit warnings in examples
+        legit = set('scipy.signal.normalize')
+
+        # Now, the meat of the matter: filter warnings,
+        # also control the random seed for each doctest.
+
+        # XXX: this matches the refguide-check behavior, but is a tad strange:
+        # makes sure that the seed the old-fashioned np.random* methods is
+        # *NOT* reproducible but the new-style `default_rng()` *IS* repoducible.
+        # Should these two be either both repro or both not repro?
+
+        from scipy._lib._util import _fixed_default_rng
+        import numpy as np
+        with _fixed_default_rng():
+            np.random.seed(None)
+            with warnings.catch_warnings():
+                if test and test.name in known_warnings:
+                    warnings.filterwarnings('ignore', **known_warnings[test.name])
+                    yield
+                elif test and test.name in legit:
+                    yield
+                else:
+                    warnings.simplefilter('error', Warning)
+                    warnings.filterwarnings('ignore', ".*odr.*", DeprecationWarning)
+                    yield
+
+    dt_config.user_context_mgr = warnings_errors_and_rng
+    dt_config.skiplist = set([
+        'scipy.linalg.LinAlgError',     # comes from numpy
+        'scipy.fftpack.fftshift',       # fftpack stuff is also from numpy
+        'scipy.fftpack.ifftshift',
+        'scipy.fftpack.fftfreq',
+        'scipy.special.sinc',           # sinc is from numpy
+        'scipy.optimize.show_options',  # does not have much to doctest
+        'scipy.signal.normalize',       # manipulates warnings (XXX temp skip)
+        'scipy.sparse.linalg.norm',     # XXX temp skip
+        # these below test things which inherit from np.ndarray
+        # cross-ref https://github.com/numpy/numpy/issues/28019
+        'scipy.io.matlab.MatlabObject.strides',
+        'scipy.io.matlab.MatlabObject.dtype',
+        'scipy.io.matlab.MatlabOpaque.dtype',
+        'scipy.io.matlab.MatlabOpaque.strides',
+        'scipy.io.matlab.MatlabFunction.strides',
+        'scipy.io.matlab.MatlabFunction.dtype'
+    ])
+
+    # these are affected by NumPy 2.0 scalar repr: rely on string comparison
+    if np.__version__ < "2":
+        dt_config.skiplist.update(set([
+            'scipy.io.hb_read',
+            'scipy.io.hb_write',
+            'scipy.sparse.csgraph.connected_components',
+            'scipy.sparse.csgraph.depth_first_order',
+            'scipy.sparse.csgraph.shortest_path',
+            'scipy.sparse.csgraph.floyd_warshall',
+            'scipy.sparse.csgraph.dijkstra',
+            'scipy.sparse.csgraph.bellman_ford',
+            'scipy.sparse.csgraph.johnson',
+            'scipy.sparse.csgraph.yen',
+            'scipy.sparse.csgraph.breadth_first_order',
+            'scipy.sparse.csgraph.reverse_cuthill_mckee',
+            'scipy.sparse.csgraph.structural_rank',
+            'scipy.sparse.csgraph.construct_dist_matrix',
+            'scipy.sparse.csgraph.reconstruct_path',
+            'scipy.ndimage.value_indices',
+            'scipy.stats.mstats.describe',
+    ]))
+
+    # help pytest collection a bit: these names are either private
+    # (distributions), or just do not need doctesting.
+    dt_config.pytest_extra_ignore = [
+        "scipy.stats.distributions",
+        "scipy.optimize.cython_optimize",
+        "scipy.test",
+        "scipy.show_config",
+        # equivalent to "pytest --ignore=path/to/file"
+        "scipy/special/_precompute",
+        "scipy/interpolate/_interpnd_info.py",
+        "scipy/interpolate/_rbfinterp_pythran.py",
+        "scipy/_build_utils/tempita.py",
+        "scipy/_lib/array_api_compat",
+        "scipy/_lib/highs",
+        "scipy/_lib/unuran",
+        "scipy/_lib/_gcutils.py",
+        "scipy/_lib/doccer.py",
+        "scipy/_lib/_uarray",
+        "scipy/linalg/_cython_signature_generator.py",
+        "scipy/linalg/_generate_pyx.py",
+        "scipy/linalg/_linalg_pythran.py",
+        "scipy/linalg/_matfuncs_sqrtm_triu.py",
+        "scipy/ndimage/utils/generate_label_testvectors.py",
+        "scipy/optimize/_group_columns.py",
+        "scipy/optimize/_max_len_seq_inner.py",
+        "scipy/signal/_max_len_seq_inner.py",
+        "scipy/sparse/_generate_sparsetools.py",
+        "scipy/special/_generate_pyx.py",
+        "scipy/stats/_stats_pythran.py",
+    ]
+
+    dt_config.pytest_extra_xfail = {
+        # name: reason
+        "ND_regular_grid.rst": "ReST parser limitation",
+        "extrapolation_examples.rst": "ReST parser limitation",
+        "sampling_pinv.rst": "__cinit__ unexpected argument",
+        "sampling_srou.rst": "nan in scalar_power",
+        "probability_distributions.rst": "integration warning",
+    }
+
+    # tutorials
+    dt_config.pseudocode = set(['integrate.nquad(func,'])
+    dt_config.local_resources = {
+        'io.rst': [
+            "octave_a.mat",
+            "octave_cells.mat",
+            "octave_struct.mat"
+        ]
+    }
+
+    dt_config.strict_check = True
+
+    # ignore Matplotlib's `ax.text`:
+    dt_config.stopwords.add('.text(')
+############################################################################
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec4ed081f9ed1dfc3adb382793d322c9d400f794
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55a9b408690e406e66549e5de835a17e2790f478
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d27a07430d1f8ffc0cc5d890fcbba852c4cc173
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f91e576fe2df6c7ce19e4cca259d6819d47115e169306e6f8dbc05dfc59ce7c9
+size 203497
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_constants.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_constants.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99aa4b9e6a0346ee58a643a3c8628d2e47fc9ae2
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_constants.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/codata.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/codata.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1da3cb64f528a0ad852596a27fd9b8855e1ed737
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/codata.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/constants.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/constants.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d89b6876e94075d896ddf597943c3fbb90a5a270
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/constants.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/_codata.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..41fdb9266b77224559d8b83da9657be060303a01
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/_codata.py
@@ -0,0 +1,2272 @@
+"""
+Fundamental Physical Constants
+------------------------------
+
+These constants are taken from CODATA Recommended Values of the Fundamental
+Physical Constants 2022.
+
+Object
+------
+physical_constants : dict
+    A dictionary containing physical constants. Keys are the names of physical
+    constants, values are tuples (value, units, precision).
+
+Functions
+---------
+value(key):
+    Returns the value of the physical constant(key).
+unit(key):
+    Returns the units of the physical constant(key).
+precision(key):
+    Returns the relative precision of the physical constant(key).
+find(sub):
+    Prints or returns list of keys containing the string sub, default is all.
+
+Source
+------
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set. Also available is an introduction to the
+constants for non-experts at
+
+https://physics.nist.gov/cuu/Constants/introduction.html
+
+References
+----------
+Theoretical and experimental publications relevant to the fundamental constants
+and closely related precision measurements published since the mid 1980s, but
+also including many older papers of particular interest, some of which date
+back to the 1800s. To search the bibliography, visit
+
+https://physics.nist.gov/cuu/Constants/
+
+"""
+
+# Compiled by Charles Harris, dated October 3, 2002
+# updated to 2002 values by BasSw, 2006
+# Updated to 2006 values by Vincent Davis June 2010
+# Updated to 2014 values by Joseph Booker, 2015
+# Updated to 2018 values by Jakob Jakobson, 2019
+# Updated to 2022 values by Jakob Jakobson, 2024
+
+import warnings
+import math
+
+from typing import Any
+from collections.abc import Callable
+
+from scipy._lib._array_api import xp_capabilities
+
+__all__ = ['physical_constants', 'value', 'unit', 'precision', 'find',
+           'ConstantWarning']
+
+"""
+Source:  https://physics.nist.gov/cuu/Constants/
+
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set.
+"""
+
+#
+# Source:  https://physics.nist.gov/cuu/Constants/
+#
+
+# Quantity                                             Value                 Uncertainty          Unit
+# ---------------------------------------------------- --------------------- -------------------- -------------
+txt2002 = """\
+Wien displacement law constant                         2.897 7685e-3         0.000 0051e-3         m K
+atomic unit of 1st hyperpolarizablity                  3.206 361 51e-53      0.000 000 28e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizablity                  6.235 3808e-65        0.000 0011e-65        C^4 m^4 J^-3
+atomic unit of electric dipole moment                  8.478 353 09e-30      0.000 000 73e-30      C m
+atomic unit of electric polarizablity                  1.648 777 274e-41     0.000 000 016e-41     C^2 m^2 J^-1
+atomic unit of electric quadrupole moment              4.486 551 24e-40      0.000 000 39e-40      C m^2
+atomic unit of magn. dipole moment                     1.854 801 90e-23      0.000 000 16e-23      J T^-1
+atomic unit of magn. flux density                      2.350 517 42e5        0.000 000 20e5        T
+deuteron magn. moment                                  0.433 073 482e-26     0.000 000 038e-26     J T^-1
+deuteron magn. moment to Bohr magneton ratio           0.466 975 4567e-3     0.000 000 0050e-3
+deuteron magn. moment to nuclear magneton ratio        0.857 438 2329        0.000 000 0092
+deuteron-electron magn. moment ratio                   -4.664 345 548e-4     0.000 000 050e-4
+deuteron-proton magn. moment ratio                     0.307 012 2084        0.000 000 0045
+deuteron-neutron magn. moment ratio                    -0.448 206 52         0.000 000 11
+electron gyromagn. ratio                               1.760 859 74e11       0.000 000 15e11       s^-1 T^-1
+electron gyromagn. ratio over 2 pi                     28 024.9532           0.0024                MHz T^-1
+electron magn. moment                                  -928.476 412e-26      0.000 080e-26         J T^-1
+electron magn. moment to Bohr magneton ratio           -1.001 159 652 1859   0.000 000 000 0038
+electron magn. moment to nuclear magneton ratio        -1838.281 971 07      0.000 000 85
+electron magn. moment anomaly                          1.159 652 1859e-3     0.000 000 0038e-3
+electron to shielded proton magn. moment ratio         -658.227 5956         0.000 0071
+electron to shielded helion magn. moment ratio         864.058 255           0.000 010
+electron-deuteron magn. moment ratio                   -2143.923 493         0.000 023
+electron-muon magn. moment ratio                       206.766 9894          0.000 0054
+electron-neutron magn. moment ratio                    960.920 50            0.000 23
+electron-proton magn. moment ratio                     -658.210 6862         0.000 0066
+magn. constant                                         12.566 370 614...e-7  (exact)               N A^-2
+magn. flux quantum                                     2.067 833 72e-15      0.000 000 18e-15      Wb
+muon magn. moment                                      -4.490 447 99e-26     0.000 000 40e-26      J T^-1
+muon magn. moment to Bohr magneton ratio               -4.841 970 45e-3      0.000 000 13e-3
+muon magn. moment to nuclear magneton ratio            -8.890 596 98         0.000 000 23
+muon-proton magn. moment ratio                         -3.183 345 118        0.000 000 089
+neutron gyromagn. ratio                                1.832 471 83e8        0.000 000 46e8        s^-1 T^-1
+neutron gyromagn. ratio over 2 pi                      29.164 6950           0.000 0073            MHz T^-1
+neutron magn. moment                                   -0.966 236 45e-26     0.000 000 24e-26      J T^-1
+neutron magn. moment to Bohr magneton ratio            -1.041 875 63e-3      0.000 000 25e-3
+neutron magn. moment to nuclear magneton ratio         -1.913 042 73         0.000 000 45
+neutron to shielded proton magn. moment ratio          -0.684 996 94         0.000 000 16
+neutron-electron magn. moment ratio                    1.040 668 82e-3       0.000 000 25e-3
+neutron-proton magn. moment ratio                      -0.684 979 34         0.000 000 16
+proton gyromagn. ratio                                 2.675 222 05e8        0.000 000 23e8        s^-1 T^-1
+proton gyromagn. ratio over 2 pi                       42.577 4813           0.000 0037            MHz T^-1
+proton magn. moment                                    1.410 606 71e-26      0.000 000 12e-26      J T^-1
+proton magn. moment to Bohr magneton ratio             1.521 032 206e-3      0.000 000 015e-3
+proton magn. moment to nuclear magneton ratio          2.792 847 351         0.000 000 028
+proton magn. shielding correction                      25.689e-6             0.015e-6
+proton-neutron magn. moment ratio                      -1.459 898 05         0.000 000 34
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded helion magn. moment                           -1.074 553 024e-26    0.000 000 093e-26     J T^-1
+shielded helion magn. moment to Bohr magneton ratio    -1.158 671 474e-3     0.000 000 014e-3
+shielded helion magn. moment to nuclear magneton ratio -2.127 497 723        0.000 000 025
+shielded helion to proton magn. moment ratio           -0.761 766 562        0.000 000 012
+shielded helion to shielded proton magn. moment ratio  -0.761 786 1313       0.000 000 0033
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded proton magn. moment                           1.410 570 47e-26      0.000 000 12e-26      J T^-1
+shielded proton magn. moment to Bohr magneton ratio    1.520 993 132e-3      0.000 000 016e-3
+shielded proton magn. moment to nuclear magneton ratio 2.792 775 604         0.000 000 030
+{220} lattice spacing of silicon                       192.015 5965e-12      0.000 0070e-12        m"""
+
+
+def exact2002(exact):
+    replace = {
+        'magn. constant': 4e-7 * math.pi,
+    }
+    return replace
+
+
+txt2006 = """\
+lattice spacing of silicon                             192.015 5762 e-12     0.000 0050 e-12       m
+alpha particle-electron mass ratio                     7294.299 5365         0.000 0031
+alpha particle mass                                    6.644 656 20 e-27     0.000 000 33 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 17 e-10     0.000 000 30 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 109          0.000 093             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 51      0.000 000 000 41
+Angstrom star                                          1.000 014 98 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 028           0.000 023             MeV
+atomic mass unit-electron volt relationship            931.494 028 e6        0.000 023 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 7149 e7     0.000 000 0049 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7369 e23    0.000 000 0032 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 671 e14     0.000 000 011 e14     m^-1
+atomic mass unit-joule relationship                    1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass unit-kelvin relationship                   1.080 9527 e13        0.000 0019 e13        K
+atomic mass unit-kilogram relationship                 1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 533 e-53    0.000 000 081 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 95 e-65     0.000 000 31 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 628 e-34    0.000 000 053 e-34    J s
+atomic unit of charge                                  1.602 176 487 e-19    0.000 000 040 e-19    C
+atomic unit of charge density                          1.081 202 300 e12     0.000 000 027 e12     C m^-3
+atomic unit of current                                 6.623 617 63 e-3      0.000 000 17 e-3      A
+atomic unit of electric dipole mom.                    8.478 352 81 e-30     0.000 000 21 e-30     C m
+atomic unit of electric field                          5.142 206 32 e11      0.000 000 13 e11      V m^-1
+atomic unit of electric field gradient                 9.717 361 66 e21      0.000 000 24 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2536 e-41   0.000 000 0034 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 383 86         0.000 000 68          V
+atomic unit of electric quadrupole mom.                4.486 551 07 e-40     0.000 000 11 e-40     C m^2
+atomic unit of energy                                  4.359 743 94 e-18     0.000 000 22 e-18     J
+atomic unit of force                                   8.238 722 06 e-8      0.000 000 41 e-8      N
+atomic unit of length                                  0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 830 e-23    0.000 000 046 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 382 e5      0.000 000 059 e5      T
+atomic unit of magnetizability                         7.891 036 433 e-29    0.000 000 027 e-29    J T^-2
+atomic unit of mass                                    9.109 382 15 e-31     0.000 000 45 e-31     kg
+atomic unit of momentum                                1.992 851 565 e-24    0.000 000 099 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 505 e-17 0.000 000 000 016 e-17 s
+atomic unit of velocity                                2.187 691 2541 e6     0.000 000 0015 e6     m s^-1
+Avogadro constant                                      6.022 141 79 e23      0.000 000 30 e23      mol^-1
+Bohr magneton                                          927.400 915 e-26      0.000 023 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 7555 e-5    0.000 000 0079 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 246 04 e9      0.000 000 35 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4515           0.000 0012            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 7131            0.000 0012            K T^-1
+Bohr radius                                            0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+Boltzmann constant                                     1.380 6504 e-23       0.000 0024 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 343 e-5         0.000 015 e-5         eV K^-1
+Boltzmann constant in Hz/K                             2.083 6644 e10        0.000 0036 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 56             0.000 12              m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 2894 e-15   0.000 000 0058 e-15   m
+Compton wavelength                                     2.426 310 2175 e-12   0.000 000 0033 e-12   m
+Compton wavelength over 2 pi                           386.159 264 59 e-15   0.000 000 53 e-15     m
+conductance quantum                                    7.748 091 7004 e-5    0.000 000 0053 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 99 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9654         0.000 0016
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 465 e-26    0.000 000 011 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 20 e-27     0.000 000 17 e-27     kg
+deuteron mass energy equivalent                        3.005 062 72 e-10     0.000 000 15 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 793          0.000 047             MeV
+deuteron mass in u                                     2.013 553 212 724     0.000 000 000 078     u
+deuteron molar mass                                    2.013 553 212 724 e-3 0.000 000 000 078 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 501 08      0.000 000 000 22
+deuteron rms charge radius                             2.1402 e-15           0.0028 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 150 e11    0.000 000 044 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1093 e-4    0.000 000 0012 e-4
+electron g factor                                      -2.002 319 304 3622   0.000 000 000 0015
+electron gyromag. ratio                                1.760 859 770 e11     0.000 000 044 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.953 64         0.000 70              MHz T^-1
+electron mag. mom.                                     -928.476 377 e-26     0.000 023 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 181 11 e-3  0.000 000 000 74 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 181 11 0.000 000 000 000 74
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 92      0.000 000 80
+electron mass                                          9.109 382 15 e-31     0.000 000 45 e-31     kg
+electron mass energy equivalent                        8.187 104 38 e-14     0.000 000 41 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 910         0.000 000 013         MeV
+electron mass in u                                     5.485 799 0943 e-4    0.000 000 0023 e-4    u
+electron molar mass                                    5.485 799 0943 e-7    0.000 000 0023 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9877          0.000 0052
+electron-muon mass ratio                               4.836 331 71 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4459 e-4    0.000 000 0033 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2177 e-4    0.000 000 0024 e-4
+electron-tau mass ratio                                2.875 64 e-4          0.000 47 e-4
+electron to alpha particle mass ratio                  1.370 933 555 70 e-4  0.000 000 000 58 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron volt                                          1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 188 e-9     0.000 000 027 e-9     u
+electron volt-hartree relationship                     3.674 932 540 e-2     0.000 000 092 e-2     E_h
+electron volt-hertz relationship                       2.417 989 454 e14     0.000 000 060 e14     Hz
+electron volt-inverse meter relationship               8.065 544 65 e5       0.000 000 20 e5       m^-1
+electron volt-joule relationship                       1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-kelvin relationship                      1.160 4505 e4         0.000 0020 e4         K
+electron volt-kilogram relationship                    1.782 661 758 e-36    0.000 000 044 e-36    kg
+elementary charge                                      1.602 176 487 e-19    0.000 000 040 e-19    C
+elementary charge over h                               2.417 989 454 e14     0.000 000 060 e14     A J^-1
+Faraday constant                                       96 485.3399           0.0024                C mol^-1
+Faraday constant for conventional electric current     96 485.3401           0.0048                C_90 mol^-1
+Fermi coupling constant                                1.166 37 e-5          0.000 01 e-5          GeV^-2
+fine-structure constant                                7.297 352 5376 e-3    0.000 000 0050 e-3
+first radiation constant                               3.741 771 18 e-16     0.000 000 19 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 759 e-16    0.000 000 059 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 2986 e-8    0.000 000 0042 e-8    u
+hartree-electron volt relationship                     27.211 383 86         0.000 000 68          eV
+Hartree energy                                         4.359 743 94 e-18     0.000 000 22 e-18     J
+Hartree energy in eV                                   27.211 383 86         0.000 000 68          eV
+hartree-hertz relationship                             6.579 683 920 722 e15 0.000 000 000 044 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 705 e7  0.000 000 000 015 e7  m^-1
+hartree-joule relationship                             4.359 743 94 e-18     0.000 000 22 e-18     J
+hartree-kelvin relationship                            3.157 7465 e5         0.000 0055 e5         K
+hartree-kilogram relationship                          4.850 869 34 e-35     0.000 000 24 e-35     kg
+helion-electron mass ratio                             5495.885 2765         0.000 0052
+helion mass                                            5.006 411 92 e-27     0.000 000 25 e-27     kg
+helion mass energy equivalent                          4.499 538 64 e-10     0.000 000 22 e-10     J
+helion mass energy equivalent in MeV                   2808.391 383          0.000 070             MeV
+helion mass in u                                       3.014 932 2473        0.000 000 0026        u
+helion molar mass                                      3.014 932 2473 e-3    0.000 000 0026 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6713        0.000 000 0026
+hertz-atomic mass unit relationship                    4.439 821 6294 e-24   0.000 000 0064 e-24   u
+hertz-electron volt relationship                       4.135 667 33 e-15     0.000 000 10 e-15     eV
+hertz-hartree relationship                             1.519 829 846 006 e-16 0.000 000 000010e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 068 96 e-34     0.000 000 33 e-34     J
+hertz-kelvin relationship                              4.799 2374 e-11       0.000 0084 e-11       K
+hertz-kilogram relationship                            7.372 496 00 e-51     0.000 000 37 e-51     kg
+inverse fine-structure constant                        137.035 999 679       0.000 000 094
+inverse meter-atomic mass unit relationship            1.331 025 0394 e-15   0.000 000 0019 e-15   u
+inverse meter-electron volt relationship               1.239 841 875 e-6     0.000 000 031 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 760 e-8 0.000 000 000 030 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 501 e-25    0.000 000 099 e-25    J
+inverse meter-kelvin relationship                      1.438 7752 e-2        0.000 0025 e-2        K
+inverse meter-kilogram relationship                    2.210 218 70 e-42     0.000 000 11 e-42     kg
+inverse of conductance quantum                         12 906.403 7787       0.000 0088            ohm
+Josephson constant                                     483 597.891 e9        0.012 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 536 41 e9       0.000 000 33 e9       u
+joule-electron volt relationship                       6.241 509 65 e18      0.000 000 16 e18      eV
+joule-hartree relationship                             2.293 712 69 e17      0.000 000 11 e17      E_h
+joule-hertz relationship                               1.509 190 450 e33     0.000 000 075 e33     Hz
+joule-inverse meter relationship                       5.034 117 47 e24      0.000 000 25 e24      m^-1
+joule-kelvin relationship                              7.242 963 e22         0.000 013 e22         K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 098 e-14        0.000 016 e-14        u
+kelvin-electron volt relationship                      8.617 343 e-5         0.000 015 e-5         eV
+kelvin-hartree relationship                            3.166 8153 e-6        0.000 0055 e-6        E_h
+kelvin-hertz relationship                              2.083 6644 e10        0.000 0036 e10        Hz
+kelvin-inverse meter relationship                      69.503 56             0.000 12              m^-1
+kelvin-joule relationship                              1.380 6504 e-23       0.000 0024 e-23       J
+kelvin-kilogram relationship                           1.536 1807 e-40       0.000 0027 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 79 e26      0.000 000 30 e26      u
+kilogram-electron volt relationship                    5.609 589 12 e35      0.000 000 14 e35      eV
+kilogram-hartree relationship                          2.061 486 16 e34      0.000 000 10 e34      E_h
+kilogram-hertz relationship                            1.356 392 733 e50     0.000 000 068 e50     Hz
+kilogram-inverse meter relationship                    4.524 439 15 e41      0.000 000 23 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 651 e39         0.000 011 e39         K
+lattice parameter of silicon                           543.102 064 e-12      0.000 014 e-12        m
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7774 e25        0.000 0047 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 667 e-15    0.000 000 052 e-15    Wb
+molar gas constant                                     8.314 472             0.000 015             J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 6821 e-10   0.000 000 0057 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 564 72      0.000 000 000 17      J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 981 e-3        0.000 040 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 996 e-3        0.000 039 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 8349 e-6       0.000 0011 e-6        m^3 mol^-1
+Mo x unit                                              1.002 099 55 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 04 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 295 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2823          0.000 0052
+muon g factor                                          -2.002 331 8414       0.000 000 0012
+muon mag. mom.                                         -4.490 447 86 e-26    0.000 000 16 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 69 e-3      0.000 000 60 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 49 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 23
+muon mass                                              1.883 531 30 e-28     0.000 000 11 e-28     kg
+muon mass energy equivalent                            1.692 833 510 e-11    0.000 000 095 e-11    J
+muon mass energy equivalent in MeV                     105.658 3668          0.000 0038            MeV
+muon mass in u                                         0.113 428 9256        0.000 000 0029        u
+muon molar mass                                        0.113 428 9256 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0029
+muon-proton mag. mom. ratio                            -3.183 345 137        0.000 000 085
+muon-proton mass ratio                                 0.112 609 5261        0.000 000 0029
+muon-tau mass ratio                                    5.945 92 e-2          0.000 97 e-2
+natural unit of action                                 1.054 571 628 e-34    0.000 000 053 e-34    J s
+natural unit of action in eV s                         6.582 118 99 e-16     0.000 000 16 e-16     eV s
+natural unit of energy                                 8.187 104 38 e-14     0.000 000 41 e-14     J
+natural unit of energy in MeV                          0.510 998 910         0.000 000 013         MeV
+natural unit of length                                 386.159 264 59 e-15   0.000 000 53 e-15     m
+natural unit of mass                                   9.109 382 15 e-31     0.000 000 45 e-31     kg
+natural unit of momentum                               2.730 924 06 e-22     0.000 000 14 e-22     kg m s^-1
+natural unit of momentum in MeV/c                      0.510 998 910         0.000 000 013         MeV/c
+natural unit of time                                   1.288 088 6570 e-21   0.000 000 0018 e-21   s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 8951 e-15   0.000 000 0020 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 413 82 e-15 0.000 000 000 31 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 85 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6954           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 41 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 211 e-27    0.000 000 084 e-27    kg
+neutron mass energy equivalent                         1.505 349 505 e-10    0.000 000 075 e-10    J
+neutron mass energy equivalent in MeV                  939.565 346           0.000 023             MeV
+neutron mass in u                                      1.008 664 915 97      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 915 97 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 09          0.000 000 23
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass ratio                              1.001 378 419 18      0.000 000 000 46
+neutron-tau mass ratio                                 0.528 740             0.000 086
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 28 e-11         0.000 67 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 81 e-39         0.000 67 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 24 e-27     0.000 000 13 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2326 e-8    0.000 000 0045 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 616 e-2     0.000 000 064 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2637 e-4        0.000 0064 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 84          0.000 000 19          MHz T^-1
+Planck constant                                        6.626 068 96 e-34     0.000 000 33 e-34     J s
+Planck constant in eV s                                4.135 667 33 e-15     0.000 000 10 e-15     eV s
+Planck constant over 2 pi                              1.054 571 628 e-34    0.000 000 053 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 118 99 e-16     0.000 000 16 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9631          0.000 0049            MeV fm
+Planck length                                          1.616 252 e-35        0.000 081 e-35        m
+Planck mass                                            2.176 44 e-8          0.000 11 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 892 e19         0.000 061 e19         GeV
+Planck temperature                                     1.416 785 e32         0.000 071 e32         K
+Planck time                                            5.391 24 e-44         0.000 27 e-44         s
+proton charge to mass quotient                         9.578 833 92 e7       0.000 000 24 e7       C kg^-1
+proton Compton wavelength                              1.321 409 8446 e-15   0.000 000 0019 e-15   m
+proton Compton wavelength over 2 pi                    0.210 308 908 61 e-15 0.000 000 000 30 e-15 m
+proton-electron mass ratio                             1836.152 672 47       0.000 000 80
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 099 e8      0.000 000 070 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4821           0.000 0011            MHz T^-1
+proton mag. mom.                                       1.410 606 662 e-26    0.000 000 037 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 209 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 637 e-27    0.000 000 083 e-27    kg
+proton mass energy equivalent                          1.503 277 359 e-10    0.000 000 075 e-10    J
+proton mass energy equivalent in MeV                   938.272 013           0.000 023             MeV
+proton mass in u                                       1.007 276 466 77      0.000 000 000 10      u
+proton molar mass                                      1.007 276 466 77 e-3  0.000 000 000 10 e-3  kg mol^-1
+proton-muon mass ratio                                 8.880 243 39          0.000 000 23
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 24      0.000 000 000 46
+proton rms charge radius                               0.8768 e-15           0.0069 e-15           m
+proton-tau mass ratio                                  0.528 012             0.000 086
+quantum of circulation                                 3.636 947 5199 e-4    0.000 000 0050 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 040 e-4     0.000 000 010 e-4     m^2 s^-1
+Rydberg constant                                       10 973 731.568 527    0.000 073             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 361 e15 0.000 000 000 022 e15 Hz
+Rydberg constant times hc in eV                        13.605 691 93         0.000 000 34          eV
+Rydberg constant times hc in J                         2.179 871 97 e-18     0.000 000 11 e-18     J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7047           0.000 0044
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8677           0.000 0044
+second radiation constant                              1.438 7752 e-2        0.000 0025 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 730 e8      0.000 000 056 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 101 98         0.000 000 90          MHz T^-1
+shielded helion mag. mom.                              -1.074 552 982 e-26   0.000 000 030 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 362 e8      0.000 000 073 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3881           0.000 0012            MHz T^-1
+shielded proton mag. mom.                              1.410 570 419 e-26    0.000 000 038 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 400 e-8         0.000 040 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 72 e-15         0.000 11 e-15         m
+tau Compton wavelength over 2 pi                       0.111 046 e-15        0.000 018 e-15        m
+tau-electron mass ratio                                3477.48               0.57
+tau mass                                               3.167 77 e-27         0.000 52 e-27         kg
+tau mass energy equivalent                             2.847 05 e-10         0.000 46 e-10         J
+tau mass energy equivalent in MeV                      1776.99               0.29                  MeV
+tau mass in u                                          1.907 68              0.000 31              u
+tau molar mass                                         1.907 68 e-3          0.000 31 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8183               0.0027
+tau-neutron mass ratio                                 1.891 29              0.000 31
+tau-proton mass ratio                                  1.893 90              0.000 31
+Thomson cross section                                  0.665 245 8558 e-28   0.000 000 0027 e-28   m^2
+triton-electron mag. mom. ratio                        -1.620 514 423 e-3    0.000 000 021 e-3
+triton-electron mass ratio                             5496.921 5269         0.000 0051
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 361 e-26    0.000 000 042 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 355 88 e-27     0.000 000 25 e-27     kg
+triton mass energy equivalent                          4.500 387 03 e-10     0.000 000 22 e-10     J
+triton mass energy equivalent in MeV                   2808.920 906          0.000 070             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-neutron mag. mom. ratio                         -1.557 185 53         0.000 000 37
+triton-proton mag. mom. ratio                          1.066 639 908         0.000 000 010
+triton-proton mass ratio                               2.993 717 0309        0.000 000 0025
+unified atomic mass unit                               1.660 538 782 e-27    0.000 000 083 e-27    kg
+von Klitzing constant                                  25 812.807 557        0.000 018             ohm
+weak mixing angle                                      0.222 55              0.000 56
+Wien frequency displacement law constant               5.878 933 e10         0.000 010 e10         Hz K^-1
+Wien wavelength displacement law constant              2.897 7685 e-3        0.000 0051 e-3        m K"""
+
+
+def exact2006(exact):
+    mu0 = 4e-7 * math.pi
+    c = exact['speed of light in vacuum']
+    epsilon0 = 1 / (mu0 * c**2)
+    replace = {
+        'mag. constant': mu0,
+        'electric constant': epsilon0,
+        'atomic unit of permittivity': 4*math.pi*epsilon0,
+        'characteristic impedance of vacuum': math.sqrt(mu0 / epsilon0),
+        'hertz-inverse meter relationship': 1/c,
+        'joule-kilogram relationship': 1/c**2,
+        'kilogram-joule relationship': c**2,
+    }
+    return replace
+
+
+txt2010 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 5361         0.000 0029
+alpha particle mass                                    6.644 656 75 e-27     0.000 000 29 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 67 e-10     0.000 000 26 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 240          0.000 082             MeV
+alpha particle mass in u                               4.001 506 179 125     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 125 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 33      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 061           0.000 021             MeV
+atomic mass unit-electron volt relationship            931.494 061 e6        0.000 021 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 6845 e7     0.000 000 0024 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7168 e23    0.000 000 0016 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6042 e14    0.000 000 0053 e14    m^-1
+atomic mass unit-joule relationship                    1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 08 e13      0.000 000 98 e13      K
+atomic mass unit-kilogram relationship                 1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 449 e-53    0.000 000 071 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 54 e-65     0.000 000 28 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 726 e-34    0.000 000 047 e-34    J s
+atomic unit of charge                                  1.602 176 565 e-19    0.000 000 035 e-19    C
+atomic unit of charge density                          1.081 202 338 e12     0.000 000 024 e12     C m^-3
+atomic unit of current                                 6.623 617 95 e-3      0.000 000 15 e-3      A
+atomic unit of electric dipole mom.                    8.478 353 26 e-30     0.000 000 19 e-30     C m
+atomic unit of electric field                          5.142 206 52 e11      0.000 000 11 e11      V m^-1
+atomic unit of electric field gradient                 9.717 362 00 e21      0.000 000 21 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2754 e-41   0.000 000 0016 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 385 05         0.000 000 60          V
+atomic unit of electric quadrupole mom.                4.486 551 331 e-40    0.000 000 099 e-40    C m^2
+atomic unit of energy                                  4.359 744 34 e-18     0.000 000 19 e-18     J
+atomic unit of force                                   8.238 722 78 e-8      0.000 000 36 e-8      N
+atomic unit of length                                  0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 936 e-23    0.000 000 041 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 464 e5      0.000 000 052 e5      T
+atomic unit of magnetizability                         7.891 036 607 e-29    0.000 000 013 e-29    J T^-2
+atomic unit of mass                                    9.109 382 91 e-31     0.000 000 40 e-31     kg
+atomic unit of mom.um                                  1.992 851 740 e-24    0.000 000 088 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 502e-17 0.000 000 000 012e-17 s
+atomic unit of velocity                                2.187 691 263 79 e6   0.000 000 000 71 e6   m s^-1
+Avogadro constant                                      6.022 141 29 e23      0.000 000 27 e23      mol^-1
+Bohr magneton                                          927.400 968 e-26      0.000 020 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 8066 e-5    0.000 000 0038 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 55 e9      0.000 000 31 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4498           0.000 0010            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 713 88          0.000 000 61          K T^-1
+Bohr radius                                            0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+Boltzmann constant                                     1.380 6488 e-23       0.000 0013 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 3324 e-5        0.000 0078 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6618 e10        0.000 0019 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 476            0.000 063             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3267 e-15   0.000 000 0027 e-15   m
+Compton wavelength                                     2.426 310 2389 e-12   0.000 000 0016 e-12   m
+Compton wavelength over 2 pi                           386.159 268 00 e-15   0.000 000 25 e-15     m
+conductance quantum                                    7.748 091 7346 e-5    0.000 000 0025 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9652         0.000 0015
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 489 e-26    0.000 000 010 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 48 e-27     0.000 000 15 e-27     kg
+deuteron mass energy equivalent                        3.005 062 97 e-10     0.000 000 13 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 859          0.000 041             MeV
+deuteron mass in u                                     2.013 553 212 712     0.000 000 000 077     u
+deuteron molar mass                                    2.013 553 212 712 e-3 0.000 000 000 077 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 500 97      0.000 000 000 18
+deuteron rms charge radius                             2.1424 e-15           0.0021 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 088 e11    0.000 000 039 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1095 e-4    0.000 000 0011 e-4
+electron g factor                                      -2.002 319 304 361 53 0.000 000 000 000 53
+electron gyromag. ratio                                1.760 859 708 e11     0.000 000 039 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.952 66         0.000 62              MHz T^-1
+electron-helion mass ratio                             1.819 543 0761 e-4    0.000 000 0017 e-4
+electron mag. mom.                                     -928.476 430 e-26     0.000 021 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 180 76 e-3  0.000 000 000 27 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 76 0.000 000 000 000 27
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 90      0.000 000 75
+electron mass                                          9.109 382 91 e-31     0.000 000 40 e-31     kg
+electron mass energy equivalent                        8.187 105 06 e-14     0.000 000 36 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 928         0.000 000 011         MeV
+electron mass in u                                     5.485 799 0946 e-4    0.000 000 0022 e-4    u
+electron molar mass                                    5.485 799 0946 e-7    0.000 000 0022 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9896          0.000 0052
+electron-muon mass ratio                               4.836 331 66 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4461 e-4    0.000 000 0032 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2178 e-4    0.000 000 0022 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 555 78 e-4  0.000 000 000 55 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 0653 e-4    0.000 000 0017 e-4
+electron volt                                          1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 150 e-9     0.000 000 024 e-9     u
+electron volt-hartree relationship                     3.674 932 379 e-2     0.000 000 081 e-2     E_h
+electron volt-hertz relationship                       2.417 989 348 e14     0.000 000 053 e14     Hz
+electron volt-inverse meter relationship               8.065 544 29 e5       0.000 000 18 e5       m^-1
+electron volt-joule relationship                       1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-kelvin relationship                      1.160 4519 e4         0.000 0011 e4         K
+electron volt-kilogram relationship                    1.782 661 845 e-36    0.000 000 039 e-36    kg
+elementary charge                                      1.602 176 565 e-19    0.000 000 035 e-19    C
+elementary charge over h                               2.417 989 348 e14     0.000 000 053 e14     A J^-1
+Faraday constant                                       96 485.3365           0.0021                C mol^-1
+Faraday constant for conventional electric current     96 485.3321           0.0043                C_90 mol^-1
+Fermi coupling constant                                1.166 364 e-5         0.000 005 e-5         GeV^-2
+fine-structure constant                                7.297 352 5698 e-3    0.000 000 0024 e-3
+first radiation constant                               3.741 771 53 e-16     0.000 000 17 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 869 e-16    0.000 000 053 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3246 e-8    0.000 000 0021 e-8    u
+hartree-electron volt relationship                     27.211 385 05         0.000 000 60          eV
+Hartree energy                                         4.359 744 34 e-18     0.000 000 19 e-18     J
+Hartree energy in eV                                   27.211 385 05         0.000 000 60          eV
+hartree-hertz relationship                             6.579 683 920 729 e15 0.000 000 000 033 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 708 e7  0.000 000 000 011 e7  m^-1
+hartree-joule relationship                             4.359 744 34 e-18     0.000 000 19 e-18     J
+hartree-kelvin relationship                            3.157 7504 e5         0.000 0029 e5         K
+hartree-kilogram relationship                          4.850 869 79 e-35     0.000 000 21 e-35     kg
+helion-electron mass ratio                             5495.885 2754         0.000 0050
+helion g factor                                        -4.255 250 613        0.000 000 050
+helion mag. mom.                                       -1.074 617 486 e-26   0.000 000 027 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 306        0.000 000 025
+helion mass                                            5.006 412 34 e-27     0.000 000 22 e-27     kg
+helion mass energy equivalent                          4.499 539 02 e-10     0.000 000 20 e-10     J
+helion mass energy equivalent in MeV                   2808.391 482          0.000 062             MeV
+helion mass in u                                       3.014 932 2468        0.000 000 0025        u
+helion molar mass                                      3.014 932 2468 e-3    0.000 000 0025 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6707        0.000 000 0025
+hertz-atomic mass unit relationship                    4.439 821 6689 e-24   0.000 000 0031 e-24   u
+hertz-electron volt relationship                       4.135 667 516 e-15    0.000 000 091 e-15    eV
+hertz-hartree relationship                             1.519 829 8460045e-16 0.000 000 0000076e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 069 57 e-34     0.000 000 29 e-34     J
+hertz-kelvin relationship                              4.799 2434 e-11       0.000 0044 e-11       K
+hertz-kilogram relationship                            7.372 496 68 e-51     0.000 000 33 e-51     kg
+inverse fine-structure constant                        137.035 999 074       0.000 000 044
+inverse meter-atomic mass unit relationship            1.331 025 051 20 e-15 0.000 000 000 94 e-15 u
+inverse meter-electron volt relationship               1.239 841 930 e-6     0.000 000 027 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 755 e-8 0.000 000 000 023 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 684 e-25    0.000 000 088 e-25    J
+inverse meter-kelvin relationship                      1.438 7770 e-2        0.000 0013 e-2        K
+inverse meter-kilogram relationship                    2.210 218 902 e-42    0.000 000 098 e-42    kg
+inverse of conductance quantum                         12 906.403 7217       0.000 0042            ohm
+Josephson constant                                     483 597.870 e9        0.011 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 85 e9       0.000 000 30 e9       u
+joule-electron volt relationship                       6.241 509 34 e18      0.000 000 14 e18      eV
+joule-hartree relationship                             2.293 712 48 e17      0.000 000 10 e17      E_h
+joule-hertz relationship                               1.509 190 311 e33     0.000 000 067 e33     Hz
+joule-inverse meter relationship                       5.034 117 01 e24      0.000 000 22 e24      m^-1
+joule-kelvin relationship                              7.242 9716 e22        0.000 0066 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0868 e-14       0.000 0084 e-14       u
+kelvin-electron volt relationship                      8.617 3324 e-5        0.000 0078 e-5        eV
+kelvin-hartree relationship                            3.166 8114 e-6        0.000 0029 e-6        E_h
+kelvin-hertz relationship                              2.083 6618 e10        0.000 0019 e10        Hz
+kelvin-inverse meter relationship                      69.503 476            0.000 063             m^-1
+kelvin-joule relationship                              1.380 6488 e-23       0.000 0013 e-23       J
+kelvin-kilogram relationship                           1.536 1790 e-40       0.000 0014 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 29 e26      0.000 000 27 e26      u
+kilogram-electron volt relationship                    5.609 588 85 e35      0.000 000 12 e35      eV
+kilogram-hartree relationship                          2.061 485 968 e34     0.000 000 091 e34     E_h
+kilogram-hertz relationship                            1.356 392 608 e50     0.000 000 060 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 73 e41      0.000 000 20 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6582 e39        0.000 0059 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6462 e25        0.000 0024 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7805 e25        0.000 0024 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 758 e-15    0.000 000 046 e-15    Wb
+molar gas constant                                     8.314 4621            0.000 0075            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7176 e-10   0.000 000 0028 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 779     0.000 000 000 084     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 953 e-3        0.000 021 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 968 e-3        0.000 020 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 833 01 e-6     0.000 000 80 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 03 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 294 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2843          0.000 0052
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 07 e-26    0.000 000 15 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 91 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 44 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 596 97         0.000 000 22
+muon mass                                              1.883 531 475 e-28    0.000 000 096 e-28    kg
+muon mass energy equivalent                            1.692 833 667 e-11    0.000 000 086 e-11    J
+muon mass energy equivalent in MeV                     105.658 3715          0.000 0035            MeV
+muon mass in u                                         0.113 428 9267        0.000 000 0029        u
+muon molar mass                                        0.113 428 9267 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5177        0.000 000 0028
+muon-proton mag. mom. ratio                            -3.183 345 107        0.000 000 084
+muon-proton mass ratio                                 0.112 609 5272        0.000 000 0028
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 726 e-34    0.000 000 047 e-34    J s
+natural unit of action in eV s                         6.582 119 28 e-16     0.000 000 15 e-16     eV s
+natural unit of energy                                 8.187 105 06 e-14     0.000 000 36 e-14     J
+natural unit of energy in MeV                          0.510 998 928         0.000 000 011         MeV
+natural unit of length                                 386.159 268 00 e-15   0.000 000 25 e-15     m
+natural unit of mass                                   9.109 382 91 e-31     0.000 000 40 e-31     kg
+natural unit of mom.um                                 2.730 924 29 e-22     0.000 000 12 e-22     kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 928         0.000 000 011         MeV/c
+natural unit of time                                   1.288 088 668 33 e-21 0.000 000 000 83 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 9068 e-15   0.000 000 0011 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 415 68 e-15 0.000 000 000 17 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 79 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6943           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 47 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 72         0.000 000 45
+neutron mass                                           1.674 927 351 e-27    0.000 000 074 e-27    kg
+neutron mass energy equivalent                         1.505 349 631 e-10    0.000 000 066 e-10    J
+neutron mass energy equivalent in MeV                  939.565 379           0.000 021             MeV
+neutron mass in u                                      1.008 664 916 00      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 916 00 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 00          0.000 000 22
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 92 e-30     0.000 000 76 e-30
+neutron-proton mass difference energy equivalent       2.072 146 50 e-13     0.000 000 68 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 17          0.000 000 42
+neutron-proton mass difference in u                    0.001 388 449 19      0.000 000 000 45
+neutron-proton mass ratio                              1.001 378 419 17      0.000 000 000 45
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.673 84 e-11         0.000 80 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 37 e-39         0.000 80 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 53 e-27     0.000 000 11 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2605 e-8    0.000 000 0022 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 527 e-2     0.000 000 056 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2682 e-4        0.000 0033 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 57          0.000 000 17          MHz T^-1
+Planck constant                                        6.626 069 57 e-34     0.000 000 29 e-34     J s
+Planck constant in eV s                                4.135 667 516 e-15    0.000 000 091 e-15    eV s
+Planck constant over 2 pi                              1.054 571 726 e-34    0.000 000 047 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 28 e-16     0.000 000 15 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9718          0.000 0044            MeV fm
+Planck length                                          1.616 199 e-35        0.000 097 e-35        m
+Planck mass                                            2.176 51 e-8          0.000 13 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 932 e19         0.000 073 e19         GeV
+Planck temperature                                     1.416 833 e32         0.000 085 e32         K
+Planck time                                            5.391 06 e-44         0.000 32 e-44         s
+proton charge to mass quotient                         9.578 833 58 e7       0.000 000 21 e7       C kg^-1
+proton Compton wavelength                              1.321 409 856 23 e-15 0.000 000 000 94 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308 910 47 e-15 0.000 000 000 15 e-15 m
+proton-electron mass ratio                             1836.152 672 45       0.000 000 75
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 005 e8      0.000 000 063 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4806           0.000 0010            MHz T^-1
+proton mag. mom.                                       1.410 606 743 e-26    0.000 000 033 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 210 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 777 e-27    0.000 000 074 e-27    kg
+proton mass energy equivalent                          1.503 277 484 e-10    0.000 000 066 e-10    J
+proton mass energy equivalent in MeV                   938.272 046           0.000 021             MeV
+proton mass in u                                       1.007 276 466 812     0.000 000 000 090     u
+proton molar mass                                      1.007 276 466 812 e-3 0.000 000 000 090 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 31          0.000 000 22
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 26      0.000 000 000 45
+proton rms charge radius                               0.8775 e-15           0.0051 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5520 e-4    0.000 000 0024 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 1040 e-4    0.000 000 0047 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 539    0.000 055             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 364 e15 0.000 000 000 017 e15 Hz
+Rydberg constant times hc in eV                        13.605 692 53         0.000 000 30          eV
+Rydberg constant times hc in J                         2.179 872 171 e-18    0.000 000 096 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7078           0.000 0023
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8708           0.000 0023
+second radiation constant                              1.438 7770 e-2        0.000 0013 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 659 e8      0.000 000 051 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 100 84         0.000 000 81          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 044 e-26   0.000 000 027 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 268 e8      0.000 000 066 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3866           0.000 0010            MHz T^-1
+shielded proton mag. mom.                              1.410 570 499 e-26    0.000 000 035 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 373 e-8         0.000 021 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 8734 e-28   0.000 000 0013 e-28   m^2
+triton-electron mass ratio                             5496.921 5267         0.000 0050
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 447 e-26    0.000 000 038 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 356 30 e-27     0.000 000 22 e-27     kg
+triton mass energy equivalent                          4.500 387 41 e-10     0.000 000 20 e-10     J
+triton mass energy equivalent in MeV                   2808.921 005          0.000 062             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-proton mass ratio                               2.993 717 0308        0.000 000 0025
+unified atomic mass unit                               1.660 538 921 e-27    0.000 000 073 e-27    kg
+von Klitzing constant                                  25 812.807 4434       0.000 0084            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9254 e10        0.000 0053 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7721 e-3        0.000 0026 e-3        m K"""
+
+
+exact2010 = exact2006
+
+
+txt2014 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 541 36       0.000 000 24
+alpha particle mass                                    6.644 657 230 e-27    0.000 000 082 e-27    kg
+alpha particle mass energy equivalent                  5.971 920 097 e-10    0.000 000 073 e-10    J
+alpha particle mass energy equivalent in MeV           3727.379 378          0.000 023             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 063     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 063 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 07      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic mass constant energy equivalent                 1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 0954          0.000 0057            MeV
+atomic mass unit-electron volt relationship            931.494 0954 e6       0.000 0057 e6         eV
+atomic mass unit-hartree relationship                  3.423 177 6902 e7     0.000 000 0016 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7206 e23    0.000 000 0010 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6166 e14    0.000 000 0034 e14    m^-1
+atomic mass unit-joule relationship                    1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 38 e13      0.000 000 62 e13      K
+atomic mass unit-kilogram relationship                 1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 329 e-53    0.000 000 020 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 085 e-65    0.000 000 077 e-65    C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 800 e-34    0.000 000 013 e-34    J s
+atomic unit of charge                                  1.602 176 6208 e-19   0.000 000 0098 e-19   C
+atomic unit of charge density                          1.081 202 3770 e12    0.000 000 0067 e12    C m^-3
+atomic unit of current                                 6.623 618 183 e-3     0.000 000 041 e-3     A
+atomic unit of electric dipole mom.                    8.478 353 552 e-30    0.000 000 052 e-30    C m
+atomic unit of electric field                          5.142 206 707 e11     0.000 000 032 e11     V m^-1
+atomic unit of electric field gradient                 9.717 362 356 e21     0.000 000 060 e21     V m^-2
+atomic unit of electric polarizability                 1.648 777 2731 e-41   0.000 000 0011 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 386 02         0.000 000 17          V
+atomic unit of electric quadrupole mom.                4.486 551 484 e-40    0.000 000 028 e-40    C m^2
+atomic unit of energy                                  4.359 744 650 e-18    0.000 000 054 e-18    J
+atomic unit of force                                   8.238 723 36 e-8      0.000 000 10 e-8      N
+atomic unit of length                                  0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 999 e-23    0.000 000 011 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 550 e5      0.000 000 014 e5      T
+atomic unit of magnetizability                         7.891 036 5886 e-29   0.000 000 0090 e-29   J T^-2
+atomic unit of mass                                    9.109 383 56 e-31     0.000 000 11 e-31     kg
+atomic unit of mom.um                                  1.992 851 882 e-24    0.000 000 024 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326509e-17  0.000 000 000014e-17  s
+atomic unit of velocity                                2.187 691 262 77 e6   0.000 000 000 50 e6   m s^-1
+Avogadro constant                                      6.022 140 857 e23     0.000 000 074 e23     mol^-1
+Bohr magneton                                          927.400 9994 e-26     0.000 0057 e-26       J T^-1
+Bohr magneton in eV/T                                  5.788 381 8012 e-5    0.000 000 0026 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 042 e9     0.000 000 086 e9      Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 448 14         0.000 000 29          m^-1 T^-1
+Bohr magneton in K/T                                   0.671 714 05          0.000 000 39          K T^-1
+Bohr radius                                            0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+Boltzmann constant                                     1.380 648 52 e-23     0.000 000 79 e-23     J K^-1
+Boltzmann constant in eV/K                             8.617 3303 e-5        0.000 0050 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6612 e10        0.000 0012 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 457            0.000 040             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3227 e-15   0.000 000 0019 e-15   m
+Compton wavelength                                     2.426 310 2367 e-12   0.000 000 0011 e-12   m
+Compton wavelength over 2 pi                           386.159 267 64 e-15   0.000 000 18 e-15     m
+conductance quantum                                    7.748 091 7310 e-5    0.000 000 0018 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 535 e-4    0.000 000 026 e-4
+deuteron-electron mass ratio                           3670.482 967 85       0.000 000 13
+deuteron g factor                                      0.857 438 2311        0.000 000 0048
+deuteron mag. mom.                                     0.433 073 5040 e-26   0.000 000 0036 e-26   J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4554 e-3    0.000 000 0026 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2311        0.000 000 0048
+deuteron mass                                          3.343 583 719 e-27    0.000 000 041 e-27    kg
+deuteron mass energy equivalent                        3.005 063 183 e-10    0.000 000 037 e-10    J
+deuteron mass energy equivalent in MeV                 1875.612 928          0.000 012             MeV
+deuteron mass in u                                     2.013 553 212 745     0.000 000 000 040     u
+deuteron molar mass                                    2.013 553 212 745 e-3 0.000 000 000 040 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2077        0.000 000 0015
+deuteron-proton mass ratio                             1.999 007 500 87      0.000 000 000 19
+deuteron rms charge radius                             2.1413 e-15           0.0025 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 024 e11    0.000 000 011 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 499         0.000 012
+electron-deuteron mass ratio                           2.724 437 107 484 e-4 0.000 000 000 096 e-4
+electron g factor                                      -2.002 319 304 361 82 0.000 000 000 000 52
+electron gyromag. ratio                                1.760 859 644 e11     0.000 000 011 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.951 64         0.000 17              MHz T^-1
+electron-helion mass ratio                             1.819 543 074 854 e-4 0.000 000 000 088 e-4
+electron mag. mom.                                     -928.476 4620 e-26    0.000 0057 e-26       J T^-1
+electron mag. mom. anomaly                             1.159 652 180 91 e-3  0.000 000 000 26 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 91 0.000 000 000 000 26
+electron mag. mom. to nuclear magneton ratio           -1838.281 972 34      0.000 000 17
+electron mass                                          9.109 383 56 e-31     0.000 000 11 e-31     kg
+electron mass energy equivalent                        8.187 105 65 e-14     0.000 000 10 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 9461        0.000 000 0031        MeV
+electron mass in u                                     5.485 799 090 70 e-4  0.000 000 000 16 e-4  u
+electron molar mass                                    5.485 799 090 70 e-7  0.000 000 000 16 e-7  kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9880          0.000 0046
+electron-muon mass ratio                               4.836 331 70 e-3      0.000 000 11 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4428 e-4    0.000 000 0027 e-4
+electron-proton mag. mom. ratio                        -658.210 6866         0.000 0020
+electron-proton mass ratio                             5.446 170 213 52 e-4  0.000 000 000 52 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 554 798 e-4 0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 062 203 e-4 0.000 000 000 084 e-4
+electron volt                                          1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-atomic mass unit relationship            1.073 544 1105 e-9    0.000 000 0066 e-9    u
+electron volt-hartree relationship                     3.674 932 248 e-2     0.000 000 023 e-2     E_h
+electron volt-hertz relationship                       2.417 989 262 e14     0.000 000 015 e14     Hz
+electron volt-inverse meter relationship               8.065 544 005 e5      0.000 000 050 e5      m^-1
+electron volt-joule relationship                       1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-kelvin relationship                      1.160 452 21 e4       0.000 000 67 e4       K
+electron volt-kilogram relationship                    1.782 661 907 e-36    0.000 000 011 e-36    kg
+elementary charge                                      1.602 176 6208 e-19   0.000 000 0098 e-19   C
+elementary charge over h                               2.417 989 262 e14     0.000 000 015 e14     A J^-1
+Faraday constant                                       96 485.332 89         0.000 59              C mol^-1
+Faraday constant for conventional electric current     96 485.3251           0.0012                C_90 mol^-1
+Fermi coupling constant                                1.166 3787 e-5        0.000 0006 e-5        GeV^-2
+fine-structure constant                                7.297 352 5664 e-3    0.000 000 0017 e-3
+first radiation constant                               3.741 771 790 e-16    0.000 000 046 e-16    W m^2
+first radiation constant for spectral radiance         1.191 042 953 e-16    0.000 000 015 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3197 e-8    0.000 000 0013 e-8    u
+hartree-electron volt relationship                     27.211 386 02         0.000 000 17          eV
+Hartree energy                                         4.359 744 650 e-18    0.000 000 054 e-18    J
+Hartree energy in eV                                   27.211 386 02         0.000 000 17          eV
+hartree-hertz relationship                             6.579 683 920 711 e15 0.000 000 000 039 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 702 e7  0.000 000 000 013 e7  m^-1
+hartree-joule relationship                             4.359 744 650 e-18    0.000 000 054 e-18    J
+hartree-kelvin relationship                            3.157 7513 e5         0.000 0018 e5         K
+hartree-kilogram relationship                          4.850 870 129 e-35    0.000 000 060 e-35    kg
+helion-electron mass ratio                             5495.885 279 22       0.000 000 27
+helion g factor                                        -4.255 250 616        0.000 000 050
+helion mag. mom.                                       -1.074 617 522 e-26   0.000 000 014 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 308        0.000 000 025
+helion mass                                            5.006 412 700 e-27    0.000 000 062 e-27    kg
+helion mass energy equivalent                          4.499 539 341 e-10    0.000 000 055 e-10    J
+helion mass energy equivalent in MeV                   2808.391 586          0.000 017             MeV
+helion mass in u                                       3.014 932 246 73      0.000 000 000 12      u
+helion molar mass                                      3.014 932 246 73 e-3  0.000 000 000 12 e-3  kg mol^-1
+helion-proton mass ratio                               2.993 152 670 46      0.000 000 000 29
+hertz-atomic mass unit relationship                    4.439 821 6616 e-24   0.000 000 0020 e-24   u
+hertz-electron volt relationship                       4.135 667 662 e-15    0.000 000 025 e-15    eV
+hertz-hartree relationship                             1.5198298460088 e-16  0.0000000000090e-16   E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 070 040 e-34    0.000 000 081 e-34    J
+hertz-kelvin relationship                              4.799 2447 e-11       0.000 0028 e-11       K
+hertz-kilogram relationship                            7.372 497 201 e-51    0.000 000 091 e-51    kg
+inverse fine-structure constant                        137.035 999 139       0.000 000 031
+inverse meter-atomic mass unit relationship            1.331 025 049 00 e-15 0.000 000 000 61 e-15 u
+inverse meter-electron volt relationship               1.239 841 9739 e-6    0.000 000 0076 e-6    eV
+inverse meter-hartree relationship                     4.556 335 252 767 e-8 0.000 000 000 027 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 824 e-25    0.000 000 024 e-25    J
+inverse meter-kelvin relationship                      1.438 777 36 e-2      0.000 000 83 e-2      K
+inverse meter-kilogram relationship                    2.210 219 057 e-42    0.000 000 027 e-42    kg
+inverse of conductance quantum                         12 906.403 7278       0.000 0029            ohm
+Josephson constant                                     483 597.8525 e9       0.0030 e9             Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 363 e9      0.000 000 082 e9      u
+joule-electron volt relationship                       6.241 509 126 e18     0.000 000 038 e18     eV
+joule-hartree relationship                             2.293 712 317 e17     0.000 000 028 e17     E_h
+joule-hertz relationship                               1.509 190 205 e33     0.000 000 019 e33     Hz
+joule-inverse meter relationship                       5.034 116 651 e24     0.000 000 062 e24     m^-1
+joule-kelvin relationship                              7.242 9731 e22        0.000 0042 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0842 e-14       0.000 0053 e-14       u
+kelvin-electron volt relationship                      8.617 3303 e-5        0.000 0050 e-5        eV
+kelvin-hartree relationship                            3.166 8105 e-6        0.000 0018 e-6        E_h
+kelvin-hertz relationship                              2.083 6612 e10        0.000 0012 e10        Hz
+kelvin-inverse meter relationship                      69.503 457            0.000 040             m^-1
+kelvin-joule relationship                              1.380 648 52 e-23     0.000 000 79 e-23     J
+kelvin-kilogram relationship                           1.536 178 65 e-40     0.000 000 88 e-40     kg
+kilogram-atomic mass unit relationship                 6.022 140 857 e26     0.000 000 074 e26     u
+kilogram-electron volt relationship                    5.609 588 650 e35     0.000 000 034 e35     eV
+kilogram-hartree relationship                          2.061 485 823 e34     0.000 000 025 e34     E_h
+kilogram-hertz relationship                            1.356 392 512 e50     0.000 000 017 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 411 e41     0.000 000 056 e41     m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6595 e39        0.000 0037 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6467 e25        0.000 0015 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7811 e25        0.000 0015 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 831 e-15    0.000 000 013 e-15    Wb
+molar gas constant                                     8.314 4598            0.000 0048            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7110 e-10   0.000 000 0018 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 582     0.000 000 000 054     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 947 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 962 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 832 14 e-6     0.000 000 61 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 11 e-15    0.000 000 26 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 308 e-15    0.000 000 042 e-15    m
+muon-electron mass ratio                               206.768 2826          0.000 0046
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 26 e-26    0.000 000 10 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 89 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 48 e-3     0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 20
+muon mass                                              1.883 531 594 e-28    0.000 000 048 e-28    kg
+muon mass energy equivalent                            1.692 833 774 e-11    0.000 000 043 e-11    J
+muon mass energy equivalent in MeV                     105.658 3745          0.000 0024            MeV
+muon mass in u                                         0.113 428 9257        0.000 000 0025        u
+muon molar mass                                        0.113 428 9257 e-3    0.000 000 0025 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0025
+muon-proton mag. mom. ratio                            -3.183 345 142        0.000 000 071
+muon-proton mass ratio                                 0.112 609 5262        0.000 000 0025
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 800 e-34    0.000 000 013 e-34    J s
+natural unit of action in eV s                         6.582 119 514 e-16    0.000 000 040 e-16    eV s
+natural unit of energy                                 8.187 105 65 e-14     0.000 000 10 e-14     J
+natural unit of energy in MeV                          0.510 998 9461        0.000 000 0031        MeV
+natural unit of length                                 386.159 267 64 e-15   0.000 000 18 e-15     m
+natural unit of mass                                   9.109 383 56 e-31     0.000 000 11 e-31     kg
+natural unit of mom.um                                 2.730 924 488 e-22    0.000 000 034 e-22    kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 9461        0.000 000 0031        MeV/c
+natural unit of time                                   1.288 088 667 12 e-21 0.000 000 000 58 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 904 81 e-15 0.000 000 000 88 e-15 m
+neutron Compton wavelength over 2 pi                   0.210 019 415 36 e-15 0.000 000 000 14 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 661 58       0.000 000 90
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 72 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6933           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 50 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 471 e-27    0.000 000 021 e-27    kg
+neutron mass energy equivalent                         1.505 349 739 e-10    0.000 000 019 e-10    J
+neutron mass energy equivalent in MeV                  939.565 4133          0.000 0058            MeV
+neutron mass in u                                      1.008 664 915 88      0.000 000 000 49      u
+neutron molar mass                                     1.008 664 915 88 e-3  0.000 000 000 49 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 08          0.000 000 20
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 77 e-30     0.000 000 85 e-30
+neutron-proton mass difference energy equivalent       2.072 146 37 e-13     0.000 000 76 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 05         0.000 000 48
+neutron-proton mass difference in u                    0.001 388 449 00      0.000 000 000 51
+neutron-proton mass ratio                              1.001 378 418 98      0.000 000 000 51
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 08 e-11         0.000 31 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 61 e-39         0.000 31 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 699 e-27    0.000 000 031 e-27    J T^-1
+nuclear magneton in eV/T                               3.152 451 2550 e-8    0.000 000 0015 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 432 e-2     0.000 000 016 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2690 e-4        0.000 0021 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 285         0.000 000 047         MHz T^-1
+Planck constant                                        6.626 070 040 e-34    0.000 000 081 e-34    J s
+Planck constant in eV s                                4.135 667 662 e-15    0.000 000 025 e-15    eV s
+Planck constant over 2 pi                              1.054 571 800 e-34    0.000 000 013 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 514 e-16    0.000 000 040 e-16    eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9788          0.000 0012            MeV fm
+Planck length                                          1.616 229 e-35        0.000 038 e-35        m
+Planck mass                                            2.176 470 e-8         0.000 051 e-8         kg
+Planck mass energy equivalent in GeV                   1.220 910 e19         0.000 029 e19         GeV
+Planck temperature                                     1.416 808 e32         0.000 033 e32         K
+Planck time                                            5.391 16 e-44         0.000 13 e-44         s
+proton charge to mass quotient                         9.578 833 226 e7      0.000 000 059 e7      C kg^-1
+proton Compton wavelength                              1.321 409 853 96 e-15 0.000 000 000 61 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308910109e-15   0.000 000 000097e-15  m
+proton-electron mass ratio                             1836.152 673 89       0.000 000 17
+proton g factor                                        5.585 694 702         0.000 000 017
+proton gyromag. ratio                                  2.675 221 900 e8      0.000 000 018 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 478 92         0.000 000 29          MHz T^-1
+proton mag. mom.                                       1.410 606 7873 e-26   0.000 000 0097 e-26   J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 2053 e-3    0.000 000 0046 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 3508        0.000 000 0085
+proton mag. shielding correction                       25.691 e-6            0.011 e-6
+proton mass                                            1.672 621 898 e-27    0.000 000 021 e-27    kg
+proton mass energy equivalent                          1.503 277 593 e-10    0.000 000 018 e-10    J
+proton mass energy equivalent in MeV                   938.272 0813          0.000 0058            MeV
+proton mass in u                                       1.007 276 466 879     0.000 000 000 091     u
+proton molar mass                                      1.007 276 466 879 e-3 0.000 000 000 091 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 38          0.000 000 20
+proton-neutron mag. mom. ratio                         -1.459 898 05         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 44      0.000 000 000 51
+proton rms charge radius                               0.8751 e-15           0.0061 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5486 e-4    0.000 000 0017 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 0972 e-4    0.000 000 0033 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 508    0.000 065             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 355 e15 0.000 000 000 019 e15 Hz
+Rydberg constant times hc in eV                        13.605 693 009        0.000 000 084         eV
+Rydberg constant times hc in J                         2.179 872 325 e-18    0.000 000 027 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7084           0.000 0014
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8714           0.000 0014
+second radiation constant                              1.438 777 36 e-2      0.000 000 83 e-2      m K
+shielded helion gyromag. ratio                         2.037 894 585 e8      0.000 000 027 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 099 66         0.000 000 43          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 080 e-26   0.000 000 014 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 720        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 5603       0.000 000 0092
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 171 e8      0.000 000 033 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 385 07         0.000 000 53          MHz T^-1
+shielded proton mag. mom.                              1.410 570 547 e-26    0.000 000 018 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 600         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 367 e-8         0.000 013 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 871 58 e-28 0.000 000 000 91 e-28 m^2
+triton-electron mass ratio                             5496.921 535 88       0.000 000 26
+triton g factor                                        5.957 924 920         0.000 000 028
+triton mag. mom.                                       1.504 609 503 e-26    0.000 000 012 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 6616 e-3    0.000 000 0076 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 460         0.000 000 014
+triton mass                                            5.007 356 665 e-27    0.000 000 062 e-27    kg
+triton mass energy equivalent                          4.500 387 735 e-10    0.000 000 055 e-10    J
+triton mass energy equivalent in MeV                   2808.921 112          0.000 017             MeV
+triton mass in u                                       3.015 500 716 32      0.000 000 000 11      u
+triton molar mass                                      3.015 500 716 32 e-3  0.000 000 000 11 e-3  kg mol^-1
+triton-proton mass ratio                               2.993 717 033 48      0.000 000 000 22
+unified atomic mass unit                               1.660 539 040 e-27    0.000 000 020 e-27    kg
+von Klitzing constant                                  25 812.807 4555       0.000 0059            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9238 e10        0.000 0034 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7729 e-3        0.000 0017 e-3        m K"""
+
+
+exact2014 = exact2010
+
+
+txt2018 = """\
+alpha particle-electron mass ratio                          7294.299 541 42          0.000 000 24
+alpha particle mass                                         6.644 657 3357 e-27      0.000 000 0020 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1914 e-10      0.000 000 0018 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4066            0.000 0011               MeV
+alpha particle mass in u                                    4.001 506 179 127        0.000 000 000 063        u
+alpha particle molar mass                                   4.001 506 1777 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 09         0.000 000 000 22
+alpha particle relative atomic mass                         4.001 506 179 127        0.000 000 000 063
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 102 42           0.000 000 28             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0242 e8        0.000 000 0028 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6874 e7        0.000 000 0010 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 718 71 e23     0.000 000 000 68 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6104 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 019 16 e13     0.000 000 000 33 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 3061 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9905 e-65      0.000 000 0038 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 384 57 e12     0.000 000 000 49 e12     C m^-3
+atomic unit of current                                      6.623 618 237 510 e-3    0.000 000 000 013 e-3    A
+atomic unit of electric dipole mom.                         8.478 353 6255 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 747 63 e11     0.000 000 000 78 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4292 e21       0.000 000 0029 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 274 36 e-41    0.000 000 000 50 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 988       0.000 000 000 053        V
+atomic unit of electric quadrupole mom.                     4.486 551 5246 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+atomic unit of force                                        8.238 723 4983 e-8       0.000 000 0012 e-8       N
+atomic unit of length                                       5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 015 66 e-23    0.000 000 000 56 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 567 58 e5      0.000 000 000 71 e5      T
+atomic unit of magnetizability                              7.891 036 6008 e-29      0.000 000 0048 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 914 10 e-24    0.000 000 000 30 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 055 45 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5857 e-17  0.000 000 000 0047 e-17  s
+atomic unit of velocity                                     2.187 691 263 64 e6      0.000 000 000 33 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0783 e-24      0.000 000 0028 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 8060 e-5       0.000 000 0017 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 493 61 e10     0.000 000 000 42 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 783           0.000 000 014            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 815 63         0.000 000 000 20         K T^-1
+Bohr radius                                                 5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 668          0.000 000 057            ohm
+classical electron radius                                   2.817 940 3262 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 238 67 e-12    0.000 000 000 73 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Cu x unit                                                   1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 551 e-4       0.000 000 012 e-4
+deuteron-electron mass ratio                                3670.482 967 88          0.000 000 13
+deuteron g factor                                           0.857 438 2338           0.000 000 0022
+deuteron mag. mom.                                          4.330 735 094 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 570 e-4        0.000 000 012 e-4
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2338           0.000 000 0022
+deuteron mass                                               3.343 583 7724 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 231 02 e-10    0.000 000 000 91 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 942 57          0.000 000 57             MeV
+deuteron mass in u                                          2.013 553 212 745        0.000 000 000 040        u
+deuteron molar mass                                         2.013 553 212 05 e-3     0.000 000 000 61 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 53            0.000 000 11
+deuteron-proton mag. mom. ratio                             0.307 012 209 39         0.000 000 000 79
+deuteron-proton mass ratio                                  1.999 007 501 39         0.000 000 000 11
+deuteron relative atomic mass                               2.013 553 212 745        0.000 000 000 040
+deuteron rms charge radius                                  2.127 99 e-15            0.000 74 e-15            m
+electron charge to mass quotient                            -1.758 820 010 76 e11    0.000 000 000 53 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4915           0.000 0056
+electron-deuteron mass ratio                                2.724 437 107 462 e-4    0.000 000 000 096 e-4
+electron g factor                                           -2.002 319 304 362 56    0.000 000 000 000 35
+electron gyromag. ratio                                     1.760 859 630 23 e11     0.000 000 000 53 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 4242          0.000 0085               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 573 e-4    0.000 000 000 079 e-4
+electron mag. mom.                                          -9.284 764 7043 e-24     0.000 000 0028 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 181 28 e-3     0.000 000 000 18 e-3
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 181 28    0.000 000 000 000 18
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 88         0.000 000 11
+electron mass                                               9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7769 e-14      0.000 000 0025 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 00         0.000 000 000 15         MeV
+electron mass in u                                          5.485 799 090 65 e-4     0.000 000 000 16 e-4     u
+electron molar mass                                         5.485 799 0888 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9883             0.000 0046
+electron-muon mass ratio                                    4.836 331 69 e-3         0.000 000 11 e-3
+electron-neutron mag. mom. ratio                            960.920 50               0.000 23
+electron-neutron mass ratio                                 5.438 673 4424 e-4       0.000 000 0026 e-4
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 20
+electron-proton mass ratio                                  5.446 170 214 87 e-4     0.000 000 000 33 e-4
+electron relative atomic mass                               5.485 799 090 65 e-4     0.000 000 000 16 e-4
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4
+electron to alpha particle mass ratio                       1.370 933 554 787 e-4    0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio                 864.058 257              0.000 010
+electron to shielded proton mag. mom. ratio                 -658.227 5971            0.000 0072
+electron-triton mass ratio                                  1.819 200 062 251 e-4    0.000 000 000 090 e-4
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 102 33 e-9     0.000 000 000 32 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5655 e-2   0.000 000 000 0071 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5693 e-3       0.000 000 0011 e-3
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 322 05 e-8     0.000 000 000 88 e-8     u
+hartree-electron volt relationship                          27.211 386 245 988       0.000 000 000 053        eV
+Hartree energy                                              4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+Hartree energy in eV                                        27.211 386 245 988       0.000 000 000 053        eV
+hartree-hertz relationship                                  6.579 683 920 502 e15    0.000 000 000 013 e15    Hz
+hartree-inverse meter relationship                          2.194 746 313 6320 e7    0.000 000 000 0043 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0407 e5    0.000 000 000 0061 e5    K
+hartree-kilogram relationship                               4.850 870 209 5432 e-35  0.000 000 000 0094 e-35  kg
+helion-electron mass ratio                                  5495.885 280 07          0.000 000 24
+helion g factor                                             -4.255 250 615           0.000 000 050
+helion mag. mom.                                            -1.074 617 532 e-26      0.000 000 013 e-26       J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 958 e-3       0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 307           0.000 000 025
+helion mass                                                 5.006 412 7796 e-27      0.000 000 0015 e-27      kg
+helion mass energy equivalent                               4.499 539 4125 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 607 43          0.000 000 85             MeV
+helion mass in u                                            3.014 932 247 175        0.000 000 000 097        u
+helion molar mass                                           3.014 932 246 13 e-3     0.000 000 000 91 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 67         0.000 000 000 13
+helion relative atomic mass                                 3.014 932 247 175        0.000 000 000 097
+helion shielding shift                                      5.996 743 e-5            0.000 010 e-5
+hertz-atomic mass unit relationship                         4.439 821 6652 e-24      0.000 000 0013 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0570 e-16  0.000 000 000 0029 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 084          0.000 000 021
+inverse meter-atomic mass unit relationship                 1.331 025 050 10 e-15    0.000 000 000 40 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9120 e-8   0.000 000 000 0088 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2565 e9        0.000 000 0020 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3963 e17   0.000 000 000 0045 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 3014 e-14      0.000 000 0028 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4556 e-6   0.000 000 000 0061 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7621 e26       0.000 000 0018 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7409 e34   0.000 000 000 0040 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         0.999 999 999 65 e-3     0.000 000 000 30 e-3     kg mol^-1
+molar mass of carbon-12                                     11.999 999 9958 e-3      0.000 000 0036 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Mo x unit                                                   1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2830             0.000 0046
+muon g factor                                               -2.002 331 8418          0.000 000 0013
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 89 e-3         0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 47 e-3        0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 03            0.000 000 20
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9259           0.000 000 0025           u
+muon molar mass                                             1.134 289 259 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5170           0.000 000 0025
+muon-proton mag. mom. ratio                                 -3.183 345 142           0.000 000 071
+muon-proton mass ratio                                      0.112 609 5264           0.000 000 0025
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7769 e-14      0.000 000 0025 e-14      J
+natural unit of energy in MeV                               0.510 998 950 00         0.000 000 000 15         MeV
+natural unit of length                                      3.861 592 6796 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 530 75 e-22    0.000 000 000 82 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 00         0.000 000 000 15         MeV/c
+natural unit of time                                        1.288 088 668 19 e-21    0.000 000 000 39 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 905 81 e-15    0.000 000 000 75 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 82 e-3         0.000 000 25 e-3
+neutron-electron mass ratio                                 1838.683 661 73          0.000 000 89
+neutron g factor                                            -3.826 085 45            0.000 000 90
+neutron gyromag. ratio                                      1.832 471 71 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6931              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3651 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 63 e-3        0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 73            0.000 000 45
+neutron mass                                                1.674 927 498 04 e-27    0.000 000 000 95 e-27    kg
+neutron mass energy equivalent                              1.505 349 762 87 e-10    0.000 000 000 86 e-10    J
+neutron mass energy equivalent in MeV                       939.565 420 52           0.000 000 54             MeV
+neutron mass in u                                           1.008 664 915 95         0.000 000 000 49         u
+neutron molar mass                                          1.008 664 915 60 e-3     0.000 000 000 57 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 06             0.000 000 20
+neutron-proton mag. mom. ratio                              -0.684 979 34            0.000 000 16
+neutron-proton mass difference                              2.305 574 35 e-30        0.000 000 82 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 146 89 e-13        0.000 000 74 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 36             0.000 000 46             MeV
+neutron-proton mass difference in u                         1.388 449 33 e-3         0.000 000 49 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 31         0.000 000 000 49
+neutron relative atomic mass                                1.008 664 915 95         0.000 000 000 49
+neutron-tau mass ratio                                      0.528 779                0.000 036
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7461 e-27      0.000 000 0015 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 258 44 e-8     0.000 000 000 96 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 413 53 e-2     0.000 000 000 78 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7756 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2291           0.000 000 0023           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1560 e7        0.000 000 0029 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 855 39 e-15    0.000 000 000 40 e-15    m
+proton-electron mass ratio                                  1836.152 673 43          0.000 000 11
+proton g factor                                             5.585 694 6893           0.000 000 0016
+proton gyromag. ratio                                       2.675 221 8744 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 518           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 797 36 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 46 e-3
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82
+proton mag. shielding correction                            2.5689 e-5               0.0011 e-5
+proton mass                                                 1.672 621 923 69 e-27    0.000 000 000 51 e-27    kg
+proton mass energy equivalent                               1.503 277 615 98 e-10    0.000 000 000 46 e-10    J
+proton mass energy equivalent in MeV                        938.272 088 16           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 621        0.000 000 000 053        u
+proton molar mass                                           1.007 276 466 27 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 37             0.000 000 20
+proton-neutron mag. mom. ratio                              -1.459 898 05            0.000 000 34
+proton-neutron mass ratio                                   0.998 623 478 12         0.000 000 000 49
+proton relative atomic mass                                 1.007 276 466 621        0.000 000 000 053
+proton rms charge radius                                    8.414 e-16               0.019 e-16               m
+proton-tau mass ratio                                       0.528 051                0.000 036
+quantum of circulation                                      3.636 947 5516 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 1032 e-4       0.000 000 0022 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6796 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1552 e-16      0.000 000 0012 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 103 36 e-16    0.000 000 000 64 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 160       0.000 021                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2508 e15   0.000 000 000 0064 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 994       0.000 000 000 026        eV
+Rydberg constant times hc in J                              2.179 872 361 1035 e-18  0.000 000 000 0042 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 537 06        0.000 000 000 45
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 523 58        0.000 000 000 45
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 569 e8         0.000 000 024 e8         s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 099 42            0.000 000 38             MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 090 e-26      0.000 000 013 e-26       J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 471 e-3       0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 719           0.000 000 025
+shielded helion to proton mag. mom. ratio                   -0.761 766 5618          0.000 000 0089
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1313          0.000 000 0033
+shielded proton gyromag. ratio                              2.675 153 151 e8         0.000 000 029 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 384 74            0.000 000 46             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 560 e-26       0.000 000 015 e-26       J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 128 e-3        0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 599            0.000 000 030
+shielding difference of d and p in HD                       2.0200 e-8               0.0020 e-8
+shielding difference of t and p in HT                       2.4140 e-8               0.0020 e-8
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011
+tau-neutron mass ratio                                      1.891 15                 0.000 13
+tau-proton mass ratio                                       1.893 76                 0.000 13
+Thomson cross section                                       6.652 458 7321 e-29      0.000 000 0060 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 73          0.000 000 27
+triton g factor                                             5.957 924 931            0.000 000 012
+triton mag. mom.                                            1.504 609 5202 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6651 e-3       0.000 000 0032 e-3
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4656           0.000 000 0059
+triton mass                                                 5.007 356 7446 e-27      0.000 000 0015 e-27      kg
+triton mass energy equivalent                               4.500 387 8060 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 132 98          0.000 000 85             MeV
+triton mass in u                                            3.015 500 716 21         0.000 000 000 12         u
+triton molar mass                                           3.015 500 715 17 e-3     0.000 000 000 92 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 14         0.000 000 000 15
+triton relative atomic mass                                 3.015 500 716 21         0.000 000 000 12
+triton to proton mag. mom. ratio                            1.066 639 9191           0.000 000 0021
+unified atomic mass unit                                    1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+vacuum electric permittivity                                8.854 187 8128 e-12      0.000 000 0013 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 062 12 e-6     0.000 000 000 19 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.222 90                 0.000 30
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 53                 0.000 17                   """
+
+
+def exact2018(exact):
+    # SI base constants
+    c = exact['speed of light in vacuum']
+    h = exact['Planck constant']
+    e = exact['elementary charge']
+    k = exact['Boltzmann constant']
+    N_A = exact['Avogadro constant']
+
+    # Other useful constants
+    R = N_A * k
+    hbar = h / (2*math.pi)
+    G_0 = 2 * e**2 / h
+
+    # Wien law numerical constants: https://en.wikipedia.org/wiki/Wien%27s_displacement_law
+    # (alpha - 3)*exp(alpha) + 3 = 0
+    # (x - 5)*exp(x) + 5 = 0
+    alpha_W = 2.821439372122078893403  # 3 + lambertw(-3 * exp(-3))
+    x_W = 4.965114231744276303699  # 5 + lambertw(-5 * exp(-5))
+
+    # Conventional electrical unit
+    # See https://en.wikipedia.org/wiki/Conventional_electrical_unit
+    K_J90 = exact['conventional value of Josephson constant']
+    K_J = 2 * e / h
+    R_K90 = exact['conventional value of von Klitzing constant']
+    R_K = h / e**2
+    V_90 = K_J90 / K_J
+    ohm_90 = R_K / R_K90
+    A_90 = V_90 / ohm_90
+
+    replace = {
+        'atomic unit of action': hbar,
+        'Boltzmann constant in eV/K': k / e,
+        'Boltzmann constant in Hz/K': k / h,
+        'Boltzmann constant in inverse meter per kelvin': k / (h * c),
+        'conductance quantum': G_0,
+        'conventional value of ampere-90': A_90,
+        'conventional value of coulomb-90': A_90,
+        'conventional value of farad-90': 1 / ohm_90,
+        'conventional value of henry-90': ohm_90,
+        'conventional value of ohm-90': ohm_90,
+        'conventional value of volt-90': V_90,
+        'conventional value of watt-90': V_90**2 / ohm_90,
+        'electron volt-hertz relationship': e / h,
+        'electron volt-inverse meter relationship': e / (h * c),
+        'electron volt-kelvin relationship': e / k,
+        'electron volt-kilogram relationship': e / c**2,
+        'elementary charge over h-bar': e / hbar,
+        'Faraday constant': e * N_A,
+        'first radiation constant': 2 * math.pi * h * c**2,
+        'first radiation constant for spectral radiance': 2 * h * c**2,
+        'hertz-electron volt relationship': h / e,
+        'hertz-inverse meter relationship': 1 / c,
+        'hertz-kelvin relationship': h / k,
+        'hertz-kilogram relationship': h / c**2,
+        'inverse meter-electron volt relationship': (h * c) / e,
+        'inverse meter-joule relationship': h * c,
+        'inverse meter-kelvin relationship': h * c / k,
+        'inverse meter-kilogram relationship': h / c,
+        'inverse of conductance quantum': 1 / G_0,
+        'Josephson constant': K_J,
+        'joule-electron volt relationship': 1 / e,
+        'joule-hertz relationship': 1 / h,
+        'joule-inverse meter relationship': 1 / (h * c),
+        'joule-kelvin relationship': 1 / k,
+        'joule-kilogram relationship': 1 / c**2,
+        'kelvin-electron volt relationship': k / e,
+        'kelvin-hertz relationship': k / h,
+        'kelvin-inverse meter relationship': k / (h * c),
+        'kelvin-kilogram relationship': k / c**2,
+        'kilogram-electron volt relationship': c**2 / e,
+        'kilogram-hertz relationship': c**2 / h,
+        'kilogram-inverse meter relationship': c / h,
+        'kilogram-joule relationship': c**2,
+        'kilogram-kelvin relationship': c**2 / k,
+        'Loschmidt constant (273.15 K, 100 kPa)': 100e3 / 273.15 / k,
+        'Loschmidt constant (273.15 K, 101.325 kPa)': 101.325e3 / 273.15 / k,
+        'mag. flux quantum': h / (2 * e),
+        'molar gas constant': R,
+        'molar Planck constant': h * N_A,
+        'molar volume of ideal gas (273.15 K, 100 kPa)': R * 273.15 / 100e3,
+        'molar volume of ideal gas (273.15 K, 101.325 kPa)': R * 273.15 / 101.325e3,
+        'natural unit of action': hbar,
+        'natural unit of action in eV s': hbar / e,
+        'Planck constant in eV/Hz': h / e,
+        'reduced Planck constant': hbar,
+        'reduced Planck constant in eV s': hbar / e,
+        'reduced Planck constant times c in MeV fm': hbar * c / (e * 1e6 * 1e-15),
+        'second radiation constant': h * c / k,
+        'Stefan-Boltzmann constant': 2 * math.pi**5 * k**4 / (15 * h**3 * c**2),
+        'von Klitzing constant': R_K,
+        'Wien frequency displacement law constant': alpha_W * k / h,
+        'Wien wavelength displacement law constant': h * c / (x_W * k),
+    }
+    return replace
+
+
+txt2022 = """\
+alpha particle-electron mass ratio                          7294.299 541 71          0.000 000 17             
+alpha particle mass                                         6.644 657 3450 e-27      0.000 000 0021 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1997 e-10      0.000 000 0019 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4118            0.000 0012               MeV
+alpha particle mass in u                                    4.001 506 179 129        0.000 000 000 062        u
+alpha particle molar mass                                   4.001 506 1833 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 252        0.000 000 000 070        
+alpha particle relative atomic mass                         4.001 506 179 129        0.000 000 000 062        
+alpha particle rms charge radius                            1.6785 e-15              0.0021 e-15              m
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 103 72           0.000 000 29             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0372 e8        0.000 000 0029 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6922 e7        0.000 000 0011 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 721 85 e23     0.000 000 000 70 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6209 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 020 67 e13     0.000 000 000 34 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 2996 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9735 e-65      0.000 000 0039 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 386 77 e12     0.000 000 000 51 e12     C m^-3
+atomic unit of current                                      6.623 618 237 5082 e-3   0.000 000 000 0072 e-3   A
+atomic unit of electric dipole mom.                         8.478 353 6198 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 751 12 e11     0.000 000 000 80 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4424 e21       0.000 000 0030 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 272 12 e-41    0.000 000 000 51 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 981       0.000 000 000 030        V
+atomic unit of electric quadrupole mom.                     4.486 551 5185 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+atomic unit of force                                        8.238 723 5038 e-8       0.000 000 0013 e-8       N
+atomic unit of length                                       5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 013 15 e-23    0.000 000 000 58 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 570 77 e5      0.000 000 000 73 e5      T
+atomic unit of magnetizability                              7.891 036 5794 e-29      0.000 000 0049 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 915 45 e-24    0.000 000 000 31 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 056 20 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5864 e-17  0.000 000 000 0026 e-17  s
+atomic unit of velocity                                     2.187 691 262 16 e6      0.000 000 000 34 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0657 e-24      0.000 000 0029 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 7982 e-5       0.000 000 0018 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 491 71 e10     0.000 000 000 44 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 719           0.000 000 015            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 814 72         0.000 000 000 21         K T^-1
+Bohr radius                                                 5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 412          0.000 000 059            ohm
+classical electron radius                                   2.817 940 3205 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 235 38 e-12    0.000 000 000 76 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Copper x unit                                               1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 550 e-4       0.000 000 012 e-4        
+deuteron-electron mass ratio                                3670.482 967 655         0.000 000 063            
+deuteron g factor                                           0.857 438 2335           0.000 000 0022           
+deuteron mag. mom.                                          4.330 735 087 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 568 e-4        0.000 000 012 e-4        
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2335           0.000 000 0022           
+deuteron mass                                               3.343 583 7768 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 234 91 e-10    0.000 000 000 94 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 945 00          0.000 000 58             MeV
+deuteron mass in u                                          2.013 553 212 544        0.000 000 000 015        u
+deuteron molar mass                                         2.013 553 214 66 e-3     0.000 000 000 63 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 52            0.000 000 11             
+deuteron-proton mag. mom. ratio                             0.307 012 209 30         0.000 000 000 79         
+deuteron-proton mass ratio                                  1.999 007 501 2699       0.000 000 000 0084       
+deuteron relative atomic mass                               2.013 553 212 544        0.000 000 000 015        
+deuteron rms charge radius                                  2.127 78 e-15            0.000 27 e-15            m
+electron charge to mass quotient                            -1.758 820 008 38 e11    0.000 000 000 55 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4921           0.000 0056               
+electron-deuteron mass ratio                                2.724 437 107 629 e-4    0.000 000 000 047 e-4    
+electron g factor                                           -2.002 319 304 360 92    0.000 000 000 000 36     
+electron gyromag. ratio                                     1.760 859 627 84 e11     0.000 000 000 55 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 3861          0.000 0087               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 649 e-4    0.000 000 000 053 e-4    
+electron mag. mom.                                          -9.284 764 6917 e-24     0.000 000 0029 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 180 46 e-3     0.000 000 000 18 e-3     
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 180 46    0.000 000 000 000 18     
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 877        0.000 000 032            
+electron mass                                               9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7880 e-14      0.000 000 0026 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 69         0.000 000 000 16         MeV
+electron mass in u                                          5.485 799 090 441 e-4    0.000 000 000 097 e-4    u
+electron molar mass                                         5.485 799 0962 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9881             0.000 0046               
+electron-muon mass ratio                                    4.836 331 70 e-3         0.000 000 11 e-3         
+electron-neutron mag. mom. ratio                            960.920 48               0.000 23                 
+electron-neutron mass ratio                                 5.438 673 4416 e-4       0.000 000 0022 e-4       
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 19             
+electron-proton mass ratio                                  5.446 170 214 889 e-4    0.000 000 000 094 e-4    
+electron relative atomic mass                               5.485 799 090 441 e-4    0.000 000 000 097 e-4    
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4             
+electron to alpha particle mass ratio                       1.370 933 554 733 e-4    0.000 000 000 032 e-4    
+electron to shielded helion mag. mom. ratio                 864.058 239 86           0.000 000 70             
+electron to shielded proton mag. mom. ratio                 -658.227 5856            0.000 0027               
+electron-triton mass ratio                                  1.819 200 062 327 e-4    0.000 000 000 068 e-4    
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 100 83 e-9     0.000 000 000 33 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5665 e-2   0.000 000 000 0040 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5643 e-3       0.000 000 0011 e-3       
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 317 97 e-8     0.000 000 000 91 e-8     u
+hartree-electron volt relationship                          27.211 386 245 981       0.000 000 000 030        eV
+Hartree energy                                              4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+Hartree energy in eV                                        27.211 386 245 981       0.000 000 000 030        eV
+hartree-hertz relationship                                  6.579 683 920 4999 e15   0.000 000 000 0072 e15   Hz
+hartree-inverse meter relationship                          2.194 746 313 6314 e7    0.000 000 000 0024 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0398 e5    0.000 000 000 0034 e5    K
+hartree-kilogram relationship                               4.850 870 209 5419 e-35  0.000 000 000 0053 e-35  kg
+helion-electron mass ratio                                  5495.885 279 84          0.000 000 16             
+helion g factor                                             -4.255 250 6995          0.000 000 0034           
+helion mag. mom.                                            -1.074 617 551 98 e-26   0.000 000 000 93 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 980 83 e-3    0.000 000 000 94 e-3     
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 3498          0.000 000 0017           
+helion mass                                                 5.006 412 7862 e-27      0.000 000 0016 e-27      kg
+helion mass energy equivalent                               4.499 539 4185 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 611 12          0.000 000 88             MeV
+helion mass in u                                            3.014 932 246 932        0.000 000 000 074        u
+helion molar mass                                           3.014 932 250 10 e-3     0.000 000 000 94 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 552        0.000 000 000 070        
+helion relative atomic mass                                 3.014 932 246 932        0.000 000 000 074        
+helion shielding shift                                      5.996 7029 e-5           0.000 0023 e-5           
+hertz-atomic mass unit relationship                         4.439 821 6590 e-24      0.000 000 0014 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0574 e-16  0.000 000 000 0017 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 177          0.000 000 021            
+inverse meter-atomic mass unit relationship                 1.331 025 048 24 e-15    0.000 000 000 41 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9132 e-8   0.000 000 000 0050 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2471 e9        0.000 000 0021 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3969 e17   0.000 000 000 0025 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 2884 e-14      0.000 000 0029 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4564 e-6   0.000 000 000 0035 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7537 e26       0.000 000 0019 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7415 e34   0.000 000 000 0022 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         1.000 000 001 05 e-3     0.000 000 000 31 e-3     kg mol^-1
+molar mass of carbon-12                                     12.000 000 0126 e-3      0.000 000 0037 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Molybdenum x unit                                           1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2827             0.000 0046               
+muon g factor                                               -2.002 331 841 23        0.000 000 000 82         
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 62 e-3         0.000 000 41 e-3         
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 48 e-3        0.000 000 11 e-3         
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 04            0.000 000 20             
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9257           0.000 000 0025           u
+muon molar mass                                             1.134 289 258 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5168           0.000 000 0025           
+muon-proton mag. mom. ratio                                 -3.183 345 146           0.000 000 071            
+muon-proton mass ratio                                      0.112 609 5262           0.000 000 0025           
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2             
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7880 e-14      0.000 000 0026 e-14      J
+natural unit of energy in MeV                               0.510 998 950 69         0.000 000 000 16         MeV
+natural unit of length                                      3.861 592 6744 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 534 46 e-22    0.000 000 000 85 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 69         0.000 000 000 16         MeV/c
+natural unit of time                                        1.288 088 666 44 e-21    0.000 000 000 40 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 903 82 e-15    0.000 000 000 67 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 84 e-3         0.000 000 24 e-3         
+neutron-electron mass ratio                                 1838.683 662 00          0.000 000 74             
+neutron g factor                                            -3.826 085 52            0.000 000 90             
+neutron gyromag. ratio                                      1.832 471 74 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6935              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3653 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 65 e-3        0.000 000 25 e-3         
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 76            0.000 000 45             
+neutron mass                                                1.674 927 500 56 e-27    0.000 000 000 85 e-27    kg
+neutron mass energy equivalent                              1.505 349 765 14 e-10    0.000 000 000 76 e-10    J
+neutron mass energy equivalent in MeV                       939.565 421 94           0.000 000 48             MeV
+neutron mass in u                                           1.008 664 916 06         0.000 000 000 40         u
+neutron molar mass                                          1.008 664 917 12 e-3     0.000 000 000 51 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 08             0.000 000 20             
+neutron-proton mag. mom. ratio                              -0.684 979 35            0.000 000 16             
+neutron-proton mass difference                              2.305 574 61 e-30        0.000 000 67 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 147 12 e-13        0.000 000 60 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 51             0.000 000 38             MeV
+neutron-proton mass difference in u                         1.388 449 48 e-3         0.000 000 40 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 46         0.000 000 000 40         
+neutron relative atomic mass                                1.008 664 916 06         0.000 000 000 40         
+neutron-tau mass ratio                                      0.528 779                0.000 036                
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16             
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7393 e-27      0.000 000 0016 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 254 17 e-8     0.000 000 000 98 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 410 09 e-2     0.000 000 000 79 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7706 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2188           0.000 000 0024           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1430 e7        0.000 000 0030 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 853 60 e-15    0.000 000 000 41 e-15    m
+proton-electron mass ratio                                  1836.152 673 426         0.000 000 032            
+proton g factor                                             5.585 694 6893           0.000 000 0016           
+proton gyromag. ratio                                       2.675 221 8708 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 461           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 795 45 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 45 e-3     
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82         
+proton mag. shielding correction                            2.567 15 e-5             0.000 41 e-5             
+proton mass                                                 1.672 621 925 95 e-27    0.000 000 000 52 e-27    kg
+proton mass energy equivalent                               1.503 277 618 02 e-10    0.000 000 000 47 e-10    J
+proton mass energy equivalent in MeV                        938.272 089 43           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 5789       0.000 000 000 0083       u
+proton molar mass                                           1.007 276 467 64 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 38             0.000 000 20             
+proton-neutron mag. mom. ratio                              -1.459 898 02            0.000 000 34             
+proton-neutron mass ratio                                   0.998 623 477 97         0.000 000 000 40         
+proton relative atomic mass                                 1.007 276 466 5789       0.000 000 000 0083       
+proton rms charge radius                                    8.4075 e-16              0.0064 e-16              m
+proton-tau mass ratio                                       0.528 051                0.000 036                
+quantum of circulation                                      3.636 947 5467 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 0934 e-4       0.000 000 0023 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6744 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1520 e-16      0.000 000 0011 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 100 51 e-16    0.000 000 000 66 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 157       0.000 012                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2500 e15   0.000 000 000 0036 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 990       0.000 000 000 015        eV
+Rydberg constant times hc in J                              2.179 872 361 1030 e-18  0.000 000 000 0024 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 534 96        0.000 000 000 47         
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 521 49        0.000 000 000 47         
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 6078 e8        0.000 000 0018 e8        s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 100 033           0.000 000 028            MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 110 35 e-26   0.000 000 000 93 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 494 57 e-3    0.000 000 000 94 e-3     
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 7624          0.000 000 0017           
+shielded helion to proton mag. mom. ratio                   -0.761 766 577 21        0.000 000 000 66         
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1334          0.000 000 0031           
+shielded proton gyromag. ratio                              2.675 153 194 e8         0.000 000 011 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 385 43            0.000 000 17             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 5830 e-26      0.000 000 0058 e-26      J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 1551 e-3       0.000 000 0062 e-3       
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 648            0.000 000 011            
+shielding difference of d and p in HD                       1.987 70 e-8             0.000 10 e-8             
+shielding difference of t and p in HT                       2.394 50 e-8             0.000 20 e-8             
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23                     
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011                   
+tau-neutron mass ratio                                      1.891 15                 0.000 13                 
+tau-proton mass ratio                                       1.893 76                 0.000 13                 
+Thomson cross section                                       6.652 458 7051 e-29      0.000 000 0062 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 51          0.000 000 21             
+triton g factor                                             5.957 924 930            0.000 000 012            
+triton mag. mom.                                            1.504 609 5178 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6648 e-3       0.000 000 0032 e-3       
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4650           0.000 000 0059           
+triton mass                                                 5.007 356 7512 e-27      0.000 000 0016 e-27      kg
+triton mass energy equivalent                               4.500 387 8119 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 136 68          0.000 000 88             MeV
+triton mass in u                                            3.015 500 715 97         0.000 000 000 10         u
+triton molar mass                                           3.015 500 719 13 e-3     0.000 000 000 94 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 03         0.000 000 000 10         
+triton relative atomic mass                                 3.015 500 715 97         0.000 000 000 10         
+triton to proton mag. mom. ratio                            1.066 639 9189           0.000 000 0021           
+unified atomic mass unit                                    1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+vacuum electric permittivity                                8.854 187 8188 e-12      0.000 000 0014 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 061 27 e-6     0.000 000 000 20 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.223 05                 0.000 23                 
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 45                 0.000 13                    """
+
+
+exact2022 = exact2018
+
+
+# -----------------------------------------------------------------------------
+
+
+def parse_constants_2002to2014(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:55].rstrip()
+        val = float(line[55:77].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[55:77]
+        is_exact = '(exact)' in line[77:99]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[77:99].replace(' ', '').replace('(exact)', '0'))
+        units = line[99:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def parse_constants_2018toXXXX(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:60].rstrip()
+        val = float(line[60:85].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[60:85]
+        is_exact = '(exact)' in line[85:110]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[85:110].replace(' ', '').replace('(exact)', '0'))
+        units = line[110:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def replace_exact(d, to_replace, exact):
+    for name in to_replace:
+        assert name in exact, f'Missing exact value: {name}'
+        assert abs(exact[name]/d[name][0] - 1) <= 1e-9, \
+            f'Bad exact value: {name}: { exact[name]}, {d[name][0]}'
+        d[name] = (exact[name],) + d[name][1:]
+    assert set(exact.keys()) == set(to_replace)
+
+
+_physical_constants_2002 = parse_constants_2002to2014(txt2002, exact2002)
+_physical_constants_2006 = parse_constants_2002to2014(txt2006, exact2006)
+_physical_constants_2010 = parse_constants_2002to2014(txt2010, exact2010)
+_physical_constants_2014 = parse_constants_2002to2014(txt2014, exact2014)
+_physical_constants_2018 = parse_constants_2018toXXXX(txt2018, exact2018)
+_physical_constants_2022 = parse_constants_2018toXXXX(txt2022, exact2022)
+
+physical_constants: dict[str, tuple[float, str, float]] = {}
+physical_constants.update(_physical_constants_2002)
+physical_constants.update(_physical_constants_2006)
+physical_constants.update(_physical_constants_2010)
+physical_constants.update(_physical_constants_2014)
+physical_constants.update(_physical_constants_2018)
+physical_constants.update(_physical_constants_2022)
+_current_constants = _physical_constants_2022
+_current_codata = "CODATA 2022"
+
+# check obsolete values
+_obsolete_constants = {}
+for k in physical_constants:
+    if k not in _current_constants:
+        _obsolete_constants[k] = True
+
+# generate some additional aliases
+_aliases = {}
+for k in _physical_constants_2002:
+    if 'magn.' in k:
+        _aliases[k] = k.replace('magn.', 'mag.')
+for k in _physical_constants_2006:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2018:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2022:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')        
+
+# CODATA 2018 and 2022: renamed and no longer exact; use as aliases
+_aliases['mag. constant'] = 'vacuum mag. permeability'
+_aliases['electric constant'] = 'vacuum electric permittivity'
+
+
+_extra_alias_keys = ['natural unit of velocity',
+                     'natural unit of action',
+                     'natural unit of action in eV s',
+                     'natural unit of mass',
+                     'natural unit of energy',
+                     'natural unit of energy in MeV',
+                     'natural unit of mom.um',
+                     'natural unit of mom.um in MeV/c',
+                     'natural unit of length',
+                     'natural unit of time']
+
+# finally, insert aliases for values
+for k, v in list(_aliases.items()):
+    if v in _current_constants or v in _extra_alias_keys:
+        physical_constants[k] = physical_constants[v]
+    else:
+        del _aliases[k]
+
+
+class ConstantWarning(DeprecationWarning):
+    """Accessing a constant no longer in current CODATA data set"""
+    pass
+
+
+def _check_obsolete(key: str) -> None:
+    if key in _obsolete_constants and key not in _aliases:
+        warnings.warn(f"Constant '{key}' is not in current {_current_codata} data set",
+                      ConstantWarning, stacklevel=3)
+
+
+@xp_capabilities(out_of_scope=True)
+def value(key: str) -> float:
+    """
+    Value in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : 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]
+
+
+@xp_capabilities(out_of_scope=True)
+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]
+
+
+@xp_capabilities(out_of_scope=True)
+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]
+
+
+@xp_capabilities(out_of_scope=True)
+def find(sub: str | None = None, disp: bool = False) -> Any:
+    """
+    Return list of physical_constant keys containing a given string.
+
+    Parameters
+    ----------
+    sub : str
+        Sub-string to search keys for. By default, return all keys.
+    disp : bool
+        If True, print the keys that are found and return None.
+        Otherwise, return the list of keys without printing anything.
+
+    Returns
+    -------
+    keys : list or None
+        If `disp` is False, the list of keys is returned.
+        Otherwise, None is returned.
+
+    Examples
+    --------
+    >>> from scipy.constants import find, physical_constants
+
+    Which keys in the ``physical_constants`` dictionary contain 'boltzmann'?
+
+    >>> find('boltzmann')
+    ['Boltzmann constant',
+     'Boltzmann constant in Hz/K',
+     'Boltzmann constant in eV/K',
+     'Boltzmann constant in inverse meter per kelvin',
+     'Stefan-Boltzmann constant']
+
+    Get the constant called 'Boltzmann constant in Hz/K':
+
+    >>> physical_constants['Boltzmann constant in Hz/K']
+    (20836619120.0, 'Hz K^-1', 0.0)
+
+    Find constants with 'radius' in the key:
+
+    >>> find('radius')
+    ['Bohr radius',
+     'alpha particle rms charge radius',
+     'classical electron radius',
+     'deuteron rms charge radius',
+     'proton rms charge radius']
+    >>> physical_constants['classical electron radius']
+    (2.8179403262e-15, 'm', 1.3e-24)
+
+    """
+    if sub is None:
+        result = list(_current_constants.keys())
+    else:
+        result = [key for key in _current_constants
+                  if sub.lower() in key.lower()]
+
+    result.sort()
+    if disp:
+        for key in result:
+            print(key)
+        return
+    else:
+        return result
+
+# This is not used here, but it must be defined to pass
+# scipy/_lib/tests/test_public_api.py::test_private_but_present_deprecation
+c = value('speed of light in vacuum')
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/_constants.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..474138f61fafb1a855e4f9b2f01e98df01deea8a
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/_constants.py
@@ -0,0 +1,369 @@
+"""
+Collection of physical constants and conversion factors.
+
+Most constants are in SI units, so you can do
+print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
+
+The list is not meant to be comprehensive, but just convenient for everyday use.
+"""
+
+import math as _math
+from typing import TYPE_CHECKING, Any
+
+from ._codata import value as _cd
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+from scipy._lib._array_api import array_namespace, _asarray, xp_capabilities
+
+
+"""
+BasSw 2006
+physical constants: imported from CODATA
+unit conversion: see e.g., NIST special publication 811
+Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
+Some constants exist in a few variants, which are marked with suffixes.
+The ones without any suffix should be the most common ones.
+"""
+
+__all__ = [
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
+    'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+# mathematical constants
+pi = _math.pi
+golden = golden_ratio = (1 + _math.sqrt(5)) / 2
+
+# SI prefixes
+quetta = 1e30
+ronna = 1e27
+yotta = 1e24
+zetta = 1e21
+exa = 1e18
+peta = 1e15
+tera = 1e12
+giga = 1e9
+mega = 1e6
+kilo = 1e3
+hecto = 1e2
+deka = 1e1
+deci = 1e-1
+centi = 1e-2
+milli = 1e-3
+micro = 1e-6
+nano = 1e-9
+pico = 1e-12
+femto = 1e-15
+atto = 1e-18
+zepto = 1e-21
+yocto = 1e-24
+ronto = 1e-27
+quecto = 1e-30
+
+# binary prefixes
+kibi = 2**10
+mebi = 2**20
+gibi = 2**30
+tebi = 2**40
+pebi = 2**50
+exbi = 2**60
+zebi = 2**70
+yobi = 2**80
+
+# physical constants
+c = speed_of_light = _cd('speed of light in vacuum')
+mu_0 = _cd('vacuum mag. permeability')
+epsilon_0 = _cd('vacuum electric permittivity')
+h = Planck = _cd('Planck constant')
+hbar = _cd('reduced Planck constant')
+G = gravitational_constant = _cd('Newtonian constant of gravitation')
+g = _cd('standard acceleration of gravity')
+e = elementary_charge = _cd('elementary charge')
+R = gas_constant = _cd('molar gas constant')
+alpha = fine_structure = _cd('fine-structure constant')
+N_A = Avogadro = _cd('Avogadro constant')
+k = Boltzmann = _cd('Boltzmann constant')
+sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
+Wien = _cd('Wien wavelength displacement law constant')
+Rydberg = _cd('Rydberg constant')
+
+# mass in kg
+gram = 1e-3
+metric_ton = 1e3
+grain = 64.79891e-6
+lb = pound = 7000 * grain  # avoirdupois
+blob = slinch = pound * g / 0.0254  # lbf*s**2/in (added in 1.0.0)
+slug = blob / 12  # lbf*s**2/foot (added in 1.0.0)
+oz = ounce = pound / 16
+stone = 14 * pound
+long_ton = 2240 * pound
+short_ton = 2000 * pound
+
+troy_ounce = 480 * grain  # only for metals / gems
+troy_pound = 12 * troy_ounce
+carat = 200e-6
+
+m_e = electron_mass = _cd('electron mass')
+m_p = proton_mass = _cd('proton mass')
+m_n = neutron_mass = _cd('neutron mass')
+m_u = u = atomic_mass = _cd('atomic mass constant')
+
+# angle in rad
+degree = pi / 180
+arcmin = arcminute = degree / 60
+arcsec = arcsecond = arcmin / 60
+
+# time in second
+minute = 60.0
+hour = 60 * minute
+day = 24 * hour
+week = 7 * day
+year = 365 * day
+Julian_year = 365.25 * day
+
+# length in meter
+inch = 0.0254
+foot = 12 * inch
+yard = 3 * foot
+mile = 1760 * yard
+mil = inch / 1000
+pt = point = inch / 72  # typography
+survey_foot = 1200.0 / 3937
+survey_mile = 5280 * survey_foot
+nautical_mile = 1852.0
+fermi = 1e-15
+angstrom = 1e-10
+micron = 1e-6
+au = astronomical_unit = 149597870700.0
+light_year = Julian_year * c
+parsec = au / arcsec
+
+# pressure in pascal
+atm = atmosphere = _cd('standard atmosphere')
+bar = 1e5
+torr = mmHg = atm / 760
+psi = pound * g / (inch * inch)
+
+# area in meter**2
+hectare = 1e4
+acre = 43560 * foot**2
+
+# volume in meter**3
+litre = liter = 1e-3
+gallon = gallon_US = 231 * inch**3  # US
+# pint = gallon_US / 8
+fluid_ounce = fluid_ounce_US = gallon_US / 128
+bbl = barrel = 42 * gallon_US  # for oil
+
+gallon_imp = 4.54609e-3  # UK
+fluid_ounce_imp = gallon_imp / 160
+
+# speed in meter per second
+kmh = 1e3 / hour
+mph = mile / hour
+# approx value of mach at 15 degrees in 1 atm. Is this a common value?
+mach = speed_of_sound = 340.5
+knot = nautical_mile / hour
+
+# temperature in kelvin
+zero_Celsius = 273.15
+degree_Fahrenheit = 1/1.8  # only for differences
+
+# energy in joule
+eV = electron_volt = elementary_charge  # * 1 Volt
+calorie = calorie_th = 4.184
+calorie_IT = 4.1868
+erg = 1e-7
+Btu_th = pound * degree_Fahrenheit * calorie_th / gram
+Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
+ton_TNT = 1e9 * calorie_th
+# Wh = watt_hour
+
+# power in watt
+hp = horsepower = 550 * foot * pound * g
+
+# force in newton
+dyn = dyne = 1e-5
+lbf = pound_force = pound * g
+kgf = kilogram_force = g  # * 1 kg
+
+# functions for conversions that are not linear
+
+
+@xp_capabilities()
+def convert_temperature(
+    val: "npt.ArrayLike",
+    old_scale: str,
+    new_scale: str,
+) -> Any:
+    """
+    Convert from a temperature scale to another one among Celsius, Kelvin,
+    Fahrenheit, and Rankine scales.
+
+    Parameters
+    ----------
+    val : array_like
+        Value(s) of the temperature(s) to be converted expressed in the
+        original scale.
+    old_scale : str
+        Specifies as a string the original scale from which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+    new_scale : str
+        Specifies as a string the new scale to which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+
+    Returns
+    -------
+    res : float or array of floats
+        Value(s) of the converted temperature(s) expressed in the new scale.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    >>> from scipy.constants import convert_temperature
+    >>> import numpy as np
+    >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
+    array([ 233.15,  313.15])
+
+    """
+    xp = array_namespace(val)
+    _val = _asarray(val, xp=xp, subok=True)
+    # Convert from `old_scale` to Kelvin
+    if old_scale.lower() in ['celsius', 'c']:
+        tempo = _val + zero_Celsius
+    elif old_scale.lower() in ['kelvin', 'k']:
+        tempo = _val
+    elif old_scale.lower() in ['fahrenheit', 'f']:
+        tempo = (_val - 32) * 5 / 9 + zero_Celsius
+    elif old_scale.lower() in ['rankine', 'r']:
+        tempo = _val * 5 / 9
+    else:
+        raise NotImplementedError(f"{old_scale=} is unsupported: supported scales "
+                                   "are Celsius, Kelvin, Fahrenheit, and "
+                                   "Rankine")
+    # and from Kelvin to `new_scale`.
+    if new_scale.lower() in ['celsius', 'c']:
+        res = tempo - zero_Celsius
+    elif new_scale.lower() in ['kelvin', 'k']:
+        res = tempo
+    elif new_scale.lower() in ['fahrenheit', 'f']:
+        res = (tempo - zero_Celsius) * 9 / 5 + 32
+    elif new_scale.lower() in ['rankine', 'r']:
+        res = tempo * 9 / 5
+    else:
+        raise NotImplementedError(f"{new_scale=} is unsupported: supported "
+                                   "scales are 'Celsius', 'Kelvin', "
+                                   "'Fahrenheit', and 'Rankine'")
+
+    return res
+
+
+# optics
+
+
+@xp_capabilities()
+def lambda2nu(lambda_: "npt.ArrayLike") -> Any:
+    """
+    Convert wavelength to optical frequency
+
+    Parameters
+    ----------
+    lambda_ : array_like
+        Wavelength(s) to be converted.
+
+    Returns
+    -------
+    nu : float or array of floats
+        Equivalent optical frequency.
+
+    Notes
+    -----
+    Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import lambda2nu, speed_of_light
+    >>> import numpy as np
+    >>> lambda2nu(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(lambda_)
+    return c / _asarray(lambda_, xp=xp, subok=True)
+
+
+@xp_capabilities()
+def nu2lambda(nu: "npt.ArrayLike") -> Any:
+    """
+    Convert optical frequency to wavelength.
+
+    Parameters
+    ----------
+    nu : array_like
+        Optical frequency to be converted.
+
+    Returns
+    -------
+    lambda : float or array of floats
+        Equivalent wavelength(s).
+
+    Notes
+    -----
+    Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import nu2lambda, speed_of_light
+    >>> import numpy as np
+    >>> nu2lambda(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(nu)
+    return c / _asarray(nu, xp=xp, subok=True)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/codata.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1f946e1bdfa13ffc485157d15b4284e5b14994b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/constants.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..2615486c1e1f6715dc4f44b6a8217794b7640d82
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/test_codata.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/test_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..78ea323913013a8b7efc1c1247daa7578d791218
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/test_codata.py
@@ -0,0 +1,78 @@
+from scipy.constants import find, value, c, speed_of_light, precision
+from numpy.testing import assert_equal, assert_, assert_almost_equal
+import scipy.constants._codata as _cd
+from scipy import constants
+
+
+def test_find():
+    keys = find('weak mixing', disp=False)
+    assert_equal(keys, ['weak mixing angle'])
+
+    keys = find('qwertyuiop', disp=False)
+    assert_equal(keys, [])
+
+    keys = find('natural unit', disp=False)
+    assert_equal(keys, sorted(['natural unit of velocity',
+                                'natural unit of action',
+                                'natural unit of action in eV s',
+                                'natural unit of mass',
+                                'natural unit of energy',
+                                'natural unit of energy in MeV',
+                                'natural unit of momentum',
+                                'natural unit of momentum in MeV/c',
+                                'natural unit of length',
+                                'natural unit of time']))
+
+
+def test_basic_table_parse():
+    c_s = 'speed of light in vacuum'
+    assert_equal(value(c_s), c)
+    assert_equal(value(c_s), speed_of_light)
+
+
+def test_basic_lookup():
+    assert_equal('{} {}'.format(int(_cd.value('speed of light in vacuum')),
+                                _cd.unit('speed of light in vacuum')),
+                 '299792458 m s^-1')
+
+
+def test_find_all():
+    assert_(len(find(disp=False)) > 300)
+
+
+def test_find_single():
+    assert_equal(find('Wien freq', disp=False)[0],
+                 'Wien frequency displacement law constant')
+
+
+def test_2002_vs_2006():
+    assert_almost_equal(value('magn. flux quantum'),
+                        value('mag. flux quantum'))
+
+
+def test_exact_values():
+    # Check that updating stored values with exact ones worked.
+    exact = dict((k, v[0]) for k, v in _cd._physical_constants_2018.items())
+    replace = _cd.exact2018(exact)
+    for key, val in replace.items():
+        assert_equal(val, value(key))
+        assert precision(key) == 0
+
+
+def test_gh11341():
+    # gh-11341 noted that these three constants should exist (for backward
+    # compatibility) and should always have the same value:
+    a = constants.epsilon_0
+    b = constants.physical_constants['electric constant'][0]
+    c = constants.physical_constants['vacuum electric permittivity'][0]
+    assert a == b == c
+
+
+def test_gh14467():
+    # gh-14467 noted that some physical constants in CODATA are rounded
+    # to only ten significant figures even though they are supposed to be
+    # exact. Check that (at least) the case mentioned in the issue is resolved.
+    res = constants.physical_constants['Boltzmann constant in eV/K'][0]
+    ref = (constants.physical_constants['Boltzmann constant'][0]
+           / constants.physical_constants['elementary charge'][0])
+    assert res == ref
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/test_constants.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/test_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b6a9a9035674bc9ed53143020a1e3f60b2c99cb
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/tests/test_constants.py
@@ -0,0 +1,83 @@
+import pytest
+
+import scipy.constants as sc
+from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
+from scipy._lib._array_api import make_xp_test_case
+
+lazy_xp_modules = [sc]
+
+
+@make_xp_test_case(sc.convert_temperature)
+class TestConvertTemperature:
+    def test_convert_temperature(self, xp):
+        xp_assert_equal(sc.convert_temperature(xp.asarray(32.), 'f', 'Celsius'),
+                        xp.asarray(0.0))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]),
+                                               'celsius', 'Kelvin'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'kelvin', 'c'),
+                        xp.asarray([-273.15, -273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([32., 32.]), 'f', 'k'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([273.15, 273.15]),
+                                               'kelvin', 'F'),
+                        xp.asarray([32., 32.]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'C', 'fahrenheit'),
+                        xp.asarray([32., 32.]))
+        xp_assert_close(sc.convert_temperature(xp.asarray([0., 0.], dtype=xp.float64),
+                                               'c', 'r'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'Rankine', 'C'),
+                        xp.asarray([0., 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'r', 'F'),
+                        xp.asarray([32., 32.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([32., 32.], dtype=xp.float64),
+                                               'fahrenheit', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([273.15, 273.15],
+                                                        dtype=xp.float64),
+                                               'K', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 0.],
+                                                          dtype=xp.float64),
+                                               'rankine', 'kelvin'),
+                        xp.asarray([273.15, 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+
+    def test_convert_temperature_array_like(self):
+        xp_assert_close(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'),
+                        [273.15, 0.], rtol=0., atol=1e-13)
+
+
+    def test_convert_temperature_errors(self):
+        with pytest.raises(NotImplementedError, match="old_scale="):
+            sc.convert_temperature(1, old_scale="cheddar", new_scale="kelvin")
+        with pytest.raises(NotImplementedError, match="new_scale="):
+            sc.convert_temperature(1, old_scale="kelvin", new_scale="brie")
+
+
+@make_xp_test_case(sc.lambda2nu)
+class TestLambdaToNu:
+    def test_lambda_to_nu(self, xp):
+        xp_assert_equal(sc.lambda2nu(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+
+    def test_lambda_to_nu_array_like(self):
+        xp_assert_close(sc.lambda2nu([sc.speed_of_light, 1]), [1, sc.speed_of_light])
+
+
+@make_xp_test_case(sc.nu2lambda)
+class TestNuToLambda:
+    def test_nu_to_lambda(self, xp):
+        xp_assert_equal(sc.nu2lambda(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+    def test_nu_to_lambda_array_like(self):
+        xp_assert_close(sc.nu2lambda([sc.speed_of_light, 1]), [1, sc.speed_of_light])
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eab63e3ae2a680e7e9d767c85bfdcc41669f3822
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_download_all.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_download_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..cab8afecb13ed4b9276c929787f698697e7c5b20
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_download_all.py
@@ -0,0 +1,74 @@
+"""
+Platform independent script to download all the
+`scipy.datasets` module data files.
+This doesn't require a full scipy build.
+
+Run: python _download_all.py 
+"""
+
+from scipy._lib._array_api import xp_capabilities
+
+import argparse
+try:
+    import pooch
+except ImportError:
+    pooch = None
+
+
+if __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
+
+
+@xp_capabilities(out_of_scope=True)
+def download_all(path=None):
+    """
+    Utility method to download all the dataset files
+    for `scipy.datasets` module.
+
+    Parameters
+    ----------
+    path : str, optional
+        Directory path to download all the dataset files.
+        If None, default to the system cache_dir detected by pooch.
+
+    Examples
+    --------
+    Download the datasets to the default cache location:
+
+    >>> from scipy import datasets
+    >>> datasets.download_all()
+
+    Download the datasets to the current directory:
+
+    >>> datasets.download_all(".")
+
+    """
+    if pooch is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    if path is None:
+        path = pooch.os_cache('scipy-data')
+    # https://github.com/scipy/scipy/issues/21879
+    downloader = pooch.HTTPDownloader(headers={"User-Agent": "SciPy"})
+    for dataset_name, dataset_hash in _registry.registry.items():
+        pooch.retrieve(url=_registry.registry_urls[dataset_name],
+                       known_hash=dataset_hash,
+                       fname=dataset_name, path=path, downloader=downloader)
+
+
+def main():
+    parser = argparse.ArgumentParser(description='Download SciPy data files.')
+    parser.add_argument("path", nargs='?', type=str,
+                        default=pooch.os_cache('scipy-data'),
+                        help="Directory path to download all the data files.")
+    args = parser.parse_args()
+    download_all(args.path)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_fetchers.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_fetchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d630a2e3833ed8b21280d211b40dd3c1e6da80e
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_fetchers.py
@@ -0,0 +1,229 @@
+import sys
+
+from numpy import array, frombuffer, load
+from ._registry import registry, registry_urls
+
+from scipy._lib._array_api import xp_capabilities
+
+try:
+    import pooch
+except ImportError:
+    pooch = None
+    data_fetcher = None
+else:
+    data_fetcher = pooch.create(
+        # 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'.")
+    # https://github.com/scipy/scipy/issues/21879
+    downloader = pooch.HTTPDownloader(
+        headers={"User-Agent": f"SciPy {sys.modules['scipy'].__version__}"}
+    )
+    # The "fetch" method returns the full path to the downloaded data file.
+    return data_fetcher.fetch(dataset_name, downloader=downloader)
+
+
+@xp_capabilities(out_of_scope=True)
+def ascent():
+    """
+    Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
+    use in demos.
+
+    The image is derived from
+    https://pixnio.com/people/accent-to-the-top
+
+    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
+
+
+@xp_capabilities(out_of_scope=True)
+def electrocardiogram():
+    """
+    Load an electrocardiogram as an example for a 1-D signal.
+
+    The returned signal is a 5 minute long electrocardiogram (ECG), a medical
+    recording of the heart's electrical activity, sampled at 360 Hz.
+
+    Returns
+    -------
+    ecg : ndarray
+        The electrocardiogram in millivolt (mV) sampled at 360 Hz.
+
+    Notes
+    -----
+    The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
+    (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
+    PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
+    heartbeats as well as pathological changes.
+
+    .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
+           IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
+           (PMID: 11446209); :doi:`10.13026/C2F305`
+    .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
+           Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
+           PhysioToolkit, and PhysioNet: Components of a New Research Resource
+           for Complex Physiologic Signals. Circulation 101(23):e215-e220;
+           :doi:`10.1161/01.CIR.101.23.e215`
+
+    Examples
+    --------
+    >>> from scipy.datasets import electrocardiogram
+    >>> ecg = electrocardiogram()
+    >>> ecg
+    array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
+    >>> ecg.shape, ecg.mean(), ecg.std()
+    ((108000,), -0.16510875, 0.5992473991177294)
+
+    As stated the signal features several areas with a different morphology.
+    E.g., the first few seconds show the electrical activity of a heart in
+    normal sinus rhythm as seen below.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> fs = 360
+    >>> time = np.arange(ecg.size) / fs
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(9, 10.2)
+    >>> plt.ylim(-1, 1.5)
+    >>> plt.show()
+
+    After second 16, however, the first premature ventricular contractions,
+    also called extrasystoles, appear. These have a different morphology
+    compared to typical heartbeats. The difference can easily be observed
+    in the following plot.
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(46.5, 50)
+    >>> plt.ylim(-2, 1.5)
+    >>> plt.show()
+
+    At several points large artifacts disturb the recording, e.g.:
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(207, 215)
+    >>> plt.ylim(-2, 3.5)
+    >>> plt.show()
+
+    Finally, examining the power spectrum reveals that most of the biosignal is
+    made up of lower frequencies. At 60 Hz the noise induced by the mains
+    electricity can be clearly observed.
+
+    >>> from scipy.signal import welch
+    >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
+    >>> plt.semilogy(f, Pxx)
+    >>> plt.xlabel("Frequency in Hz")
+    >>> plt.ylabel("Power spectrum of the ECG in mV**2")
+    >>> plt.xlim(f[[0, -1]])
+    >>> plt.show()
+    """
+    fname = fetch_data("ecg.dat")
+    with load(fname) as file:
+        ecg = file["ecg"].astype(int)  # np.uint16 -> int
+    # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
+    ecg = (ecg - 1024) / 200.0
+    return ecg
+
+
+@xp_capabilities(out_of_scope=True)
+def face(gray=False):
+    """
+    Get a 1024 x 768, color image of a raccoon face.
+
+    The image is derived from
+    https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
+
+    Parameters
+    ----------
+    gray : bool, optional
+        If True return 8-bit grey-scale image, otherwise return a color image
+
+    Returns
+    -------
+    face : ndarray
+        image of a raccoon face
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> face = scipy.datasets.face()
+    >>> face.shape
+    (768, 1024, 3)
+    >>> face.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(face)
+    >>> plt.show()
+
+    """
+    import bz2
+    fname = fetch_data("face.dat")
+    with open(fname, 'rb') as f:
+        rawdata = f.read()
+    face_data = bz2.decompress(rawdata)
+    face = frombuffer(face_data, dtype='uint8').reshape((768, 1024, 3))
+    if gray is True:
+        face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
+                0.07 * face[:, :, 2]).astype('uint8')
+    return face
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_registry.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..9df4cf4de4d23ebdd8c036b26daee004663dfe0f
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_utils.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..83cf39651c0da9d3ece1e2e591c6b7e0d5a7e2f8
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/_utils.py
@@ -0,0 +1,84 @@
+import os
+import shutil
+from ._registry import method_files_map
+
+from scipy._lib._array_api import xp_capabilities
+
+try:
+    import platformdirs
+except ImportError:
+    platformdirs = None  # type: ignore[assignment]
+
+
+def _clear_cache(datasets, cache_dir=None, method_map=None):
+    if method_map is None:
+        # Use SciPy Datasets method map
+        method_map = method_files_map
+    if cache_dir is None:
+        # Use default cache_dir path
+        if platformdirs is None:
+            # platformdirs is pooch dependency
+            raise ImportError("Missing optional dependency 'pooch' required "
+                              "for scipy.datasets module. Please use pip or "
+                              "conda to install 'pooch'.")
+        cache_dir = platformdirs.user_cache_dir("scipy-data")
+
+    if not os.path.exists(cache_dir):
+        print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
+        return
+
+    if datasets is None:
+        print(f"Cleaning the cache directory {cache_dir}!")
+        shutil.rmtree(cache_dir)
+    else:
+        if not isinstance(datasets, list | tuple):
+            # single dataset method passed should be converted to list
+            datasets = [datasets, ]
+        for dataset in datasets:
+            assert callable(dataset)
+            dataset_name = dataset.__name__  # Name of the dataset method
+            if dataset_name not in method_map:
+                raise ValueError(f"Dataset method {dataset_name} doesn't "
+                                 "exist. Please check if the passed dataset "
+                                 "is a subset of the following dataset "
+                                 f"methods: {list(method_map.keys())}")
+
+            data_files = method_map[dataset_name]
+            data_filepaths = [os.path.join(cache_dir, file)
+                              for file in data_files]
+            for data_filepath in data_filepaths:
+                if os.path.exists(data_filepath):
+                    print("Cleaning the file "
+                          f"{os.path.split(data_filepath)[1]} "
+                          f"for dataset {dataset_name}")
+                    os.remove(data_filepath)
+                else:
+                    print(f"Path {data_filepath} doesn't exist. "
+                          "Nothing to clear.")
+
+
+@xp_capabilities(out_of_scope=True)
+def clear_cache(datasets=None):
+    """
+    Cleans the scipy datasets cache directory.
+
+    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/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/tests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/tests/test_data.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/datasets/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebc27bdae480ef00346f3b9808884fbc48738512
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..940cd71abc0b7ea954f04433ca261d542e664b25
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/_differentiate.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b2f02036421e9f2b748af945669dd38244c9364
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/_differentiate.py
@@ -0,0 +1,1140 @@
+# mypy: disable-error-code="attr-defined"
+import warnings
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import array_namespace, xp_copy, xp_promote, xp_capabilities
+import scipy._lib.array_api_extra as xpx
+
+_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)
+
+
+
+_array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
+_dask_reason = 'boolean indexing assignment'
+
+
+@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
+                                ('dask.array', _dask_reason)], jax_jit=False)
+def derivative(f, x, *, args=(), tolerances=None, maxiter=10,
+               order=8, initial_step=0.5, step_factor=2.0,
+               step_direction=0, preserve_shape=False, callback=None):
+    """Evaluate the derivative of an elementwise, real scalar function numerically.
+
+    For each element of the output of `f`, `derivative` approximates the first
+    derivative of `f` at the corresponding element of `x` using finite difference
+    differentiation.
+
+    This function works elementwise when `x`, `step_direction`, and `args` contain
+    (broadcastable) arrays.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose derivative is desired. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable with
+        ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
+        must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
+        ``xi`` or the arrays in ``argsi``.
+    x : float array_like
+        Abscissae at which to evaluate the derivative. Must be broadcastable with
+        `args` and `step_direction`.
+    args : tuple of array_like, optional
+        Additional positional array arguments to be passed to `f`. Arrays
+        must be broadcastable with one another and the arrays of `init`.
+        If the callable for which the root is desired requires arguments that are
+        not broadcastable with `x`, wrap that callable with `f` such that `f`
+        accepts only `x` and broadcastable ``*args``.
+    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 = xpx.at(h0)[h0 <= 0].set(xp.nan)
+
+    status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32)  # in progress
+    nit, nfev = 0, 1  # one function evaluations performed above
+    # Boolean indices of left, central, right, and (all) one-sided steps
+    il = hdir < 0
+    ic = hdir == 0
+    ir = hdir > 0
+    io = il | ir
+
+    # Most of these attributes are reasonably obvious, but:
+    # - `fs` holds all the function values of all active `x`. The zeroth
+    #   axis corresponds with active points `x`, the first axis corresponds
+    #   with the different steps (in the order described in
+    #   `_derivative_weights`).
+    # - `terms` (which could probably use a better name) is half the `order`,
+    #   which is always even.
+    work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
+                       df_last=xp.nan, error_last=xp.nan, fac=fac,
+                       atol=atol, rtol=rtol, nit=nit, nfev=nfev,
+                       status=status, dtype=dtype, terms=(order+1)//2,
+                       hdir=hdir, il=il, ic=ic, ir=ir, io=io,
+                       # Store the weights in an object so they can't get compressed
+                       # Using RichResult to allow dot notation, but a dict would work
+                       diff_state=_RichResult(central=[], right=[], fac=None))
+
+    # This is the correspondence between terms in the `work` object and the
+    # final result. In this case, the mapping is trivial. Note that `success`
+    # is prepended automatically.
+    res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
+                      ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
+
+    def pre_func_eval(work):
+        """Determine the abscissae at which the function needs to be evaluated.
+
+        See `_derivative_weights` for a description of the stencil (pattern
+        of the abscissae).
+
+        In the first iteration, there is only one stored function value in
+        `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
+        subsequent iterations, we evaluate at two new points. Note that
+        `work.x` is always flattened into a 1D array after broadcasting with
+        all `args`, so we add a new axis at the end and evaluate all point
+        in one call to the function.
+
+        For improvement:
+        - Consider measuring the step size actually taken, since ``(x + h) - x``
+          is not identically equal to `h` with floating point arithmetic.
+        - Adjust the step size automatically if `x` is too big to resolve the
+          step.
+        - We could probably save some work if there are no central difference
+          steps or no one-sided steps.
+        """
+        n = work.terms  # half the order
+        h = work.h[:, xp.newaxis]  # step size
+        c = work.fac  # step reduction factor
+        d = c**0.5  # square root of step reduction factor (one-sided stencil)
+        # Note - no need to be careful about dtypes until we allocate `x_eval`
+
+        if work.nit == 0:
+            hc = h / c**xp.arange(n, dtype=work.dtype)
+            hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
+        else:
+            hc = xp.concat((-h, h), axis=-1) / c**(n-1)
+
+        if work.nit == 0:
+            hr = h / d**xp.arange(2*n, dtype=work.dtype)
+        else:
+            hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
+
+        n_new = 2*n if work.nit == 0 else 2  # number of new abscissae
+        x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
+        il, ic, ir = work.il, work.ic, work.ir
+        x_eval = xpx.at(x_eval)[ir].set(work.x[ir][:, xp.newaxis] + hr[ir])
+        x_eval = xpx.at(x_eval)[ic].set(work.x[ic][:, xp.newaxis] + hc[ic])
+        x_eval = xpx.at(x_eval)[il].set(work.x[il][:, xp.newaxis] - hr[il])
+        return x_eval
+
+    def post_func_eval(x, f, work):
+        """ Estimate the derivative and error from the function evaluations
+
+        As in `pre_func_eval`: in the first iteration, there is only one stored
+        function value in `work.fs`, `f(x)`, so we need to add the `order` new
+        points. In subsequent iterations, we add two new points. The tricky
+        part is getting the order to match that of the weights, which is
+        described in `_derivative_weights`.
+
+        For improvement:
+        - Change the order of the weights (and steps in `pre_func_eval`) to
+          simplify `work_fc` concatenation and eliminate `fc` concatenation.
+        - It would be simple to do one-step Richardson extrapolation with `df`
+          and `df_last` to increase the order of the estimate and/or improve
+          the error estimate.
+        - Process the function evaluations in a more numerically favorable
+          way. For instance, combining the pairs of central difference evals
+          into a second-order approximation and using Richardson extrapolation
+          to produce a higher order approximation seemed to retain accuracy up
+          to very high order.
+        - Alternatively, we could use `polyfit` like Jacobi. An advantage of
+          fitting polynomial to more points than necessary is improved noise
+          tolerance.
+        """
+        n = work.terms
+        n_new = n if work.nit == 0 else 1
+        il, ic, io = work.il, work.ic, work.io
+
+        # Central difference
+        # `work_fc` is *all* the points at which the function has been evaluated
+        # `fc` is the points we're using *this iteration* to produce the estimate
+        work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
+        work_fc = xp.concat(work_fc, axis=-1)
+        if work.nit == 0:
+            fc = work_fc
+        else:
+            fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
+            fc = xp.concat(fc, axis=-1)
+
+        # One-sided difference
+        work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
+        if work.nit == 0:
+            fo = work_fo
+        else:
+            fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
+
+        work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
+        work.fs = xpx.at(work.fs)[ic].set(work_fc)
+        work.fs = xpx.at(work.fs)[io].set(work_fo)
+
+        wc, wo = _derivative_weights(work, n, xp)
+        work.df_last = xp.asarray(work.df, copy=True)
+        work.df = xpx.at(work.df)[ic].set(fc @ wc / work.h[ic])
+        work.df = xpx.at(work.df)[io].set(fo @ wo / work.h[io])
+        work.df = xpx.at(work.df)[il].multiply(-1)
+
+        work.h /= work.fac
+        work.error_last = work.error
+        # Simple error estimate - the difference in derivative estimates between
+        # this iteration and the last. This is typically conservative because if
+        # convergence has begin, the true error is much closer to the difference
+        # between the current estimate and the *next* error estimate. However,
+        # we could use Richarson extrapolation to produce an error estimate that
+        # is one order higher, and take the difference between that and
+        # `work.df` (which would just be constant factor that depends on `fac`.)
+        work.error = xp.abs(work.df - work.df_last)
+
+    def check_termination(work):
+        """Terminate due to convergence, non-finite values, or error increase"""
+        stop = xp.astype(xp.zeros_like(work.df), xp.bool)
+
+        i = work.error < work.atol + work.rtol*abs(work.df)
+        work.status = xpx.at(work.status)[i].set(eim._ECONVERGED)
+        stop = xpx.at(stop)[i].set(True)
+
+        if work.nit > 0:
+            i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
+            work.df = xpx.at(work.df)[i].set(xp.nan)
+            work.status = xpx.at(work.status)[i].set(eim._EVALUEERR)
+            stop = xpx.at(stop)[i].set(True)
+
+        # With infinite precision, there is a step size below which
+        # all smaller step sizes will reduce the error. But in floating point
+        # arithmetic, catastrophic cancellation will begin to cause the error
+        # to increase again. This heuristic tries to avoid step sizes that are
+        # too small. There may be more theoretically sound approaches for
+        # detecting a step size that minimizes the total error, but this
+        # heuristic seems simple and effective.
+        i = (work.error > work.error_last*10) & ~stop
+        work.status = xpx.at(work.status)[i].set(_EERRORINCREASE)
+        stop = xpx.at(stop)[i].set(True)
+
+        return stop
+
+    def post_termination_check(work):
+        return
+
+    def customize_result(res, shape):
+        return shape
+
+    return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+                     pre_func_eval, post_func_eval, check_termination,
+                     post_termination_check, customize_result, res_work_pairs,
+                     xp, preserve_shape)
+
+
+def _derivative_weights(work, n, xp):
+    # This produces the weights of the finite difference formula for a given
+    # stencil. In experiments, use of a second-order central difference formula
+    # with Richardson extrapolation was more accurate numerically, but it was
+    # more complicated, and it would have become even more complicated when
+    # adding support for one-sided differences. However, now that all the
+    # function evaluation values are stored, they can be processed in whatever
+    # way is desired to produce the derivative estimate. We leave alternative
+    # approaches to future work. To be more self-contained, here is the theory
+    # for deriving the weights below.
+    #
+    # Recall that the Taylor expansion of a univariate, scalar-values function
+    # about a point `x` may be expressed as:
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # Suppose we evaluate f(x), f(x+h), and f(x-h).  We have:
+    #      f(x)      =     f(x)
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    #      f(x - h)  =     f(x) - f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # We can solve for weights `wi` such that:
+    #   w1*f(x)      = w1*(f(x))
+    # + w2*f(x + h)  = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    # + w3*f(x - h)  = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    #                =     0    + f'(x)*h + 0               + O(h**3)
+    # Then
+    #     f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
+    # is a finite difference derivative approximation with error O(h**2),
+    # and so it is said to be a "second-order" approximation. Under certain
+    # conditions (e.g. well-behaved function, `h` sufficiently small), the
+    # error in the approximation will decrease with h**2; that is, if `h` is
+    # reduced by a factor of 2, the error is reduced by a factor of 4.
+    #
+    # By default, we use eighth-order formulae. Our central-difference formula
+    # uses abscissae:
+    #   x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
+    # where `c` is the step factor. (Typically, the step factor is greater than
+    # one, so the outermost points - as written above - are actually closest to
+    # `x`.) This "stencil" is chosen so that each iteration, the step can be
+    # reduced by the factor `c`, and most of the function evaluations can be
+    # reused with the new step size. For example, in the next iteration, we
+    # will have:
+    #   x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
+    # We do not reuse `x-h` and `x+h` for the new derivative estimate.
+    # While this would increase the order of the formula and thus the
+    # theoretical convergence rate, it is also less stable numerically.
+    # (As noted above, there are other ways of processing the values that are
+    # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
+    # to simplify future development of this sort of improvement.)
+    #
+    # The (right) one-sided formula is produced similarly using abscissae
+    #   x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
+    # where `d` is the square root of `c`. (The left one-sided formula simply
+    # uses -h.) When the step size is reduced by factor `c = d**2`, we have
+    # abscissae:
+    #   x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
+    # `d` is chosen as the square root of `c` so that the rate of the step-size
+    # reduction is the same per iteration as in the central difference case.
+    # Note that because the central difference formulas are inherently of even
+    # order, for simplicity, we use only even-order formulas for one-sided
+    # differences, too.
+
+    # It's possible for the user to specify `fac` in, say, double precision but
+    # `x` and `args` in single precision. `fac` gets converted to single
+    # precision, but we should always use double precision for the intermediate
+    # calculations here to avoid additional error in the weights.
+    fac = float(work.fac)
+
+    # Note that if the user switches back to floating point precision with
+    # `x` and `args`, then `fac` will not necessarily equal the (lower
+    # precision) cached `_derivative_weights.fac`, and the weights will
+    # need to be recalculated. This could be fixed, but it's late, and of
+    # low consequence.
+
+    diff_state = work.diff_state
+    if fac != diff_state.fac:
+        diff_state.central = []
+        diff_state.right = []
+        diff_state.fac = fac
+
+    if len(diff_state.central) != 2*n + 1:
+        # Central difference weights. Consider refactoring this; it could
+        # probably be more compact.
+        # Note: Using NumPy here is OK; we convert to xp-type at the end
+        i = np.arange(-n, n + 1)
+        p = np.abs(i) - 1.  # center point has power `p` -1, but sign `s` is 0
+        s = np.sign(i)
+
+        h = s / fac ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2*n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        # Enforce identities to improve accuracy
+        weights[n] = 0
+        for i in range(n):
+            weights[-i-1] = -weights[i]
+
+        # Cache the weights. We only need to calculate them once unless
+        # the step factor changes.
+        diff_state.central = weights
+
+        # One-sided difference weights. The left one-sided weights (with
+        # negative steps) are simply the negative of the right one-sided
+        # weights, so no need to compute them separately.
+        i = np.arange(2*n + 1)
+        p = i - 1.
+        s = np.sign(i)
+
+        h = s / np.sqrt(fac) ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2 * n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        diff_state.right = weights
+
+    return (xp.asarray(diff_state.central, dtype=work.dtype),
+            xp.asarray(diff_state.right, dtype=work.dtype))
+
+
+@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
+                                ('dask.array', _dask_reason)], jax_jit=False)
+def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
+             step_factor=2.0, step_direction=0):
+    r"""Evaluate the Jacobian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Jacobian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `jacobian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Jacobian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation. Must be broadcastable with `x` and `step_direction`.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    step_direction : 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)
+    x0 = xp_promote(x, force_floating=True, xp=xp)
+
+    if x0.ndim < 1:
+        message = "Argument `x` must be at least 1-D."
+        raise ValueError(message)
+
+    m = x0.shape[0]
+    i = xp.arange(m)
+
+    def wrapped(x):
+        p = () if x.ndim == x0.ndim else (x.shape[-1],)  # number of abscissae
+
+        new_shape = (m, m) + x0.shape[1:] + p
+        xph = xp.expand_dims(x0, axis=1)
+        if x.ndim != x0.ndim:
+            xph = xp.expand_dims(xph, axis=-1)
+        xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
+        xph = xpx.at(xph)[i, i].set(x)
+        return f(xph)
+
+    res = derivative(wrapped, x, tolerances=tolerances,
+                     maxiter=maxiter, order=order, initial_step=initial_step,
+                     step_factor=step_factor, preserve_shape=True,
+                     step_direction=step_direction)
+
+    del res.x  # the user knows `x`, and the way it gets broadcasted is meaningless here
+    return res
+
+
+@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
+                                ('dask.array', _dask_reason)], jax_jit=False)
+def hessian(f, x, *, tolerances=None, maxiter=10,
+            order=8, initial_step=0.5, step_factor=2.0):
+    r"""Evaluate the Hessian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Hessian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `hessian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Hessian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    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)
+    x0 = xp_promote(x, force_floating=True, xp=xp)
+
+    finfo = xp.finfo(x0.dtype)
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `derivative`
+
+    # tighten the inner tolerance to make the inner error negligible
+    rtol_min = finfo.eps * 100
+    message = (f"The specified `{rtol=}`, but error estimates are likely to be "
+               f"unreliable when `rtol < {rtol_min}`.")
+    if 0 < rtol < rtol_min:  # rtol <= 0 is an error
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+        rtol = rtol_min
+
+    def df(x):
+        tolerances = dict(rtol=rtol/100, atol=atol)
+        temp = jacobian(f, x, tolerances=tolerances, **kwargs)
+        nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
+        return temp.df
+
+    nfev = []  # track inner function evaluations
+    res = jacobian(df, x, tolerances=tolerances, **kwargs)  # jacobian of jacobian
+
+    nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
+    res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64)  # appease torch
+    res.nfev = xp.take_along_axis(nfev, res_nit, axis=0)[0]
+    res.ddf = res.df
+    del res.df  # this is renamed to ddf
+    del res.nit  # this is only the outer-jacobian nit
+
+    return res
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/tests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..00b800833d1aca192b53621a28ac287fcf34d76d
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py
@@ -0,0 +1,690 @@
+import math
+import pytest
+
+import numpy as np
+
+import scipy._lib._elementwise_iterative_method as eim
+import scipy._lib.array_api_extra as xpx
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal, xp_assert_less
+from scipy._lib._array_api import is_numpy, is_torch, make_xp_test_case
+
+from scipy import stats, optimize, special
+from scipy.differentiate import derivative, jacobian, hessian
+from scipy.differentiate._differentiate import _EERRORINCREASE
+
+
+
+@make_xp_test_case(derivative)
+class TestDerivative:
+
+    def f(self, x):
+        return special.ndtr(x)
+
+    @pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)])
+    def test_basic(self, x, xp):
+        # Invert distribution CDF and compare against distribution `ppf`
+        default_dtype = xp.asarray(1.).dtype
+        res = derivative(self.f, xp.asarray(x, dtype=default_dtype))
+        ref = xp.asarray(stats.norm().pdf(x), dtype=default_dtype)
+        xp_assert_close(res.df, ref)
+        # This would be nice, but doesn't always work out. `error` is an
+        # estimate, not a bound.
+        if not is_torch(xp):
+            xp_assert_less(xp.abs(res.df - ref), res.error)
+
+    @pytest.mark.parametrize('case', stats._distr_params.distcont)
+    def test_accuracy(self, case):
+        distname, params = case
+        dist = getattr(stats, distname)(*params)
+        x = dist.median() + 0.1
+        res = derivative(dist.cdf, x)
+        ref = dist.pdf(x)
+        xp_assert_close(res.df, ref, atol=1e-10)
+
+    @pytest.mark.parametrize('order', [1, 6])
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, order, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
+        n = np.size(x)
+        state = {}
+
+        @np.vectorize
+        def _derivative_single(x):
+            return derivative(self.f, x, order=order)
+
+        def f(x, *args, **kwargs):
+            state['nit'] += 1
+            state['feval'] += 1 if (x.size == n or x.ndim <=1) else x.shape[-1]
+            return self.f(x, *args, **kwargs)
+
+        state['nit'] = -1
+        state['feval'] = 0
+
+        res = derivative(f, xp.asarray(x, dtype=xp.float64), order=order)
+        refs = _derivative_single(x).ravel()
+
+        ref_x = [ref.x for ref in refs]
+        xp_assert_close(xp.reshape(res.x, (-1,)), xp.asarray(ref_x))
+
+        ref_df = [ref.df for ref in refs]
+        xp_assert_close(xp.reshape(res.df, (-1,)), xp.asarray(ref_df))
+
+        ref_error = [ref.error for ref in refs]
+        xp_assert_close(xp.reshape(res.error, (-1,)), xp.asarray(ref_error),
+                        atol=1e-12)
+
+        ref_success = [bool(ref.success) for ref in refs]
+        xp_assert_equal(xp.reshape(res.success, (-1,)), xp.asarray(ref_success))
+
+        ref_flag = [np.int32(ref.status) for ref in refs]
+        xp_assert_equal(xp.reshape(res.status, (-1,)), xp.asarray(ref_flag))
+
+        ref_nfev = [np.int32(ref.nfev) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nfev, (-1,)), xp.asarray(ref_nfev))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nfev) == state['feval']
+
+        ref_nit = [np.int32(ref.nit) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nit, (-1,)), xp.asarray(ref_nit))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nit) == state['nit']
+
+    def test_flags(self, xp):
+        # Test cases that should produce different status flags; show that all
+        # can be produced simultaneously.
+        rng = np.random.default_rng(5651219684984213)
+        def f(xs, js):
+            f.nit += 1
+            funcs = [lambda x: x - 2.5,  # converges
+                     lambda x: xp.exp(x)*rng.random(),  # error increases
+                     lambda x: xp.exp(x),  # reaches maxiter due to order=2
+                     lambda x: xp.full_like(x, xp.nan)]  # stops due to NaN
+            res = [funcs[int(j)](x) for x, j in zip(xs, xp.reshape(js, (-1,)))]
+            return xp.stack(res)
+        f.nit = 0
+
+        args = (xp.arange(4, dtype=xp.int64),)
+        res = derivative(f, xp.ones(4, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, args=args)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_flags_preserve_shape(self, xp):
+        # Same test as above but using `preserve_shape` option to simplify.
+        rng = np.random.default_rng(5651219684984213)
+        def f(x):
+            out = [x - 2.5,  # converges
+                   xp.exp(x)*rng.random(),  # error increases
+                   xp.exp(x),  # reaches maxiter due to order=2
+                   xp.full_like(x, xp.nan)]  # stops due to NaN
+            return xp.stack(out)
+
+        res = derivative(f, xp.asarray(1, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, preserve_shape=True)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_preserve_shape(self, xp):
+        # Test `preserve_shape` option
+        def f(x):
+            out = [x, xp.sin(3*x), x+xp.sin(10*x), xp.sin(20*x)*(x-1)**2]
+            return xp.stack(out)
+
+        x = xp.asarray(0.)
+        ref = xp.asarray([xp.asarray(1), 3*xp.cos(3*x), 1+10*xp.cos(10*x),
+                          20*xp.cos(20*x)*(x-1)**2 + 2*xp.sin(20*x)*(x-1)])
+        res = derivative(f, x, preserve_shape=True)
+        xp_assert_close(res.df, ref)
+
+    def test_convergence(self, xp):
+        # Test that the convergence tolerances behave as expected
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+        tolerances0 = dict(atol=0, rtol=0)
+
+        tolerances = tolerances0.copy()
+        tolerances['atol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3
+        tolerances['atol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        tolerances = tolerances0.copy()
+        tolerances['rtol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3 * ref
+        tolerances['rtol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6 * ref
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+    def test_step_parameters(self, xp):
+        # Test that step factors have the expected effect on accuracy
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+
+        res1 = derivative(f, x, initial_step=0.5, maxiter=1)
+        res2 = derivative(f, x, initial_step=0.05, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        res1 = derivative(f, x, step_factor=2, maxiter=1)
+        res2 = derivative(f, x, step_factor=20, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        # `step_factor` can be less than 1: `initial_step` is the minimum step
+        kwargs = dict(order=4, maxiter=1, step_direction=0)
+        res = derivative(f, x, initial_step=0.5, step_factor=0.5, **kwargs)
+        ref = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        # This is a similar test for one-sided difference
+        kwargs = dict(order=2, maxiter=1, step_direction=1)
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        kwargs['step_direction'] = -1
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+    def test_step_direction(self, xp):
+        # test that `step_direction` works as expected
+        def f(x):
+            y = xp.exp(x)
+            y = xpx.at(y)[(x < 0) + (x > 2)].set(xp.nan)
+            return y
+
+        x = xp.linspace(0, 2, 10)
+        step_direction = xp.zeros_like(x)
+        step_direction = xpx.at(step_direction)[x < 0.6].set(1)
+        step_direction = xpx.at(step_direction)[x > 1.4].set(-1)
+        res = derivative(f, x, step_direction=step_direction)
+        xp_assert_close(res.df, xp.exp(x))
+        assert xp.all(res.success)
+
+    def test_vectorized_step_direction_args(self, xp):
+        # test that `step_direction` and `args` are vectorized properly
+        def f(x, p):
+            return x ** p
+
+        def df(x, p):
+            return p * x ** (p - 1)
+
+        x = xp.reshape(xp.asarray([1, 2, 3, 4]), (-1, 1, 1))
+        hdir = xp.reshape(xp.asarray([-1, 0, 1]), (1, -1, 1))
+        p = xp.reshape(xp.asarray([2, 3]), (1, 1, -1))
+        res = derivative(f, x, step_direction=hdir, args=(p,))
+        ref = xp.broadcast_to(df(x, p), res.df.shape)
+        ref = xp.asarray(ref, dtype=xp.asarray(1.).dtype)
+        xp_assert_close(res.df, ref)
+
+    def test_initial_step(self, xp):
+        # Test that `initial_step` works as expected and is vectorized
+        def f(x):
+            return xp.exp(x)
+
+        x = xp.asarray(0., dtype=xp.float64)
+        step_direction = xp.asarray([-1, 0, 1])
+        h0 = xp.reshape(xp.logspace(-3, 0, 10), (-1, 1))
+        res = derivative(f, x, initial_step=h0, order=2, maxiter=1,
+                         step_direction=step_direction)
+        err = xp.abs(res.df - f(x))
+
+        # error should be smaller for smaller step sizes
+        assert xp.all(err[:-1, ...] < err[1:, ...])
+
+        # results of vectorized call should match results with
+        # initial_step taken one at a time
+        for i in range(h0.shape[0]):
+            ref = derivative(f, x, initial_step=h0[i, 0], order=2, maxiter=1,
+                             step_direction=step_direction)
+            xp_assert_close(res.df[i, :], ref.df, rtol=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
+            elif key == 'error':
+                # switched from equality check to accommodate
+                # macosx-x86_64/Accelerate
+                xp_assert_close(res2[key], res[key], atol=1e-14)
+                xp_assert_close(callback.res[key], res[key], atol=1e-14)
+            else:
+                assert res2[key] == callback.res[key] == res[key]
+
+    @pytest.mark.parametrize("hdir", (-1, 0, 1))
+    @pytest.mark.parametrize("x", (0.65, [0.65, 0.7]))
+    @pytest.mark.parametrize("dtype", ('float32', 'float64'))
+    def test_dtype(self, hdir, x, dtype, xp):
+        # Test that dtypes are preserved
+        dtype = getattr(xp, dtype)
+        x = xp.asarray(x, dtype=dtype)
+
+        def f(x):
+            assert x.dtype == dtype
+            return xp.exp(x)
+
+        def callback(res):
+            assert res.x.dtype == dtype
+            assert res.df.dtype == dtype
+            assert res.error.dtype == dtype
+
+        res = derivative(f, x, order=4, step_direction=hdir, callback=callback)
+        assert res.x.dtype == dtype
+        assert res.df.dtype == dtype
+        assert res.error.dtype == dtype
+        eps = xp.finfo(dtype).eps
+        # not sure why torch is less accurate here; might be worth investigating
+        rtol = eps**0.5 * 50 if is_torch(xp) else eps**0.5
+        xp_assert_close(res.df, xp.exp(res.x), rtol=rtol)
+
+    def test_input_validation(self, xp):
+        # Test input validation for appropriate error messages
+        one = xp.asarray(1)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(None, one)
+
+        message = 'Abscissae and function output must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, xp.asarray(-4+1j))
+
+        message = "When `preserve_shape=False`, the shape of the array..."
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: [1, 2, 3], xp.asarray([-2, -3]))
+
+        message = 'Tolerances and step parameters must be non-negative...'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(rtol='ekki'))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, step_factor=object())
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=0)
+
+        message = '`order` must be a positive integer'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=0)
+
+        message = '`preserve_shape` must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, preserve_shape='herring')
+
+        message = '`callback` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, callback='shrubbery')
+
+    def test_special_cases(self, xp):
+        # Test edge cases and other special cases
+
+        # Test that integers are not passed to `f`
+        # (otherwise this would overflow)
+        def f(x):
+            assert xp.isdtype(x.dtype, 'real floating')
+            return x ** 99 - 1
+
+        if not is_torch(xp):  # torch defaults to float32
+            res = derivative(f, xp.asarray(7), tolerances=dict(rtol=1e-10))
+            assert res.success
+            xp_assert_close(res.df, xp.asarray(99*7.**98))
+
+        # Test invalid step size and direction
+        res = derivative(xp.exp, xp.asarray(1), step_direction=xp.nan)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        res = derivative(xp.exp, xp.asarray(1), initial_step=0)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        # Test that if success is achieved in the correct number
+        # of iterations if function is a polynomial. Ideally, all polynomials
+        # of order 0-2 would get exact result with 0 refinement iterations,
+        # all polynomials of order 3-4 would be differentiated exactly after
+        # 1 iteration, etc. However, it seems that `derivative` needs an
+        # extra iteration to detect convergence based on the error estimate.
+
+        for n in range(6):
+            x = xp.asarray(1.5, dtype=xp.float64)
+            def f(x):
+                return 2*x**n
+
+            ref = 2*n*x**(n-1)
+
+            res = derivative(f, x, maxiter=1, order=max(1, n))
+            xp_assert_close(res.df, ref, rtol=1e-15)
+            xp_assert_equal(res.error, xp.asarray(xp.nan, dtype=xp.float64))
+
+            res = derivative(f, x, order=max(1, n))
+            assert res.success
+            assert res.nit == 2
+            xp_assert_close(res.df, ref, rtol=1e-15)
+
+        # Test scalar `args` (not in tuple)
+        def f(x, c):
+            return c*x - 1
+
+        res = derivative(f, xp.asarray(2), args=xp.asarray(3))
+        xp_assert_close(res.df, xp.asarray(3.))
+
+    # no need to run a test on multiple backends if it's xfailed
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.xfail
+    @pytest.mark.parametrize("case", (  # function, evaluation point
+        (lambda x: (x - 1) ** 3, 1),
+        (lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1)
+    ))
+    def test_saddle_gh18811(self, case, xp):
+        # With default settings, `derivative` will not always converge when
+        # the true derivative is exactly zero. This tests that specifying a
+        # (tight) `atol` alleviates the problem. See discussion in gh-18811.
+        atol = 1e-16
+        res = derivative(*case, step_direction=[-1, 0, 1], atol=atol)
+        assert np.all(res.success)
+        xp_assert_close(res.df, 0, atol=atol)
+
+
+class JacobianHessianTest:
+    def test_iv(self, xp):
+        jh_func = self.jh_func.__func__
+
+        # Test input validation
+        message = "Argument `x` must be at least 1-D."
+        with pytest.raises(ValueError, match=message):
+            jh_func(xp.sin, 1, tolerances=dict(atol=-1))
+
+        # Confirm that other parameters are being passed to `derivative`,
+        # which raises an appropriate error message.
+        x = xp.ones(3)
+        func = optimize.rosen
+        message = 'Tolerances and step parameters must be non-negative scalars.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(rtol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, step_factor=-1)
+
+        message = '`order` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, order=-1)
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, maxiter=-1)
+
+
+@make_xp_test_case(jacobian)
+class TestJacobian(JacobianHessianTest):
+    jh_func = jacobian
+
+    # Example functions and Jacobians from Wikipedia:
+    # https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Examples
+
+    def f1(z, xp):
+        x, y = z
+        return xp.stack([x ** 2 * y, 5 * x + xp.sin(y)])
+
+    def df1(z):
+        x, y = z
+        return [[2 * x * y, x ** 2], [np.full_like(x, 5), np.cos(y)]]
+
+    f1.mn = 2, 2  # type: ignore[attr-defined]
+    f1.ref = df1  # type: ignore[attr-defined]
+
+    def f2(z, xp):
+        r, phi = z
+        return xp.stack([r * xp.cos(phi), r * xp.sin(phi)])
+
+    def df2(z):
+        r, phi = z
+        return [[np.cos(phi), -r * np.sin(phi)],
+                [np.sin(phi), r * np.cos(phi)]]
+
+    f2.mn = 2, 2  # type: ignore[attr-defined]
+    f2.ref = df2  # type: ignore[attr-defined]
+
+    def f3(z, xp):
+        r, phi, th = z
+        return xp.stack([r * xp.sin(phi) * xp.cos(th), r * xp.sin(phi) * xp.sin(th),
+                         r * xp.cos(phi)])
+
+    def df3(z):
+        r, phi, th = z
+        return [[np.sin(phi) * np.cos(th), r * np.cos(phi) * np.cos(th),
+                 -r * np.sin(phi) * np.sin(th)],
+                [np.sin(phi) * np.sin(th), r * np.cos(phi) * np.sin(th),
+                 r * np.sin(phi) * np.cos(th)],
+                [np.cos(phi), -r * np.sin(phi), np.zeros_like(r)]]
+
+    f3.mn = 3, 3  # type: ignore[attr-defined]
+    f3.ref = df3  # type: ignore[attr-defined]
+
+    def f4(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([x1, 5 * x3, 4 * x2 ** 2 - 2 * x3, x3 * xp.sin(x1)])
+
+    def df4(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[one, 0 * one, 0 * one],
+                [0 * one, 0 * one, 5 * one],
+                [0 * one, 8 * x2, -2 * one],
+                [x3 * np.cos(x1), 0 * one, np.sin(x1)]]
+
+    f4.mn = 3, 4  # type: ignore[attr-defined]
+    f4.ref = df4  # type: ignore[attr-defined]
+
+    def f5(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([5 * x2, 4 * x1 ** 2 - 2 * xp.sin(x2 * x3), x2 * x3])
+
+    def df5(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[0 * one, 5 * one, 0 * one],
+                [8 * x1, -2 * x3 * np.cos(x2 * x3), -2 * x2 * np.cos(x2 * x3)],
+                [0 * one, x3, x2]]
+
+    f5.mn = 3, 3  # type: ignore[attr-defined]
+    f5.ref = df5  # type: ignore[attr-defined]
+
+    def rosen(x, _): return optimize.rosen(x)
+    rosen.mn = 5, 1  # type: ignore[attr-defined]
+    rosen.ref = optimize.rosen_der  # type: ignore[attr-defined]
+
+    @pytest.mark.parametrize('dtype', ('float32', 'float64'))
+    @pytest.mark.parametrize('size', [(), (6,), (2, 3)])
+    @pytest.mark.parametrize('func', [f1, f2, f3, f4, f5, rosen])
+    def test_examples(self, dtype, size, func, xp):
+        atol = 1e-10 if dtype == 'float64' else 1.99e-3
+        dtype = getattr(xp, dtype)
+        rng = np.random.default_rng(458912319542)
+        m, n = func.mn
+        x = rng.random(size=(m,) + size)
+        res = jacobian(lambda x: func(x , xp), xp.asarray(x, dtype=dtype))
+        # convert list of arrays to single array before converting to xp array
+        ref = xp.asarray(np.asarray(func.ref(x)), dtype=dtype)
+        xp_assert_close(res.df, ref, atol=atol)
+
+    def test_attrs(self, xp):
+        # Test attributes of result object
+        z = xp.asarray([0.5, 0.25])
+
+        # case in which some elements of the Jacobian are harder
+        # to calculate than others
+        def df1(z):
+            x, y = z
+            return xp.stack([xp.cos(0.5*x) * xp.cos(y), xp.sin(2*x) * y**2])
+
+        def df1_0xy(x, y):
+            return xp.cos(0.5*x) * xp.cos(y)
+
+        def df1_1xy(x, y):
+            return xp.sin(2*x) * y**2
+
+        res = jacobian(df1, z, initial_step=10)
+        # FIXME https://github.com/scipy/scipy/pull/22320#discussion_r1914898175
+        if not is_torch(xp):
+            assert xpx.nunique(res.nit) == 4
+            assert xpx.nunique(res.nfev) == 4
+
+        res00 = jacobian(lambda x: df1_0xy(x, z[1]), z[0:1], initial_step=10)
+        res01 = jacobian(lambda y: df1_0xy(z[0], y), z[1:2], initial_step=10)
+        res10 = jacobian(lambda x: df1_1xy(x, z[1]), z[0:1], initial_step=10)
+        res11 = jacobian(lambda y: df1_1xy(z[0], y), z[1:2], initial_step=10)
+        ref = optimize.OptimizeResult()
+        for attr in ['success', 'status', 'df', 'nit', 'nfev']:
+            ref_attr = xp.asarray([[getattr(res00, attr), getattr(res01, attr)],
+                                   [getattr(res10, attr), getattr(res11, attr)]])
+            ref[attr] = xp.squeeze(
+                ref_attr,
+                axis=tuple(ax for ax, size in enumerate(ref_attr.shape) if size == 1)
+            )
+            rtol = 1.5e-5 if res[attr].dtype == xp.float32 else 1.5e-14
+            xp_assert_close(res[attr], ref[attr], rtol=rtol)
+
+    def test_step_direction_size(self, xp):
+        # Check that `step_direction` and `initial_step` can be used to ensure that
+        # the usable domain of a function is respected.
+        rng = np.random.default_rng(23892589425245)
+        b = rng.random(3)
+        eps = 1e-7  # torch needs wiggle room?
+
+        def f(x):
+            x = xpx.at(x)[0, x[0] < b[0]].set(xp.nan)
+            x = xpx.at(x)[0, x[0] > b[0] + 0.25].set(xp.nan)
+            x = xpx.at(x)[1, x[1] > b[1]].set(xp.nan)
+            x = xpx.at(x)[1, x[1] < b[1] - 0.1-eps].set(xp.nan)
+            return TestJacobian.f5(x, xp)
+
+        dir = [1, -1, 0]
+        h0 = [0.25, 0.1, 0.5]
+        atol = {'atol': 1e-8}
+        res = jacobian(f, xp.asarray(b, dtype=xp.float64), initial_step=h0,
+                       step_direction=dir, tolerances=atol)
+        ref = xp.asarray(TestJacobian.df5(b), dtype=xp.float64)
+        xp_assert_close(res.df, ref, atol=1e-8)
+        assert xp.all(xp.isfinite(ref))
+
+
+@make_xp_test_case(hessian)
+class TestHessian(JacobianHessianTest):
+    jh_func = hessian
+
+    @pytest.mark.parametrize('shape', [(), (4,), (2, 4)])
+    def test_example(self, shape, xp):
+        rng = np.random.default_rng(458912319542)
+        m = 3
+        x = xp.asarray(rng.random((m,) + shape), dtype=xp.float64)
+        res = hessian(optimize.rosen, x)
+        if shape:
+            x = xp.reshape(x, (m, -1))
+            ref = xp.stack([optimize.rosen_hess(xi) for xi in x.T])
+            ref = xp.moveaxis(ref, 0, -1)
+            ref = xp.reshape(ref, (m, m,) + shape)
+        else:
+            ref = optimize.rosen_hess(x)
+        xp_assert_close(res.ddf, ref, atol=1e-8)
+
+        # # Removed symmetry enforcement; consider adding back in as a feature
+        # # check symmetry
+        # for key in ['ddf', 'error', 'nfev', 'success', 'status']:
+        #     assert_equal(res[key], np.swapaxes(res[key], 0, 1))
+
+    def test_float32(self, xp):
+        rng = np.random.default_rng(458912319542)
+        x = xp.asarray(rng.random(3), dtype=xp.float32)
+        res = hessian(optimize.rosen, x)
+        ref = optimize.rosen_hess(x)
+        mask = (ref != 0)
+        xp_assert_close(res.ddf[mask], ref[mask])
+        atol = 1e-2 * xp.abs(xp.min(ref[mask]))
+        xp_assert_close(res.ddf[~mask], ref[~mask], atol=atol)
+
+    def test_nfev(self, xp):
+        z = xp.asarray([0.5, 0.25])
+
+        def f1(z):
+            x, y = xp.broadcast_arrays(*z)
+            f1.nfev = f1.nfev + (math.prod(x.shape[2:]) if x.ndim > 2 else 1)
+            return xp.sin(x) * y ** 3
+        f1.nfev = 0
+
+
+        res = hessian(f1, z, initial_step=10)
+        f1.nfev = 0
+        res00 = hessian(lambda x: f1([x[0], z[1]]), z[0:1], initial_step=10)
+        assert res.nfev[0, 0] == f1.nfev == res00.nfev[0, 0]
+
+        f1.nfev = 0
+        res11 = hessian(lambda y: f1([z[0], y[0]]), z[1:2], initial_step=10)
+        assert res.nfev[1, 1] == f1.nfev == res11.nfev[0, 0]
+
+        # Removed symmetry enforcement; consider adding back in as a feature
+        # assert_equal(res.nfev, res.nfev.T)  # check symmetry
+        # assert np.unique(res.nfev).size == 3
+
+
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason='Python list input uses NumPy backend')
+    def test_small_rtol_warning(self, xp):
+        message = 'The specified `rtol=1e-15`, but...'
+        with pytest.warns(RuntimeWarning, match=message):
+            hessian(xp.sin, [1.], tolerances=dict(rtol=1e-15))
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c68df69e8a7ff6fedb6cf30dc852b60b006c639b
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6f3fb5064b88d6dae861d3db645b45028691efe
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_backend.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cbd411cabf9be22a582b16dd997dae6f2c9748a
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_backend.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_basic.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66d87796ebf5050c50285aa48228fb8e252d3582
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_basic.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c3f84bcddbb14deaf2ccd7397ed07d8279cb1ae
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_fftlog.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_fftlog.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..857c4a324e085f77d97e423bc8a358d0c1a7091d
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_fftlog.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fba3c715f6913d5af76dc112d7a37da30740b37
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_helper.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_helper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c60741ce0bbb0fc206c6a0f4505bccf204b86c1
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_helper.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d6767d4c3ff229e4d59d033b0b823c1c4c83c93
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6929fd74ff6f82dc4c99d35ba2ddf9fbf050db68
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_backend.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..63b235cc34948586529d0166c1b7daa29e56c402
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_backend.py
@@ -0,0 +1,201 @@
+import scipy._lib.uarray as ua
+from scipy._lib._array_api import xp_capabilities
+from . import _basic_backend
+from . import _realtransforms_backend
+from . import _fftlog_backend
+
+
+class _ScipyBackend:
+    """The default backend for fft calculations
+
+    Notes
+    -----
+    We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
+    treats the domain as a hierarchy. This means the user can install a single
+    backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
+    """
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+
+        fn = getattr(_basic_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_realtransforms_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_fftlog_backend, method.__name__, None)
+        if fn is None:
+            return NotImplemented
+        return fn(*args, **kwargs)
+
+
+_named_backends = {
+    'scipy': _ScipyBackend,
+}
+
+
+def _backend_from_arg(backend):
+    """Maps strings to known backends and validates the backend"""
+
+    if isinstance(backend, str):
+        try:
+            backend = _named_backends[backend]
+        except KeyError as e:
+            raise ValueError(f'Unknown backend {backend}') from e
+
+    if backend.__ua_domain__ != 'numpy.scipy.fft':
+        raise ValueError('Backend does not implement "numpy.scipy.fft"')
+
+    return backend
+
+
+@xp_capabilities(out_of_scope=True)
+def set_global_backend(backend, coerce=False, only=False, try_last=False):
+    """Sets the global fft backend
+
+    This utility method replaces the default backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend. This will be the first tried
+    backend outside the :obj:`set_backend` context manager.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool
+        Whether to coerce input types when trying this backend.
+    only : bool
+        If ``True``, no more backends will be tried if this fails.
+        Implied by ``coerce=True``.
+    try_last : bool
+        If ``True``, the global backend is tried after registered backends.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Notes
+    -----
+    This will overwrite the previously set global backend, which, by default, is
+    the SciPy implementation.
+
+    Examples
+    --------
+    We can set the global fft backend:
+
+    >>> from scipy.fft import fft, set_global_backend
+    >>> set_global_backend("scipy")  # Sets global backend (default is "scipy").
+    >>> fft([1])  # Calls the global backend
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
+
+
+@xp_capabilities(out_of_scope=True)
+def register_backend(backend):
+    """
+    Register a backend for permanent use.
+
+    Registered backends have the lowest priority and will be tried after the
+    global backend.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Examples
+    --------
+    We can register a new fft backend:
+
+    >>> from scipy.fft import fft, register_backend, set_global_backend
+    >>> class NoopBackend:  # Define an invalid Backend
+    ...     __ua_domain__ = "numpy.scipy.fft"
+    ...     def __ua_function__(self, func, args, kwargs):
+    ...          return NotImplemented
+    >>> set_global_backend(NoopBackend())  # Set the invalid backend as global
+    >>> register_backend("scipy")  # Register a new backend
+    # The registered backend is called because
+    # the global backend returns `NotImplemented`
+    >>> fft([1])
+    array([1.+0.j])
+    >>> set_global_backend("scipy")  # Restore global backend to default
+
+    """
+    backend = _backend_from_arg(backend)
+    ua.register_backend(backend)
+
+
+@xp_capabilities(out_of_scope=True)
+def set_backend(backend, coerce=False, only=False):
+    """Context manager to set the backend within a fixed scope.
+
+    Upon entering the ``with`` statement, the given backend will be added to
+    the list of available backends with the highest priority. Upon exit, the
+    backend is reset to the state before entering the scope.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool, optional
+        Whether to allow expensive conversions for the ``x`` parameter. e.g.,
+        copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
+    only : bool, optional
+        If only is ``True`` and this backend returns ``NotImplemented``, then a
+        BackendNotImplemented error will be raised immediately. Ignoring any
+        lower priority backends.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> with fft.set_backend('scipy', only=True):
+    ...     fft.fft([1])  # Always calls the scipy implementation
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    return ua.set_backend(backend, coerce=coerce, only=only)
+
+
+@xp_capabilities(out_of_scope=True)
+def skip_backend(backend):
+    """Context manager to skip a backend within a fixed scope.
+
+    Within the context of a ``with`` statement, the given backend will not be
+    called. This covers backends registered both locally and globally. Upon
+    exit, the backend will again be considered.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to skip.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    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/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_basic.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..6929fbaf792933122cf244944e904818d574864c
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_basic.py
@@ -0,0 +1,1670 @@
+from scipy._lib.uarray import generate_multimethod, Dispatchable
+from scipy._lib._array_api import xp_capabilities
+
+import numpy as np
+
+
+def _x_replacer(args, kwargs, dispatchables):
+    """
+    uarray argument replacer to replace the transform input array (``x``)
+    """
+    if len(args) > 0:
+        return (dispatchables[0],) + args[1:], kwargs
+    kw = kwargs.copy()
+    kw['x'] = dispatchables[0]
+    return args, kw
+
+
+def _dispatch(func):
+    """
+    Function annotation that creates a uarray multimethod from the function
+    """
+    return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft")
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+        plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) with the efficient Fast Fourier Transform (FFT)
+    algorithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode. Default is "backward", meaning no normalization on
+        the forward transforms and scaling by ``1/n`` on the `ifft`.
+        "forward" instead applies the ``1/n`` factor on the forward transform.
+        For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``.
+
+        .. versionadded:: 1.6.0
+           ``norm={"forward", "backward"}`` options were added
+
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See the notes below for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``. See below for more
+        details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        if `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    ifft : The inverse of `fft`.
+    fft2 : The 2-D FFT.
+    fftn : The N-D FFT.
+    rfftn : The N-D FFT of real input.
+    fftfreq : Frequency bins for given FFT parameters.
+    next_fast_len : Size to pad input to for most efficient transforms
+
+    Notes
+    -----
+    FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform
+    (DFT) can be calculated efficiently, by using symmetries in the calculated
+    terms. The symmetry is highest when `n` is a power of 2, and the transform
+    is therefore most efficient for these sizes. For poorly factorizable sizes,
+    `scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than
+    O(`n` log `n`). Further performance improvements may be seen by zero-padding
+    the input using `next_fast_len`.
+
+    If ``x`` is a 1d array, then the `fft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))
+
+    The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach
+    the Nyquist frequency and wrap around to the negative-frequency terms. So,
+    for an 8-point transform, the frequencies of the result are
+    [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the
+    zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3],
+    use `fftshift`.
+
+    Transforms can be done in single, double, or extended precision (long
+    double) floating point. Half precision inputs will be converted to single
+    precision and non-floating-point inputs will be converted to double
+    precision.
+
+    If the data type of ``x`` is real, a "real FFT" algorithm is automatically
+    used, which roughly halves the computation time. To increase efficiency
+    a little further, use `rfft`, which does the same calculation, but only
+    outputs half of the symmetrical spectrum. If the data are both real and
+    symmetrical, the `dct` can again double the efficiency, by generating
+    half of the spectrum from half of the signal.
+
+    When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may
+    be used by the implementation in any way. This may include reusing the
+    memory for the result, but this is in no way guaranteed. You should not
+    rely on the contents of ``x`` after the transform as this may change in
+    future without warning.
+
+    The ``workers`` argument specifies the maximum number of parallel jobs to
+    split the FFT computation into. This will execute independent 1-D
+    FFTs within ``x``. So, ``x`` must be at least 2-D and the
+    non-transformed axes must be large enough to split into chunks. If ``x`` is
+    too small, fewer jobs may be used than requested.
+
+    References
+    ----------
+    .. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
+           machine calculation of complex Fourier series," *Math. Comput.*
+           19: 297-301.
+    .. [2] Bluestein, L., 1970, "A linear filtering approach to the
+           computation of discrete Fourier transform". *IEEE Transactions on
+           Audio and Electroacoustics.* 18 (4): 451-455.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
+    array([-2.33486982e-16+1.14423775e-17j,  8.00000000e+00-1.25557246e-15j,
+            2.33486982e-16+2.33486982e-16j,  0.00000000e+00+1.22464680e-16j,
+           -1.14423775e-17+2.33486982e-16j,  0.00000000e+00+5.20784380e-16j,
+            1.14423775e-17+1.14423775e-17j,  0.00000000e+00+1.22464680e-16j])
+
+    In this example, real input has an FFT which is Hermitian, i.e., symmetric
+    in the real part and anti-symmetric in the imaginary part:
+
+    >>> from scipy.fft import fft, fftfreq, fftshift
+    >>> import matplotlib.pyplot as plt
+    >>> t = np.arange(256)
+    >>> sp = fftshift(fft(np.sin(t)))
+    >>> freq = fftshift(fftfreq(t.shape[-1]))
+    >>> plt.plot(freq, sp.real, freq, sp.imag)
+    [,
+     ]
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier transform computed by `fft`.  In other words,
+    ``ifft(fft(x)) == x`` to within numerical accuracy.
+
+    The input should be ordered in the same way as is returned by `fft`,
+    i.e.,
+
+    * ``x[0]`` should contain the zero frequency term,
+    * ``x[1:n//2]`` should contain the positive-frequency terms,
+    * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
+      increasing order starting from the most negative frequency.
+
+    For an even number of input points, ``x[n//2]`` represents the sum of
+    the values at the positive and negative Nyquist frequencies, as the two
+    are aliased together. See `fft` for details.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+        See notes about padding issues.
+    axis : int, optional
+        Axis over which to compute the inverse DFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        If `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    fft : The 1-D (forward) FFT, of which `ifft` is the inverse.
+    ifft2 : The 2-D inverse FFT.
+    ifftn : The N-D inverse FFT.
+
+    Notes
+    -----
+    If the input parameter `n` is larger than the size of the input, the input
+    is padded by appending zeros at the end. Even though this is the common
+    approach, it might lead to surprising results. If a different padding is
+    desired, it must be performed before calling `ifft`.
+
+    If ``x`` is a 1-D array, then the `ifft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)
+
+    As with `fft`, `ifft` has support for all floating point types and is
+    optimized for real input.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.ifft([0, 4, 0, 0])
+    array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j]) # may vary
+
+    Create and plot a band-limited signal with random phases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> t = np.arange(400)
+    >>> n = np.zeros((400,), dtype=complex)
+    >>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,)))
+    >>> s = scipy.fft.ifft(n)
+    >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
+    [, ]
+    >>> plt.legend(('real', 'imaginary'))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform for real input.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) of a real-valued array by means of an efficient algorithm
+    called the Fast Fourier Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array
+    n : int, optional
+        Number of points along transformation axis in the input to use.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        If `n` is even, the length of the transformed axis is ``(n/2)+1``.
+        If `n` is odd, the length is ``(n+1)/2``.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    irfft : The inverse of `rfft`.
+    fft : The 1-D FFT of general (complex) input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+    rfftn : The N-D FFT of real input.
+
+    Notes
+    -----
+    When the DFT is computed for purely real input, the output is
+    Hermitian-symmetric, i.e., the negative frequency terms are just the complex
+    conjugates of the corresponding positive-frequency terms, and the
+    negative-frequency terms are therefore redundant. This function does not
+    compute the negative frequency terms, and the length of the transformed
+    axis of the output is therefore ``n//2 + 1``.
+
+    When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains
+    the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
+
+    If `n` is even, ``A[-1]`` contains the term representing both positive
+    and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
+    real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
+    the largest positive frequency (fs/2*(n-1)/n), and is complex in the
+    general case.
+
+    If the input `a` contains an imaginary part, it is silently discarded.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.fft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j,  0.+1.j]) # may vary
+    >>> scipy.fft.rfft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j]) # may vary
+
+    Notice how the final element of the `fft` output is the complex conjugate
+    of the second element, for real input. For `rfft`, this symmetry is
+    exploited to compute only the non-negative frequency terms.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Computes the inverse of `rfft`.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier Transform of real input computed by `rfft`.
+    In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical
+    accuracy. (See Notes below for why ``len(a)`` is necessary here.)
+
+    The input is expected to be in the form returned by `rfft`, i.e., the
+    real zero-frequency term followed by the complex positive frequency terms
+    in order of increasing frequency. Since the discrete Fourier Transform of
+    real input is Hermitian-symmetric, the negative frequency terms are taken
+    to be the complex conjugates of the corresponding positive frequency terms.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output.
+        For `n` output points, ``n//2+1`` input points are necessary. If the
+        input is longer than this, it is cropped. If it is shorter than this,
+        it is padded with zeros. If `n` is not given, it is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along the axis
+        specified by `axis`.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
+        input. To get an odd number of output points, `n` must be specified.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    rfft : The 1-D FFT of real input, of which `irfft` is inverse.
+    fft : The 1-D FFT.
+    irfft2 : The inverse of the 2-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    Returns the real valued `n`-point inverse discrete Fourier transform
+    of `x`, where `x` contains the non-negative frequency terms of a
+    Hermitian-symmetric sequence. `n` is the length of the result, not the
+    input.
+
+    If you specify an `n` such that `a` must be zero-padded or truncated, the
+    extra/removed values will be added/removed at high frequencies. One can
+    thus resample a series to `m` points via Fourier interpolation by:
+    ``a_resamp = irfft(rfft(a), m)``.
+
+    The default value of `n` assumes an even output length. By the Hermitian
+    symmetry, the last imaginary component must be 0 and so is ignored. To
+    avoid losing information, the correct length of the real input *must* be
+    given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.ifft([1, -1j, -1, 1j])
+    array([0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]) # may vary
+    >>> scipy.fft.irfft([1, -1j, -1])
+    array([0.,  1.,  0.,  0.])
+
+    Notice how the last term in the input to the ordinary `ifft` is the
+    complex conjugate of the second term, and the output has zero imaginary
+    part everywhere. When calling `irfft`, the negative frequencies are not
+    specified, and the output array is purely real.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
+    spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output. For `n` output
+        points, ``n//2 + 1`` input points are necessary. If the input is
+        longer than this, it is cropped. If it is shorter than this, it is
+        padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``,
+        where ``m`` is the length of the input along the axis specified by
+        `axis`.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*m - 2``, where ``m`` is the length of the transformed axis of
+        the input. To get an odd number of output points, `n` must be
+        specified, for instance, as ``2*m - 1`` in the typical case,
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    rfft : Compute the 1-D FFT for real input.
+    ihfft : The inverse of `hfft`.
+    hfftn : Compute the N-D FFT of a Hermitian signal.
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd.
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import fft, hfft
+    >>> import numpy as np
+    >>> a = 2 * np.pi * np.arange(10) / 10
+    >>> signal = np.cos(a) + 3j * np.sin(3 * a)
+    >>> fft(signal).round(10)
+    array([ -0.+0.j,   5.+0.j,  -0.+0.j,  15.-0.j,   0.+0.j,   0.+0.j,
+            -0.+0.j, -15.-0.j,   0.+0.j,   5.+0.j])
+    >>> hfft(signal[:6]).round(10) # Input first half of signal
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    >>> hfft(signal, 10)  # Input entire signal and truncate
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the inverse FFT of a signal that has Hermitian symmetry.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    n : int, optional
+        Length of the inverse FFT, the number of points along
+        transformation axis in the input to use.  If `n` is smaller than
+        the length of the input, the input is cropped. If it is larger,
+        the input is padded with zeros. If `n` is not given, the length of
+        the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is ``n//2 + 1``.
+
+    See Also
+    --------
+    hfft, irfft
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here, the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd:
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import ifft, ihfft
+    >>> import numpy as np
+    >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
+    >>> ifft(spectrum)
+    array([1.+0.j,  2.+0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.+0.j]) # may vary
+    >>> ihfft(spectrum)
+    array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j]) # may vary
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the N-D discrete Fourier Transform.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D array by means of the Fast Fourier
+    Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifftn : The inverse of `fftn`, the inverse N-D FFT.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfftn : The N-D FFT of real input.
+    fft2 : The 2-D FFT.
+    fftshift : Shifts zero-frequency terms to centre of array.
+
+    Notes
+    -----
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of all axes, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:3, :3, :3][0]
+    >>> scipy.fft.fftn(x, axes=(1, 2))
+    array([[[ 0.+0.j,   0.+0.j,   0.+0.j], # may vary
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[ 9.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[18.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]]])
+    >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1))
+    array([[[ 2.+0.j,  2.+0.j,  2.+0.j], # may vary
+            [ 0.+0.j,  0.+0.j,  0.+0.j]],
+           [[-2.+0.j, -2.+0.j, -2.+0.j],
+            [ 0.+0.j,  0.+0.j,  0.+0.j]]])
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
+    ...                      2 * np.pi * np.arange(200) / 34)
+    >>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape)
+    >>> FS = scipy.fft.fftn(S)
+    >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform over any number of axes in an M-D array by
+    means of the Fast Fourier Transform (FFT).  In other words,
+    ``ifftn(fftn(x)) == x`` to within numerical accuracy.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fftn`, i.e., it should have the term for zero frequency
+    in all axes in the low-order corner, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``ifft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used. See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the IFFT.  If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fftn : The forward N-D FFT, of which `ifftn` is the inverse.
+    ifft : The 1-D inverse FFT.
+    ifft2 : The 2-D inverse FFT.
+    ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
+        of array.
+
+    Notes
+    -----
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifftn` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.eye(4)
+    >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,))
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j]])
+
+
+    Create and plot an image with band-limited frequency content:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> n = np.zeros((200,200), dtype=complex)
+    >>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20)))
+    >>> im = scipy.fft.ifftn(n).real
+    >>> plt.imshow(im)
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 2-D discrete Fourier Transform
+
+    This function computes the N-D discrete Fourier Transform
+    over any axes in an M-D array by means of the
+    Fast Fourier Transform (FFT). By default, the transform is computed over
+    the last two axes of the input array, i.e., a 2-dimensional FFT.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two axes are
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifft2 : The inverse 2-D FFT.
+    fft : The 1-D FFT.
+    fftn : The N-D FFT.
+    fftshift : Shifts zero-frequency terms to the center of the array.
+        For 2-D input, swaps first and third quadrants, and second
+        and fourth quadrants.
+
+    Notes
+    -----
+    `fft2` is just `fftn` with a different default for `axes`.
+
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of the transformed axes, the positive frequency terms
+    in the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    the axes, in order of decreasingly negative frequency.
+
+    See `fftn` for details and a plotting example, and `fft` for
+    definitions and conventions used.
+
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:5, :5][0]
+    >>> scipy.fft.fft2(x)
+    array([[ 50.  +0.j        ,   0.  +0.j        ,   0.  +0.j        , # may vary
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5+17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 +4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 -4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5-17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 2-D discrete Fourier
+    Transform over any number of axes in an M-D array by means of
+    the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
+    to within numerical accuracy. By default, the inverse transform is
+    computed over the last two axes of the input array.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fft2`, i.e., it should have the term for zero frequency
+    in the low-order corner of the two axes, the positive frequency terms in
+    the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    both axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
+        ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.  See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two
+        axes are used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fft2 : The forward 2-D FFT, of which `ifft2` is the inverse.
+    ifftn : The inverse of the N-D FFT.
+    fft : The 1-D FFT.
+    ifft : The 1-D inverse FFT.
+
+    Notes
+    -----
+    `ifft2` is just `ifftn` with a different default for `axes`.
+
+    See `ifftn` for details and a plotting example, and `fft` for
+    definition and conventions used.
+
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifft2` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = 4 * np.eye(4)
+    >>> scipy.fft.ifft2(x)
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D discrete Fourier Transform for real input.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining
+    transforms are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
+        for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT
+         of real input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : The 1-D FFT of real input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `rfft`, then the transform over the remaining axes is
+    performed as by `fftn`. The order of the output is as for `rfft` for the
+    final transformation axis, and as for `fftn` for the remaining
+    transformation axes.
+
+    See `fft` for details, definitions and conventions used.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.rfftn(x)
+    array([[[8.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    >>> scipy.fft.rfftn(x, axes=(2, 0))
+    array([[[4.+0.j,  0.+0.j], # may vary
+            [4.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a real array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape of the FFT.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the real 2-D FFT.
+
+    See Also
+    --------
+    irfft2 : The inverse of the 2-D FFT of real input.
+    rfft : The 1-D FFT of real input.
+    rfftn : Compute the N-D discrete Fourier Transform for real
+            input.
+
+    Notes
+    -----
+    This is really just `rfftn` with different default behavior.
+    For more details see `rfftn`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.broadcast_to([1, 0, -1, 0], (4, 4))
+    >>> scipy.fft.rfft2(x)
+    array([[0.+0.j, 8.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfftn`
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform for real input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In
+    other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
+    accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
+    and for the same reason.)
+
+    The input should be ordered in the same way as is returned by `rfftn`,
+    i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
+    along all the other axes.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given. In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the
+        length of the final transformed axis of the input. To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    rfftn : The forward N-D FFT of real input,
+            of which `ifftn` is the inverse.
+    fft : The 1-D FFT, with definitions and conventions used.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfft2 : The inverse of the 2-D FFT of real input.
+
+    Notes
+    -----
+    See `fft` for definitions and conventions used.
+
+    See `rfft` for definitions and conventions used for real input.
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.zeros((3, 2, 2))
+    >>> x[0, 0, 0] = 3 * 2 * 2
+    >>> scipy.fft.irfftn(x)
+    array([[[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfft2`
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real output to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    rfft2 : The 2-D FFT of real input.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    This is really `irfftn` with different defaults.
+    For more details see `irfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
+    signal with a real spectrum.
+
+    This function computes the N-D discrete Fourier Transform for a
+    Hermitian symmetric complex input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In other
+    words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s``
+    here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary
+    for the same reason ``x.shape`` would be necessary for `irfft`.)
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)`` where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given.  In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
+        length of the final transformed axis of the input.  To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : Forward FFT of real input.
+
+    Notes
+    -----
+    For a 1-D signal ``x`` to have a real spectrum, it must satisfy
+    the Hermitian property::
+
+        x[i] == np.conj(x[-i]) for all i
+
+    This generalizes into higher dimensions by reflecting over each axis in
+    turn::
+
+        x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ...
+
+    This should not be confused with a Hermitian matrix, for which the
+    transpose is its own conjugate::
+
+        x[i, j] == np.conj(x[j, i]) for all i, j
+
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((3, 2, 2))
+    >>> scipy.fft.hfftn(x)
+    array([[[12.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a Hermitian complex array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be Hermitian complex.
+    s : sequence of ints, optional
+        Shape of the real output.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The real result of the 2-D Hermitian complex real FFT.
+
+    See Also
+    --------
+    hfftn : Compute the N-D discrete Fourier Transform for Hermitian
+            complex input.
+
+    Notes
+    -----
+    This is really just `hfftn` with different default behavior.
+    For more details see `hfftn`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.array([[1+0j, 2+0j], [2+0j, 1+0j]])  # Hermitian-symmetric input
+    >>> scipy.fft.hfft2(x, s=(2, 2))
+    array([[ 6.,  0.],
+           [ 0., -2.]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform for a real
+    spectrum.
+
+    This function computes the N-D inverse discrete Fourier Transform
+    over any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining transforms
+    are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    hfftn : The forward N-D FFT of Hermitian input.
+    hfft : The 1-D FFT of Hermitian input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    fftn : The N-D FFT.
+    hfft2 : The 2-D FFT of Hermitian input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `ihfft`, then the transform over the remaining axes is
+    performed as by `ifftn`. The order of the output is the positive part of
+    the Hermitian output signal, in the same format as `rfft`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.ihfftn(x)
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+    >>> scipy.fft.ihfftn(x, axes=(2, 0))
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [1.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the 2-D inverse FFT of a real spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real input to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    ihfftn : Compute the inverse of the N-D FFT of Hermitian input.
+
+    Notes
+    -----
+    This is really `ihfftn` with different defaults.
+    For more details see `ihfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_basic_backend.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_basic_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..3549631eefb75669fd39cdad6a5252fc20ac2de4
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_debug_backends.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_debug_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a09866e5b4f647c7de3c5292afece0a7a0d3378
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_fftlog.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..01bd1dccedb2e164b1368e5b609b7bef84b05033
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_fftlog.py
@@ -0,0 +1,227 @@
+"""Fast Hankel transforms using the FFTLog algorithm.
+
+The implementation closely follows the Fortran code of Hamilton (2000).
+
+added: 14/11/2020 Nicolas Tessore 
+"""
+
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+from ._fftlog_backend import fhtoffset
+from scipy._lib._array_api import xp_capabilities
+
+import numpy as np
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    r'''Compute the fast Hankel transform.
+
+    Computes the discrete Hankel transform of a logarithmically spaced periodic
+    sequence using the FFTLog algorithm [1]_, [2]_.
+
+    Parameters
+    ----------
+    a : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    A : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    ifht : The inverse of `fht`.
+    fhtoffset : Return an optimal offset for `fht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a(r) \, J_\mu(kr) \, k \, dr \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative.  Note that the
+    numerical Hankel transform uses an integrand of :math:`k \, dr`, while the
+    mathematical Hankel transform is commonly defined using :math:`r \, dr`.
+
+    The input array `a` is a periodic sequence of length :math:`n`, uniformly
+    logarithmically spaced with spacing `dln`,
+
+    .. math::
+
+        a_j = a(r_j) \;, \quad
+        r_j = r_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`r_c`.  Note that the central index
+    :math:`j_c = (n-1)/2` is half-integral if :math:`n` is even, so that
+    :math:`r_c` falls between two input elements.  Similarly, the output
+    array `A` is a periodic sequence of length :math:`n`, also uniformly
+    logarithmically spaced with spacing `dln`
+
+    .. math::
+
+       A_j = A(k_j) \;, \quad
+       k_j = k_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`k_c`.
+
+    The centre points :math:`r_c` and :math:`k_c` of the periodic intervals may
+    be chosen arbitrarily, but it would be usual to choose the product
+    :math:`k_c r_c = k_j r_{n-1-j} = k_{n-1-j} r_j` to be unity.  This can be
+    changed using the `offset` parameter, which controls the logarithmic offset
+    :math:`\log(k_c) = \mathtt{offset} - \log(r_c)` of the output array.
+    Choosing an optimal value for `offset` may reduce ringing of the discrete
+    Hankel transform.
+
+    If the `bias` parameter is nonzero, this function computes a discrete
+    version of the biased Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a_q(r) \, (kr)^q \, J_\mu(kr) \, k \, dr
+
+    where :math:`q` is the value of `bias`, and a power law bias
+    :math:`a_q(r) = a(r) \, (kr)^{-q}` is applied to the input sequence.
+    Biasing the transform can help approximate the continuous transform of
+    :math:`a(r)` if there is a value :math:`q` such that :math:`a_q(r)` is
+    close to a periodic sequence, in which case the resulting :math:`A(k)` will
+    be close to the continuous transform.
+
+    References
+    ----------
+    .. [1] Talman J. D., 1978, J. Comp. Phys., 29, 35
+    .. [2] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    Examples
+    --------
+
+    This example is the adapted version of ``fftlogtest.f`` which is provided
+    in [2]_. It evaluates the integral
+
+    .. math::
+
+        \int^\infty_0 r^{\mu+1} \exp(-r^2/2) J_\mu(kr) k dr
+        = k^{\mu+1} \exp(-k^2/2) .
+
+    >>> import numpy as np
+    >>> from scipy import fft
+    >>> import matplotlib.pyplot as plt
+
+    Parameters for the transform.
+
+    >>> mu = 0.0                     # Order mu of Bessel function
+    >>> r = np.logspace(-7, 1, 128)  # Input evaluation points
+    >>> dln = np.log(r[1]/r[0])      # Step size
+    >>> offset = fft.fhtoffset(dln, initial=-6*np.log(10), mu=mu)
+    >>> k = np.exp(offset)/r[::-1]   # Output evaluation points
+
+    Define the analytical function.
+
+    >>> def f(x, mu):
+    ...     """Analytical function: x^(mu+1) exp(-x^2/2)."""
+    ...     return x**(mu + 1)*np.exp(-x**2/2)
+
+    Evaluate the function at ``r`` and compute the corresponding values at
+    ``k`` using FFTLog.
+
+    >>> a_r = f(r, mu)
+    >>> fht = fft.fht(a_r, dln, mu=mu, offset=offset)
+
+    For this example we can actually compute the analytical response (which in
+    this case is the same as the input function) for comparison and compute the
+    relative error.
+
+    >>> a_k = f(k, mu)
+    >>> rel_err = abs((fht-a_k)/a_k)
+
+    Plot the result.
+
+    >>> figargs = {'sharex': True, 'sharey': True, 'constrained_layout': True}
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), **figargs)
+    >>> ax1.set_title(r'$r^{\mu+1}\ \exp(-r^2/2)$')
+    >>> ax1.loglog(r, a_r, 'k', lw=2)
+    >>> ax1.set_xlabel('r')
+    >>> ax2.set_title(r'$k^{\mu+1} \exp(-k^2/2)$')
+    >>> ax2.loglog(k, a_k, 'k', lw=2, label='Analytical')
+    >>> ax2.loglog(k, fht, 'C3--', lw=2, label='FFTLog')
+    >>> ax2.set_xlabel('k')
+    >>> ax2.legend(loc=3, framealpha=1)
+    >>> ax2.set_ylim([1e-10, 1e1])
+    >>> ax2b = ax2.twinx()
+    >>> ax2b.loglog(k, rel_err, 'C0', label='Rel. Error (-)')
+    >>> ax2b.set_ylabel('Rel. Error (-)', color='C0')
+    >>> ax2b.tick_params(axis='y', labelcolor='C0')
+    >>> ax2b.legend(loc=4, framealpha=1)
+    >>> ax2b.set_ylim([1e-9, 1e-3])
+    >>> plt.show()
+
+    '''
+    return (Dispatchable(a, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    r"""Compute the inverse fast Hankel transform.
+
+    Computes the discrete inverse Hankel transform of a logarithmically spaced
+    periodic sequence. This is the inverse operation to `fht`.
+
+    Parameters
+    ----------
+    A : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    a : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+    fhtoffset : Return an optimal offset for `ifht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        a(r) = \int_{0}^{\infty} \! A(k) \, J_\mu(kr) \, r \, dk \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative. Note that the
+    numerical inverse Hankel transform uses an integrand of :math:`r \, dk`, while the
+    mathematical inverse Hankel transform is commonly defined using :math:`k \, dk`.
+
+    See `fht` for further details.
+    """
+    return (Dispatchable(A, np.ndarray),)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_fftlog_backend.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_fftlog_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a155b0233526929f08dc387e2d3073e44c240
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_fftlog_backend.py
@@ -0,0 +1,201 @@
+import numpy as np
+from warnings import warn
+from ._basic import rfft, irfft
+from ..special import loggamma, poch
+
+from scipy._lib._array_api import array_namespace, xp_capabilities
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+# constants
+LN_2 = np.log(2)
+
+
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(a)
+    a = xp.asarray(a)
+
+    # size of transform
+    n = a.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # a_q(r) = a(r) (r/r_c)^{-q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        a = a * xp.exp(-bias*(j - j_c)*dln)
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias))
+
+    # transform
+    A = _fhtq(a, u, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # A(k) = A_q(k) (k/k_c)^{-q} (k_c r_c)^{-q}
+        A *= xp.exp(-bias*((j - j_c)*dln + offset))
+
+    return A
+
+
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(A)
+    A = xp.asarray(A)
+
+    # size of transform
+    n = A.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # A_q(k) = A(k) (k/k_c)^{q} (k_c r_c)^{q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        A = A * xp.exp(bias*((j - j_c)*dln + offset))
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias, inverse=True))
+
+    # transform
+    a = _fhtq(A, u, inverse=True, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # a(r) = a_q(r) (r/r_c)^{q}
+        a /= xp.exp(-bias*(j - j_c)*dln)
+
+    return a
+
+
+def fhtcoeff(n, dln, mu, offset=0.0, bias=0.0, inverse=False):
+    """Compute the coefficient array for a fast Hankel transform."""
+    lnkr, q = offset, bias
+
+    # Hankel transform coefficients
+    # u_m = (kr)^{-i 2m pi/(n dlnr)} U_mu(q + i 2m pi/(n dlnr))
+    # with U_mu(x) = 2^x Gamma((mu+1+x)/2)/Gamma((mu+1-x)/2)
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.linspace(0, np.pi*(n//2)/(n*dln), n//2+1)
+    u = np.empty(n//2+1, dtype=complex)
+    v = np.empty(n//2+1, dtype=complex)
+    u.imag[:] = y
+    u.real[:] = xm
+    loggamma(u, out=v)
+    u.real[:] = xp
+    loggamma(u, out=u)
+    y *= 2*(LN_2 - lnkr)
+    u.real -= v.real
+    u.real += LN_2*q
+    u.imag += v.imag
+    u.imag += y
+    np.exp(u, out=u)
+
+    # fix last coefficient to be real
+    if n % 2 == 0:
+        u.imag[-1] = 0
+
+    # deal with special cases
+    if not np.isfinite(u[0]):
+        # write u_0 = 2^q Gamma(xp)/Gamma(xm) = 2^q poch(xm, xp-xm)
+        # poch() handles special cases for negative integers correctly
+        u[0] = 2**q * poch(xm, xp-xm)
+        # the coefficient may be inf or 0, meaning the transform or the
+        # inverse transform, respectively, is singular
+
+    # check for singular transform or singular inverse transform
+    if np.isinf(u[0]) and not inverse:
+        warn('singular transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) transform anyway
+        u = np.copy(u)
+        u[0] = 0
+    elif u[0] == 0 and inverse:
+        warn('singular inverse transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) inverse anyway
+        u = np.copy(u)
+        u[0] = np.inf
+
+    return u
+
+
+@xp_capabilities(out_of_scope=True)
+def fhtoffset(dln, mu, initial=0.0, bias=0.0):
+    """Return optimal offset for a fast Hankel transform.
+
+    Returns an offset close to `initial` that fulfils the low-ringing
+    condition of [1]_ for the fast Hankel transform `fht` with logarithmic
+    spacing `dln`, order `mu` and bias `bias`.
+
+    Parameters
+    ----------
+    dln : float
+        Uniform logarithmic spacing of the transform.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    initial : float, optional
+        Initial value for the offset. Returns the closest value that fulfils
+        the low-ringing condition.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    offset : float
+        Optimal offset of the uniform logarithmic spacing of the transform that
+        fulfils a low-ringing condition.
+
+    Examples
+    --------
+    >>> from scipy.fft import fhtoffset
+    >>> dln = 0.1
+    >>> mu = 2.0
+    >>> initial = 0.5
+    >>> bias = 0.0
+    >>> offset = fhtoffset(dln, mu, initial, bias)
+    >>> offset
+    0.5454581477676637
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+
+    References
+    ----------
+    .. [1] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    """
+
+    lnkr, q = initial, bias
+
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.pi/(2*dln)
+    zp = loggamma(xp + 1j*y)
+    zm = loggamma(xm + 1j*y)
+    arg = (LN_2 - lnkr)/dln + (zp.imag + zm.imag)/np.pi
+    return lnkr + (arg - np.round(arg))*dln
+
+
+def _fhtq(a, u, inverse=False, *, xp=None):
+    """Compute the biased fast Hankel transform.
+
+    This is the basic FFTLog routine.
+    """
+    if xp is None:
+        xp = np
+
+    # size of transform
+    n = a.shape[-1]
+
+    # biased fast Hankel transform via real FFT
+    A = rfft(a, axis=-1)
+    if not inverse:
+        # forward transform
+        A *= u
+    else:
+        # backward transform
+        A /= xp.conj(u)
+    A = irfft(A, n, axis=-1)
+    A = xp.flip(A, axis=-1)
+
+    return A
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_helper.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4664235cc44267f5e86626849da0b8eb3f09ddd
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_helper.py
@@ -0,0 +1,355 @@
+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
+from scipy._lib._array_api import xp_capabilities
+
+
+_init_nd_shape_and_axes = _helper._init_nd_shape_and_axes
+
+
+def next_fast_len(target, real=False):
+    """Find the next fast size of input data to ``fft``, for zero-padding, etc.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    >= ``target`` with only prime factors < `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The smallest fast length greater than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 11.4 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fft.fft(a)
+
+    Zero-padding to the next regular length reduces computation time to
+    1.6 ms, a speedup of 7.3 times:
+
+    >>> fft.next_fast_len(min_len, real=True)
+    93312
+    >>> b = fft.fft(a, 93312)
+
+    Rounding up to the next power of 2 is not optimal, taking 3.0 ms to
+    compute; 1.9 times longer than the size given by ``next_fast_len``:
+
+    >>> b = fft.fft(a, 131072)
+
+    """
+    pass
+
+
+# Directly wrap the c-function good_size but take the docstring etc., from the
+# next_fast_len function above
+_sig = inspect.signature(next_fast_len)
+next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len)
+next_fast_len = xp_capabilities(out_of_scope=True)(next_fast_len)
+next_fast_len.__wrapped__ = _helper.good_size
+next_fast_len.__signature__ = _sig
+
+
+def prev_fast_len(target, real=False):
+    """Find the previous fast size of input data to ``fft``.
+    Useful for discarding a minimal number of samples before FFT.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    <= ``target`` with only prime factors <= `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Maximum length to search until. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The largest fast length less than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    In the current implementation, prev_fast_len assumes radices of
+    2,3,5,7,11 for complex FFT and 2,3,5 for real FFT.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 16.2 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> max_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(max_len)
+    >>> b = fft.fft(a)
+
+    Performing FFT on the maximum fast length less than max_len
+    reduces the computation time to 1.5 ms, a speedup of 10.5 times:
+
+    >>> fft.prev_fast_len(max_len, real=True)
+    92160
+    >>> c = fft.fft(a[:92160]) # discard last 899 samples
+
+    """
+    pass
+
+
+# Directly wrap the c-function prev_good_size but take the docstring etc.,
+# from the prev_fast_len function above
+_sig_prev_fast_len = inspect.signature(prev_fast_len)
+prev_fast_len = update_wrapper(lru_cache()(_helper.prev_good_size), prev_fast_len)
+prev_fast_len = xp_capabilities(out_of_scope=True)(prev_fast_len)
+prev_fast_len.__wrapped__ = _helper.prev_good_size
+prev_fast_len.__signature__ = _sig_prev_fast_len
+
+
+@xp_capabilities()
+def fftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies.
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.fftfreq` implements the device parameter.
+
+    Returns
+    -------
+    f : ndarray
+        Array of length `n` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> fourier = scipy.fft.fft(signal)
+    >>> n = signal.size
+    >>> timestep = 0.1
+    >>> freq = scipy.fft.fftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  2.5 , ..., -3.75, -2.5 , -1.25])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.fftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.fftfreq(n, d=d)
+
+
+@xp_capabilities()
+def rfftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies
+    (for usage with rfft, irfft).
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd
+
+    Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
+    the Nyquist frequency component is considered to be positive.
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.rfftfreq` implements the device parameter.
+
+    Returns
+    -------
+    f : ndarray
+        Array of length ``n//2 + 1`` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
+    >>> fourier = scipy.fft.rfft(signal)
+    >>> n = signal.size
+    >>> sample_rate = 100
+    >>> freq = scipy.fft.fftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20., ..., -30., -20., -10.])
+    >>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20.,  30.,  40.,  50.])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.rfftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.rfftfreq(n, d=d)
+
+
+@xp_capabilities()
+def fftshift(x, axes=None):
+    """Shift the zero-frequency component to the center of the spectrum.
+
+    This function swaps half-spaces for all axes listed (defaults to all).
+    Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to shift.  Default is None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    ifftshift : The inverse of `fftshift`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(10, 0.1)
+    >>> freqs
+    array([ 0.,  1.,  2., ..., -3., -2., -1.])
+    >>> np.fft.fftshift(freqs)
+    array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+
+    Shift the zero-frequency component only along the second axis:
+
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.fftshift(freqs, axes=(1,))
+    array([[ 2.,  0.,  1.],
+           [-4.,  3.,  4.],
+           [-1., -3., -2.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.fftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.fftshift(x, axes=axes)
+    return xp.asarray(y)
+
+
+@xp_capabilities()
+def ifftshift(x, axes=None):
+    """The inverse of `fftshift`. Although identical for even-length `x`, the
+    functions differ by one sample for odd-length `x`.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to calculate.  Defaults to None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    fftshift : Shift zero-frequency component to the center of the spectrum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.ifftshift(np.fft.fftshift(freqs))
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.ifftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.ifftshift(x, axes=axes)
+    return xp.asarray(y)
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c792b8c23a0fc76098950623875e45427d848077
--- /dev/null
+++ b/loan-advisor-agent/.venv/Lib/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/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8d6ea06e4a42a803400731d53201c7da76a045b
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-312.pyc differ
diff --git a/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15b8acdac2402e142ef551da084b80f2ec717bbd
Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-312.pyc differ