techprotrade commited on
Commit
23b367b
·
verified ·
1 Parent(s): 1dd739d

Add loan-advisor-agent

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +7 -0
  2. loan-advisor-agent/.venv/Lib/site-packages/scipy/__config__.py +173 -0
  3. loan-advisor-agent/.venv/Lib/site-packages/scipy/__init__.py +150 -0
  4. loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__config__.cpython-312.pyc +0 -0
  5. loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__init__.cpython-312.pyc +0 -0
  6. loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc +0 -0
  7. loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/version.cpython-312.pyc +0 -0
  8. loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.dll.a +0 -0
  9. loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd +3 -0
  10. loan-advisor-agent/.venv/Lib/site-packages/scipy/_distributor_init.py +18 -0
  11. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__init__.py +14 -0
  12. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc +0 -0
  13. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc +0 -0
  14. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc +0 -0
  15. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc +0 -0
  16. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pyc +0 -0
  17. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc +0 -0
  18. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc +0 -0
  19. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc +0 -0
  20. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pyc +0 -0
  21. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc +0 -0
  22. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc +0 -0
  23. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc +0 -0
  24. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc +0 -0
  25. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pyc +0 -0
  26. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc +0 -0
  27. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api.py +1036 -0
  28. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_compat_vendor.py +9 -0
  29. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_docs_tables.py +294 -0
  30. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_no_0d.py +103 -0
  31. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_override.py +150 -0
  32. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_bunch.py +229 -0
  33. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback.py +251 -0
  34. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a +0 -0
  35. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd +3 -0
  36. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_disjoint_set.py +254 -0
  37. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_docscrape.py +761 -0
  38. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py +346 -0
  39. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a +0 -0
  40. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.pyd +0 -0
  41. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_gcutils.py +105 -0
  42. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_pep440.py +487 -0
  43. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_public_api.py +56 -0
  44. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_sparse.py +41 -0
  45. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a +0 -0
  46. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.pyd +0 -0
  47. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a +0 -0
  48. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.pyd +0 -0
  49. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a +0 -0
  50. loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.pyd +0 -0
.gitattributes CHANGED
@@ -555,3 +555,10 @@ loan-advisor-agent/.venv/Lib/site-packages/regex/__pycache__/_regex_core.cpython
555
  loan-advisor-agent/.venv/Lib/site-packages/regex/_regex.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
556
  loan-advisor-agent/.venv/Lib/site-packages/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
557
  loan-advisor-agent/.venv/Lib/site-packages/rpds/rpds.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
555
  loan-advisor-agent/.venv/Lib/site-packages/regex/_regex.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
556
  loan-advisor-agent/.venv/Lib/site-packages/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
557
  loan-advisor-agent/.venv/Lib/site-packages/rpds/rpds.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
558
+ loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
559
+ loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
560
+ loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
561
+ loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
562
+ loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
563
+ loan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
564
+ loan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
loan-advisor-agent/.venv/Lib/site-packages/scipy/__config__.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is generated by SciPy's build process
2
+ # It contains system_info results at the time of building this package.
3
+ from enum import Enum
4
+
5
+ __all__ = ["show"]
6
+ _built_with_meson = True
7
+
8
+
9
+ class DisplayModes(Enum):
10
+ stdout = "stdout"
11
+ dicts = "dicts"
12
+
13
+
14
+ def _cleanup(d):
15
+ """
16
+ Removes empty values in a `dict` recursively
17
+ This ensures we remove values that Meson could not provide to CONFIG
18
+ """
19
+ if isinstance(d, dict):
20
+ return { k: _cleanup(v) for k, v in d.items() if v != '' and _cleanup(v) != '' }
21
+ else:
22
+ return d
23
+
24
+
25
+ CONFIG = _cleanup(
26
+ {
27
+ "Compilers": {
28
+ "c": {
29
+ "name": "gcc",
30
+ "linker": r"ld.bfd",
31
+ "version": "10.3.0",
32
+ "commands": r"C:\Strawberry\c\bin\ccache.EXE, cc",
33
+ "args": r"",
34
+ "linker args": r"",
35
+ },
36
+ "cython": {
37
+ "name": r"cython",
38
+ "linker": r"cython",
39
+ "version": r"3.2.4",
40
+ "commands": r"cython",
41
+ "args": r"",
42
+ "linker args": r"",
43
+ },
44
+ "c++": {
45
+ "name": "gcc",
46
+ "linker": r"ld.bfd",
47
+ "version": "10.3.0",
48
+ "commands": r"C:\Strawberry\c\bin\ccache.EXE, c++",
49
+ "args": r"",
50
+ "linker args": r"",
51
+ },
52
+ "fortran": {
53
+ "name": "gcc",
54
+ "linker": r"ld.bfd",
55
+ "version": "10.3.0",
56
+ "commands": r"gfortran",
57
+ "args": r"",
58
+ "linker args": r"",
59
+ },
60
+ "pythran": {
61
+ "version": r"0.18.1",
62
+ "include directory": r"C:\Users\runneradmin\AppData\Local\Temp\build-env-jfo4tcpw\Lib\site-packages/pythran"
63
+ },
64
+ },
65
+ "Machine Information": {
66
+ "host": {
67
+ "cpu": r"x86_64",
68
+ "family": r"x86_64",
69
+ "endian": r"little",
70
+ "system": r"windows",
71
+ },
72
+ "build": {
73
+ "cpu": r"x86_64",
74
+ "family": r"x86_64",
75
+ "endian": r"little",
76
+ "system": r"windows",
77
+ },
78
+ "cross-compiled": bool("False".lower().replace('false', '')),
79
+ },
80
+ "Build Dependencies": {
81
+ "blas": {
82
+ "name": "scipy-openblas",
83
+ "found": bool("True".lower().replace('false', '')),
84
+ "version": "0.3.30",
85
+ "detection method": "pkgconfig",
86
+ "include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/include",
87
+ "lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/lib",
88
+ "openblas configuration": r"OpenBLAS 0.3.30 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24",
89
+ "pc file directory": r"D:/a/scipy/scipy",
90
+ "has ilp64": bool(r"False".lower().replace('false', '')),
91
+ },
92
+ "lapack": {
93
+ "name": "scipy-openblas",
94
+ "found": bool("True".lower().replace('false', '')),
95
+ "version": "0.3.30",
96
+ "detection method": "pkgconfig",
97
+ "include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/include",
98
+ "lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/lib",
99
+ "openblas configuration": r"OpenBLAS 0.3.30 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24",
100
+ "pc file directory": r"D:/a/scipy/scipy",
101
+ "has ilp64": bool(r"False".lower().replace('false', '')),
102
+ },
103
+ "pybind11": {
104
+ "name": "pybind11",
105
+ "version": "3.0.2",
106
+ "detection method": "config-tool",
107
+ "include directory": r"unknown",
108
+ },
109
+ },
110
+ "Python Information": {
111
+ "path": r"C:\Users\runneradmin\AppData\Local\Temp\build-env-jfo4tcpw\Scripts\python.exe",
112
+ "version": "3.12",
113
+ },
114
+ }
115
+ )
116
+
117
+
118
+ def _check_pyyaml():
119
+ import yaml
120
+
121
+ return yaml
122
+
123
+
124
+ def show(mode=DisplayModes.stdout.value):
125
+ """
126
+ Show libraries and system information on which SciPy was built
127
+ and is being used
128
+
129
+ Parameters
130
+ ----------
131
+ mode : {`'stdout'`, `'dicts'`}, optional.
132
+ Indicates how to display the config information.
133
+ `'stdout'` prints to console, `'dicts'` returns a dictionary
134
+ of the configuration.
135
+
136
+ Returns
137
+ -------
138
+ out : {`dict`, `None`}
139
+ If mode is `'dicts'`, a dict is returned, else None
140
+
141
+ Examples
142
+ --------
143
+ >>> import scipy
144
+ >>> scipy.show_config()
145
+ ... # formatted output is printed to the console
146
+
147
+ >>> config_dict = scipy.show_config(mode='dicts')
148
+ >>> list(config_dict.keys())
149
+ ['Compilers', 'Machine Information', 'Build Dependencies', 'Python Information']
150
+
151
+ Notes
152
+ -----
153
+ 1. The `'stdout'` mode will give more readable
154
+ output if ``pyyaml`` is installed
155
+
156
+ """
157
+ if mode == DisplayModes.stdout.value:
158
+ try: # Non-standard library, check import
159
+ yaml = _check_pyyaml()
160
+
161
+ print(yaml.dump(CONFIG))
162
+ except ModuleNotFoundError:
163
+ import warnings
164
+ import json
165
+
166
+ warnings.warn("Install `pyyaml` for better output", stacklevel=1)
167
+ print(json.dumps(CONFIG, indent=2))
168
+ elif mode == DisplayModes.dicts.value:
169
+ return CONFIG
170
+ else:
171
+ raise AttributeError(
172
+ f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}"
173
+ )
loan-advisor-agent/.venv/Lib/site-packages/scipy/__init__.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SciPy: A scientific computing package for Python
3
+ ================================================
4
+
5
+ Documentation is available in the docstrings and
6
+ online at https://docs.scipy.org/doc/scipy/
7
+
8
+ Subpackages
9
+ -----------
10
+ ::
11
+
12
+ cluster --- Vector Quantization / Kmeans
13
+ constants --- Physical and mathematical constants and units
14
+ datasets --- Dataset methods
15
+ differentiate --- Finite difference differentiation tools
16
+ fft --- Discrete Fourier transforms
17
+ fftpack --- Legacy discrete Fourier transforms
18
+ integrate --- Integration routines
19
+ interpolate --- Interpolation Tools
20
+ io --- Data input and output
21
+ linalg --- Linear algebra routines
22
+ ndimage --- N-D image package
23
+ odr --- Orthogonal Distance Regression
24
+ optimize --- Optimization Tools
25
+ signal --- Signal Processing Tools
26
+ sparse --- Sparse Matrices
27
+ spatial --- Spatial data structures and algorithms
28
+ special --- Special functions
29
+ stats --- Statistical Functions
30
+
31
+ Public API in the main SciPy namespace
32
+ --------------------------------------
33
+ ::
34
+
35
+ __version__ --- SciPy version string
36
+ LowLevelCallable --- Low-level callback function
37
+ show_config --- Show scipy build configuration
38
+ test --- Run scipy unittests
39
+
40
+ """
41
+
42
+
43
+ # start delvewheel patch
44
+ def _delvewheel_patch_1_12_0():
45
+ import os
46
+ if os.path.isdir(libs_dir := os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'scipy.libs'))):
47
+ os.add_dll_directory(libs_dir)
48
+
49
+
50
+ _delvewheel_patch_1_12_0()
51
+ del _delvewheel_patch_1_12_0
52
+ # end delvewheel patch
53
+
54
+ import importlib as _importlib
55
+
56
+ from numpy import __version__ as __numpy_version__
57
+
58
+
59
+ try:
60
+ from scipy.__config__ import show as show_config
61
+ except ImportError as e:
62
+ msg = """Error importing SciPy: you cannot import SciPy while
63
+ being in scipy source directory; please exit the SciPy source
64
+ tree first and relaunch your Python interpreter."""
65
+ raise ImportError(msg) from e
66
+
67
+
68
+ from scipy.version import version as __version__
69
+
70
+
71
+ # Allow distributors to run custom init code
72
+ from . import _distributor_init
73
+ del _distributor_init
74
+
75
+
76
+ from scipy._lib import _pep440
77
+ # In maintenance branch, change to np_maxversion N+3 if numpy is at N
78
+ np_minversion = '1.26.4'
79
+ np_maxversion = '2.7.0'
80
+ if (_pep440.parse(__numpy_version__) < _pep440.Version(np_minversion) or
81
+ _pep440.parse(__numpy_version__) >= _pep440.Version(np_maxversion)):
82
+ import warnings
83
+ warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
84
+ f" is required for this version of SciPy (detected "
85
+ f"version {__numpy_version__})",
86
+ UserWarning, stacklevel=2)
87
+ del _pep440
88
+
89
+
90
+ # This is the first import of an extension module within SciPy. If there's
91
+ # a general issue with the install, such that extension modules are missing
92
+ # or cannot be imported, this is where we'll get a failure - so give an
93
+ # informative error message.
94
+ try:
95
+ from scipy._lib._ccallback import LowLevelCallable
96
+ except ImportError as e:
97
+ msg = "The `scipy` install you are using seems to be broken, " + \
98
+ "(extension modules cannot be imported), " + \
99
+ "please try reinstalling."
100
+ raise ImportError(msg) from e
101
+
102
+
103
+ from scipy._lib._testutils import PytestTester
104
+ test = PytestTester(__name__)
105
+ del PytestTester
106
+
107
+
108
+ submodules = [
109
+ 'cluster',
110
+ 'constants',
111
+ 'datasets',
112
+ 'differentiate',
113
+ 'fft',
114
+ 'fftpack',
115
+ 'integrate',
116
+ 'interpolate',
117
+ 'io',
118
+ 'linalg',
119
+ 'ndimage',
120
+ 'odr',
121
+ 'optimize',
122
+ 'signal',
123
+ 'sparse',
124
+ 'spatial',
125
+ 'special',
126
+ 'stats'
127
+ ]
128
+
129
+ __all__ = submodules + [
130
+ 'LowLevelCallable',
131
+ 'test',
132
+ 'show_config',
133
+ '__version__',
134
+ ]
135
+
136
+
137
+ def __dir__():
138
+ return __all__
139
+
140
+
141
+ def __getattr__(name):
142
+ if name in submodules:
143
+ return _importlib.import_module(f'scipy.{name}')
144
+ else:
145
+ try:
146
+ return globals()[name]
147
+ except KeyError:
148
+ raise AttributeError(
149
+ f"Module 'scipy' has no attribute '{name}'"
150
+ )
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__config__.cpython-312.pyc ADDED
Binary file (5.34 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (4.82 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc ADDED
Binary file (850 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/version.cpython-312.pyc ADDED
Binary file (557 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.dll.a ADDED
Binary file (1.58 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1990a1fbef9f2f75556db35b81d7180c903fc54db3f8fd08c14ac2cbc805c61b
3
+ size 186368
loan-advisor-agent/.venv/Lib/site-packages/scipy/_distributor_init.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Distributor init file
2
+
3
+ Distributors: you can replace the contents of this file with your own custom
4
+ code to support particular distributions of SciPy.
5
+
6
+ For example, this is a good place to put any checks for hardware requirements
7
+ or BLAS/LAPACK library initialization.
8
+
9
+ The SciPy standard source distribution will not put code in this file beyond
10
+ the try-except import of `_distributor_init_local` (which is not part of a
11
+ standard source distribution), so you can safely replace this file with your
12
+ own version.
13
+ """
14
+
15
+ try:
16
+ from . import _distributor_init_local # noqa: F401
17
+ except ImportError:
18
+ pass
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module containing private utility functions
3
+ ===========================================
4
+
5
+ The ``scipy._lib`` namespace is empty (for now). Tests for all
6
+ utilities in submodules of ``_lib`` can be run with::
7
+
8
+ from scipy import _lib
9
+ _lib.test()
10
+
11
+ """
12
+ from scipy._lib._testutils import PytestTester
13
+ test = PytestTester(__name__)
14
+ del PytestTester
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (569 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc ADDED
Binary file (38.1 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc ADDED
Binary file (337 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc ADDED
Binary file (5.68 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pyc ADDED
Binary file (9 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc ADDED
Binary file (9.4 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc ADDED
Binary file (32.5 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc ADDED
Binary file (14.9 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pyc ADDED
Binary file (18.8 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc ADDED
Binary file (1.31 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc ADDED
Binary file (16.3 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc ADDED
Binary file (56.1 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc ADDED
Binary file (11.2 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pyc ADDED
Binary file (12.6 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc ADDED
Binary file (925 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api.py ADDED
@@ -0,0 +1,1036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility functions to use Python Array API compatible libraries.
2
+
3
+ For the context about the Array API see:
4
+ https://data-apis.org/array-api/latest/purpose_and_scope.html
5
+
6
+ The SciPy use case of the Array API is described on the following page:
7
+ https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy
8
+ """
9
+ import operator
10
+ import dataclasses
11
+ import functools
12
+ import textwrap
13
+
14
+ from collections.abc import Generator
15
+ from contextlib import contextmanager
16
+ from contextvars import ContextVar
17
+ from types import ModuleType
18
+ from typing import Any, Literal, TypeAlias
19
+ from collections.abc import Iterable
20
+
21
+ import numpy as np
22
+ import numpy.typing as npt
23
+
24
+ from scipy._lib.array_api_compat import (
25
+ is_array_api_obj,
26
+ is_lazy_array,
27
+ is_numpy_array,
28
+ is_cupy_array,
29
+ is_torch_array,
30
+ is_jax_array,
31
+ is_dask_array,
32
+ size as xp_size,
33
+ numpy as np_compat,
34
+ device as xp_device,
35
+ is_numpy_namespace as is_numpy,
36
+ is_cupy_namespace as is_cupy,
37
+ is_torch_namespace as is_torch,
38
+ is_jax_namespace as is_jax,
39
+ is_dask_namespace as is_dask,
40
+ is_array_api_strict_namespace as is_array_api_strict,
41
+ )
42
+ from scipy._lib.array_api_compat.common._helpers import _compat_module_name
43
+ from scipy._lib.array_api_extra.testing import lazy_xp_function
44
+ from scipy._lib._array_api_override import (
45
+ array_namespace, SCIPY_ARRAY_API, SCIPY_DEVICE
46
+ )
47
+ from scipy._lib._docscrape import FunctionDoc
48
+ from scipy._lib import array_api_extra as xpx
49
+
50
+
51
+ __all__ = [
52
+ '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal',
53
+ 'default_xp', 'eager_warns', 'is_lazy_array', 'is_marray',
54
+ 'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch',
55
+ 'np_compat', 'get_native_namespace_name',
56
+ 'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for',
57
+ 'xp_assert_close', 'xp_assert_equal', 'xp_assert_less',
58
+ 'xp_copy', 'xp_device', 'xp_ravel', 'xp_size',
59
+ 'xp_unsupported_param_msg', 'xp_vector_norm', 'xp_capabilities',
60
+ 'xp_result_type', 'xp_promote',
61
+ 'make_xp_test_case', 'make_xp_pytest_marks', 'make_xp_pytest_param',
62
+ ]
63
+
64
+
65
+ Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589)
66
+ ArrayLike: TypeAlias = Array | npt.ArrayLike
67
+
68
+
69
+ def _check_finite(array: Array, xp: ModuleType) -> None:
70
+ """Check for NaNs or Infs."""
71
+ if not xp.all(xp.isfinite(array)):
72
+ msg = "array must not contain infs or NaNs"
73
+ raise ValueError(msg)
74
+
75
+ def _asarray(
76
+ array: ArrayLike,
77
+ dtype: Any = None,
78
+ order: Literal['K', 'A', 'C', 'F'] | None = None,
79
+ copy: bool | None = None,
80
+ *,
81
+ xp: ModuleType | None = None,
82
+ check_finite: bool = False,
83
+ subok: bool = False,
84
+ ) -> Array:
85
+ """SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and
86
+ `subok`.
87
+
88
+ Memory layout parameter `order` is not exposed in the Array API standard.
89
+ `order` is only enforced if the input array implementation
90
+ is NumPy based, otherwise `order` is just silently ignored.
91
+
92
+ `check_finite` is also not a keyword in the array API standard; included
93
+ here for convenience rather than that having to be a separate function
94
+ call inside SciPy functions.
95
+
96
+ `subok` is included to allow this function to preserve the behaviour of
97
+ `np.asanyarray` for NumPy based inputs.
98
+ """
99
+ if xp is None:
100
+ xp = array_namespace(array)
101
+ if is_numpy(xp):
102
+ # Use NumPy API to support order
103
+ if copy is True:
104
+ array = np.array(array, order=order, dtype=dtype, subok=subok)
105
+ elif subok:
106
+ array = np.asanyarray(array, order=order, dtype=dtype)
107
+ else:
108
+ array = np.asarray(array, order=order, dtype=dtype)
109
+ else:
110
+ try:
111
+ array = xp.asarray(array, dtype=dtype, copy=copy)
112
+ except TypeError:
113
+ coerced_xp = array_namespace(xp.asarray(3))
114
+ array = coerced_xp.asarray(array, dtype=dtype, copy=copy)
115
+
116
+ if check_finite:
117
+ _check_finite(array, xp)
118
+
119
+ return array
120
+
121
+
122
+ def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array:
123
+ """
124
+ Copies an array.
125
+
126
+ Parameters
127
+ ----------
128
+ x : array
129
+
130
+ xp : array_namespace
131
+
132
+ Returns
133
+ -------
134
+ copy : array
135
+ Copied array
136
+
137
+ Notes
138
+ -----
139
+ This copy function does not offer all the semantics of `np.copy`, i.e. the
140
+ `subok` and `order` keywords are not used.
141
+ """
142
+ # Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg,
143
+ # so this uses our other helper `_asarray`.
144
+ if xp is None:
145
+ xp = array_namespace(x)
146
+
147
+ return _asarray(x, copy=True, xp=xp)
148
+
149
+
150
+ def _xp_copy_to_numpy(x: Array) -> np.ndarray:
151
+ """Copies a possibly on device array to a NumPy array.
152
+
153
+ This function is intended only for converting alternative backend
154
+ arrays to numpy arrays within test code, to make it easier for use
155
+ of the alternative backend to be isolated only to the function being
156
+ tested. `_xp_copy_to_numpy` should NEVER be used except in test code
157
+ for the specific purpose mentioned above. In production code, attempts
158
+ to copy device arrays to NumPy arrays should fail, or else functions
159
+ may appear to be working on the GPU when they actually aren't.
160
+
161
+ Parameters
162
+ ----------
163
+ x : array
164
+
165
+ Returns
166
+ -------
167
+ ndarray
168
+ """
169
+ xp = array_namespace(x)
170
+ if is_numpy(xp):
171
+ return x.copy()
172
+ if is_cupy(xp):
173
+ return x.get()
174
+ if is_torch(xp):
175
+ return x.cpu().numpy()
176
+ if is_array_api_strict(xp):
177
+ # array api strict supports multiple devices, so need to
178
+ # ensure x is on the cpu before copying to NumPy.
179
+ return np.asarray(
180
+ xp.asarray(x, device=xp.Device("CPU_DEVICE")), copy=True
181
+ )
182
+ # Fall back to np.asarray. This works for dask.array. It
183
+ # currently works for jax.numpy, but hopefully JAX will make
184
+ # the transfer guard workable enough for use in scipy tests, in
185
+ # which case, JAX will have to be handled explicitly.
186
+ # If new backends are added, they may require explicit handling as
187
+ # well.
188
+ return np.asarray(x, copy=True)
189
+
190
+
191
+ _default_xp_ctxvar: ContextVar[ModuleType] = ContextVar("_default_xp")
192
+
193
+ @contextmanager
194
+ def default_xp(xp: ModuleType) -> Generator[None, None, None]:
195
+ """In all ``xp_assert_*`` and ``assert_*`` function calls executed within this
196
+ context manager, test by default that the array namespace is
197
+ the provided across all arrays, unless one explicitly passes the ``xp=``
198
+ parameter or ``check_namespace=False``.
199
+
200
+ Without this context manager, the default value for `xp` is the namespace
201
+ for the desired array (the second parameter of the tests).
202
+ """
203
+ token = _default_xp_ctxvar.set(xp)
204
+ try:
205
+ yield
206
+ finally:
207
+ _default_xp_ctxvar.reset(token)
208
+
209
+
210
+ def eager_warns(warning_type, *, match=None, xp):
211
+ """pytest.warns context manager if arrays of specified namespace are always eager.
212
+
213
+ Otherwise, context manager that *ignores* specified warning.
214
+ """
215
+ import pytest
216
+ from scipy._lib._util import ignore_warns
217
+ if is_numpy(xp) or is_array_api_strict(xp) or is_cupy(xp):
218
+ return pytest.warns(warning_type, match=match)
219
+ return ignore_warns(warning_type, match='' if match is None else match)
220
+
221
+
222
+ def _strict_check(actual, desired, xp, *,
223
+ check_namespace=True, check_dtype=True, check_shape=True,
224
+ check_0d=True):
225
+ __tracebackhide__ = True # Hide traceback for py.test
226
+
227
+ if xp is None:
228
+ try:
229
+ xp = _default_xp_ctxvar.get()
230
+ except LookupError:
231
+ xp = array_namespace(desired)
232
+
233
+ if check_namespace:
234
+ _assert_matching_namespace(actual, desired, xp)
235
+
236
+ # only NumPy distinguishes between scalars and arrays; we do if check_0d=True.
237
+ # do this first so we can then cast to array (and thus use the array API) below.
238
+ if is_numpy(xp) and check_0d:
239
+ _msg = ("Array-ness does not match:\n Actual: "
240
+ f"{type(actual)}\n Desired: {type(desired)}")
241
+ assert ((xp.isscalar(actual) and xp.isscalar(desired))
242
+ or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg
243
+
244
+ actual = xp.asarray(actual)
245
+ desired = xp.asarray(desired)
246
+
247
+ if check_dtype:
248
+ _msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}"
249
+ assert actual.dtype == desired.dtype, _msg
250
+
251
+ if check_shape:
252
+ if is_dask(xp):
253
+ actual.compute_chunk_sizes()
254
+ desired.compute_chunk_sizes()
255
+ _msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}"
256
+ assert actual.shape == desired.shape, _msg
257
+
258
+ desired = xp.broadcast_to(desired, actual.shape)
259
+ return actual, desired, xp
260
+
261
+
262
+ def _assert_matching_namespace(actual, desired, xp):
263
+ __tracebackhide__ = True # Hide traceback for py.test
264
+
265
+ desired_arr_space = array_namespace(desired)
266
+ _msg = ("Namespace of desired array does not match expectations "
267
+ "set by the `default_xp` context manager or by the `xp`"
268
+ "pytest fixture.\n"
269
+ f"Desired array's space: {desired_arr_space.__name__}\n"
270
+ f"Expected namespace: {xp.__name__}")
271
+ assert desired_arr_space == xp, _msg
272
+
273
+ actual_arr_space = array_namespace(actual)
274
+ _msg = ("Namespace of actual and desired arrays do not match.\n"
275
+ f"Actual: {actual_arr_space.__name__}\n"
276
+ f"Desired: {xp.__name__}")
277
+ assert actual_arr_space == xp, _msg
278
+
279
+
280
+ def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True,
281
+ check_shape=True, check_0d=True, err_msg='', xp=None):
282
+ __tracebackhide__ = True # Hide traceback for py.test
283
+
284
+ actual, desired, xp = _strict_check(
285
+ actual, desired, xp, check_namespace=check_namespace,
286
+ check_dtype=check_dtype, check_shape=check_shape,
287
+ check_0d=check_0d
288
+ )
289
+
290
+ if is_cupy(xp):
291
+ return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg)
292
+ elif is_torch(xp):
293
+ # PyTorch recommends using `rtol=0, atol=0` like this
294
+ # to test for exact equality
295
+ err_msg = None if err_msg == '' else err_msg
296
+ return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True,
297
+ check_dtype=False, msg=err_msg)
298
+ # JAX uses `np.testing`
299
+ return np.testing.assert_array_equal(actual, desired, err_msg=err_msg)
300
+
301
+
302
+ def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True,
303
+ check_dtype=True, check_shape=True, check_0d=True,
304
+ err_msg='', xp=None):
305
+ __tracebackhide__ = True # Hide traceback for py.test
306
+
307
+ actual, desired, xp = _strict_check(
308
+ actual, desired, xp,
309
+ check_namespace=check_namespace, check_dtype=check_dtype,
310
+ check_shape=check_shape, check_0d=check_0d
311
+ )
312
+
313
+ floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating'))
314
+ if rtol is None and floating:
315
+ # multiplier of 4 is used as for `np.float64` this puts the default `rtol`
316
+ # roughly half way between sqrt(eps) and the default for
317
+ # `numpy.testing.assert_allclose`, 1e-7
318
+ rtol = xp.finfo(actual.dtype).eps**0.5 * 4
319
+ elif rtol is None:
320
+ rtol = 1e-7
321
+
322
+ if is_cupy(xp):
323
+ return xp.testing.assert_allclose(actual, desired, rtol=rtol,
324
+ atol=atol, err_msg=err_msg)
325
+ elif is_torch(xp):
326
+ err_msg = None if err_msg == '' else err_msg
327
+ return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol,
328
+ equal_nan=True, check_dtype=False, msg=err_msg)
329
+ # JAX uses `np.testing`
330
+ return np.testing.assert_allclose(actual, desired, rtol=rtol,
331
+ atol=atol, err_msg=err_msg)
332
+
333
+
334
+ def xp_assert_close_nulp(actual, desired, *, nulp=1, check_namespace=True,
335
+ check_dtype=True, check_shape=True, check_0d=True,
336
+ err_msg='', xp=None):
337
+ __tracebackhide__ = True # Hide traceback for py.test
338
+
339
+ actual, desired, xp = _strict_check(
340
+ actual, desired, xp,
341
+ check_namespace=check_namespace, check_dtype=check_dtype,
342
+ check_shape=check_shape, check_0d=check_0d
343
+ )
344
+
345
+ actual, desired = map(_xp_copy_to_numpy, (actual, desired))
346
+ return np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=nulp)
347
+
348
+
349
+ def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True,
350
+ check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None):
351
+ __tracebackhide__ = True # Hide traceback for py.test
352
+
353
+ actual, desired, xp = _strict_check(
354
+ actual, desired, xp, check_namespace=check_namespace,
355
+ check_dtype=check_dtype, check_shape=check_shape,
356
+ check_0d=check_0d
357
+ )
358
+
359
+ if is_cupy(xp):
360
+ return xp.testing.assert_array_less(actual, desired,
361
+ err_msg=err_msg, verbose=verbose)
362
+ elif is_torch(xp):
363
+ if actual.device.type != 'cpu':
364
+ actual = actual.cpu()
365
+ if desired.device.type != 'cpu':
366
+ desired = desired.cpu()
367
+ # JAX uses `np.testing`
368
+ return np.testing.assert_array_less(actual, desired,
369
+ err_msg=err_msg, verbose=verbose)
370
+
371
+
372
+ def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
373
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
374
+ """
375
+ rtol, atol = 0, 1.5*10**(-decimal)
376
+ return xp_assert_close(actual, desired,
377
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
378
+ *args, **kwds)
379
+
380
+
381
+ def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
382
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
383
+ """
384
+ rtol, atol = 0, 1.5*10**(-decimal)
385
+ return xp_assert_close(actual, desired,
386
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
387
+ *args, **kwds)
388
+
389
+
390
+ def xp_unsupported_param_msg(param: Any) -> str:
391
+ return f'Providing {param!r} is only supported for numpy arrays.'
392
+
393
+
394
+ def is_complex(x: Array, xp: ModuleType) -> bool:
395
+ return xp.isdtype(x.dtype, 'complex floating')
396
+
397
+
398
+ def get_native_namespace_name(xp: ModuleType) -> str:
399
+ """Return name for native namespace (without array_api_compat prefix)."""
400
+ name = xp.__name__
401
+ return name.removeprefix(f"{_compat_module_name()}.")
402
+
403
+
404
+ def scipy_namespace_for(xp: ModuleType) -> ModuleType | None:
405
+ """Return the `scipy`-like namespace of a non-NumPy backend
406
+
407
+ That is, return the namespace corresponding with backend `xp` that contains
408
+ `scipy` sub-namespaces like `linalg` and `special`. If no such namespace
409
+ exists, return ``None``. Useful for dispatching.
410
+ """
411
+
412
+ if is_cupy(xp):
413
+ import cupyx # type: ignore[import-not-found,import-untyped]
414
+ return cupyx.scipy
415
+
416
+ if is_jax(xp):
417
+ import jax # type: ignore[import-not-found]
418
+ return jax.scipy
419
+
420
+ if is_torch(xp):
421
+ return xp
422
+
423
+ return None
424
+
425
+
426
+ # maybe use `scipy.linalg` if/when array API support is added
427
+ def xp_vector_norm(x: Array, /, *,
428
+ axis: int | tuple[int] | None = None,
429
+ keepdims: bool = False,
430
+ ord: int | float = 2,
431
+ xp: ModuleType | None = None) -> Array:
432
+ xp = array_namespace(x) if xp is None else xp
433
+
434
+ if SCIPY_ARRAY_API:
435
+ # check for optional `linalg` extension
436
+ if hasattr(xp, 'linalg'):
437
+ return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord)
438
+ else:
439
+ if ord != 2:
440
+ raise ValueError(
441
+ "only the Euclidean norm (`ord=2`) is currently supported in "
442
+ "`xp_vector_norm` for backends not implementing the `linalg` "
443
+ "extension."
444
+ )
445
+ # return (x @ x)**0.5
446
+ # or to get the right behavior with nd, complex arrays
447
+ return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5
448
+ else:
449
+ # to maintain backwards compatibility
450
+ return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims)
451
+
452
+
453
+ def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array:
454
+ # Equivalent of np.ravel written in terms of array API
455
+ # Even though it's one line, it comes up so often that it's worth having
456
+ # this function for readability
457
+ xp = array_namespace(x) if xp is None else xp
458
+ return xp.reshape(x, (-1,))
459
+
460
+
461
+ def xp_swapaxes(a, axis1, axis2, xp=None):
462
+ # Equivalent of np.swapaxes written in terms of array API
463
+ xp = array_namespace(a) if xp is None else xp
464
+ axes = list(range(a.ndim))
465
+ axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
466
+ a = xp.permute_dims(a, axes)
467
+ return a
468
+
469
+
470
+ # utility to find common dtype with option to force floating
471
+ def xp_result_type(*args, force_floating=False, xp):
472
+ """
473
+ Returns the dtype that results from applying type promotion rules
474
+ (see Array API Standard Type Promotion Rules) to the arguments. Augments
475
+ standard `result_type` in a few ways:
476
+
477
+ - There is a `force_floating` argument that ensures that the result type
478
+ is floating point, even when all args are integer.
479
+ - When a TypeError is raised (e.g. due to an unsupported promotion)
480
+ and `force_floating=True`, we define a custom rule: use the result type
481
+ of the default float and any other floats passed. See
482
+ https://github.com/scipy/scipy/pull/22695/files#r1997905891
483
+ for rationale.
484
+ - This function accepts array-like iterables, which are immediately converted
485
+ to the namespace's arrays before result type calculation. Consequently, the
486
+ result dtype may be different when an argument is `1.` vs `[1.]`.
487
+
488
+ Typically, this function will be called shortly after `array_namespace`
489
+ on a subset of the arguments passed to `array_namespace`.
490
+ """
491
+ # prevent double conversion of iterable to array
492
+ # avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334
493
+ # don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars
494
+ args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg)
495
+ else arg) for arg in args]
496
+ args_not_none = [arg for arg in args if arg is not None]
497
+ if force_floating:
498
+ args_not_none.append(1.0)
499
+
500
+ if is_numpy(xp) and xp.__version__ < '2.0':
501
+ # Follow NEP 50 promotion rules anyway
502
+ args_not_none = [arg.dtype if getattr(arg, 'size', 0) == 1 else arg
503
+ for arg in args_not_none]
504
+ return xp.result_type(*args_not_none)
505
+
506
+ try: # follow library's preferred promotion rules
507
+ return xp.result_type(*args_not_none)
508
+ except TypeError: # mixed type promotion isn't defined
509
+ if not force_floating:
510
+ raise
511
+ # use `result_type` of default floating point type and any floats present
512
+ # This can be revisited, but right now, the only backends that get here
513
+ # are array-api-strict (which is not for production use) and PyTorch
514
+ # (due to data-apis/array-api-compat#279).
515
+ float_args = []
516
+ for arg in args_not_none:
517
+ arg_array = xp.asarray(arg) if np.isscalar(arg) else arg
518
+ dtype = getattr(arg_array, 'dtype', arg)
519
+ if xp.isdtype(dtype, ('real floating', 'complex floating')):
520
+ float_args.append(arg)
521
+ return xp.result_type(*float_args, xp_default_dtype(xp))
522
+
523
+
524
+ def xp_promote(*args, broadcast=False, force_floating=False, xp):
525
+ """
526
+ Promotes elements of *args to result dtype, ignoring `None`s.
527
+ Includes options for forcing promotion to floating point and
528
+ broadcasting the arrays, again ignoring `None`s.
529
+ Type promotion rules follow `xp_result_type` instead of `xp.result_type`.
530
+
531
+ Typically, this function will be called shortly after `array_namespace`
532
+ on a subset of the arguments passed to `array_namespace`.
533
+
534
+ This function accepts array-like iterables, which are immediately converted
535
+ to the namespace's arrays before result type calculation. Consequently, the
536
+ result dtype may be different when an argument is `1.` vs `[1.]`.
537
+
538
+ See Also
539
+ --------
540
+ xp_result_type
541
+ """
542
+ if not args:
543
+ return args
544
+
545
+ # prevent double conversion of iterable to array
546
+ # avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334
547
+ # don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars
548
+ args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg)
549
+ else arg) for arg in args]
550
+
551
+ dtype = xp_result_type(*args, force_floating=force_floating, xp=xp)
552
+
553
+ args = [(_asarray(arg, dtype=dtype, subok=True, xp=xp) if arg is not None else arg)
554
+ for arg in args]
555
+
556
+ if not broadcast:
557
+ return args[0] if len(args)==1 else tuple(args)
558
+
559
+ args_not_none = [arg for arg in args if arg is not None]
560
+
561
+ # determine result shape
562
+ shapes = {arg.shape for arg in args_not_none}
563
+ try:
564
+ shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1
565
+ else args_not_none[0].shape)
566
+ except ValueError as e:
567
+ message = "Array shapes are incompatible for broadcasting."
568
+ raise ValueError(message) from e
569
+
570
+ out = []
571
+ for arg in args:
572
+ if arg is None:
573
+ out.append(arg)
574
+ continue
575
+
576
+ # broadcast only if needed
577
+ # Even if two arguments need broadcasting, this is faster than
578
+ # `broadcast_arrays`, especially since we've already determined `shape`
579
+ if arg.shape != shape:
580
+ kwargs = {'subok': True} if is_numpy(xp) else {}
581
+ arg = xp.broadcast_to(arg, shape, **kwargs)
582
+
583
+ # This is much faster than xp.astype(arg, dtype, copy=False)
584
+ if arg.dtype != dtype:
585
+ arg = xp.astype(arg, dtype)
586
+
587
+ out.append(arg)
588
+
589
+ return out[0] if len(out)==1 else tuple(out)
590
+
591
+
592
+ def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array:
593
+ xp = array_namespace(arr) if xp is None else xp
594
+ arr_dtype = arr.dtype
595
+ # The standard float dtypes are float32 and float64.
596
+ # Convert float32 to complex64,
597
+ # and float64 (and non-standard real dtypes) to complex128
598
+ if xp.isdtype(arr_dtype, xp.float32):
599
+ arr = xp.astype(arr, xp.complex64)
600
+ elif xp.isdtype(arr_dtype, 'real floating'):
601
+ arr = xp.astype(arr, xp.complex128)
602
+
603
+ return arr
604
+
605
+
606
+ def xp_default_dtype(xp):
607
+ """Query the namespace-dependent default floating-point dtype.
608
+ """
609
+ if is_torch(xp):
610
+ # historically, we allow pytorch to keep its default of float32
611
+ return xp.get_default_dtype()
612
+ else:
613
+ # we default to float64
614
+ return xp.float64
615
+
616
+
617
+ ### MArray Helpers ###
618
+ def xp_result_device(*args):
619
+ """Return the device of an array in `args`, for the purpose of
620
+ input-output device propagation.
621
+ If there are multiple devices, return an arbitrary one.
622
+ If there are no arrays, return None (this typically happens only on NumPy).
623
+ """
624
+ for arg in args:
625
+ # Do not do a duck-type test for the .device attribute, as many backends today
626
+ # don't have it yet. See workarouunds in array_api_compat.device().
627
+ if is_array_api_obj(arg):
628
+ return xp_device(arg)
629
+ return None
630
+
631
+
632
+ # np.r_ replacement
633
+ def concat_1d(xp: ModuleType | None, *arrays: Iterable[ArrayLike]) -> Array:
634
+ """A replacement for `np.r_` as `xp.concat` does not accept python scalars
635
+ or 0-D arrays.
636
+ """
637
+ arys = [xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp) for a in arrays]
638
+ return xp.concat(arys)
639
+
640
+
641
+ def is_marray(xp):
642
+ """Returns True if `xp` is an MArray namespace; False otherwise."""
643
+ return "marray" in xp.__name__
644
+
645
+
646
+ def _length_nonmasked(x, axis, keepdims=False, xp=None):
647
+ xp = array_namespace(x) if xp is None else xp
648
+ if is_marray(xp):
649
+ if np.iterable(axis):
650
+ message = '`axis` must be an integer or None for use with `MArray`.'
651
+ raise NotImplementedError(message)
652
+ return xp.astype(xp.count(x, axis=axis, keepdims=keepdims), x.dtype)
653
+ return (xp_size(x) if axis is None else
654
+ # compact way to deal with axis tuples or ints
655
+ int(np.prod(np.asarray(x.shape)[np.asarray(axis)])))
656
+
657
+
658
+ def _share_masks(*args, xp):
659
+ if is_marray(xp):
660
+ mask = functools.reduce(operator.or_, (arg.mask for arg in args))
661
+ args = [xp.asarray(arg.data, mask=mask) for arg in args]
662
+ return args[0] if len(args) == 1 else args
663
+
664
+ ### End MArray Helpers ###
665
+
666
+
667
+ @dataclasses.dataclass(repr=False)
668
+ class _XPSphinxCapability:
669
+ cpu: bool | None # None if not applicable
670
+ gpu: bool | None
671
+ warnings: list[str] = dataclasses.field(default_factory=list)
672
+
673
+ def _render(self, value):
674
+ if value is None:
675
+ return "n/a"
676
+ if not value:
677
+ return "⛔"
678
+ if self.warnings:
679
+ res = "⚠️ " + '; '.join(self.warnings)
680
+ assert len(res) <= 20, "Warnings too long"
681
+ return res
682
+ return "✅"
683
+
684
+ def __str__(self):
685
+ cpu = self._render(self.cpu)
686
+ gpu = self._render(self.gpu)
687
+ return f"{cpu:20} {gpu:20}"
688
+
689
+
690
+ def _make_sphinx_capabilities(
691
+ # lists of tuples [(module name, reason), ...]
692
+ skip_backends=(), xfail_backends=(),
693
+ # @pytest.mark.skip/xfail_xp_backends kwargs
694
+ cpu_only=False, np_only=False, out_of_scope=False, exceptions=(),
695
+ # xpx.lazy_xp_backends kwargs
696
+ allow_dask_compute=False, jax_jit=True,
697
+ # list of tuples [(module name, reason), ...]
698
+ warnings = (),
699
+ # unused in documentation
700
+ reason=None,
701
+ ):
702
+ if out_of_scope:
703
+ return {"out_of_scope": True}
704
+
705
+ exceptions = set(exceptions)
706
+
707
+ # Default capabilities
708
+ capabilities = {
709
+ "numpy": _XPSphinxCapability(cpu=True, gpu=None),
710
+ "array_api_strict": _XPSphinxCapability(cpu=True, gpu=None),
711
+ "cupy": _XPSphinxCapability(cpu=None, gpu=True),
712
+ "torch": _XPSphinxCapability(cpu=True, gpu=True),
713
+ "jax.numpy": _XPSphinxCapability(cpu=True, gpu=True,
714
+ warnings=[] if jax_jit else ["no JIT"]),
715
+ # Note: Dask+CuPy is currently untested and unsupported
716
+ "dask.array": _XPSphinxCapability(cpu=True, gpu=None,
717
+ warnings=["computes graph"] if allow_dask_compute else []),
718
+ }
719
+
720
+ # documentation doesn't display the reason
721
+ for module, _ in list(skip_backends) + list(xfail_backends):
722
+ backend = capabilities[module]
723
+ if backend.cpu is not None:
724
+ backend.cpu = False
725
+ if backend.gpu is not None:
726
+ backend.gpu = False
727
+
728
+ for module, backend in capabilities.items():
729
+ if np_only and module not in exceptions | {"numpy"}:
730
+ if backend.cpu is not None:
731
+ backend.cpu = False
732
+ if backend.gpu is not None:
733
+ backend.gpu = False
734
+ elif cpu_only and module not in exceptions and backend.gpu is not None:
735
+ backend.gpu = False
736
+
737
+ for module, warning in warnings:
738
+ backend = capabilities[module]
739
+ backend.warnings.append(warning)
740
+
741
+ return capabilities
742
+
743
+
744
+ def _make_capabilities_note(fun_name, capabilities, extra_note=None):
745
+ if "out_of_scope" in capabilities:
746
+ # It will be better to link to a section of the dev-arrayapi docs
747
+ # that explains what is and isn't in-scope, but such a section
748
+ # doesn't exist yet. Using :ref:`dev-arrayapi` as a placeholder.
749
+ note = f"""
750
+ **Array API Standard Support**
751
+
752
+ `{fun_name}` is not in-scope for support of Python Array API Standard compatible
753
+ backends other than NumPy.
754
+
755
+ See :ref:`dev-arrayapi` for more information.
756
+ """
757
+ return textwrap.dedent(note)
758
+
759
+ # Note: deliberately not documenting array-api-strict
760
+ note = f"""
761
+ **Array API Standard Support**
762
+
763
+ `{fun_name}` has experimental support for Python Array API Standard compatible
764
+ backends in addition to NumPy. Please consider testing these features
765
+ by setting an environment variable ``SCIPY_ARRAY_API=1`` and providing
766
+ CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following
767
+ combinations of backend and device (or other capability) are supported.
768
+
769
+ ==================== ==================== ====================
770
+ Library CPU GPU
771
+ ==================== ==================== ====================
772
+ NumPy {capabilities['numpy'] }
773
+ CuPy {capabilities['cupy'] }
774
+ PyTorch {capabilities['torch'] }
775
+ JAX {capabilities['jax.numpy'] }
776
+ Dask {capabilities['dask.array'] }
777
+ ==================== ==================== ====================
778
+
779
+ """ + (extra_note or "") + " See :ref:`dev-arrayapi` for more information."
780
+
781
+ return textwrap.dedent(note)
782
+
783
+
784
+ def xp_capabilities(
785
+ *,
786
+ # Alternative capabilities table.
787
+ # Used only for testing this decorator.
788
+ capabilities_table=None,
789
+ # Generate pytest.mark.skip/xfail_xp_backends.
790
+ # See documentation in conftest.py.
791
+ # lists of tuples [(module name, reason), ...]
792
+ skip_backends=(), xfail_backends=(),
793
+ cpu_only=False, np_only=False, reason=None,
794
+ out_of_scope=False, exceptions=(),
795
+ # lists of tuples [(module name, reason), ...]
796
+ warnings=(),
797
+ # xpx.testing.lazy_xp_function kwargs.
798
+ # Refer to array-api-extra documentation.
799
+ allow_dask_compute=False, jax_jit=True,
800
+ # Extra note to inject into the docstring
801
+ extra_note=None,
802
+ ):
803
+ """Decorator for a function that states its support among various
804
+ Array API compatible backends.
805
+
806
+ This decorator has two effects:
807
+ 1. It allows tagging tests with ``@make_xp_test_case`` or
808
+ ``make_xp_pytest_param`` (see below) to automatically generate
809
+ SKIP/XFAIL markers and perform additional backend-specific
810
+ testing, such as extra validation for Dask and JAX;
811
+ 2. It automatically adds a note to the function's docstring, containing
812
+ a table matching what has been tested.
813
+
814
+ See Also
815
+ --------
816
+ make_xp_test_case
817
+ make_xp_pytest_param
818
+ array_api_extra.testing.lazy_xp_function
819
+ """
820
+ capabilities_table = (xp_capabilities_table if capabilities_table is None
821
+ else capabilities_table)
822
+
823
+ if out_of_scope:
824
+ np_only = True
825
+
826
+ capabilities = dict(
827
+ skip_backends=skip_backends,
828
+ xfail_backends=xfail_backends,
829
+ cpu_only=cpu_only,
830
+ np_only=np_only,
831
+ out_of_scope=out_of_scope,
832
+ reason=reason,
833
+ exceptions=exceptions,
834
+ allow_dask_compute=allow_dask_compute,
835
+ jax_jit=jax_jit,
836
+ warnings=warnings,
837
+ )
838
+ sphinx_capabilities = _make_sphinx_capabilities(**capabilities)
839
+
840
+ def decorator(f):
841
+ # Don't use a wrapper, as in some cases @xp_capabilities is
842
+ # applied to a ufunc
843
+ capabilities_table[f] = capabilities
844
+ note = _make_capabilities_note(f.__name__, sphinx_capabilities, extra_note)
845
+ doc = FunctionDoc(f)
846
+ doc['Notes'].append(note)
847
+ doc = str(doc).split("\n", 1)[1].lstrip(" \n") # remove signature
848
+ try:
849
+ f.__doc__ = doc
850
+ except AttributeError:
851
+ # Can't update __doc__ on ufuncs if SciPy
852
+ # was compiled against NumPy < 2.2.
853
+ pass
854
+
855
+ return f
856
+ return decorator
857
+
858
+
859
+ def make_xp_test_case(*funcs, capabilities_table=None):
860
+ capabilities_table = (xp_capabilities_table if capabilities_table is None
861
+ else capabilities_table)
862
+ """Generate pytest decorator for a test function that tests functionality
863
+ of one or more Array API compatible functions.
864
+
865
+ Read the parameters of the ``@xp_capabilities`` decorator applied to the
866
+ listed functions and:
867
+
868
+ - Generate the ``@pytest.mark.skip_xp_backends`` and
869
+ ``@pytest.mark.xfail_xp_backends`` decorators
870
+ for the decorated test function
871
+ - Tag the function with `xpx.testing.lazy_xp_function`
872
+
873
+ Example::
874
+
875
+ @make_xp_test_case(f1)
876
+ def test_f1(xp):
877
+ ...
878
+
879
+ @make_xp_test_case(f2)
880
+ def test_f2(xp):
881
+ ...
882
+
883
+ @make_xp_test_case(f1, f2)
884
+ def test_f1_and_f2(xp):
885
+ ...
886
+
887
+ The above is equivalent to::
888
+ @pytest.mark.skip_xp_backends(...)
889
+ @pytest.mark.skip_xp_backends(...)
890
+ @pytest.mark.xfail_xp_backends(...)
891
+ @pytest.mark.xfail_xp_backends(...)
892
+ def test_f1(xp):
893
+ ...
894
+
895
+ etc., where the arguments of ``skip_xp_backends`` and ``xfail_xp_backends`` are
896
+ determined by the ``@xp_capabilities`` decorator applied to the functions.
897
+
898
+ See Also
899
+ --------
900
+ xp_capabilities
901
+ make_xp_pytest_marks
902
+ make_xp_pytest_param
903
+ array_api_extra.testing.lazy_xp_function
904
+ """
905
+ marks = make_xp_pytest_marks(*funcs, capabilities_table=capabilities_table)
906
+ return lambda func: functools.reduce(lambda f, g: g(f), marks, func)
907
+
908
+
909
+ def make_xp_pytest_param(func, *args, capabilities_table=None):
910
+ """Variant of ``make_xp_test_case`` that returns a pytest.param for a function,
911
+ with all necessary skip_xp_backends and xfail_xp_backends marks applied::
912
+
913
+ @pytest.mark.parametrize(
914
+ "func", [make_xp_pytest_param(f1), make_xp_pytest_param(f2)]
915
+ )
916
+ def test(func, xp):
917
+ ...
918
+
919
+ The above is equivalent to::
920
+
921
+ @pytest.mark.parametrize(
922
+ "func", [
923
+ pytest.param(f1, marks=[
924
+ pytest.mark.skip_xp_backends(...),
925
+ pytest.mark.xfail_xp_backends(...), ...]),
926
+ pytest.param(f2, marks=[
927
+ pytest.mark.skip_xp_backends(...),
928
+ pytest.mark.xfail_xp_backends(...), ...]),
929
+ )
930
+ def test(func, xp):
931
+ ...
932
+
933
+ Parameters
934
+ ----------
935
+ func : Callable
936
+ Function to be tested. It must be decorated with ``@xp_capabilities``.
937
+ *args : Any, optional
938
+ Extra pytest parameters for the use case, e.g.::
939
+
940
+ @pytest.mark.parametrize("func,verb", [
941
+ make_xp_pytest_param(f1, "hello"),
942
+ make_xp_pytest_param(f2, "world")])
943
+ def test(func, verb, xp):
944
+ # iterates on (func=f1, verb="hello")
945
+ # and (func=f2, verb="world")
946
+
947
+ See Also
948
+ --------
949
+ xp_capabilities
950
+ make_xp_test_case
951
+ make_xp_pytest_marks
952
+ array_api_extra.testing.lazy_xp_function
953
+ """
954
+ import pytest
955
+
956
+ marks = make_xp_pytest_marks(func, capabilities_table=capabilities_table)
957
+ return pytest.param(func, *args, marks=marks, id=func.__name__)
958
+
959
+
960
+ def make_xp_pytest_marks(*funcs, capabilities_table=None):
961
+ """Variant of ``make_xp_test_case`` that returns a list of pytest marks,
962
+ which can be used with the module-level `pytestmark = ...` variable::
963
+
964
+ pytestmark = make_xp_pytest_marks(f1, f2)
965
+
966
+ def test(xp):
967
+ ...
968
+
969
+ In this example, the whole test module is dedicated to testing `f1` or `f2`,
970
+ and the two functions have the same capabilities, so it's unnecessary to
971
+ cherry-pick which test tests which function.
972
+ The above is equivalent to::
973
+
974
+ pytestmark = [
975
+ pytest.mark.skip_xp_backends(...),
976
+ pytest.mark.xfail_xp_backends(...), ...]),
977
+ ]
978
+
979
+ def test(xp):
980
+ ...
981
+
982
+ See Also
983
+ --------
984
+ xp_capabilities
985
+ make_xp_test_case
986
+ make_xp_pytest_param
987
+ array_api_extra.testing.lazy_xp_function
988
+ """
989
+ capabilities_table = (xp_capabilities_table if capabilities_table is None
990
+ else capabilities_table)
991
+ import pytest
992
+
993
+ marks = []
994
+ for func in funcs:
995
+ capabilities = capabilities_table[func]
996
+ exceptions = capabilities['exceptions']
997
+ reason = capabilities['reason']
998
+
999
+ if capabilities['cpu_only']:
1000
+ marks.append(pytest.mark.skip_xp_backends(
1001
+ cpu_only=True, exceptions=exceptions, reason=reason))
1002
+ if capabilities['np_only']:
1003
+ marks.append(pytest.mark.skip_xp_backends(
1004
+ np_only=True, exceptions=exceptions, reason=reason))
1005
+
1006
+ for mod_name, reason in capabilities['skip_backends']:
1007
+ marks.append(pytest.mark.skip_xp_backends(mod_name, reason=reason))
1008
+ for mod_name, reason in capabilities['xfail_backends']:
1009
+ marks.append(pytest.mark.xfail_xp_backends(mod_name, reason=reason))
1010
+
1011
+ lazy_kwargs = {k: capabilities[k]
1012
+ for k in ('allow_dask_compute', 'jax_jit')}
1013
+ lazy_xp_function(func, **lazy_kwargs)
1014
+
1015
+ return marks
1016
+
1017
+
1018
+ # Is it OK to have a dictionary that is mutated (once upon import) in many places?
1019
+ xp_capabilities_table = {} # type: ignore[var-annotated]
1020
+
1021
+
1022
+ def xp_device_type(a: Array) -> Literal["cpu", "cuda", None]:
1023
+ if is_numpy_array(a):
1024
+ return "cpu"
1025
+ if is_cupy_array(a):
1026
+ return "cuda"
1027
+ if is_torch_array(a):
1028
+ # TODO this can return other backends e.g. tpu but they're unsupported in scipy
1029
+ return a.device.type
1030
+ if is_jax_array(a):
1031
+ # TODO this can return other backends e.g. tpu but they're unsupported in scipy
1032
+ return "cuda" if (p := a.device.platform) == "gpu" else p
1033
+ if is_dask_array(a):
1034
+ return xp_device_type(a._meta)
1035
+ # array-api-strict is a stand-in for unknown libraries; don't special-case it
1036
+ return None
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_compat_vendor.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # DO NOT RENAME THIS FILE
2
+ # This is a hook for array_api_extra/src/array_api_extra/_lib/_compat.py
3
+ # to override functions of array_api_compat.
4
+
5
+ from .array_api_compat import * # noqa: F403
6
+ from ._array_api_override import array_namespace as scipy_array_namespace
7
+
8
+ # overrides array_api_compat.array_namespace inside array-api-extra
9
+ array_namespace = scipy_array_namespace # type: ignore[assignment]
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_docs_tables.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate flat tables showing Array API capabilities for use in docs.
2
+
3
+ These tables are intended for presenting Array API capabilities across
4
+ a wide number of functions at once. Rows correspond to functions and
5
+ columns correspond to library/device/option combinations.
6
+ """
7
+
8
+ from collections import defaultdict
9
+ from enum import auto, Enum
10
+ from importlib import import_module
11
+ from types import ModuleType
12
+
13
+ from scipy._lib._array_api import xp_capabilities_table
14
+ from scipy._lib._array_api import _make_sphinx_capabilities
15
+
16
+ # For undocumented aliases of public functions which are kept around for
17
+ # backwards compatibility reasons. These should be excluded from the
18
+ # tables since they would be redundant. There are also no docs pages to
19
+ # link entries to.
20
+ ALIASES = {
21
+ "scipy.linalg": {
22
+ # Alias of scipy.linalg.solve_continuous_lyapunov
23
+ "solve_lyapunov",
24
+ },
25
+ "scipy.ndimage": {
26
+ # Alias of scipy.ndimage.sum_labels
27
+ "sum",
28
+ },
29
+ "scipy.special": {
30
+ # Alias of scipy.special.jv
31
+ "jn",
32
+ # Alias of scipy.special.roots_legendre
33
+ "p_roots",
34
+ # Alias of scipy.special.roots_chebyt
35
+ "t_roots",
36
+ # Alias of scipy.special.roots_chebyu
37
+ "u_roots",
38
+ # Alias of scipy.special.roots_chebyc
39
+ "c_roots",
40
+ # Alias of scipy.special.roots_chebys
41
+ "s_roots",
42
+ # Alias of scipy.special.roots_jacobi
43
+ "j_roots",
44
+ # Alias of scipy.special.roots_laguerre
45
+ "l_roots",
46
+ # Alias of scipy.special.roots_genlaguerre
47
+ "la_roots",
48
+ # Alias of scipy.special.roots_hermite
49
+ "h_roots",
50
+ # Alias of scipy.special.roots_hermitenorm
51
+ "he_roots",
52
+ # Alias of scipy.special.roots_gegenbauer
53
+ "cg_roots",
54
+ # Alias of scipy.special.roots_sh_legendre
55
+ "ps_roots",
56
+ # Alias of scipy.special.roots_sh_chebyt
57
+ "ts_roots",
58
+ # Alias of scipy.special.roots_chebyu
59
+ "us_roots",
60
+ # Alias of scipy.special.roots_sh_jacobi
61
+ "js_roots",
62
+ }
63
+ }
64
+
65
+ # Shortened names for use in table.
66
+ BACKEND_NAMES_MAP = {
67
+ "jax.numpy": "jax",
68
+ "dask.array": "dask",
69
+ }
70
+
71
+
72
+ class BackendSupportStatus(Enum):
73
+ YES = auto()
74
+ NO = auto()
75
+ OUT_OF_SCOPE = auto()
76
+ UNKNOWN = auto()
77
+
78
+
79
+ def _process_capabilities_table_entry(entry: dict | None) -> dict[str, dict[str, bool]]:
80
+ """Returns dict showing alternative backend support in easy to consume form.
81
+
82
+ Parameters
83
+ ----------
84
+ entry : Optional[dict]
85
+ A dict with the structure of the values of the dict
86
+ scipy._lib._array_api.xp_capabilities_table. If None, it is
87
+ assumped that no alternative backends are supported.
88
+ Default: None.
89
+
90
+ Returns
91
+ -------
92
+ dict[str, dict[str, bool]]
93
+ The output dict currently has keys "cpu", "gpu", "jit" and "lazy".
94
+ The value associated to each key is itself a dict. The keys of
95
+ the inner dicts correspond to backends, with bool values stating
96
+ whether or not the backend is supported with a given device or
97
+ mode. Inapplicable backends do not appear in the inner dicts
98
+ (e.g. since cupy is gpu-only, it does not appear in the inner
99
+ dict keyed on "cpu"). Only alternative backends to NumPy are
100
+ included since NumPY support should be guaranteed.
101
+
102
+ """
103
+ # This is a template for the output format. If more backends and
104
+ # backend options are added, it will need to be updated manually.
105
+ # Entries start as boolean, but upon returning, will take values
106
+ # from the BackendSupportStatus Enum.
107
+ output = {
108
+ "cpu": {"torch": False, "jax": False, "dask": False},
109
+ "gpu": {"cupy": False, "torch": False, "jax": False},
110
+ "jit": {"jax": False},
111
+ "lazy": {"dask": False},
112
+ }
113
+ S = BackendSupportStatus
114
+ if entry is None:
115
+ # If there is no entry, assume no alternative backends are supported.
116
+ # If the list of supported backends will grows, this hard-coded dict
117
+ # will need to be updated.
118
+ return {
119
+ outer_key: {inner_key: S.UNKNOWN for inner_key in outer_value}
120
+ for outer_key, outer_value in output.items()
121
+ }
122
+
123
+ if entry["out_of_scope"]:
124
+ # None is used to signify out-of-scope functions.
125
+ return {
126
+ outer_key: {inner_key: S.OUT_OF_SCOPE for inner_key in outer_value}
127
+ for outer_key, outer_value in output.items()
128
+ }
129
+
130
+ # For now, use _make_sphinx_capabilities because that's where
131
+ # the relevant logic for determining what is and isn't
132
+ # supported based on xp_capabilities_table entries lives.
133
+ # Perhaps this logic should be decoupled from sphinx.
134
+ for backend, capabilities in _make_sphinx_capabilities(**entry).items():
135
+ if backend in {"array_api_strict", "numpy"}:
136
+ continue
137
+ backend = BACKEND_NAMES_MAP.get(backend, backend)
138
+ cpu, gpu = capabilities.cpu, capabilities.gpu
139
+ if cpu is not None:
140
+ if backend not in output["cpu"]:
141
+ raise ValueError(
142
+ "Input capabilities table entry contains unhandled"
143
+ f" backend {backend} on cpu."
144
+ )
145
+ output["cpu"][backend] = cpu
146
+ if gpu is not None:
147
+ if backend not in output["gpu"]:
148
+ raise ValueError(
149
+ "Input capabilities table entry contains unhandled"
150
+ f" backend {backend} on gpu."
151
+ )
152
+ output["gpu"][backend] = gpu
153
+ if backend == "jax":
154
+ output["jit"]["jax"] = entry["jax_jit"] and output["cpu"]["jax"]
155
+ if backend == "dask.array":
156
+ support_lazy = not entry["allow_dask_compute"] and output["dask"]
157
+ output["lazy"]["dask"] = support_lazy
158
+ return {
159
+ outer_key: {
160
+ inner_key: S.YES if inner_value else S.NO
161
+ for inner_key, inner_value in outer_value.items()
162
+ }
163
+ for outer_key, outer_value in output.items()
164
+ }
165
+
166
+
167
+ def is_named_function_like_object(obj):
168
+ return (
169
+ not isinstance(obj, ModuleType | type)
170
+ and callable(obj) and hasattr(obj, "__name__")
171
+ )
172
+
173
+
174
+ def make_flat_capabilities_table(
175
+ modules: str | list[str],
176
+ backend_type: str,
177
+ /,
178
+ *,
179
+ capabilities_table: list[str] | None = None,
180
+ ) -> list[dict[str, str]]:
181
+ """Generate full table of array api capabilities across public functions.
182
+
183
+ Parameters
184
+ ----------
185
+ modules : str | list[str]
186
+ A string containing single SciPy module, (e.g `scipy.stats`, `scipy.fft`)
187
+ or a list of such strings.
188
+
189
+ backend_type : {'cpu', 'gpu', 'jit', 'lazy'}
190
+
191
+ capabilities_table : Optional[list[str]]
192
+ Table in the form of `scipy._lib._array_api.xp_capabilities_table`.
193
+ If None, uses `scipy._lib._array_api.xp_capabilities_table`.
194
+ Default: None.
195
+
196
+ Returns
197
+ -------
198
+ output : list[dict[str, str]]
199
+ `output` is a table in dict format
200
+ (keys corresponding to column names). The first column is "module".
201
+ The other columns correspond to supported backends for the given
202
+ `backend_type`, e.g. jax.numpy, torch, and dask on cpu.
203
+ numpy is excluded because it should always be supported.
204
+ See the helper function
205
+ `_process_capabilities_table_entry` above).
206
+
207
+ """
208
+ if backend_type not in {"cpu", "gpu", "jit", "lazy"}:
209
+ raise ValueError(f"Received unhandled backend type {backend_type}")
210
+
211
+ if isinstance(modules, str):
212
+ modules = [modules]
213
+
214
+ if capabilities_table is None:
215
+ capabilities_table = xp_capabilities_table
216
+
217
+ output = []
218
+
219
+ for module_name in modules:
220
+ module = import_module(module_name)
221
+ public_things = module.__all__
222
+ for name in public_things:
223
+ if name in ALIASES.get(module_name, {}):
224
+ # Skip undocumented aliases that are kept
225
+ # for backwards compatibility reasons.
226
+ continue
227
+ thing = getattr(module, name)
228
+ if not is_named_function_like_object(thing):
229
+ continue
230
+ entry = xp_capabilities_table.get(thing, None)
231
+ capabilities = _process_capabilities_table_entry(entry)[backend_type]
232
+ row = {"module": module_name}
233
+ row.update({"function": name})
234
+ row.update(capabilities)
235
+ output.append(row)
236
+ return output
237
+
238
+
239
+ def calculate_table_statistics(
240
+ flat_table: list[dict[str, str]]
241
+ ) -> dict[str, tuple[dict[str, str], bool]]:
242
+ """Get counts of what is supported per module.
243
+
244
+ Parameters
245
+ ----------
246
+ flat_table : list[dict[str, str]]
247
+ A table as returned by `make_flat_capabilities_table`
248
+
249
+ Returns
250
+ -------
251
+ dict[str, tuple[dict[str, str], bool]]
252
+ dict mapping module names to 2-tuples containing an inner dict and a
253
+ bool. The inner dicts have a key "total" along with keys for each
254
+ backend column of the supplied flat capabilities table. The value
255
+ corresponding to total is the total count of functions in the given
256
+ module, and the value associated to the other keys is the count of
257
+ functions that support that particular backend. The bool is False if
258
+ the calculation may be innacurate due to missing xp_capabilities
259
+ decorators, and True if all functions for that particular module have
260
+ been decorated with xp_capabilities.
261
+ """
262
+ if not flat_table:
263
+ return []
264
+
265
+ counter = defaultdict(lambda: defaultdict(int))
266
+
267
+ S = BackendSupportStatus
268
+ # Keep track of which modules have functions with missing xp_capabilities
269
+ # decorators so this information can be passed back to the caller.
270
+ missing_xp_capabilities = set()
271
+ for entry in flat_table:
272
+ entry = entry.copy()
273
+ entry.pop("function")
274
+ module = entry.pop("module")
275
+ current_counter = counter[module]
276
+
277
+ # By design, all backends and options must be considered out-of-scope
278
+ # if one is, so just pick an arbitrary entry here to test if function is
279
+ # in-scope.
280
+ if next(iter(entry.values())) != S.OUT_OF_SCOPE:
281
+ current_counter["total"] += 1
282
+ for key, value in entry.items():
283
+ # Functions missing xp_capabilities will be tabulated as
284
+ # unsupported, but may actually be supported. There is a
285
+ # note about this in the documentation and this function is
286
+ # set up to return information needed to put asterisks next
287
+ # to percentages impacted by missing xp_capabilities decorators.
288
+ current_counter[key] += 1 if value == S.YES else 0
289
+ if value == S.UNKNOWN:
290
+ missing_xp_capabilities.add(module)
291
+ return {
292
+ key: (dict(value), key not in missing_xp_capabilities)
293
+ for key, value in counter.items()
294
+ }
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_no_0d.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Extra testing functions that forbid 0d-input, see #21044
3
+
4
+ While the xp_assert_* functions generally aim to follow the conventions of the
5
+ underlying `xp` library, NumPy in particular is inconsistent in its handling
6
+ of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897.
7
+
8
+ For example, this means that the following operations (as of v2.0.1) currently
9
+ return scalars, even though a 0d-array would often be more appropriate:
10
+
11
+ import numpy as np
12
+ np.array(0) * 2 # scalar, not 0d array
13
+ - np.array(0) # scalar, not 0d-array
14
+ np.sin(np.array(0)) # scalar, not 0d array
15
+ np.mean([1, 2, 3]) # scalar, not 0d array
16
+
17
+ Libraries like CuPy tend to return a 0d-array in scenarios like those above,
18
+ and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality
19
+ of the inconsistencies present in NumPy, as well as 20+ years of code on top,
20
+ the `xp_assert_*` functions here enforce consistency in the only way that
21
+ doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type.
22
+
23
+ However, when scalars are not generally the expected NumPy return type,
24
+ it remains preferable to use the assert functions from
25
+ the `scipy._lib._array_api` module, which have less surprising behaviour.
26
+ """
27
+ from scipy._lib._array_api import array_namespace, is_numpy
28
+ from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base,
29
+ xp_assert_equal as xp_assert_equal_base,
30
+ xp_assert_less as xp_assert_less_base)
31
+
32
+ __all__: list[str] = []
33
+
34
+
35
+ def _check_scalar(actual, desired, *, xp=None, **kwargs):
36
+ __tracebackhide__ = True # Hide traceback for py.test
37
+
38
+ if xp is None:
39
+ xp = array_namespace(actual)
40
+
41
+ # necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape
42
+ desired = xp.asarray(desired)
43
+
44
+ # Only NumPy distinguishes between scalars and arrays;
45
+ # shape check in xp_assert_* is sufficient except for shape == ()
46
+ if not (is_numpy(xp) and desired.shape == ()):
47
+ return
48
+
49
+ _msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow "
50
+ "the convention of many NumPy functions, returning a scalar when a "
51
+ "0d-array would be correct. The specialized `xp_assert_*` functions "
52
+ "in the `scipy._lib._array_api_no_0d` module err on the side of "
53
+ "caution and do not accept 0d-arrays by default. If the correct "
54
+ "result may legitimately be a 0d-array, pass `check_0d=True`, "
55
+ "or use the `xp_assert_*` functions from `scipy._lib._array_api`.")
56
+ assert xp.isscalar(actual), _msg
57
+
58
+
59
+ def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs):
60
+ # in contrast to xp_assert_equal_base, this defaults to check_0d=False,
61
+ # but will do an extra check in that case, which forbids 0d-arrays for `actual`
62
+ __tracebackhide__ = True # Hide traceback for py.test
63
+
64
+ # array-ness (check_0d == True) is taken care of by the *_base functions
65
+ if not check_0d:
66
+ _check_scalar(actual, desired, **kwargs)
67
+ return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs)
68
+
69
+
70
+ def xp_assert_close(actual, desired, *, check_0d=False, **kwargs):
71
+ # as for xp_assert_equal
72
+ __tracebackhide__ = True
73
+
74
+ if not check_0d:
75
+ _check_scalar(actual, desired, **kwargs)
76
+ return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs)
77
+
78
+
79
+ def xp_assert_less(actual, desired, *, check_0d=False, **kwargs):
80
+ # as for xp_assert_equal
81
+ __tracebackhide__ = True
82
+
83
+ if not check_0d:
84
+ _check_scalar(actual, desired, **kwargs)
85
+ return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs)
86
+
87
+
88
+ def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
89
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
90
+ """
91
+ rtol, atol = 0, 1.5*10**(-decimal)
92
+ return xp_assert_close(actual, desired,
93
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
94
+ *args, **kwds)
95
+
96
+
97
+ def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
98
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
99
+ """
100
+ rtol, atol = 0, 1.5*10**(-decimal)
101
+ return xp_assert_close(actual, desired,
102
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
103
+ *args, **kwds)
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_override.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Override functions from array_api_compat, for use by array-api-extra
3
+ and internally.
4
+
5
+ See also _array_api_compat_vendor.py
6
+ """
7
+ import enum
8
+ import os
9
+
10
+ from functools import lru_cache
11
+ from types import ModuleType
12
+ from typing import Any, TypeAlias
13
+
14
+ import numpy as np
15
+ import numpy.typing as npt
16
+
17
+ from scipy._lib import array_api_compat
18
+ import scipy._lib.array_api_compat.numpy as np_compat
19
+ from scipy._lib.array_api_compat import is_array_api_obj, is_jax_array
20
+ from scipy._lib._sparse import SparseABC
21
+
22
+
23
+ Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589)
24
+ ArrayLike: TypeAlias = Array | npt.ArrayLike
25
+
26
+ # To enable array API and strict array-like input validation
27
+ SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False)
28
+ # To control the default device - for use in the test suite only
29
+ SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu")
30
+
31
+
32
+ class _ArrayClsInfo(enum.Enum):
33
+ skip = 0
34
+ numpy = 1
35
+ array_like = 2
36
+ unknown = 3
37
+
38
+
39
+ @lru_cache(100)
40
+ def _validate_array_cls(cls: type) -> _ArrayClsInfo:
41
+ if issubclass(cls, (list, tuple)):
42
+ return _ArrayClsInfo.array_like
43
+
44
+ # this comes from `_util._asarray_validated`
45
+ if issubclass(cls, SparseABC):
46
+ msg = ('Sparse arrays/matrices are not supported by this function. '
47
+ 'Perhaps one of the `scipy.sparse.linalg` functions '
48
+ 'would work instead.')
49
+ raise ValueError(msg)
50
+
51
+ if issubclass(cls, np.ma.MaskedArray):
52
+ raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.")
53
+
54
+ if issubclass(cls, np.matrix):
55
+ raise TypeError("Inputs of type `numpy.matrix` are not supported.")
56
+
57
+ if issubclass(cls, (np.ndarray, np.generic)):
58
+ return _ArrayClsInfo.numpy
59
+
60
+ # Note: this must happen after the test for np.generic, because
61
+ # np.float64 and np.complex128 are subclasses of float and complex respectively.
62
+ # This matches the behavior of array_api_compat.
63
+ if issubclass(cls, (int, float, complex, bool, type(None))):
64
+ return _ArrayClsInfo.skip
65
+
66
+ return _ArrayClsInfo.unknown
67
+
68
+
69
+ def array_namespace(*arrays: Array) -> ModuleType:
70
+ """Get the array API compatible namespace for the arrays xs.
71
+
72
+ Parameters
73
+ ----------
74
+ *arrays : sequence of array_like
75
+ Arrays used to infer the common namespace.
76
+
77
+ Returns
78
+ -------
79
+ namespace : module
80
+ Common namespace.
81
+
82
+ Notes
83
+ -----
84
+ Wrapper around `array_api_compat.array_namespace`.
85
+
86
+ 1. Check for the global switch `SCIPY_ARRAY_API`. If disabled, just
87
+ return array_api_compat.numpy namespace and skip all compliance checks.
88
+
89
+ 2. Check for known-bad array classes.
90
+ The following subclasses are not supported and raise and error:
91
+
92
+ - `numpy.ma.MaskedArray`
93
+ - `numpy.matrix`
94
+ - NumPy arrays which do not have a boolean or numerical dtype
95
+ - `scipy.sparse` arrays
96
+
97
+ 3. Coerce array-likes to NumPy arrays and check their dtype.
98
+ Note that non-scalar array-likes can't be mixed with non-NumPy Array
99
+ API objects; e.g.
100
+
101
+ - `array_namespace([1, 2])` returns NumPy namespace;
102
+ - `array_namespace(np.asarray([1, 2], [3, 4])` returns NumPy namespace;
103
+ - `array_namespace(cp.asarray([1, 2], [3, 4])` raises an error.
104
+ """
105
+ if not SCIPY_ARRAY_API:
106
+ # here we could wrap the namespace if needed
107
+ return np_compat
108
+
109
+ numpy_arrays = []
110
+ api_arrays = []
111
+
112
+ for array in arrays:
113
+ arr_info = _validate_array_cls(type(array))
114
+ if arr_info is _ArrayClsInfo.skip:
115
+ pass
116
+
117
+ elif arr_info is _ArrayClsInfo.numpy:
118
+ if array.dtype.kind in 'iufcb': # Numeric or bool
119
+ numpy_arrays.append(array)
120
+ elif array.dtype.kind == 'V' and is_jax_array(array):
121
+ # Special case for JAX zero gradient arrays;
122
+ # see array_api_compat._common._helpers._is_jax_zero_gradient_array
123
+ api_arrays.append(array) # JAX zero gradient array
124
+ else:
125
+ raise TypeError(f"An argument has dtype `{array.dtype!r}`; "
126
+ "only boolean and numerical dtypes are supported.")
127
+
128
+ elif arr_info is _ArrayClsInfo.unknown and is_array_api_obj(array):
129
+ api_arrays.append(array)
130
+
131
+ else:
132
+ # list, tuple, or arbitrary object
133
+ try:
134
+ array = np.asanyarray(array)
135
+ except TypeError:
136
+ raise TypeError("An argument is neither array API compatible nor "
137
+ "coercible by NumPy.")
138
+ if array.dtype.kind not in 'iufcb': # Numeric or bool
139
+ raise TypeError(f"An argument has dtype `{array.dtype!r}`; "
140
+ "only boolean and numerical dtypes are supported.")
141
+ numpy_arrays.append(array)
142
+
143
+ # When there are exclusively NumPy and ArrayLikes, skip calling
144
+ # array_api_compat.array_namespace for performance.
145
+ if not api_arrays:
146
+ return np_compat
147
+
148
+ # In case of mix of NumPy/ArrayLike and non-NumPy Array API arrays,
149
+ # let array_api_compat.array_namespace raise an error.
150
+ return array_api_compat.array_namespace(*numpy_arrays, *api_arrays)
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_bunch.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys as _sys
2
+ from keyword import iskeyword as _iskeyword
3
+
4
+
5
+ def _validate_names(typename, field_names, extra_field_names):
6
+ """
7
+ Ensure that all the given names are valid Python identifiers that
8
+ do not start with '_'. Also check that there are no duplicates
9
+ among field_names + extra_field_names.
10
+ """
11
+ for name in [typename] + field_names + extra_field_names:
12
+ if not isinstance(name, str):
13
+ raise TypeError('typename and all field names must be strings')
14
+ if not name.isidentifier():
15
+ raise ValueError('typename and all field names must be valid '
16
+ f'identifiers: {name!r}')
17
+ if _iskeyword(name):
18
+ raise ValueError('typename and all field names cannot be a '
19
+ f'keyword: {name!r}')
20
+
21
+ seen = set()
22
+ for name in field_names + extra_field_names:
23
+ if name.startswith('_'):
24
+ raise ValueError('Field names cannot start with an underscore: '
25
+ f'{name!r}')
26
+ if name in seen:
27
+ raise ValueError(f'Duplicate field name: {name!r}')
28
+ seen.add(name)
29
+
30
+
31
+ # Note: This code is adapted from CPython:Lib/collections/__init__.py
32
+ def _make_tuple_bunch(typename, field_names, extra_field_names=None,
33
+ module=None):
34
+ """
35
+ Create a namedtuple-like class with additional attributes.
36
+
37
+ This function creates a subclass of tuple that acts like a namedtuple
38
+ and that has additional attributes.
39
+
40
+ The additional attributes are listed in `extra_field_names`. The
41
+ values assigned to these attributes are not part of the tuple.
42
+
43
+ The reason this function exists is to allow functions in SciPy
44
+ that currently return a tuple or a namedtuple to returned objects
45
+ that have additional attributes, while maintaining backwards
46
+ compatibility.
47
+
48
+ This should only be used to enhance *existing* functions in SciPy.
49
+ New functions are free to create objects as return values without
50
+ having to maintain backwards compatibility with an old tuple or
51
+ namedtuple return value.
52
+
53
+ Parameters
54
+ ----------
55
+ typename : str
56
+ The name of the type.
57
+ field_names : list of str
58
+ List of names of the values to be stored in the tuple. These names
59
+ will also be attributes of instances, so the values in the tuple
60
+ can be accessed by indexing or as attributes. At least one name
61
+ is required. See the Notes for additional restrictions.
62
+ extra_field_names : list of str, optional
63
+ List of names of values that will be stored as attributes of the
64
+ object. See the notes for additional restrictions.
65
+
66
+ Returns
67
+ -------
68
+ cls : type
69
+ The new class.
70
+
71
+ Notes
72
+ -----
73
+ There are restrictions on the names that may be used in `field_names`
74
+ and `extra_field_names`:
75
+
76
+ * The names must be unique--no duplicates allowed.
77
+ * The names must be valid Python identifiers, and must not begin with
78
+ an underscore.
79
+ * The names must not be Python keywords (e.g. 'def', 'and', etc., are
80
+ not allowed).
81
+
82
+ Examples
83
+ --------
84
+ >>> from scipy._lib._bunch import _make_tuple_bunch
85
+
86
+ Create a class that acts like a namedtuple with length 2 (with field
87
+ names `x` and `y`) that will also have the attributes `w` and `beta`:
88
+
89
+ >>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta'])
90
+
91
+ `Result` is the new class. We call it with keyword arguments to create
92
+ a new instance with given values.
93
+
94
+ >>> result1 = Result(x=1, y=2, w=99, beta=0.5)
95
+ >>> result1
96
+ Result(x=1, y=2, w=99, beta=0.5)
97
+
98
+ `result1` acts like a tuple of length 2:
99
+
100
+ >>> len(result1)
101
+ 2
102
+ >>> result1[:]
103
+ (1, 2)
104
+
105
+ The values assigned when the instance was created are available as
106
+ attributes:
107
+
108
+ >>> result1.y
109
+ 2
110
+ >>> result1.beta
111
+ 0.5
112
+ """
113
+ if len(field_names) == 0:
114
+ raise ValueError('field_names must contain at least one name')
115
+
116
+ if extra_field_names is None:
117
+ extra_field_names = []
118
+ _validate_names(typename, field_names, extra_field_names)
119
+
120
+ typename = _sys.intern(str(typename))
121
+ field_names = tuple(map(_sys.intern, field_names))
122
+ extra_field_names = tuple(map(_sys.intern, extra_field_names))
123
+
124
+ all_names = field_names + extra_field_names
125
+ arg_list = ', '.join(field_names)
126
+ full_list = ', '.join(all_names)
127
+ repr_fmt = ''.join(('(',
128
+ ', '.join(f'{name}=%({name})r' for name in all_names),
129
+ ')'))
130
+ tuple_new = tuple.__new__
131
+ _dict, _tuple, _zip = dict, tuple, zip
132
+
133
+ # Create all the named tuple methods to be added to the class namespace
134
+
135
+ s = f"""\
136
+ def __new__(_cls, {arg_list}, **extra_fields):
137
+ return _tuple_new(_cls, ({arg_list},))
138
+
139
+ def __init__(self, {arg_list}, **extra_fields):
140
+ for key in self._extra_fields:
141
+ if key not in extra_fields:
142
+ raise TypeError("missing keyword argument '%s'" % (key,))
143
+ for key, val in extra_fields.items():
144
+ if key not in self._extra_fields:
145
+ raise TypeError("unexpected keyword argument '%s'" % (key,))
146
+ self.__dict__[key] = val
147
+
148
+ def __setattr__(self, key, val):
149
+ if key in {repr(field_names)}:
150
+ raise AttributeError("can't set attribute %r of class %r"
151
+ % (key, self.__class__.__name__))
152
+ else:
153
+ self.__dict__[key] = val
154
+ """
155
+ del arg_list
156
+ namespace = {'_tuple_new': tuple_new,
157
+ '__builtins__': dict(TypeError=TypeError,
158
+ AttributeError=AttributeError),
159
+ '__name__': f'namedtuple_{typename}'}
160
+ exec(s, namespace)
161
+ __new__ = namespace['__new__']
162
+ __new__.__doc__ = f'Create new instance of {typename}({full_list})'
163
+ __init__ = namespace['__init__']
164
+ __init__.__doc__ = f'Instantiate instance of {typename}({full_list})'
165
+ __setattr__ = namespace['__setattr__']
166
+
167
+ def __repr__(self):
168
+ 'Return a nicely formatted representation string'
169
+ return self.__class__.__name__ + repr_fmt % self._asdict()
170
+
171
+ def _asdict(self):
172
+ 'Return a new dict which maps field names to their values.'
173
+ out = _dict(_zip(self._fields, self))
174
+ out.update(self.__dict__)
175
+ return out
176
+
177
+ def __getnewargs_ex__(self):
178
+ 'Return self as a plain tuple. Used by copy and pickle.'
179
+ return _tuple(self), self.__dict__
180
+
181
+ # Modify function metadata to help with introspection and debugging
182
+ for method in (__new__, __repr__, _asdict, __getnewargs_ex__):
183
+ method.__qualname__ = f'{typename}.{method.__name__}'
184
+
185
+ # Build-up the class namespace dictionary
186
+ # and use type() to build the result class
187
+ class_namespace = {
188
+ '__doc__': f'{typename}({full_list})',
189
+ '_fields': field_names,
190
+ '__new__': __new__,
191
+ '__init__': __init__,
192
+ '__repr__': __repr__,
193
+ '__setattr__': __setattr__,
194
+ '_asdict': _asdict,
195
+ '_extra_fields': extra_field_names,
196
+ '__getnewargs_ex__': __getnewargs_ex__,
197
+ # _field_defaults and _replace are added to get Polars to detect
198
+ # a bunch object as a namedtuple. See gh-22450
199
+ '_field_defaults': {},
200
+ '_replace': None,
201
+ }
202
+ for index, name in enumerate(field_names):
203
+
204
+ def _get(self, index=index):
205
+ return self[index]
206
+ class_namespace[name] = property(_get)
207
+ for name in extra_field_names:
208
+
209
+ def _get(self, name=name):
210
+ return self.__dict__[name]
211
+ class_namespace[name] = property(_get)
212
+
213
+ result = type(typename, (tuple,), class_namespace)
214
+
215
+ # For pickling to work, the __module__ variable needs to be set to the
216
+ # frame where the named tuple is created. Bypass this step in environments
217
+ # where sys._getframe is not defined (Jython for example) or sys._getframe
218
+ # is not defined for arguments greater than 0 (IronPython), or where the
219
+ # user has specified a particular module.
220
+ if module is None:
221
+ try:
222
+ module = _sys._getframe(1).f_globals.get('__name__', '__main__')
223
+ except (AttributeError, ValueError):
224
+ pass
225
+ if module is not None:
226
+ result.__module__ = module
227
+ __new__.__module__ = module
228
+
229
+ return result
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import _ccallback_c
2
+
3
+ import ctypes
4
+
5
+ PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0]
6
+
7
+ ffi = None
8
+
9
+ class CData:
10
+ pass
11
+
12
+ def _import_cffi():
13
+ global ffi, CData
14
+
15
+ if ffi is not None:
16
+ return
17
+
18
+ try:
19
+ import cffi
20
+ ffi = cffi.FFI()
21
+ CData = ffi.CData
22
+ except ImportError:
23
+ ffi = False
24
+
25
+
26
+ class LowLevelCallable(tuple):
27
+ """
28
+ Low-level callback function.
29
+
30
+ Some functions in SciPy take as arguments callback functions, which
31
+ can either be python callables or low-level compiled functions. Using
32
+ compiled callback functions can improve performance somewhat by
33
+ avoiding wrapping data in Python objects.
34
+
35
+ Such low-level functions in SciPy are wrapped in `LowLevelCallable`
36
+ objects, which can be constructed from function pointers obtained from
37
+ ctypes, cffi, Cython, or contained in Python `PyCapsule` objects.
38
+
39
+ .. seealso::
40
+
41
+ Functions accepting low-level callables:
42
+
43
+ `scipy.integrate.quad`, `scipy.ndimage.generic_filter`,
44
+ `scipy.ndimage.generic_filter1d`, `scipy.ndimage.geometric_transform`
45
+
46
+ Usage examples:
47
+
48
+ :ref:`ndimage-ccallbacks`, :ref:`quad-callbacks`
49
+
50
+ Parameters
51
+ ----------
52
+ function : {PyCapsule, ctypes function pointer, cffi function pointer}
53
+ Low-level callback function.
54
+ user_data : {PyCapsule, ctypes void pointer, cffi void pointer}
55
+ User data to pass on to the callback function.
56
+ signature : str, optional
57
+ Signature of the function. If omitted, determined from *function*,
58
+ if possible.
59
+
60
+ Attributes
61
+ ----------
62
+ function
63
+ Callback function given.
64
+ user_data
65
+ User data given.
66
+ signature
67
+ Signature of the function.
68
+
69
+ Methods
70
+ -------
71
+ from_cython
72
+ Class method for constructing callables from Cython C-exported
73
+ functions.
74
+
75
+ Notes
76
+ -----
77
+ The argument ``function`` can be one of:
78
+
79
+ - PyCapsule, whose name contains the C function signature
80
+ - ctypes function pointer
81
+ - cffi function pointer
82
+
83
+ The signature of the low-level callback must match one of those expected
84
+ by the routine it is passed to.
85
+
86
+ If constructing low-level functions from a PyCapsule, the name of the
87
+ capsule must be the corresponding signature, in the format::
88
+
89
+ return_type (arg1_type, arg2_type, ...)
90
+
91
+ For example::
92
+
93
+ "void (double)"
94
+ "double (double, int *, void *)"
95
+
96
+ The context of a PyCapsule passed in as ``function`` is used as ``user_data``,
97
+ if an explicit value for ``user_data`` was not given.
98
+
99
+ """
100
+
101
+ # Make the class immutable
102
+ __slots__ = ()
103
+
104
+ def __new__(cls, function, user_data=None, signature=None):
105
+ # We need to hold a reference to the function & user data,
106
+ # to prevent them going out of scope
107
+ item = cls._parse_callback(function, user_data, signature)
108
+ return tuple.__new__(cls, (item, function, user_data))
109
+
110
+ def __repr__(self):
111
+ return f"LowLevelCallable({self.function!r}, {self.user_data!r})"
112
+
113
+ @property
114
+ def function(self):
115
+ return tuple.__getitem__(self, 1)
116
+
117
+ @property
118
+ def user_data(self):
119
+ return tuple.__getitem__(self, 2)
120
+
121
+ @property
122
+ def signature(self):
123
+ return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0))
124
+
125
+ def __getitem__(self, idx):
126
+ raise ValueError()
127
+
128
+ @classmethod
129
+ def from_cython(cls, module, name, user_data=None, signature=None):
130
+ """
131
+ Create a low-level callback function from an exported Cython function.
132
+
133
+ Parameters
134
+ ----------
135
+ module : module
136
+ Cython module where the exported function resides
137
+ name : str
138
+ Name of the exported function
139
+ user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional
140
+ User data to pass on to the callback function.
141
+ signature : str, optional
142
+ Signature of the function. If omitted, determined from *function*.
143
+
144
+ """
145
+ try:
146
+ function = module.__pyx_capi__[name]
147
+ except AttributeError as e:
148
+ message = "Given module is not a Cython module with __pyx_capi__ attribute"
149
+ raise ValueError(message) from e
150
+ except KeyError as e:
151
+ message = f"No function {name!r} found in __pyx_capi__ of the module"
152
+ raise ValueError(message) from e
153
+ return cls(function, user_data, signature)
154
+
155
+ @classmethod
156
+ def _parse_callback(cls, obj, user_data=None, signature=None):
157
+ _import_cffi()
158
+
159
+ if isinstance(obj, LowLevelCallable):
160
+ func = tuple.__getitem__(obj, 0)
161
+ elif isinstance(obj, PyCFuncPtr):
162
+ func, signature = _get_ctypes_func(obj, signature)
163
+ elif isinstance(obj, CData):
164
+ func, signature = _get_cffi_func(obj, signature)
165
+ elif _ccallback_c.check_capsule(obj):
166
+ func = obj
167
+ else:
168
+ raise ValueError("Given input is not a callable or a "
169
+ "low-level callable (pycapsule/ctypes/cffi)")
170
+
171
+ if isinstance(user_data, ctypes.c_void_p):
172
+ context = _get_ctypes_data(user_data)
173
+ elif isinstance(user_data, CData):
174
+ context = _get_cffi_data(user_data)
175
+ elif user_data is None:
176
+ context = 0
177
+ elif _ccallback_c.check_capsule(user_data):
178
+ context = user_data
179
+ else:
180
+ raise ValueError("Given user data is not a valid "
181
+ "low-level void* pointer (pycapsule/ctypes/cffi)")
182
+
183
+ return _ccallback_c.get_raw_capsule(func, signature, context)
184
+
185
+
186
+ #
187
+ # ctypes helpers
188
+ #
189
+
190
+ def _get_ctypes_func(func, signature=None):
191
+ # Get function pointer
192
+ func_ptr = ctypes.cast(func, ctypes.c_void_p).value
193
+
194
+ # Construct function signature
195
+ if signature is None:
196
+ signature = _typename_from_ctypes(func.restype) + " ("
197
+ for j, arg in enumerate(func.argtypes):
198
+ if j == 0:
199
+ signature += _typename_from_ctypes(arg)
200
+ else:
201
+ signature += ", " + _typename_from_ctypes(arg)
202
+ signature += ")"
203
+
204
+ return func_ptr, signature
205
+
206
+
207
+ def _typename_from_ctypes(item):
208
+ if item is None:
209
+ return "void"
210
+ elif item is ctypes.c_void_p:
211
+ return "void *"
212
+
213
+ name = item.__name__
214
+
215
+ pointer_level = 0
216
+ while name.startswith("LP_"):
217
+ pointer_level += 1
218
+ name = name[3:]
219
+
220
+ if name.startswith('c_'):
221
+ name = name[2:]
222
+
223
+ if pointer_level > 0:
224
+ name += " " + "*"*pointer_level
225
+
226
+ return name
227
+
228
+
229
+ def _get_ctypes_data(data):
230
+ # Get voidp pointer
231
+ return ctypes.cast(data, ctypes.c_void_p).value
232
+
233
+
234
+ #
235
+ # CFFI helpers
236
+ #
237
+
238
+ def _get_cffi_func(func, signature=None):
239
+ # Get function pointer
240
+ func_ptr = ffi.cast('uintptr_t', func)
241
+
242
+ # Get signature
243
+ if signature is None:
244
+ signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ')
245
+
246
+ return func_ptr, signature
247
+
248
+
249
+ def _get_cffi_data(data):
250
+ # Get pointer
251
+ return ffi.cast('uintptr_t', data)
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a ADDED
Binary file (1.61 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:509d2e681897f4253263c063ad8a2aa0c2459b85ce3d86754b401d42ab26dc9a
3
+ size 105472
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_disjoint_set.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Disjoint set data structure
3
+ """
4
+
5
+
6
+ class DisjointSet:
7
+ """ Disjoint set data structure for incremental connectivity queries.
8
+
9
+ .. versionadded:: 1.6.0
10
+
11
+ Attributes
12
+ ----------
13
+ n_subsets : int
14
+ The number of subsets.
15
+
16
+ Methods
17
+ -------
18
+ add
19
+ merge
20
+ connected
21
+ subset
22
+ subset_size
23
+ subsets
24
+ __getitem__
25
+
26
+ Notes
27
+ -----
28
+ This class implements the disjoint set [1]_, also known as the *union-find*
29
+ or *merge-find* data structure. The *find* operation (implemented in
30
+ `__getitem__`) implements the *path halving* variant. The *merge* method
31
+ implements the *merge by size* variant.
32
+
33
+ References
34
+ ----------
35
+ .. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure
36
+
37
+ Examples
38
+ --------
39
+ >>> from scipy.cluster.hierarchy import DisjointSet
40
+
41
+ Initialize a disjoint set:
42
+
43
+ >>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b'])
44
+
45
+ Merge some subsets:
46
+
47
+ >>> disjoint_set.merge(1, 2)
48
+ True
49
+ >>> disjoint_set.merge(3, 'a')
50
+ True
51
+ >>> disjoint_set.merge('a', 'b')
52
+ True
53
+ >>> disjoint_set.merge('b', 'b')
54
+ False
55
+
56
+ Find root elements:
57
+
58
+ >>> disjoint_set[2]
59
+ 1
60
+ >>> disjoint_set['b']
61
+ 3
62
+
63
+ Test connectivity:
64
+
65
+ >>> disjoint_set.connected(1, 2)
66
+ True
67
+ >>> disjoint_set.connected(1, 'b')
68
+ False
69
+
70
+ List elements in disjoint set:
71
+
72
+ >>> list(disjoint_set)
73
+ [1, 2, 3, 'a', 'b']
74
+
75
+ Get the subset containing 'a':
76
+
77
+ >>> disjoint_set.subset('a')
78
+ {'a', 3, 'b'}
79
+
80
+ Get the size of the subset containing 'a' (without actually instantiating
81
+ the subset):
82
+
83
+ >>> disjoint_set.subset_size('a')
84
+ 3
85
+
86
+ Get all subsets in the disjoint set:
87
+
88
+ >>> disjoint_set.subsets()
89
+ [{1, 2}, {'a', 3, 'b'}]
90
+ """
91
+ def __init__(self, elements=None):
92
+ self.n_subsets = 0
93
+ self._sizes = {}
94
+ self._parents = {}
95
+ # _nbrs is a circular linked list which links connected elements.
96
+ self._nbrs = {}
97
+ # _indices tracks the element insertion order in `__iter__`.
98
+ self._indices = {}
99
+ if elements is not None:
100
+ for x in elements:
101
+ self.add(x)
102
+
103
+ def __iter__(self):
104
+ """Returns an iterator of the elements in the disjoint set.
105
+
106
+ Elements are ordered by insertion order.
107
+ """
108
+ return iter(self._indices)
109
+
110
+ def __len__(self):
111
+ return len(self._indices)
112
+
113
+ def __contains__(self, x):
114
+ return x in self._indices
115
+
116
+ def __getitem__(self, x):
117
+ """Find the root element of `x`.
118
+
119
+ Parameters
120
+ ----------
121
+ x : hashable object
122
+ Input element.
123
+
124
+ Returns
125
+ -------
126
+ root : hashable object
127
+ Root element of `x`.
128
+ """
129
+ if x not in self._indices:
130
+ raise KeyError(x)
131
+
132
+ # find by "path halving"
133
+ parents = self._parents
134
+ while self._indices[x] != self._indices[parents[x]]:
135
+ parents[x] = parents[parents[x]]
136
+ x = parents[x]
137
+ return x
138
+
139
+ def add(self, x):
140
+ """Add element `x` to disjoint set
141
+ """
142
+ if x in self._indices:
143
+ return
144
+
145
+ self._sizes[x] = 1
146
+ self._parents[x] = x
147
+ self._nbrs[x] = x
148
+ self._indices[x] = len(self._indices)
149
+ self.n_subsets += 1
150
+
151
+ def merge(self, x, y):
152
+ """Merge the subsets of `x` and `y`.
153
+
154
+ The smaller subset (the child) is merged into the larger subset (the
155
+ parent). If the subsets are of equal size, the root element which was
156
+ first inserted into the disjoint set is selected as the parent.
157
+
158
+ Parameters
159
+ ----------
160
+ x, y : hashable object
161
+ Elements to merge.
162
+
163
+ Returns
164
+ -------
165
+ merged : bool
166
+ True if `x` and `y` were in disjoint sets, False otherwise.
167
+ """
168
+ xr = self[x]
169
+ yr = self[y]
170
+ if self._indices[xr] == self._indices[yr]:
171
+ return False
172
+
173
+ sizes = self._sizes
174
+ if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]):
175
+ xr, yr = yr, xr
176
+ self._parents[yr] = xr
177
+ self._sizes[xr] += self._sizes[yr]
178
+ self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr]
179
+ self.n_subsets -= 1
180
+ return True
181
+
182
+ def connected(self, x, y):
183
+ """Test whether `x` and `y` are in the same subset.
184
+
185
+ Parameters
186
+ ----------
187
+ x, y : hashable object
188
+ Elements to test.
189
+
190
+ Returns
191
+ -------
192
+ result : bool
193
+ True if `x` and `y` are in the same set, False otherwise.
194
+ """
195
+ return self._indices[self[x]] == self._indices[self[y]]
196
+
197
+ def subset(self, x):
198
+ """Get the subset containing `x`.
199
+
200
+ Parameters
201
+ ----------
202
+ x : hashable object
203
+ Input element.
204
+
205
+ Returns
206
+ -------
207
+ result : set
208
+ Subset containing `x`.
209
+ """
210
+ if x not in self._indices:
211
+ raise KeyError(x)
212
+
213
+ result = [x]
214
+ nxt = self._nbrs[x]
215
+ while self._indices[nxt] != self._indices[x]:
216
+ result.append(nxt)
217
+ nxt = self._nbrs[nxt]
218
+ return set(result)
219
+
220
+ def subset_size(self, x):
221
+ """Get the size of the subset containing `x`.
222
+
223
+ Note that this method is faster than ``len(self.subset(x))`` because
224
+ the size is directly read off an internal field, without the need to
225
+ instantiate the full subset.
226
+
227
+ Parameters
228
+ ----------
229
+ x : hashable object
230
+ Input element.
231
+
232
+ Returns
233
+ -------
234
+ result : int
235
+ Size of the subset containing `x`.
236
+ """
237
+ return self._sizes[self[x]]
238
+
239
+ def subsets(self):
240
+ """Get all the subsets in the disjoint set.
241
+
242
+ Returns
243
+ -------
244
+ result : list
245
+ Subsets in the disjoint set.
246
+ """
247
+ result = []
248
+ visited = set()
249
+ for x in self:
250
+ if x not in visited:
251
+ xset = self.subset(x)
252
+ visited.update(xset)
253
+ result.append(xset)
254
+ return result
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_docscrape.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2
2
+ """Extract reference documentation from the NumPy source tree."""
3
+
4
+ import copy
5
+ import inspect
6
+ import pydoc
7
+ import re
8
+ import sys
9
+ import textwrap
10
+ from collections import namedtuple
11
+ from collections.abc import Callable, Mapping
12
+ from functools import cached_property
13
+ from warnings import warn
14
+
15
+
16
+ def strip_blank_lines(l):
17
+ "Remove leading and trailing blank lines from a list of lines"
18
+ while l and not l[0].strip():
19
+ del l[0]
20
+ while l and not l[-1].strip():
21
+ del l[-1]
22
+ return l
23
+
24
+
25
+ class Reader:
26
+ """A line-based string reader."""
27
+
28
+ def __init__(self, data):
29
+ """
30
+ Parameters
31
+ ----------
32
+ data : str
33
+ String with lines separated by '\\n'.
34
+
35
+ """
36
+ if isinstance(data, list):
37
+ self._str = data
38
+ else:
39
+ self._str = data.split("\n") # store string as list of lines
40
+
41
+ self.reset()
42
+
43
+ def __getitem__(self, n):
44
+ return self._str[n]
45
+
46
+ def reset(self):
47
+ self._l = 0 # current line nr
48
+
49
+ def read(self):
50
+ if not self.eof():
51
+ out = self[self._l]
52
+ self._l += 1
53
+ return out
54
+ else:
55
+ return ""
56
+
57
+ def seek_next_non_empty_line(self):
58
+ for l in self[self._l :]:
59
+ if l.strip():
60
+ break
61
+ else:
62
+ self._l += 1
63
+
64
+ def eof(self):
65
+ return self._l >= len(self._str)
66
+
67
+ def read_to_condition(self, condition_func):
68
+ start = self._l
69
+ for line in self[start:]:
70
+ if condition_func(line):
71
+ return self[start : self._l]
72
+ self._l += 1
73
+ if self.eof():
74
+ return self[start : self._l + 1]
75
+ return []
76
+
77
+ def read_to_next_empty_line(self):
78
+ self.seek_next_non_empty_line()
79
+
80
+ def is_empty(line):
81
+ return not line.strip()
82
+
83
+ return self.read_to_condition(is_empty)
84
+
85
+ def read_to_next_unindented_line(self):
86
+ def is_unindented(line):
87
+ return line.strip() and (len(line.lstrip()) == len(line))
88
+
89
+ return self.read_to_condition(is_unindented)
90
+
91
+ def peek(self, n=0):
92
+ if self._l + n < len(self._str):
93
+ return self[self._l + n]
94
+ else:
95
+ return ""
96
+
97
+ def is_empty(self):
98
+ return not "".join(self._str).strip()
99
+
100
+
101
+ class ParseError(Exception):
102
+ def __str__(self):
103
+ message = self.args[0]
104
+ if hasattr(self, "docstring"):
105
+ message = f"{message} in {self.docstring!r}"
106
+ return message
107
+
108
+
109
+ Parameter = namedtuple("Parameter", ["name", "type", "desc"])
110
+
111
+
112
+ class NumpyDocString(Mapping):
113
+ """Parses a numpydoc string to an abstract representation
114
+
115
+ Instances define a mapping from section title to structured data.
116
+
117
+ """
118
+
119
+ sections = {
120
+ "Signature": "",
121
+ "Summary": [""],
122
+ "Extended Summary": [],
123
+ "Parameters": [],
124
+ "Attributes": [],
125
+ "Methods": [],
126
+ "Returns": [],
127
+ "Yields": [],
128
+ "Receives": [],
129
+ "Other Parameters": [],
130
+ "Raises": [],
131
+ "Warns": [],
132
+ "Warnings": [],
133
+ "See Also": [],
134
+ "Notes": [],
135
+ "References": "",
136
+ "Examples": "",
137
+ "index": {},
138
+ }
139
+
140
+ def __init__(self, docstring, config=None):
141
+ orig_docstring = docstring
142
+ docstring = textwrap.dedent(docstring).split("\n")
143
+
144
+ self._doc = Reader(docstring)
145
+ self._parsed_data = copy.deepcopy(self.sections)
146
+
147
+ try:
148
+ self._parse()
149
+ except ParseError as e:
150
+ e.docstring = orig_docstring
151
+ raise
152
+
153
+ def __getitem__(self, key):
154
+ return self._parsed_data[key]
155
+
156
+ def __setitem__(self, key, val):
157
+ if key not in self._parsed_data:
158
+ self._error_location(f"Unknown section {key}", error=False)
159
+ else:
160
+ self._parsed_data[key] = val
161
+
162
+ def __iter__(self):
163
+ return iter(self._parsed_data)
164
+
165
+ def __len__(self):
166
+ return len(self._parsed_data)
167
+
168
+ def _is_at_section(self):
169
+ self._doc.seek_next_non_empty_line()
170
+
171
+ if self._doc.eof():
172
+ return False
173
+
174
+ l1 = self._doc.peek().strip() # e.g. Parameters
175
+
176
+ if l1.startswith(".. index::"):
177
+ return True
178
+
179
+ l2 = self._doc.peek(1).strip() # ---------- or ==========
180
+ if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1):
181
+ snip = "\n".join(self._doc._str[:2]) + "..."
182
+ self._error_location(
183
+ f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}",
184
+ error=False,
185
+ )
186
+ return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1))
187
+
188
+ def _strip(self, doc):
189
+ i = 0
190
+ j = 0
191
+ for i, line in enumerate(doc):
192
+ if line.strip():
193
+ break
194
+
195
+ for j, line in enumerate(doc[::-1]):
196
+ if line.strip():
197
+ break
198
+
199
+ return doc[i : len(doc) - j]
200
+
201
+ def _read_to_next_section(self):
202
+ section = self._doc.read_to_next_empty_line()
203
+
204
+ while not self._is_at_section() and not self._doc.eof():
205
+ if not self._doc.peek(-1).strip(): # previous line was empty
206
+ section += [""]
207
+
208
+ section += self._doc.read_to_next_empty_line()
209
+
210
+ return section
211
+
212
+ def _read_sections(self):
213
+ while not self._doc.eof():
214
+ data = self._read_to_next_section()
215
+ name = data[0].strip()
216
+
217
+ if name.startswith(".."): # index section
218
+ yield name, data[1:]
219
+ elif len(data) < 2:
220
+ yield StopIteration
221
+ else:
222
+ yield name, self._strip(data[2:])
223
+
224
+ def _parse_param_list(self, content, single_element_is_type=False):
225
+ content = dedent_lines(content)
226
+ r = Reader(content)
227
+ params = []
228
+ while not r.eof():
229
+ header = r.read().strip()
230
+ if " : " in header:
231
+ arg_name, arg_type = header.split(" : ", maxsplit=1)
232
+ else:
233
+ # NOTE: param line with single element should never have a
234
+ # a " :" before the description line, so this should probably
235
+ # warn.
236
+ if header.endswith(" :"):
237
+ header = header[:-2]
238
+ if single_element_is_type:
239
+ arg_name, arg_type = "", header
240
+ else:
241
+ arg_name, arg_type = header, ""
242
+
243
+ desc = r.read_to_next_unindented_line()
244
+ desc = dedent_lines(desc)
245
+ desc = strip_blank_lines(desc)
246
+
247
+ params.append(Parameter(arg_name, arg_type, desc))
248
+
249
+ return params
250
+
251
+ # See also supports the following formats.
252
+ #
253
+ # <FUNCNAME>
254
+ # <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE*
255
+ # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE*
256
+ # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE*
257
+
258
+ # <FUNCNAME> is one of
259
+ # <PLAIN_FUNCNAME>
260
+ # COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK
261
+ # where
262
+ # <PLAIN_FUNCNAME> is a legal function name, and
263
+ # <ROLE> is any nonempty sequence of word characters.
264
+ # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`
265
+ # <DESC> is a string describing the function.
266
+
267
+ _role = r":(?P<role>(py:)?\w+):"
268
+ _funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`"
269
+ _funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)"
270
+ _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")"
271
+ _funcnamenext = _funcname.replace("role", "rolenext")
272
+ _funcnamenext = _funcnamenext.replace("name", "namenext")
273
+ _description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$"
274
+ _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*")
275
+ _line_rgx = re.compile(
276
+ r"^\s*"
277
+ + r"(?P<allfuncs>"
278
+ + _funcname # group for all function names
279
+ + r"(?P<morefuncs>([,]\s+"
280
+ + _funcnamenext
281
+ + r")*)"
282
+ + r")"
283
+ + r"(?P<trailing>[,\.])?" # end of "allfuncs"
284
+ + _description # Some function lists have a trailing comma (or period) '\s*'
285
+ )
286
+
287
+ # Empty <DESC> elements are replaced with '..'
288
+ empty_description = ".."
289
+
290
+ def _parse_see_also(self, content):
291
+ """
292
+ func_name : Descriptive text
293
+ continued text
294
+ another_func_name : Descriptive text
295
+ func_name1, func_name2, :meth:`func_name`, func_name3
296
+
297
+ """
298
+
299
+ content = dedent_lines(content)
300
+
301
+ items = []
302
+
303
+ def parse_item_name(text):
304
+ """Match ':role:`name`' or 'name'."""
305
+ m = self._func_rgx.match(text)
306
+ if not m:
307
+ self._error_location(f"Error parsing See Also entry {line!r}")
308
+ role = m.group("role")
309
+ name = m.group("name") if role else m.group("name2")
310
+ return name, role, m.end()
311
+
312
+ rest = []
313
+ for line in content:
314
+ if not line.strip():
315
+ continue
316
+
317
+ line_match = self._line_rgx.match(line)
318
+ description = None
319
+ if line_match:
320
+ description = line_match.group("desc")
321
+ if line_match.group("trailing") and description:
322
+ self._error_location(
323
+ "Unexpected comma or period after function list at index %d of "
324
+ 'line "%s"' % (line_match.end("trailing"), line),
325
+ error=False,
326
+ )
327
+ if not description and line.startswith(" "):
328
+ rest.append(line.strip())
329
+ elif line_match:
330
+ funcs = []
331
+ text = line_match.group("allfuncs")
332
+ while True:
333
+ if not text.strip():
334
+ break
335
+ name, role, match_end = parse_item_name(text)
336
+ funcs.append((name, role))
337
+ text = text[match_end:].strip()
338
+ if text and text[0] == ",":
339
+ text = text[1:].strip()
340
+ rest = list(filter(None, [description]))
341
+ items.append((funcs, rest))
342
+ else:
343
+ self._error_location(f"Error parsing See Also entry {line!r}")
344
+ return items
345
+
346
+ def _parse_index(self, section, content):
347
+ """
348
+ .. index:: default
349
+ :refguide: something, else, and more
350
+
351
+ """
352
+
353
+ def strip_each_in(lst):
354
+ return [s.strip() for s in lst]
355
+
356
+ out = {}
357
+ section = section.split("::")
358
+ if len(section) > 1:
359
+ out["default"] = strip_each_in(section[1].split(","))[0]
360
+ for line in content:
361
+ line = line.split(":")
362
+ if len(line) > 2:
363
+ out[line[1]] = strip_each_in(line[2].split(","))
364
+ return out
365
+
366
+ def _parse_summary(self):
367
+ """Grab signature (if given) and summary"""
368
+ if self._is_at_section():
369
+ return
370
+
371
+ # If several signatures present, take the last one
372
+ while True:
373
+ summary = self._doc.read_to_next_empty_line()
374
+ summary_str = " ".join([s.strip() for s in summary]).strip()
375
+ compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$")
376
+ if compiled.match(summary_str):
377
+ self["Signature"] = summary_str
378
+ if not self._is_at_section():
379
+ continue
380
+ break
381
+
382
+ if summary is not None:
383
+ self["Summary"] = summary
384
+
385
+ if not self._is_at_section():
386
+ self["Extended Summary"] = self._read_to_next_section()
387
+
388
+ def _parse(self):
389
+ self._doc.reset()
390
+ self._parse_summary()
391
+
392
+ sections = list(self._read_sections())
393
+ section_names = {section for section, content in sections}
394
+
395
+ has_yields = "Yields" in section_names
396
+ # We could do more tests, but we are not. Arbitrarily.
397
+ if not has_yields and "Receives" in section_names:
398
+ msg = "Docstring contains a Receives section but not Yields."
399
+ raise ValueError(msg)
400
+
401
+ for section, content in sections:
402
+ if not section.startswith(".."):
403
+ section = (s.capitalize() for s in section.split(" "))
404
+ section = " ".join(section)
405
+ if self.get(section):
406
+ self._error_location(
407
+ "The section %s appears twice in %s"
408
+ % (section, "\n".join(self._doc._str))
409
+ )
410
+
411
+ if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):
412
+ self[section] = self._parse_param_list(content)
413
+ elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"):
414
+ self[section] = self._parse_param_list(
415
+ content, single_element_is_type=True
416
+ )
417
+ elif section.startswith(".. index::"):
418
+ self["index"] = self._parse_index(section, content)
419
+ elif section == "See Also":
420
+ self["See Also"] = self._parse_see_also(content)
421
+ else:
422
+ self[section] = content
423
+
424
+ @property
425
+ def _obj(self):
426
+ if hasattr(self, "_cls"):
427
+ return self._cls
428
+ elif hasattr(self, "_f"):
429
+ return self._f
430
+ return None
431
+
432
+ def _error_location(self, msg, error=True):
433
+ if self._obj is not None:
434
+ # we know where the docs came from:
435
+ try:
436
+ filename = inspect.getsourcefile(self._obj)
437
+ except TypeError:
438
+ filename = None
439
+ # Make UserWarning more descriptive via object introspection.
440
+ # Skip if introspection fails
441
+ name = getattr(self._obj, "__name__", None)
442
+ if name is None:
443
+ name = getattr(getattr(self._obj, "__class__", None), "__name__", None)
444
+ if name is not None:
445
+ msg += f" in the docstring of {name}"
446
+ msg += f" in {filename}." if filename else ""
447
+ if error:
448
+ raise ValueError(msg)
449
+ else:
450
+ warn(msg, stacklevel=3)
451
+
452
+ # string conversion routines
453
+
454
+ def _str_header(self, name, symbol="-"):
455
+ return [name, len(name) * symbol]
456
+
457
+ def _str_indent(self, doc, indent=4):
458
+ return [" " * indent + line for line in doc]
459
+
460
+ def _str_signature(self):
461
+ if self["Signature"]:
462
+ return [self["Signature"].replace("*", r"\*")] + [""]
463
+ return [""]
464
+
465
+ def _str_summary(self):
466
+ if self["Summary"]:
467
+ return self["Summary"] + [""]
468
+ return []
469
+
470
+ def _str_extended_summary(self):
471
+ if self["Extended Summary"]:
472
+ return self["Extended Summary"] + [""]
473
+ return []
474
+
475
+ def _str_param_list(self, name):
476
+ out = []
477
+ if self[name]:
478
+ out += self._str_header(name)
479
+ for param in self[name]:
480
+ parts = []
481
+ if param.name:
482
+ parts.append(param.name)
483
+ if param.type:
484
+ parts.append(param.type)
485
+ out += [" : ".join(parts)]
486
+ if param.desc and "".join(param.desc).strip():
487
+ out += self._str_indent(param.desc)
488
+ out += [""]
489
+ return out
490
+
491
+ def _str_section(self, name):
492
+ out = []
493
+ if self[name]:
494
+ out += self._str_header(name)
495
+ out += self[name]
496
+ out += [""]
497
+ return out
498
+
499
+ def _str_see_also(self, func_role):
500
+ if not self["See Also"]:
501
+ return []
502
+ out = []
503
+ out += self._str_header("See Also")
504
+ out += [""]
505
+ last_had_desc = True
506
+ for funcs, desc in self["See Also"]:
507
+ assert isinstance(funcs, list)
508
+ links = []
509
+ for func, role in funcs:
510
+ if role:
511
+ link = f":{role}:`{func}`"
512
+ elif func_role:
513
+ link = f":{func_role}:`{func}`"
514
+ else:
515
+ link = f"`{func}`_"
516
+ links.append(link)
517
+ link = ", ".join(links)
518
+ out += [link]
519
+ if desc:
520
+ out += self._str_indent([" ".join(desc)])
521
+ last_had_desc = True
522
+ else:
523
+ last_had_desc = False
524
+ out += self._str_indent([self.empty_description])
525
+
526
+ if last_had_desc:
527
+ out += [""]
528
+ out += [""]
529
+ return out
530
+
531
+ def _str_index(self):
532
+ idx = self["index"]
533
+ out = []
534
+ output_index = False
535
+ default_index = idx.get("default", "")
536
+ if default_index:
537
+ output_index = True
538
+ out += [f".. index:: {default_index}"]
539
+ for section, references in idx.items():
540
+ if section == "default":
541
+ continue
542
+ output_index = True
543
+ out += [f" :{section}: {', '.join(references)}"]
544
+ if output_index:
545
+ return out
546
+ return ""
547
+
548
+ def __str__(self, func_role=""):
549
+ out = []
550
+ out += self._str_signature()
551
+ out += self._str_summary()
552
+ out += self._str_extended_summary()
553
+ out += self._str_param_list("Parameters")
554
+ for param_list in ("Attributes", "Methods"):
555
+ out += self._str_param_list(param_list)
556
+ for param_list in (
557
+ "Returns",
558
+ "Yields",
559
+ "Receives",
560
+ "Other Parameters",
561
+ "Raises",
562
+ "Warns",
563
+ ):
564
+ out += self._str_param_list(param_list)
565
+ out += self._str_section("Warnings")
566
+ out += self._str_see_also(func_role)
567
+ for s in ("Notes", "References", "Examples"):
568
+ out += self._str_section(s)
569
+ out += self._str_index()
570
+ return "\n".join(out)
571
+
572
+
573
+ def dedent_lines(lines):
574
+ """Deindent a list of lines maximally"""
575
+ return textwrap.dedent("\n".join(lines)).split("\n")
576
+
577
+
578
+ class FunctionDoc(NumpyDocString):
579
+ def __init__(self, func, role="func", doc=None, config=None):
580
+ self._f = func
581
+ self._role = role # e.g. "func" or "meth"
582
+
583
+ if doc is None:
584
+ if func is None:
585
+ raise ValueError("No function or docstring given")
586
+ doc = inspect.getdoc(func) or ""
587
+ if config is None:
588
+ config = {}
589
+ NumpyDocString.__init__(self, doc, config)
590
+
591
+ def get_func(self):
592
+ func_name = getattr(self._f, "__name__", self.__class__.__name__)
593
+ if inspect.isclass(self._f):
594
+ func = getattr(self._f, "__call__", self._f.__init__)
595
+ else:
596
+ func = self._f
597
+ return func, func_name
598
+
599
+ def __str__(self):
600
+ out = ""
601
+
602
+ func, func_name = self.get_func()
603
+
604
+ roles = {"func": "function", "meth": "method"}
605
+
606
+ if self._role:
607
+ if self._role not in roles:
608
+ print(f"Warning: invalid role {self._role}")
609
+ out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
610
+
611
+ out += super().__str__(func_role=self._role)
612
+ return out
613
+
614
+
615
+ class ObjDoc(NumpyDocString):
616
+ def __init__(self, obj, doc=None, config=None):
617
+ self._f = obj
618
+ if config is None:
619
+ config = {}
620
+ NumpyDocString.__init__(self, doc, config=config)
621
+
622
+
623
+ class ClassDoc(NumpyDocString):
624
+ extra_public_methods = ["__call__"]
625
+
626
+ def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
627
+ if not inspect.isclass(cls) and cls is not None:
628
+ raise ValueError(f"Expected a class or None, but got {cls!r}")
629
+ self._cls = cls
630
+
631
+ if "sphinx" in sys.modules:
632
+ from sphinx.ext.autodoc import ALL
633
+ else:
634
+ ALL = object()
635
+
636
+ if config is None:
637
+ config = {}
638
+ self.show_inherited_members = config.get("show_inherited_class_members", True)
639
+
640
+ if modulename and not modulename.endswith("."):
641
+ modulename += "."
642
+ self._mod = modulename
643
+
644
+ if doc is None:
645
+ if cls is None:
646
+ raise ValueError("No class or documentation string given")
647
+ doc = pydoc.getdoc(cls)
648
+
649
+ NumpyDocString.__init__(self, doc)
650
+
651
+ _members = config.get("members", [])
652
+ if _members is ALL:
653
+ _members = None
654
+ _exclude = config.get("exclude-members", [])
655
+
656
+ if config.get("show_class_members", True) and _exclude is not ALL:
657
+
658
+ def splitlines_x(s):
659
+ if not s:
660
+ return []
661
+ else:
662
+ return s.splitlines()
663
+
664
+ for field, items in [
665
+ ("Methods", self.methods),
666
+ ("Attributes", self.properties),
667
+ ]:
668
+ if not self[field]:
669
+ doc_list = []
670
+ for name in sorted(items):
671
+ if name in _exclude or (_members and name not in _members):
672
+ continue
673
+ try:
674
+ doc_item = pydoc.getdoc(getattr(self._cls, name))
675
+ doc_list.append(Parameter(name, "", splitlines_x(doc_item)))
676
+ except AttributeError:
677
+ pass # method doesn't exist
678
+ self[field] = doc_list
679
+
680
+ @property
681
+ def methods(self):
682
+ if self._cls is None:
683
+ return []
684
+ return [
685
+ name
686
+ for name, func in inspect.getmembers(self._cls)
687
+ if (
688
+ (not name.startswith("_") or name in self.extra_public_methods)
689
+ and isinstance(func, Callable)
690
+ and self._is_show_member(name)
691
+ )
692
+ ]
693
+
694
+ @property
695
+ def properties(self):
696
+ if self._cls is None:
697
+ return []
698
+ return [
699
+ name
700
+ for name, func in inspect.getmembers(self._cls)
701
+ if (
702
+ not name.startswith("_")
703
+ and not self._should_skip_member(name, self._cls)
704
+ and (
705
+ func is None
706
+ or isinstance(func, property | cached_property)
707
+ or inspect.isdatadescriptor(func)
708
+ )
709
+ and self._is_show_member(name)
710
+ )
711
+ ]
712
+
713
+ @staticmethod
714
+ def _should_skip_member(name, klass):
715
+ return (
716
+ # Namedtuples should skip everything in their ._fields as the
717
+ # docstrings for each of the members is: "Alias for field number X"
718
+ issubclass(klass, tuple)
719
+ and hasattr(klass, "_asdict")
720
+ and hasattr(klass, "_fields")
721
+ and name in klass._fields
722
+ )
723
+
724
+ def _is_show_member(self, name):
725
+ return (
726
+ # show all class members
727
+ self.show_inherited_members
728
+ # or class member is not inherited
729
+ or name in self._cls.__dict__
730
+ )
731
+
732
+
733
+ def get_doc_object(
734
+ obj,
735
+ what=None,
736
+ doc=None,
737
+ config=None,
738
+ class_doc=ClassDoc,
739
+ func_doc=FunctionDoc,
740
+ obj_doc=ObjDoc,
741
+ ):
742
+ if what is None:
743
+ if inspect.isclass(obj):
744
+ what = "class"
745
+ elif inspect.ismodule(obj):
746
+ what = "module"
747
+ elif isinstance(obj, Callable):
748
+ what = "function"
749
+ else:
750
+ what = "object"
751
+ if config is None:
752
+ config = {}
753
+
754
+ if what == "class":
755
+ return class_doc(obj, func_doc=func_doc, doc=doc, config=config)
756
+ elif what in ("function", "method"):
757
+ return func_doc(obj, doc=doc, config=config)
758
+ else:
759
+ if doc is None:
760
+ doc = pydoc.getdoc(obj)
761
+ return obj_doc(obj, doc, config=config)
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `_elementwise_iterative_method.py` includes tools for writing functions that
2
+ # - are vectorized to work elementwise on arrays,
3
+ # - implement non-trivial, iterative algorithms with a callback interface, and
4
+ # - return rich objects with iteration count, termination status, etc.
5
+ #
6
+ # Examples include:
7
+ # `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding,
8
+ # `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization,
9
+ # `scipy.optimize._differentiate._differentiate for numerical differentiation,
10
+ # `scipy.optimize._bracket._bracket_root for finding rootfinding brackets,
11
+ # `scipy.optimize._bracket._bracket_minimize for finding minimization brackets,
12
+ # `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature,
13
+ # `scipy.differentiate.derivative` for finite difference based differentiation.
14
+
15
+ import math
16
+ import numpy as np
17
+ from ._util import _RichResult, _call_callback_maybe_halt
18
+ from ._array_api import array_namespace, xp_size, xp_result_type
19
+ import scipy._lib.array_api_extra as xpx
20
+
21
+ _ESIGNERR = -1
22
+ _ECONVERR = -2
23
+ _EVALUEERR = -3
24
+ _ECALLBACK = -4
25
+ _EINPUTERR = -5
26
+ _ECONVERGED = 0
27
+ _EINPROGRESS = 1
28
+
29
+ def _initialize(func, xs, args, complex_ok=False, preserve_shape=None, xp=None):
30
+ """Initialize abscissa, function, and args arrays for elementwise function
31
+
32
+ Parameters
33
+ ----------
34
+ func : callable
35
+ An elementwise function with signature
36
+
37
+ func(x: ndarray, *args) -> ndarray
38
+
39
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
40
+ which may contain an arbitrary number of arrays that are broadcastable
41
+ with ``x``.
42
+ xs : tuple of arrays
43
+ Finite real abscissa arrays. Must be broadcastable.
44
+ args : tuple, optional
45
+ Additional positional arguments to be passed to `func`.
46
+ preserve_shape : bool, default:False
47
+ When ``preserve_shape=False`` (default), `func` may be passed
48
+ arguments of any shape; `_scalar_optimization_loop` is permitted
49
+ to reshape and compress arguments at will. When
50
+ ``preserve_shape=False``, arguments passed to `func` must have shape
51
+ `shape` or ``shape + (n,)``, where ``n`` is any integer.
52
+ xp : namespace
53
+ Namespace of array arguments in `xs`.
54
+
55
+ Returns
56
+ -------
57
+ xs, fs, args : tuple of arrays
58
+ Broadcasted, writeable, 1D abscissa and function value arrays (or
59
+ NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are
60
+ `xfat`; the dtype of the `args` are unchanged.
61
+ shape : tuple of ints
62
+ Original shape of broadcasted arrays.
63
+ xfat : NumPy dtype
64
+ Result dtype of abscissae, function values, and args determined using
65
+ `np.result_type`, except integer types are promoted to `np.float64`.
66
+
67
+ Raises
68
+ ------
69
+ ValueError
70
+ If the result dtype is not that of a real scalar
71
+
72
+ Notes
73
+ -----
74
+ Useful for initializing the input of SciPy functions that accept
75
+ an elementwise callable, abscissae, and arguments; e.g.
76
+ `scipy.optimize._chandrupatla`.
77
+ """
78
+ nx = len(xs)
79
+ xp = array_namespace(*xs) if xp is None else xp
80
+
81
+ # Try to preserve `dtype`, but we need to ensure that the arguments are at
82
+ # least floats before passing them into the function; integers can overflow
83
+ # and cause failure.
84
+ # There might be benefit to combining the `xs` into a single array and
85
+ # calling `func` once on the combined array. For now, keep them separate.
86
+ xat = xp_result_type(*xs, force_floating=True, xp=xp)
87
+ xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename
88
+ xs, args = xas[:nx], xas[nx:]
89
+ xs = [xp.asarray(x, dtype=xat) for x in xs] # use copy=False when implemented
90
+ fs = [xp.asarray(func(x, *args)) for x in xs]
91
+ shape = xs[0].shape
92
+ fshape = fs[0].shape
93
+
94
+ if preserve_shape:
95
+ # bind original shape/func now to avoid late-binding gotcha
96
+ def func(x, *args, shape=shape, func=func, **kwargs):
97
+ i = (0,)*(len(fshape) - len(shape))
98
+ return func(x[i], *args, **kwargs)
99
+ shape = np.broadcast_shapes(fshape, shape) # just shapes; use of NumPy OK
100
+ xs = [xp.broadcast_to(x, shape) for x in xs]
101
+ args = [xp.broadcast_to(arg, shape) for arg in args]
102
+
103
+ message = ("The shape of the array returned by `func` must be the same as "
104
+ "the broadcasted shape of `x` and all other `args`.")
105
+ if preserve_shape is not None: # only in tanhsinh for now
106
+ message = f"When `preserve_shape=False`, {message.lower()}"
107
+ shapes_equal = [f.shape == shape for f in fs]
108
+ if not all(shapes_equal): # use Python all to reduce overhead
109
+ raise ValueError(message)
110
+
111
+ # These algorithms tend to mix the dtypes of the abscissae and function
112
+ # values, so figure out what the result will be and convert them all to
113
+ # that type from the outset.
114
+ xfat = xp.result_type(*([f.dtype for f in fs] + [xat]))
115
+ if not complex_ok and not xp.isdtype(xfat, "real floating"):
116
+ raise ValueError("Abscissae and function output must be real numbers.")
117
+ xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs]
118
+ fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs]
119
+
120
+ # To ensure that we can do indexing, we'll work with at least 1d arrays,
121
+ # but remember the appropriate shape of the output.
122
+ xs = [xp.reshape(x, (-1,)) for x in xs]
123
+ fs = [xp.reshape(f, (-1,)) for f in fs]
124
+ args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args]
125
+ return func, xs, fs, args, shape, xfat, xp
126
+
127
+
128
+ def _loop(work, callback, shape, maxiter, func, args, dtype, pre_func_eval,
129
+ post_func_eval, check_termination, post_termination_check,
130
+ customize_result, res_work_pairs, xp, preserve_shape=False):
131
+ """Main loop of a vectorized scalar optimization algorithm
132
+
133
+ Parameters
134
+ ----------
135
+ work : _RichResult
136
+ All variables that need to be retained between iterations. Must
137
+ contain attributes `nit`, `nfev`, and `success`. All arrays are
138
+ subject to being "compressed" if `preserve_shape is False`; nest
139
+ arrays that should not be compressed inside another object (e.g.
140
+ `dict` or `_RichResult`).
141
+ callback : callable
142
+ User-specified callback function
143
+ shape : tuple of ints
144
+ The shape of all output arrays
145
+ maxiter :
146
+ Maximum number of iterations of the algorithm
147
+ func : callable
148
+ The user-specified callable that is being optimized or solved
149
+ args : tuple
150
+ Additional positional arguments to be passed to `func`.
151
+ dtype : NumPy dtype
152
+ The common dtype of all abscissae and function values
153
+ pre_func_eval : callable
154
+ A function that accepts `work` and returns `x`, the active elements
155
+ of `x` at which `func` will be evaluated. May modify attributes
156
+ of `work` with any algorithmic steps that need to happen
157
+ at the beginning of an iteration, before `func` is evaluated,
158
+ post_func_eval : callable
159
+ A function that accepts `x`, `func(x)`, and `work`. May modify
160
+ attributes of `work` with any algorithmic steps that need to happen
161
+ in the middle of an iteration, after `func` is evaluated but before
162
+ the termination check.
163
+ check_termination : callable
164
+ A function that accepts `work` and returns `stop`, a boolean array
165
+ indicating which of the active elements have met a termination
166
+ condition.
167
+ post_termination_check : callable
168
+ A function that accepts `work`. May modify `work` with any algorithmic
169
+ steps that need to happen after the termination check and before the
170
+ end of the iteration.
171
+ customize_result : callable
172
+ A function that accepts `res` and `shape` and returns `shape`. May
173
+ modify `res` (in-place) according to preferences (e.g. rearrange
174
+ elements between attributes) and modify `shape` if needed.
175
+ res_work_pairs : list of (str, str)
176
+ Identifies correspondence between attributes of `res` and attributes
177
+ of `work`; i.e., attributes of active elements of `work` will be
178
+ copied to the appropriate indices of `res` when appropriate. The order
179
+ determines the order in which _RichResult attributes will be
180
+ pretty-printed.
181
+ preserve_shape : bool, default: False
182
+ Whether to compress the attributes of `work` (to avoid unnecessary
183
+ computation on elements that have already converged).
184
+
185
+ Returns
186
+ -------
187
+ res : _RichResult
188
+ The final result object
189
+
190
+ Notes
191
+ -----
192
+ Besides providing structure, this framework provides several important
193
+ services for a vectorized optimization algorithm.
194
+
195
+ - It handles common tasks involving iteration count, function evaluation
196
+ count, a user-specified callback, and associated termination conditions.
197
+ - It compresses the attributes of `work` to eliminate unnecessary
198
+ computation on elements that have already converged.
199
+
200
+ """
201
+ if xp is None:
202
+ raise NotImplementedError("Must provide xp.")
203
+
204
+ cb_terminate = False
205
+
206
+ # Initialize the result object and active element index array
207
+ n_elements = math.prod(shape)
208
+ active = xp.arange(n_elements) # in-progress element indices
209
+ res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs}
210
+ res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool)
211
+ res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32)
212
+ res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32)
213
+ res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32)
214
+ res = _RichResult(res_dict)
215
+ work.args = args
216
+
217
+ active = _check_termination(work, res, res_work_pairs, active,
218
+ check_termination, preserve_shape, xp)
219
+
220
+ if callback is not None:
221
+ temp = _prepare_result(work, res, res_work_pairs, active, shape,
222
+ customize_result, preserve_shape, xp)
223
+ if _call_callback_maybe_halt(callback, temp):
224
+ cb_terminate = True
225
+
226
+ while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements:
227
+ x = pre_func_eval(work)
228
+
229
+ if work.args and work.args[0].ndim != x.ndim:
230
+ # `x` always starts as 1D. If the SciPy function that uses
231
+ # _loop added dimensions to `x`, we need to
232
+ # add them to the elements of `args`.
233
+ args = []
234
+ for arg in work.args:
235
+ n_new_dims = x.ndim - arg.ndim
236
+ new_shape = arg.shape + (1,)*n_new_dims
237
+ args.append(xp.reshape(arg, new_shape))
238
+ work.args = args
239
+
240
+ x_shape = x.shape
241
+ if preserve_shape:
242
+ x = xp.reshape(x, (shape + (-1,)))
243
+ f = func(x, *work.args)
244
+ f = xp.asarray(f, dtype=dtype)
245
+ if preserve_shape:
246
+ x = xp.reshape(x, x_shape)
247
+ f = xp.reshape(f, x_shape)
248
+ work.nfev += 1 if x.ndim == 1 else x.shape[-1]
249
+
250
+ post_func_eval(x, f, work)
251
+
252
+ work.nit += 1
253
+ active = _check_termination(work, res, res_work_pairs, active,
254
+ check_termination, preserve_shape, xp)
255
+
256
+ if callback is not None:
257
+ temp = _prepare_result(work, res, res_work_pairs, active, shape,
258
+ customize_result, preserve_shape, xp)
259
+ if _call_callback_maybe_halt(callback, temp):
260
+ cb_terminate = True
261
+ break
262
+ if xp_size(active) == 0:
263
+ break
264
+
265
+ post_termination_check(work)
266
+
267
+ work.status = xpx.at(work.status)[:].set(_ECALLBACK if cb_terminate else _ECONVERR)
268
+ return _prepare_result(work, res, res_work_pairs, active, shape,
269
+ customize_result, preserve_shape, xp)
270
+
271
+
272
+ def _check_termination(work, res, res_work_pairs, active, check_termination,
273
+ preserve_shape, xp):
274
+ # Checks termination conditions, updates elements of `res` with
275
+ # corresponding elements of `work`, and compresses `work`.
276
+
277
+ stop = check_termination(work)
278
+
279
+ if xp.any(stop):
280
+ # update the active elements of the result object with the active
281
+ # elements for which a termination condition has been met
282
+ _update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp)
283
+
284
+ if preserve_shape:
285
+ stop = stop[active]
286
+
287
+ proceed = ~stop
288
+ active = active[proceed]
289
+
290
+ if not preserve_shape:
291
+ # compress the arrays to avoid unnecessary computation
292
+ for key, val in work.items():
293
+ # `continued_fraction` hacks `n`; improve if this becomes a problem
294
+ if key in {'args', 'n'}:
295
+ continue
296
+ work[key] = val[proceed] if getattr(val, 'ndim', 0) > 0 else val
297
+ work.args = [arg[proceed] for arg in work.args]
298
+
299
+ return active
300
+
301
+
302
+ def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp):
303
+ # Update `active` indices of the arrays in result object `res` with the
304
+ # contents of the scalars and arrays in `update_dict`. When provided,
305
+ # `mask` is a boolean array applied both to the arrays in `update_dict`
306
+ # that are to be used and to the arrays in `res` that are to be updated.
307
+ update_dict = {key1: work[key2] for key1, key2 in res_work_pairs}
308
+ update_dict['success'] = work.status == 0
309
+
310
+ if mask is not None:
311
+ if preserve_shape:
312
+ active_mask = xp.zeros_like(mask)
313
+ active_mask = xpx.at(active_mask)[active].set(True)
314
+ active_mask = active_mask & mask
315
+ for key, val in update_dict.items():
316
+ val = val[active_mask] if getattr(val, 'ndim', 0) > 0 else val
317
+ res[key] = xpx.at(res[key])[active_mask].set(val)
318
+ else:
319
+ active_mask = active[mask]
320
+ for key, val in update_dict.items():
321
+ val = val[mask] if getattr(val, 'ndim', 0) > 0 else val
322
+ res[key] = xpx.at(res[key])[active_mask].set(val)
323
+ else:
324
+ for key, val in update_dict.items():
325
+ if preserve_shape and getattr(val, 'ndim', 0) > 0:
326
+ val = val[active]
327
+ res[key] = xpx.at(res[key])[active].set(val)
328
+
329
+
330
+ def _prepare_result(work, res, res_work_pairs, active, shape, customize_result,
331
+ preserve_shape, xp):
332
+ # Prepare the result object `res` by creating a copy, copying the latest
333
+ # data from work, running the provided result customization function,
334
+ # and reshaping the data to the original shapes.
335
+ res = res.copy()
336
+ _update_active(work, res, res_work_pairs, active, None, preserve_shape, xp)
337
+
338
+ shape = customize_result(res, shape)
339
+
340
+ for key, val in res.items():
341
+ # this looks like it won't work for xp != np if val is not numeric
342
+ temp = xp.reshape(val, shape)
343
+ res[key] = temp[()] if temp.ndim == 0 else temp
344
+
345
+ res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs]
346
+ return _RichResult(**res)
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a ADDED
Binary file (1.56 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.pyd ADDED
Binary file (15.9 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_gcutils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module for testing automatic garbage collection of objects
3
+
4
+ .. autosummary::
5
+ :toctree: generated/
6
+
7
+ set_gc_state - enable or disable garbage collection
8
+ gc_state - context manager for given state of garbage collector
9
+ assert_deallocated - context manager to check for circular references on object
10
+
11
+ """
12
+ import weakref
13
+ import gc
14
+
15
+ from contextlib import contextmanager
16
+ from platform import python_implementation
17
+
18
+ __all__ = ['set_gc_state', 'gc_state', 'assert_deallocated']
19
+
20
+
21
+ IS_PYPY = python_implementation() == 'PyPy'
22
+
23
+
24
+ class ReferenceError(AssertionError):
25
+ pass
26
+
27
+
28
+ def set_gc_state(state):
29
+ """ Set status of garbage collector """
30
+ if gc.isenabled() == state:
31
+ return
32
+ if state:
33
+ gc.enable()
34
+ else:
35
+ gc.disable()
36
+
37
+
38
+ @contextmanager
39
+ def gc_state(state):
40
+ """ Context manager to set state of garbage collector to `state`
41
+
42
+ Parameters
43
+ ----------
44
+ state : bool
45
+ True for gc enabled, False for disabled
46
+
47
+ Examples
48
+ --------
49
+ >>> with gc_state(False):
50
+ ... assert not gc.isenabled()
51
+ >>> with gc_state(True):
52
+ ... assert gc.isenabled()
53
+ """
54
+ orig_state = gc.isenabled()
55
+ set_gc_state(state)
56
+ yield
57
+ set_gc_state(orig_state)
58
+
59
+
60
+ @contextmanager
61
+ def assert_deallocated(func, *args, **kwargs):
62
+ """Context manager to check that object is deallocated
63
+
64
+ This is useful for checking that an object can be freed directly by
65
+ reference counting, without requiring gc to break reference cycles.
66
+ GC is disabled inside the context manager.
67
+
68
+ This check is not available on PyPy.
69
+
70
+ Parameters
71
+ ----------
72
+ func : callable
73
+ Callable to create object to check
74
+ \\*args : sequence
75
+ positional arguments to `func` in order to create object to check
76
+ \\*\\*kwargs : dict
77
+ keyword arguments to `func` in order to create object to check
78
+
79
+ Examples
80
+ --------
81
+ >>> class C: pass
82
+ >>> with assert_deallocated(C) as c:
83
+ ... # do something
84
+ ... del c
85
+
86
+ >>> class C:
87
+ ... def __init__(self):
88
+ ... self._circular = self # Make circular reference
89
+ >>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL
90
+ ... # do something
91
+ ... del c
92
+ Traceback (most recent call last):
93
+ ...
94
+ ReferenceError: Remaining reference(s) to object
95
+ """
96
+ if IS_PYPY:
97
+ raise RuntimeError("assert_deallocated is unavailable on PyPy")
98
+
99
+ with gc_state(False):
100
+ obj = func(*args, **kwargs)
101
+ ref = weakref.ref(obj)
102
+ yield obj
103
+ del obj
104
+ if ref() is not None:
105
+ raise ReferenceError("Remaining reference(s) to object")
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_pep440.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility to compare pep440 compatible version strings.
2
+
3
+ The LooseVersion and StrictVersion classes that distutils provides don't
4
+ work; they don't recognize anything like alpha/beta/rc/dev versions.
5
+ """
6
+
7
+ # Copyright (c) Donald Stufft and individual contributors.
8
+ # All rights reserved.
9
+
10
+ # Redistribution and use in source and binary forms, with or without
11
+ # modification, are permitted provided that the following conditions are met:
12
+
13
+ # 1. Redistributions of source code must retain the above copyright notice,
14
+ # this list of conditions and the following disclaimer.
15
+
16
+ # 2. Redistributions in binary form must reproduce the above copyright
17
+ # notice, this list of conditions and the following disclaimer in the
18
+ # documentation and/or other materials provided with the distribution.
19
+
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ # POSSIBILITY OF SUCH DAMAGE.
31
+
32
+ import collections
33
+ import itertools
34
+ import re
35
+
36
+
37
+ __all__ = [
38
+ "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
39
+ ]
40
+
41
+
42
+ # BEGIN packaging/_structures.py
43
+
44
+
45
+ class Infinity:
46
+ def __repr__(self):
47
+ return "Infinity"
48
+
49
+ def __hash__(self):
50
+ return hash(repr(self))
51
+
52
+ def __lt__(self, other):
53
+ return False
54
+
55
+ def __le__(self, other):
56
+ return False
57
+
58
+ def __eq__(self, other):
59
+ return isinstance(other, self.__class__)
60
+
61
+ def __ne__(self, other):
62
+ return not isinstance(other, self.__class__)
63
+
64
+ def __gt__(self, other):
65
+ return True
66
+
67
+ def __ge__(self, other):
68
+ return True
69
+
70
+ def __neg__(self):
71
+ return NegativeInfinity
72
+
73
+
74
+ Infinity = Infinity()
75
+
76
+
77
+ class NegativeInfinity:
78
+ def __repr__(self):
79
+ return "-Infinity"
80
+
81
+ def __hash__(self):
82
+ return hash(repr(self))
83
+
84
+ def __lt__(self, other):
85
+ return True
86
+
87
+ def __le__(self, other):
88
+ return True
89
+
90
+ def __eq__(self, other):
91
+ return isinstance(other, self.__class__)
92
+
93
+ def __ne__(self, other):
94
+ return not isinstance(other, self.__class__)
95
+
96
+ def __gt__(self, other):
97
+ return False
98
+
99
+ def __ge__(self, other):
100
+ return False
101
+
102
+ def __neg__(self):
103
+ return Infinity
104
+
105
+
106
+ # BEGIN packaging/version.py
107
+
108
+
109
+ NegativeInfinity = NegativeInfinity()
110
+
111
+ _Version = collections.namedtuple(
112
+ "_Version",
113
+ ["epoch", "release", "dev", "pre", "post", "local"],
114
+ )
115
+
116
+
117
+ def parse(version):
118
+ """
119
+ Parse the given version string and return either a :class:`Version` object
120
+ or a :class:`LegacyVersion` object depending on if the given version is
121
+ a valid PEP 440 version or a legacy version.
122
+ """
123
+ try:
124
+ return Version(version)
125
+ except InvalidVersion:
126
+ return LegacyVersion(version)
127
+
128
+
129
+ class InvalidVersion(ValueError):
130
+ """
131
+ An invalid version was found, users should refer to PEP 440.
132
+ """
133
+
134
+
135
+ class _BaseVersion:
136
+
137
+ def __hash__(self):
138
+ return hash(self._key)
139
+
140
+ def __lt__(self, other):
141
+ return self._compare(other, lambda s, o: s < o)
142
+
143
+ def __le__(self, other):
144
+ return self._compare(other, lambda s, o: s <= o)
145
+
146
+ def __eq__(self, other):
147
+ return self._compare(other, lambda s, o: s == o)
148
+
149
+ def __ge__(self, other):
150
+ return self._compare(other, lambda s, o: s >= o)
151
+
152
+ def __gt__(self, other):
153
+ return self._compare(other, lambda s, o: s > o)
154
+
155
+ def __ne__(self, other):
156
+ return self._compare(other, lambda s, o: s != o)
157
+
158
+ def _compare(self, other, method):
159
+ if not isinstance(other, _BaseVersion):
160
+ return NotImplemented
161
+
162
+ return method(self._key, other._key)
163
+
164
+
165
+ class LegacyVersion(_BaseVersion):
166
+
167
+ def __init__(self, version):
168
+ self._version = str(version)
169
+ self._key = _legacy_cmpkey(self._version)
170
+
171
+ def __str__(self):
172
+ return self._version
173
+
174
+ def __repr__(self):
175
+ return f"<LegacyVersion({repr(str(self))})>"
176
+
177
+ @property
178
+ def public(self):
179
+ return self._version
180
+
181
+ @property
182
+ def base_version(self):
183
+ return self._version
184
+
185
+ @property
186
+ def local(self):
187
+ return None
188
+
189
+ @property
190
+ def is_prerelease(self):
191
+ return False
192
+
193
+ @property
194
+ def is_postrelease(self):
195
+ return False
196
+
197
+
198
+ _legacy_version_component_re = re.compile(
199
+ r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
200
+ )
201
+
202
+ _legacy_version_replacement_map = {
203
+ "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
204
+ }
205
+
206
+
207
+ def _parse_version_parts(s):
208
+ for part in _legacy_version_component_re.split(s):
209
+ part = _legacy_version_replacement_map.get(part, part)
210
+
211
+ if not part or part == ".":
212
+ continue
213
+
214
+ if part[:1] in "0123456789":
215
+ # pad for numeric comparison
216
+ yield part.zfill(8)
217
+ else:
218
+ yield "*" + part
219
+
220
+ # ensure that alpha/beta/candidate are before final
221
+ yield "*final"
222
+
223
+
224
+ def _legacy_cmpkey(version):
225
+ # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch
226
+ # greater than or equal to 0. This will effectively put the LegacyVersion,
227
+ # which uses the defacto standard originally implemented by setuptools,
228
+ # as before all PEP 440 versions.
229
+ epoch = -1
230
+
231
+ # This scheme is taken from pkg_resources.parse_version setuptools prior to
232
+ # its adoption of the packaging library.
233
+ parts = []
234
+ for part in _parse_version_parts(version.lower()):
235
+ if part.startswith("*"):
236
+ # remove "-" before a prerelease tag
237
+ if part < "*final":
238
+ while parts and parts[-1] == "*final-":
239
+ parts.pop()
240
+
241
+ # remove trailing zeros from each series of numeric parts
242
+ while parts and parts[-1] == "00000000":
243
+ parts.pop()
244
+
245
+ parts.append(part)
246
+ parts = tuple(parts)
247
+
248
+ return epoch, parts
249
+
250
+
251
+ # Deliberately not anchored to the start and end of the string, to make it
252
+ # easier for 3rd party code to reuse
253
+ VERSION_PATTERN = r"""
254
+ v?
255
+ (?:
256
+ (?:(?P<epoch>[0-9]+)!)? # epoch
257
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
258
+ (?P<pre> # pre-release
259
+ [-_\.]?
260
+ (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
261
+ [-_\.]?
262
+ (?P<pre_n>[0-9]+)?
263
+ )?
264
+ (?P<post> # post release
265
+ (?:-(?P<post_n1>[0-9]+))
266
+ |
267
+ (?:
268
+ [-_\.]?
269
+ (?P<post_l>post|rev|r)
270
+ [-_\.]?
271
+ (?P<post_n2>[0-9]+)?
272
+ )
273
+ )?
274
+ (?P<dev> # dev release
275
+ [-_\.]?
276
+ (?P<dev_l>dev)
277
+ [-_\.]?
278
+ (?P<dev_n>[0-9]+)?
279
+ )?
280
+ )
281
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
282
+ """
283
+
284
+
285
+ class Version(_BaseVersion):
286
+
287
+ _regex = re.compile(
288
+ r"^\s*" + VERSION_PATTERN + r"\s*$",
289
+ re.VERBOSE | re.IGNORECASE,
290
+ )
291
+
292
+ def __init__(self, version):
293
+ # Validate the version and parse it into pieces
294
+ match = self._regex.search(version)
295
+ if not match:
296
+ raise InvalidVersion(f"Invalid version: '{version}'")
297
+
298
+ # Store the parsed out pieces of the version
299
+ self._version = _Version(
300
+ epoch=int(match.group("epoch")) if match.group("epoch") else 0,
301
+ release=tuple(int(i) for i in match.group("release").split(".")),
302
+ pre=_parse_letter_version(
303
+ match.group("pre_l"),
304
+ match.group("pre_n"),
305
+ ),
306
+ post=_parse_letter_version(
307
+ match.group("post_l"),
308
+ match.group("post_n1") or match.group("post_n2"),
309
+ ),
310
+ dev=_parse_letter_version(
311
+ match.group("dev_l"),
312
+ match.group("dev_n"),
313
+ ),
314
+ local=_parse_local_version(match.group("local")),
315
+ )
316
+
317
+ # Generate a key which will be used for sorting
318
+ self._key = _cmpkey(
319
+ self._version.epoch,
320
+ self._version.release,
321
+ self._version.pre,
322
+ self._version.post,
323
+ self._version.dev,
324
+ self._version.local,
325
+ )
326
+
327
+ def __repr__(self):
328
+ return f"<Version({repr(str(self))})>"
329
+
330
+ def __str__(self):
331
+ parts = []
332
+
333
+ # Epoch
334
+ if self._version.epoch != 0:
335
+ parts.append(f"{self._version.epoch}!")
336
+
337
+ # Release segment
338
+ parts.append(".".join(str(x) for x in self._version.release))
339
+
340
+ # Pre-release
341
+ if self._version.pre is not None:
342
+ parts.append("".join(str(x) for x in self._version.pre))
343
+
344
+ # Post-release
345
+ if self._version.post is not None:
346
+ parts.append(f".post{self._version.post[1]}")
347
+
348
+ # Development release
349
+ if self._version.dev is not None:
350
+ parts.append(f".dev{self._version.dev[1]}")
351
+
352
+ # Local version segment
353
+ if self._version.local is not None:
354
+ parts.append(
355
+ "+{}".format(".".join(str(x) for x in self._version.local))
356
+ )
357
+
358
+ return "".join(parts)
359
+
360
+ @property
361
+ def public(self):
362
+ return str(self).split("+", 1)[0]
363
+
364
+ @property
365
+ def base_version(self):
366
+ parts = []
367
+
368
+ # Epoch
369
+ if self._version.epoch != 0:
370
+ parts.append(f"{self._version.epoch}!")
371
+
372
+ # Release segment
373
+ parts.append(".".join(str(x) for x in self._version.release))
374
+
375
+ return "".join(parts)
376
+
377
+ @property
378
+ def local(self):
379
+ version_string = str(self)
380
+ if "+" in version_string:
381
+ return version_string.split("+", 1)[1]
382
+
383
+ @property
384
+ def is_prerelease(self):
385
+ return bool(self._version.dev or self._version.pre)
386
+
387
+ @property
388
+ def is_postrelease(self):
389
+ return bool(self._version.post)
390
+
391
+
392
+ def _parse_letter_version(letter, number):
393
+ if letter:
394
+ # We assume there is an implicit 0 in a pre-release if there is
395
+ # no numeral associated with it.
396
+ if number is None:
397
+ number = 0
398
+
399
+ # We normalize any letters to their lower-case form
400
+ letter = letter.lower()
401
+
402
+ # We consider some words to be alternate spellings of other words and
403
+ # in those cases we want to normalize the spellings to our preferred
404
+ # spelling.
405
+ if letter == "alpha":
406
+ letter = "a"
407
+ elif letter == "beta":
408
+ letter = "b"
409
+ elif letter in ["c", "pre", "preview"]:
410
+ letter = "rc"
411
+ elif letter in ["rev", "r"]:
412
+ letter = "post"
413
+
414
+ return letter, int(number)
415
+ if not letter and number:
416
+ # We assume that if we are given a number but not given a letter,
417
+ # then this is using the implicit post release syntax (e.g., 1.0-1)
418
+ letter = "post"
419
+
420
+ return letter, int(number)
421
+
422
+
423
+ _local_version_seperators = re.compile(r"[\._-]")
424
+
425
+
426
+ def _parse_local_version(local):
427
+ """
428
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
429
+ """
430
+ if local is not None:
431
+ return tuple(
432
+ part.lower() if not part.isdigit() else int(part)
433
+ for part in _local_version_seperators.split(local)
434
+ )
435
+
436
+
437
+ def _cmpkey(epoch, release, pre, post, dev, local):
438
+ # When we compare a release version, we want to compare it with all of the
439
+ # trailing zeros removed. So we'll use a reverse the list, drop all the now
440
+ # leading zeros until we come to something non-zero, then take the rest,
441
+ # re-reverse it back into the correct order, and make it a tuple and use
442
+ # that for our sorting key.
443
+ release = tuple(
444
+ reversed(list(
445
+ itertools.dropwhile(
446
+ lambda x: x == 0,
447
+ reversed(release),
448
+ )
449
+ ))
450
+ )
451
+
452
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
453
+ # We'll do this by abusing the pre-segment, but we _only_ want to do this
454
+ # if there is no pre- or a post-segment. If we have one of those, then
455
+ # the normal sorting rules will handle this case correctly.
456
+ if pre is None and post is None and dev is not None:
457
+ pre = -Infinity
458
+ # Versions without a pre-release (except as noted above) should sort after
459
+ # those with one.
460
+ elif pre is None:
461
+ pre = Infinity
462
+
463
+ # Versions without a post-segment should sort before those with one.
464
+ if post is None:
465
+ post = -Infinity
466
+
467
+ # Versions without a development segment should sort after those with one.
468
+ if dev is None:
469
+ dev = Infinity
470
+
471
+ if local is None:
472
+ # Versions without a local segment should sort before those with one.
473
+ local = -Infinity
474
+ else:
475
+ # Versions with a local segment need that segment parsed to implement
476
+ # the sorting rules in PEP440.
477
+ # - Alphanumeric segments sort before numeric segments
478
+ # - Alphanumeric segments sort lexicographically
479
+ # - Numeric segments sort numerically
480
+ # - Shorter versions sort before longer versions when the prefixes
481
+ # match exactly
482
+ local = tuple(
483
+ (i, "") if isinstance(i, int) else (-Infinity, i)
484
+ for i in local
485
+ )
486
+
487
+ return epoch, release, pre, post, dev, local
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_public_api.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PUBLIC_MODULES was once included in scipy._lib.tests.test_public_api.
2
+
3
+ It has been separated into this file so that this list of public modules
4
+ could be used when generating tables showing support for alternative
5
+ array API backends across modules in
6
+ scipy/doc/source/array_api_capabilities.py.
7
+ """
8
+
9
+ # Historically SciPy has not used leading underscores for private submodules
10
+ # much. This has resulted in lots of things that look like public modules
11
+ # (i.e. things that can be imported as `import scipy.somesubmodule.somefile`),
12
+ # but were never intended to be public. The PUBLIC_MODULES list contains
13
+ # modules that are either public because they were meant to be, or because they
14
+ # contain public functions/objects that aren't present in any other namespace
15
+ # for whatever reason and therefore should be treated as public.
16
+ PUBLIC_MODULES = ["scipy." + s for s in [
17
+ "cluster",
18
+ "cluster.vq",
19
+ "cluster.hierarchy",
20
+ "constants",
21
+ "datasets",
22
+ "differentiate",
23
+ "fft",
24
+ "fftpack",
25
+ "integrate",
26
+ "interpolate",
27
+ "io",
28
+ "io.arff",
29
+ "io.matlab",
30
+ "io.wavfile",
31
+ "linalg",
32
+ "linalg.blas",
33
+ "linalg.cython_blas",
34
+ "linalg.lapack",
35
+ "linalg.cython_lapack",
36
+ "linalg.interpolative",
37
+ "ndimage",
38
+ "odr",
39
+ "optimize",
40
+ "optimize.elementwise",
41
+ "signal",
42
+ "signal.windows",
43
+ "sparse",
44
+ "sparse.linalg",
45
+ "sparse.csgraph",
46
+ "spatial",
47
+ "spatial.distance",
48
+ "spatial.transform",
49
+ "special",
50
+ "stats",
51
+ "stats.contingency",
52
+ "stats.distributions",
53
+ "stats.mstats",
54
+ "stats.qmc",
55
+ "stats.sampling"
56
+ ]]
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_sparse.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+
3
+ __all__ = ["SparseABC", "issparse"]
4
+
5
+
6
+ class SparseABC(ABC):
7
+ pass
8
+
9
+
10
+ def issparse(x):
11
+ """Is `x` of a sparse array or sparse matrix type?
12
+
13
+ Parameters
14
+ ----------
15
+ x
16
+ object to check for being a sparse array or sparse matrix
17
+
18
+ Returns
19
+ -------
20
+ bool
21
+ True if `x` is a sparse array or a sparse matrix, False otherwise
22
+
23
+ Notes
24
+ -----
25
+ Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
26
+ Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.
27
+
28
+ Examples
29
+ --------
30
+ >>> import numpy as np
31
+ >>> from scipy.sparse import csr_array, csr_matrix, issparse
32
+ >>> issparse(csr_matrix([[5]]))
33
+ True
34
+ >>> issparse(csr_array([[5]]))
35
+ True
36
+ >>> issparse(np.array([[5]]))
37
+ False
38
+ >>> issparse(5)
39
+ False
40
+ """
41
+ return isinstance(x, SparseABC)
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a ADDED
Binary file (1.64 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.pyd ADDED
Binary file (52.2 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a ADDED
Binary file (1.72 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.pyd ADDED
Binary file (33.8 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a ADDED
Binary file (1.71 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.pyd ADDED
Binary file (24.6 kB). View file