Add loan-advisor-agent
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+7
- loan-advisor-agent/.venv/Lib/site-packages/scipy/__config__.pyAdded+173
- loan-advisor-agent/.venv/Lib/site-packages/scipy/__init__.pyAdded+150
- loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__config__.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__init__.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/version.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.dll.aAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pydAdded+3
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_distributor_init.pyAdded+18
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__init__.pyAdded+14
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pycAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api.pyAdded+1036
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_compat_vendor.pyAdded+9
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_docs_tables.pyAdded+294
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_no_0d.pyAdded+103
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_override.pyAdded+150
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_bunch.pyAdded+229
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback.pyAdded+251
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.aAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pydAdded+3
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_disjoint_set.pyAdded+254
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_docscrape.pyAdded+761
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.pyAdded+346
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.aAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.pydAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_gcutils.pyAdded+105
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_pep440.pyAdded+487
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_public_api.pyAdded+56
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_sparse.pyAdded+41
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.aAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.pydAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.aAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.pydAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.aAdded
- loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.pydAdded
554 unmodified lines555556557554 unmodified linesloan-advisor-agent/.venv/Lib/site-packages/regex/_regex.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/rpds/rpds.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text554 unmodified lines555556557558559560561562563564554 unmodified linesloan-advisor-agent/.venv/Lib/site-packages/regex/_regex.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/rpds/rpds.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_uarray/_uarray.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -textloan-advisor-agent/.venv/Lib/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173# This file is generated by SciPy's build process
# It contains system_info results at the time of building this package.
from enum import Enum
__all__ = ["show"]
_built_with_meson = True
class DisplayModes(Enum):
stdout = "stdout"
dicts = "dicts"
def _cleanup(d):
"""
Removes empty values in a `dict` recursively
This ensures we remove values that Meson could not provide to CONFIG
"""
if isinstance(d, dict):
return { k: _cleanup(v) for k, v in d.items() if v != '' and _cleanup(v) != '' }
else:
return d
CONFIG = _cleanup(
{
"Compilers": {
"c": {
"name": "gcc",
"linker": r"ld.bfd",
"version": "10.3.0",
"commands": r"C:\Strawberry\c\bin\ccache.EXE, cc",
"args": r"",
"linker args": r"",
},
"cython": {
"name": r"cython",
"linker": r"cython",
"version": r"3.2.4",
"commands": r"cython",
"args": r"",
"linker args": r"",
},
"c++": {
"name": "gcc",
"linker": r"ld.bfd",
"version": "10.3.0",
"commands": r"C:\Strawberry\c\bin\ccache.EXE, c++",
"args": r"",
"linker args": r"",
},
"fortran": {
"name": "gcc",
"linker": r"ld.bfd",
"version": "10.3.0",
"commands": r"gfortran",
"args": r"",
"linker args": r"",
},
"pythran": {
"version": r"0.18.1",
"include directory": r"C:\Users\runneradmin\AppData\Local\Temp\build-env-jfo4tcpw\Lib\site-packages/pythran"
},
},
"Machine Information": {
"host": {
"cpu": r"x86_64",
"family": r"x86_64",
"endian": r"little",
"system": r"windows",
},
"build": {
"cpu": r"x86_64",
"family": r"x86_64",
"endian": r"little",
"system": r"windows",
},
"cross-compiled": bool("False".lower().replace('false', '')),
},
"Build Dependencies": {
"blas": {
"name": "scipy-openblas",
"found": bool("True".lower().replace('false', '')),
"version": "0.3.30",
"detection method": "pkgconfig",
"include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/include",
"lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/lib",
"openblas configuration": r"OpenBLAS 0.3.30 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24",
"pc file directory": r"D:/a/scipy/scipy",
"has ilp64": bool(r"False".lower().replace('false', '')),
},
"lapack": {
"name": "scipy-openblas",
"found": bool("True".lower().replace('false', '')),
"version": "0.3.30",
"detection method": "pkgconfig",
"include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/include",
"lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-xk1ry62f/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas32/lib",
"openblas configuration": r"OpenBLAS 0.3.30 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24",
"pc file directory": r"D:/a/scipy/scipy",
"has ilp64": bool(r"False".lower().replace('false', '')),
},
"pybind11": {
"name": "pybind11",
"version": "3.0.2",
"detection method": "config-tool",
"include directory": r"unknown",
},
},
"Python Information": {
"path": r"C:\Users\runneradmin\AppData\Local\Temp\build-env-jfo4tcpw\Scripts\python.exe",
"version": "3.12",
},
}
)
def _check_pyyaml():
import yaml
return yaml
def show(mode=DisplayModes.stdout.value):
"""
Show libraries and system information on which SciPy was built
and is being used
Parameters
----------
mode : {`'stdout'`, `'dicts'`}, optional.
Indicates how to display the config information.
`'stdout'` prints to console, `'dicts'` returns a dictionary
of the configuration.
Returns
-------
out : {`dict`, `None`}
If mode is `'dicts'`, a dict is returned, else None
Examples
--------
>>> import scipy
>>> scipy.show_config()
... # formatted output is printed to the console
>>> config_dict = scipy.show_config(mode='dicts')
>>> list(config_dict.keys())
['Compilers', 'Machine Information', 'Build Dependencies', 'Python Information']
Notes
-----
1. The `'stdout'` mode will give more readable
output if ``pyyaml`` is installed
"""
if mode == DisplayModes.stdout.value:
try: # Non-standard library, check import
yaml = _check_pyyaml()
print(yaml.dump(CONFIG))
except ModuleNotFoundError:
import warnings
import json
warnings.warn("Install `pyyaml` for better output", stacklevel=1)
print(json.dumps(CONFIG, indent=2))
elif mode == DisplayModes.dicts.value:
return CONFIG
else:
raise AttributeError(
f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}"
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""
SciPy: A scientific computing package for Python
================================================
Documentation is available in the docstrings and
online at https://docs.scipy.org/doc/scipy/
Subpackages
-----------
::
cluster --- Vector Quantization / Kmeans
constants --- Physical and mathematical constants and units
datasets --- Dataset methods
differentiate --- Finite difference differentiation tools
fft --- Discrete Fourier transforms
fftpack --- Legacy discrete Fourier transforms
integrate --- Integration routines
interpolate --- Interpolation Tools
io --- Data input and output
linalg --- Linear algebra routines
ndimage --- N-D image package
odr --- Orthogonal Distance Regression
optimize --- Optimization Tools
signal --- Signal Processing Tools
sparse --- Sparse Matrices
spatial --- Spatial data structures and algorithms
special --- Special functions
stats --- Statistical Functions
Public API in the main SciPy namespace
--------------------------------------
::
__version__ --- SciPy version string
LowLevelCallable --- Low-level callback function
show_config --- Show scipy build configuration
test --- Run scipy unittests
"""
# start delvewheel patch
def _delvewheel_patch_1_12_0():
import os
if os.path.isdir(libs_dir := os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'scipy.libs'))):
os.add_dll_directory(libs_dir)
_delvewheel_patch_1_12_0()
del _delvewheel_patch_1_12_0
# end delvewheel patch
import importlib as _importlib
from numpy import __version__ as __numpy_version__
try:
from scipy.__config__ import show as show_config
except ImportError as e:
msg = """Error importing SciPy: you cannot import SciPy while
being in scipy source directory; please exit the SciPy source
tree first and relaunch your Python interpreter."""
raise ImportError(msg) from e
from scipy.version import version as __version__
# Allow distributors to run custom init code
from . import _distributor_init
del _distributor_init
from scipy._lib import _pep440
# In maintenance branch, change to np_maxversion N+3 if numpy is at N
np_minversion = '1.26.4'
np_maxversion = '2.7.0'
if (_pep440.parse(__numpy_version__) < _pep440.Version(np_minversion) or
_pep440.parse(__numpy_version__) >= _pep440.Version(np_maxversion)):
import warnings
warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
f" is required for this version of SciPy (detected "
f"version {__numpy_version__})",
UserWarning, stacklevel=2)
del _pep440
# This is the first import of an extension module within SciPy. If there's
# a general issue with the install, such that extension modules are missing
# or cannot be imported, this is where we'll get a failure - so give an
# informative error message.
try:
from scipy._lib._ccallback import LowLevelCallable
except ImportError as e:
msg = "The `scipy` install you are using seems to be broken, " + \
"(extension modules cannot be imported), " + \
"please try reinstalling."
raise ImportError(msg) from e
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
submodules = [
'cluster',
'constants',
'datasets',
'differentiate',
'fft',
'fftpack',
'integrate',
'interpolate',
'io',
'linalg',
'ndimage',
'odr',
'optimize',
'signal',
'sparse',
'spatial',
'special',
'stats'
]
__all__ = submodules + [
'LowLevelCallable',
'test',
'show_config',
'__version__',
]
def __dir__():
return __all__
def __getattr__(name):
if name in submodules:
return _importlib.import_module(f'scipy.{name}')
else:
try:
return globals()[name]
except KeyError:
raise AttributeError(
f"Module 'scipy' has no attribute '{name}'"
)123version https://git-lfs.github.com/spec/v1oid sha256:1990a1fbef9f2f75556db35b81d7180c903fc54db3f8fd08c14ac2cbc805c61bsize 186368123456789101112131415161718""" Distributor init file
Distributors: you can replace the contents of this file with your own custom
code to support particular distributions of SciPy.
For example, this is a good place to put any checks for hardware requirements
or BLAS/LAPACK library initialization.
The SciPy standard source distribution will not put code in this file beyond
the try-except import of `_distributor_init_local` (which is not part of a
standard source distribution), so you can safely replace this file with your
own version.
"""
try:
from . import _distributor_init_local # noqa: F401
except ImportError:
pass1234567891011121314"""
Module containing private utility functions
===========================================
The ``scipy._lib`` namespace is empty (for now). Tests for all
utilities in submodules of ``_lib`` can be run with::
from scipy import _lib
_lib.test()
"""
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036"""Utility functions to use Python Array API compatible libraries.
For the context about the Array API see:
https://data-apis.org/array-api/latest/purpose_and_scope.html
The SciPy use case of the Array API is described on the following page:
https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy
"""
import operator
import dataclasses
import functools
import textwrap
from collections.abc import Generator
from contextlib import contextmanager
from contextvars import ContextVar
from types import ModuleType
from typing import Any, Literal, TypeAlias
from collections.abc import Iterable
import numpy as np
import numpy.typing as npt
from scipy._lib.array_api_compat import (
is_array_api_obj,
is_lazy_array,
is_numpy_array,
is_cupy_array,
is_torch_array,
is_jax_array,
is_dask_array,
size as xp_size,
numpy as np_compat,
device as xp_device,
is_numpy_namespace as is_numpy,
is_cupy_namespace as is_cupy,
is_torch_namespace as is_torch,
is_jax_namespace as is_jax,
is_dask_namespace as is_dask,
is_array_api_strict_namespace as is_array_api_strict,
)
from scipy._lib.array_api_compat.common._helpers import _compat_module_name
from scipy._lib.array_api_extra.testing import lazy_xp_function
from scipy._lib._array_api_override import (
array_namespace, SCIPY_ARRAY_API, SCIPY_DEVICE
)
from scipy._lib._docscrape import FunctionDoc
from scipy._lib import array_api_extra as xpx
__all__ = [
'_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal',
'default_xp', 'eager_warns', 'is_lazy_array', 'is_marray',
'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch',
'np_compat', 'get_native_namespace_name',
'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for',
'xp_assert_close', 'xp_assert_equal', 'xp_assert_less',
'xp_copy', 'xp_device', 'xp_ravel', 'xp_size',
'xp_unsupported_param_msg', 'xp_vector_norm', 'xp_capabilities',
'xp_result_type', 'xp_promote',
'make_xp_test_case', 'make_xp_pytest_marks', 'make_xp_pytest_param',
]
Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589)
ArrayLike: TypeAlias = Array | npt.ArrayLike
def _check_finite(array: Array, xp: ModuleType) -> None:
"""Check for NaNs or Infs."""
if not xp.all(xp.isfinite(array)):
msg = "array must not contain infs or NaNs"
raise ValueError(msg)
def _asarray(
array: ArrayLike,
dtype: Any = None,
order: Literal['K', 'A', 'C', 'F'] | None = None,
copy: bool | None = None,
*,
xp: ModuleType | None = None,
check_finite: bool = False,
subok: bool = False,
) -> Array:
"""SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and
`subok`.
Memory layout parameter `order` is not exposed in the Array API standard.
`order` is only enforced if the input array implementation
is NumPy based, otherwise `order` is just silently ignored.
`check_finite` is also not a keyword in the array API standard; included
here for convenience rather than that having to be a separate function
call inside SciPy functions.
`subok` is included to allow this function to preserve the behaviour of
`np.asanyarray` for NumPy based inputs.
"""
if xp is None:
xp = array_namespace(array)
if is_numpy(xp):
# Use NumPy API to support order
if copy is True:
array = np.array(array, order=order, dtype=dtype, subok=subok)
elif subok:
array = np.asanyarray(array, order=order, dtype=dtype)
else:
array = np.asarray(array, order=order, dtype=dtype)
else:
try:
array = xp.asarray(array, dtype=dtype, copy=copy)
except TypeError:
coerced_xp = array_namespace(xp.asarray(3))
array = coerced_xp.asarray(array, dtype=dtype, copy=copy)
if check_finite:
_check_finite(array, xp)
return array
def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array:
"""
Copies an array.
Parameters
----------
x : array
xp : array_namespace
Returns
-------
copy : array
Copied array
Notes
-----
This copy function does not offer all the semantics of `np.copy`, i.e. the
`subok` and `order` keywords are not used.
"""
# Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg,
# so this uses our other helper `_asarray`.
if xp is None:
xp = array_namespace(x)
return _asarray(x, copy=True, xp=xp)
def _xp_copy_to_numpy(x: Array) -> np.ndarray:
"""Copies a possibly on device array to a NumPy array.
This function is intended only for converting alternative backend
arrays to numpy arrays within test code, to make it easier for use
of the alternative backend to be isolated only to the function being
tested. `_xp_copy_to_numpy` should NEVER be used except in test code
for the specific purpose mentioned above. In production code, attempts
to copy device arrays to NumPy arrays should fail, or else functions
may appear to be working on the GPU when they actually aren't.
Parameters
----------
x : array
Returns
-------
ndarray
"""
xp = array_namespace(x)
if is_numpy(xp):
return x.copy()
if is_cupy(xp):
return x.get()
if is_torch(xp):
return x.cpu().numpy()
if is_array_api_strict(xp):
# array api strict supports multiple devices, so need to
# ensure x is on the cpu before copying to NumPy.
return np.asarray(
xp.asarray(x, device=xp.Device("CPU_DEVICE")), copy=True
)
# Fall back to np.asarray. This works for dask.array. It
# currently works for jax.numpy, but hopefully JAX will make
# the transfer guard workable enough for use in scipy tests, in
# which case, JAX will have to be handled explicitly.
# If new backends are added, they may require explicit handling as
# well.
return np.asarray(x, copy=True)
_default_xp_ctxvar: ContextVar[ModuleType] = ContextVar("_default_xp")
@contextmanager
def default_xp(xp: ModuleType) -> Generator[None, None, None]:
"""In all ``xp_assert_*`` and ``assert_*`` function calls executed within this
context manager, test by default that the array namespace is
the provided across all arrays, unless one explicitly passes the ``xp=``
parameter or ``check_namespace=False``.
Without this context manager, the default value for `xp` is the namespace
for the desired array (the second parameter of the tests).
"""
token = _default_xp_ctxvar.set(xp)
try:
yield
finally:
_default_xp_ctxvar.reset(token)
def eager_warns(warning_type, *, match=None, xp):
"""pytest.warns context manager if arrays of specified namespace are always eager.
Otherwise, context manager that *ignores* specified warning.
"""
import pytest
from scipy._lib._util import ignore_warns
if is_numpy(xp) or is_array_api_strict(xp) or is_cupy(xp):
return pytest.warns(warning_type, match=match)
return ignore_warns(warning_type, match='' if match is None else match)
def _strict_check(actual, desired, xp, *,
check_namespace=True, check_dtype=True, check_shape=True,
check_0d=True):
__tracebackhide__ = True # Hide traceback for py.test
if xp is None:
try:
xp = _default_xp_ctxvar.get()
except LookupError:
xp = array_namespace(desired)
if check_namespace:
_assert_matching_namespace(actual, desired, xp)
# only NumPy distinguishes between scalars and arrays; we do if check_0d=True.
# do this first so we can then cast to array (and thus use the array API) below.
if is_numpy(xp) and check_0d:
_msg = ("Array-ness does not match:\n Actual: "
f"{type(actual)}\n Desired: {type(desired)}")
assert ((xp.isscalar(actual) and xp.isscalar(desired))
or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg
actual = xp.asarray(actual)
desired = xp.asarray(desired)
if check_dtype:
_msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}"
assert actual.dtype == desired.dtype, _msg
if check_shape:
if is_dask(xp):
actual.compute_chunk_sizes()
desired.compute_chunk_sizes()
_msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}"
assert actual.shape == desired.shape, _msg
desired = xp.broadcast_to(desired, actual.shape)
return actual, desired, xp
def _assert_matching_namespace(actual, desired, xp):
__tracebackhide__ = True # Hide traceback for py.test
desired_arr_space = array_namespace(desired)
_msg = ("Namespace of desired array does not match expectations "
"set by the `default_xp` context manager or by the `xp`"
"pytest fixture.\n"
f"Desired array's space: {desired_arr_space.__name__}\n"
f"Expected namespace: {xp.__name__}")
assert desired_arr_space == xp, _msg
actual_arr_space = array_namespace(actual)
_msg = ("Namespace of actual and desired arrays do not match.\n"
f"Actual: {actual_arr_space.__name__}\n"
f"Desired: {xp.__name__}")
assert actual_arr_space == xp, _msg
def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True,
check_shape=True, check_0d=True, err_msg='', xp=None):
__tracebackhide__ = True # Hide traceback for py.test
actual, desired, xp = _strict_check(
actual, desired, xp, check_namespace=check_namespace,
check_dtype=check_dtype, check_shape=check_shape,
check_0d=check_0d
)
if is_cupy(xp):
return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg)
elif is_torch(xp):
# PyTorch recommends using `rtol=0, atol=0` like this
# to test for exact equality
err_msg = None if err_msg == '' else err_msg
return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True,
check_dtype=False, msg=err_msg)
# JAX uses `np.testing`
return np.testing.assert_array_equal(actual, desired, err_msg=err_msg)
def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True,
check_dtype=True, check_shape=True, check_0d=True,
err_msg='', xp=None):
__tracebackhide__ = True # Hide traceback for py.test
actual, desired, xp = _strict_check(
actual, desired, xp,
check_namespace=check_namespace, check_dtype=check_dtype,
check_shape=check_shape, check_0d=check_0d
)
floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating'))
if rtol is None and floating:
# multiplier of 4 is used as for `np.float64` this puts the default `rtol`
# roughly half way between sqrt(eps) and the default for
# `numpy.testing.assert_allclose`, 1e-7
rtol = xp.finfo(actual.dtype).eps**0.5 * 4
elif rtol is None:
rtol = 1e-7
if is_cupy(xp):
return xp.testing.assert_allclose(actual, desired, rtol=rtol,
atol=atol, err_msg=err_msg)
elif is_torch(xp):
err_msg = None if err_msg == '' else err_msg
return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol,
equal_nan=True, check_dtype=False, msg=err_msg)
# JAX uses `np.testing`
return np.testing.assert_allclose(actual, desired, rtol=rtol,
atol=atol, err_msg=err_msg)
def xp_assert_close_nulp(actual, desired, *, nulp=1, check_namespace=True,
check_dtype=True, check_shape=True, check_0d=True,
err_msg='', xp=None):
__tracebackhide__ = True # Hide traceback for py.test
actual, desired, xp = _strict_check(
actual, desired, xp,
check_namespace=check_namespace, check_dtype=check_dtype,
check_shape=check_shape, check_0d=check_0d
)
actual, desired = map(_xp_copy_to_numpy, (actual, desired))
return np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=nulp)
def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True,
check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None):
__tracebackhide__ = True # Hide traceback for py.test
actual, desired, xp = _strict_check(
actual, desired, xp, check_namespace=check_namespace,
check_dtype=check_dtype, check_shape=check_shape,
check_0d=check_0d
)
if is_cupy(xp):
return xp.testing.assert_array_less(actual, desired,
err_msg=err_msg, verbose=verbose)
elif is_torch(xp):
if actual.device.type != 'cpu':
actual = actual.cpu()
if desired.device.type != 'cpu':
desired = desired.cpu()
# JAX uses `np.testing`
return np.testing.assert_array_less(actual, desired,
err_msg=err_msg, verbose=verbose)
def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
"""
rtol, atol = 0, 1.5*10**(-decimal)
return xp_assert_close(actual, desired,
atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
*args, **kwds)
def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
"""
rtol, atol = 0, 1.5*10**(-decimal)
return xp_assert_close(actual, desired,
atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
*args, **kwds)
def xp_unsupported_param_msg(param: Any) -> str:
return f'Providing {param!r} is only supported for numpy arrays.'
def is_complex(x: Array, xp: ModuleType) -> bool:
return xp.isdtype(x.dtype, 'complex floating')
def get_native_namespace_name(xp: ModuleType) -> str:
"""Return name for native namespace (without array_api_compat prefix)."""
name = xp.__name__
return name.removeprefix(f"{_compat_module_name()}.")
def scipy_namespace_for(xp: ModuleType) -> ModuleType | None:
"""Return the `scipy`-like namespace of a non-NumPy backend
That is, return the namespace corresponding with backend `xp` that contains
`scipy` sub-namespaces like `linalg` and `special`. If no such namespace
exists, return ``None``. Useful for dispatching.
"""
if is_cupy(xp):
import cupyx # type: ignore[import-not-found,import-untyped]
return cupyx.scipy
if is_jax(xp):
import jax # type: ignore[import-not-found]
return jax.scipy
if is_torch(xp):
return xp
return None
# maybe use `scipy.linalg` if/when array API support is added
def xp_vector_norm(x: Array, /, *,
axis: int | tuple[int] | None = None,
keepdims: bool = False,
ord: int | float = 2,
xp: ModuleType | None = None) -> Array:
xp = array_namespace(x) if xp is None else xp
if SCIPY_ARRAY_API:
# check for optional `linalg` extension
if hasattr(xp, 'linalg'):
return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord)
else:
if ord != 2:
raise ValueError(
"only the Euclidean norm (`ord=2`) is currently supported in "
"`xp_vector_norm` for backends not implementing the `linalg` "
"extension."
)
# return (x @ x)**0.5
# or to get the right behavior with nd, complex arrays
return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5
else:
# to maintain backwards compatibility
return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims)
def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array:
# Equivalent of np.ravel written in terms of array API
# Even though it's one line, it comes up so often that it's worth having
# this function for readability
xp = array_namespace(x) if xp is None else xp
return xp.reshape(x, (-1,))
def xp_swapaxes(a, axis1, axis2, xp=None):
# Equivalent of np.swapaxes written in terms of array API
xp = array_namespace(a) if xp is None else xp
axes = list(range(a.ndim))
axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
a = xp.permute_dims(a, axes)
return a
# utility to find common dtype with option to force floating
def xp_result_type(*args, force_floating=False, xp):
"""
Returns the dtype that results from applying type promotion rules
(see Array API Standard Type Promotion Rules) to the arguments. Augments
standard `result_type` in a few ways:
- There is a `force_floating` argument that ensures that the result type
is floating point, even when all args are integer.
- When a TypeError is raised (e.g. due to an unsupported promotion)
and `force_floating=True`, we define a custom rule: use the result type
of the default float and any other floats passed. See
https://github.com/scipy/scipy/pull/22695/files#r1997905891
for rationale.
- This function accepts array-like iterables, which are immediately converted
to the namespace's arrays before result type calculation. Consequently, the
result dtype may be different when an argument is `1.` vs `[1.]`.
Typically, this function will be called shortly after `array_namespace`
on a subset of the arguments passed to `array_namespace`.
"""
# prevent double conversion of iterable to array
# avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334
# don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars
args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg)
else arg) for arg in args]
args_not_none = [arg for arg in args if arg is not None]
if force_floating:
args_not_none.append(1.0)
if is_numpy(xp) and xp.__version__ < '2.0':
# Follow NEP 50 promotion rules anyway
args_not_none = [arg.dtype if getattr(arg, 'size', 0) == 1 else arg
for arg in args_not_none]
return xp.result_type(*args_not_none)
try: # follow library's preferred promotion rules
return xp.result_type(*args_not_none)
except TypeError: # mixed type promotion isn't defined
if not force_floating:
raise
# use `result_type` of default floating point type and any floats present
# This can be revisited, but right now, the only backends that get here
# are array-api-strict (which is not for production use) and PyTorch
# (due to data-apis/array-api-compat#279).
float_args = []
for arg in args_not_none:
arg_array = xp.asarray(arg) if np.isscalar(arg) else arg
dtype = getattr(arg_array, 'dtype', arg)
if xp.isdtype(dtype, ('real floating', 'complex floating')):
float_args.append(arg)
return xp.result_type(*float_args, xp_default_dtype(xp))
def xp_promote(*args, broadcast=False, force_floating=False, xp):
"""
Promotes elements of *args to result dtype, ignoring `None`s.
Includes options for forcing promotion to floating point and
broadcasting the arrays, again ignoring `None`s.
Type promotion rules follow `xp_result_type` instead of `xp.result_type`.
Typically, this function will be called shortly after `array_namespace`
on a subset of the arguments passed to `array_namespace`.
This function accepts array-like iterables, which are immediately converted
to the namespace's arrays before result type calculation. Consequently, the
result dtype may be different when an argument is `1.` vs `[1.]`.
See Also
--------
xp_result_type
"""
if not args:
return args
# prevent double conversion of iterable to array
# avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334
# don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars
args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg)
else arg) for arg in args]
dtype = xp_result_type(*args, force_floating=force_floating, xp=xp)
args = [(_asarray(arg, dtype=dtype, subok=True, xp=xp) if arg is not None else arg)
for arg in args]
if not broadcast:
return args[0] if len(args)==1 else tuple(args)
args_not_none = [arg for arg in args if arg is not None]
# determine result shape
shapes = {arg.shape for arg in args_not_none}
try:
shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1
else args_not_none[0].shape)
except ValueError as e:
message = "Array shapes are incompatible for broadcasting."
raise ValueError(message) from e
out = []
for arg in args:
if arg is None:
out.append(arg)
continue
# broadcast only if needed
# Even if two arguments need broadcasting, this is faster than
# `broadcast_arrays`, especially since we've already determined `shape`
if arg.shape != shape:
kwargs = {'subok': True} if is_numpy(xp) else {}
arg = xp.broadcast_to(arg, shape, **kwargs)
# This is much faster than xp.astype(arg, dtype, copy=False)
if arg.dtype != dtype:
arg = xp.astype(arg, dtype)
out.append(arg)
return out[0] if len(out)==1 else tuple(out)
def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array:
xp = array_namespace(arr) if xp is None else xp
arr_dtype = arr.dtype
# The standard float dtypes are float32 and float64.
# Convert float32 to complex64,
# and float64 (and non-standard real dtypes) to complex128
if xp.isdtype(arr_dtype, xp.float32):
arr = xp.astype(arr, xp.complex64)
elif xp.isdtype(arr_dtype, 'real floating'):
arr = xp.astype(arr, xp.complex128)
return arr
def xp_default_dtype(xp):
"""Query the namespace-dependent default floating-point dtype.
"""
if is_torch(xp):
# historically, we allow pytorch to keep its default of float32
return xp.get_default_dtype()
else:
# we default to float64
return xp.float64
### MArray Helpers ###
def xp_result_device(*args):
"""Return the device of an array in `args`, for the purpose of
input-output device propagation.
If there are multiple devices, return an arbitrary one.
If there are no arrays, return None (this typically happens only on NumPy).
"""
for arg in args:
# Do not do a duck-type test for the .device attribute, as many backends today
# don't have it yet. See workarouunds in array_api_compat.device().
if is_array_api_obj(arg):
return xp_device(arg)
return None
# np.r_ replacement
def concat_1d(xp: ModuleType | None, *arrays: Iterable[ArrayLike]) -> Array:
"""A replacement for `np.r_` as `xp.concat` does not accept python scalars
or 0-D arrays.
"""
arys = [xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp) for a in arrays]
return xp.concat(arys)
def is_marray(xp):
"""Returns True if `xp` is an MArray namespace; False otherwise."""
return "marray" in xp.__name__
def _length_nonmasked(x, axis, keepdims=False, xp=None):
xp = array_namespace(x) if xp is None else xp
if is_marray(xp):
if np.iterable(axis):
message = '`axis` must be an integer or None for use with `MArray`.'
raise NotImplementedError(message)
return xp.astype(xp.count(x, axis=axis, keepdims=keepdims), x.dtype)
return (xp_size(x) if axis is None else
# compact way to deal with axis tuples or ints
int(np.prod(np.asarray(x.shape)[np.asarray(axis)])))
def _share_masks(*args, xp):
if is_marray(xp):
mask = functools.reduce(operator.or_, (arg.mask for arg in args))
args = [xp.asarray(arg.data, mask=mask) for arg in args]
return args[0] if len(args) == 1 else args
### End MArray Helpers ###
@dataclasses.dataclass(repr=False)
class _XPSphinxCapability:
cpu: bool | None # None if not applicable
gpu: bool | None
warnings: list[str] = dataclasses.field(default_factory=list)
def _render(self, value):
if value is None:
return "n/a"
if not value:
return "⛔"
if self.warnings:
res = "⚠️ " + '; '.join(self.warnings)
assert len(res) <= 20, "Warnings too long"
return res
return "✅"
def __str__(self):
cpu = self._render(self.cpu)
gpu = self._render(self.gpu)
return f"{cpu:20} {gpu:20}"
def _make_sphinx_capabilities(
# lists of tuples [(module name, reason), ...]
skip_backends=(), xfail_backends=(),
# @pytest.mark.skip/xfail_xp_backends kwargs
cpu_only=False, np_only=False, out_of_scope=False, exceptions=(),
# xpx.lazy_xp_backends kwargs
allow_dask_compute=False, jax_jit=True,
# list of tuples [(module name, reason), ...]
warnings = (),
# unused in documentation
reason=None,
):
if out_of_scope:
return {"out_of_scope": True}
exceptions = set(exceptions)
# Default capabilities
capabilities = {
"numpy": _XPSphinxCapability(cpu=True, gpu=None),
"array_api_strict": _XPSphinxCapability(cpu=True, gpu=None),
"cupy": _XPSphinxCapability(cpu=None, gpu=True),
"torch": _XPSphinxCapability(cpu=True, gpu=True),
"jax.numpy": _XPSphinxCapability(cpu=True, gpu=True,
warnings=[] if jax_jit else ["no JIT"]),
# Note: Dask+CuPy is currently untested and unsupported
"dask.array": _XPSphinxCapability(cpu=True, gpu=None,
warnings=["computes graph"] if allow_dask_compute else []),
}
# documentation doesn't display the reason
for module, _ in list(skip_backends) + list(xfail_backends):
backend = capabilities[module]
if backend.cpu is not None:
backend.cpu = False
if backend.gpu is not None:
backend.gpu = False
for module, backend in capabilities.items():
if np_only and module not in exceptions | {"numpy"}:
if backend.cpu is not None:
backend.cpu = False
if backend.gpu is not None:
backend.gpu = False
elif cpu_only and module not in exceptions and backend.gpu is not None:
backend.gpu = False
for module, warning in warnings:
backend = capabilities[module]
backend.warnings.append(warning)
return capabilities
def _make_capabilities_note(fun_name, capabilities, extra_note=None):
if "out_of_scope" in capabilities:
# It will be better to link to a section of the dev-arrayapi docs
# that explains what is and isn't in-scope, but such a section
# doesn't exist yet. Using :ref:`dev-arrayapi` as a placeholder.
note = f"""
**Array API Standard Support**
`{fun_name}` is not in-scope for support of Python Array API Standard compatible
backends other than NumPy.
See :ref:`dev-arrayapi` for more information.
"""
return textwrap.dedent(note)
# Note: deliberately not documenting array-api-strict
note = f"""
**Array API Standard Support**
`{fun_name}` has experimental support for Python Array API Standard compatible
backends in addition to NumPy. Please consider testing these features
by setting an environment variable ``SCIPY_ARRAY_API=1`` and providing
CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following
combinations of backend and device (or other capability) are supported.
==================== ==================== ====================
Library CPU GPU
==================== ==================== ====================
NumPy {capabilities['numpy'] }
CuPy {capabilities['cupy'] }
PyTorch {capabilities['torch'] }
JAX {capabilities['jax.numpy'] }
Dask {capabilities['dask.array'] }
==================== ==================== ====================
""" + (extra_note or "") + " See :ref:`dev-arrayapi` for more information."
return textwrap.dedent(note)
def xp_capabilities(
*,
# Alternative capabilities table.
# Used only for testing this decorator.
capabilities_table=None,
# Generate pytest.mark.skip/xfail_xp_backends.
# See documentation in conftest.py.
# lists of tuples [(module name, reason), ...]
skip_backends=(), xfail_backends=(),
cpu_only=False, np_only=False, reason=None,
out_of_scope=False, exceptions=(),
# lists of tuples [(module name, reason), ...]
warnings=(),
# xpx.testing.lazy_xp_function kwargs.
# Refer to array-api-extra documentation.
allow_dask_compute=False, jax_jit=True,
# Extra note to inject into the docstring
extra_note=None,
):
"""Decorator for a function that states its support among various
Array API compatible backends.
This decorator has two effects:
1. It allows tagging tests with ``@make_xp_test_case`` or
``make_xp_pytest_param`` (see below) to automatically generate
SKIP/XFAIL markers and perform additional backend-specific
testing, such as extra validation for Dask and JAX;
2. It automatically adds a note to the function's docstring, containing
a table matching what has been tested.
See Also
--------
make_xp_test_case
make_xp_pytest_param
array_api_extra.testing.lazy_xp_function
"""
capabilities_table = (xp_capabilities_table if capabilities_table is None
else capabilities_table)
if out_of_scope:
np_only = True
capabilities = dict(
skip_backends=skip_backends,
xfail_backends=xfail_backends,
cpu_only=cpu_only,
np_only=np_only,
out_of_scope=out_of_scope,
reason=reason,
exceptions=exceptions,
allow_dask_compute=allow_dask_compute,
jax_jit=jax_jit,
warnings=warnings,
)
sphinx_capabilities = _make_sphinx_capabilities(**capabilities)
def decorator(f):
# Don't use a wrapper, as in some cases @xp_capabilities is
# applied to a ufunc
capabilities_table[f] = capabilities
note = _make_capabilities_note(f.__name__, sphinx_capabilities, extra_note)
doc = FunctionDoc(f)
doc['Notes'].append(note)
doc = str(doc).split("\n", 1)[1].lstrip(" \n") # remove signature
try:
f.__doc__ = doc
except AttributeError:
# Can't update __doc__ on ufuncs if SciPy
# was compiled against NumPy < 2.2.
pass
return f
return decorator
def make_xp_test_case(*funcs, capabilities_table=None):
capabilities_table = (xp_capabilities_table if capabilities_table is None
else capabilities_table)
"""Generate pytest decorator for a test function that tests functionality
of one or more Array API compatible functions.
Read the parameters of the ``@xp_capabilities`` decorator applied to the
listed functions and:
- Generate the ``@pytest.mark.skip_xp_backends`` and
``@pytest.mark.xfail_xp_backends`` decorators
for the decorated test function
- Tag the function with `xpx.testing.lazy_xp_function`
Example::
@make_xp_test_case(f1)
def test_f1(xp):
...
@make_xp_test_case(f2)
def test_f2(xp):
...
@make_xp_test_case(f1, f2)
def test_f1_and_f2(xp):
...
The above is equivalent to::
@pytest.mark.skip_xp_backends(...)
@pytest.mark.skip_xp_backends(...)
@pytest.mark.xfail_xp_backends(...)
@pytest.mark.xfail_xp_backends(...)
def test_f1(xp):
...
etc., where the arguments of ``skip_xp_backends`` and ``xfail_xp_backends`` are
determined by the ``@xp_capabilities`` decorator applied to the functions.
See Also
--------
xp_capabilities
make_xp_pytest_marks
make_xp_pytest_param
array_api_extra.testing.lazy_xp_function
"""
marks = make_xp_pytest_marks(*funcs, capabilities_table=capabilities_table)
return lambda func: functools.reduce(lambda f, g: g(f), marks, func)
def make_xp_pytest_param(func, *args, capabilities_table=None):
"""Variant of ``make_xp_test_case`` that returns a pytest.param for a function,
with all necessary skip_xp_backends and xfail_xp_backends marks applied::
@pytest.mark.parametrize(
"func", [make_xp_pytest_param(f1), make_xp_pytest_param(f2)]
)
def test(func, xp):
...
The above is equivalent to::
@pytest.mark.parametrize(
"func", [
pytest.param(f1, marks=[
pytest.mark.skip_xp_backends(...),
pytest.mark.xfail_xp_backends(...), ...]),
pytest.param(f2, marks=[
pytest.mark.skip_xp_backends(...),
pytest.mark.xfail_xp_backends(...), ...]),
)
def test(func, xp):
...
Parameters
----------
func : Callable
Function to be tested. It must be decorated with ``@xp_capabilities``.
*args : Any, optional
Extra pytest parameters for the use case, e.g.::
@pytest.mark.parametrize("func,verb", [
make_xp_pytest_param(f1, "hello"),
make_xp_pytest_param(f2, "world")])
def test(func, verb, xp):
# iterates on (func=f1, verb="hello")
# and (func=f2, verb="world")
See Also
--------
xp_capabilities
make_xp_test_case
make_xp_pytest_marks
array_api_extra.testing.lazy_xp_function
"""
import pytest
marks = make_xp_pytest_marks(func, capabilities_table=capabilities_table)
return pytest.param(func, *args, marks=marks, id=func.__name__)
def make_xp_pytest_marks(*funcs, capabilities_table=None):
"""Variant of ``make_xp_test_case`` that returns a list of pytest marks,
which can be used with the module-level `pytestmark = ...` variable::
pytestmark = make_xp_pytest_marks(f1, f2)
def test(xp):
...
In this example, the whole test module is dedicated to testing `f1` or `f2`,
and the two functions have the same capabilities, so it's unnecessary to
cherry-pick which test tests which function.
The above is equivalent to::
pytestmark = [
pytest.mark.skip_xp_backends(...),
pytest.mark.xfail_xp_backends(...), ...]),
]
def test(xp):
...
See Also
--------
xp_capabilities
make_xp_test_case
make_xp_pytest_param
array_api_extra.testing.lazy_xp_function
"""
capabilities_table = (xp_capabilities_table if capabilities_table is None
else capabilities_table)
import pytest
marks = []
for func in funcs:
capabilities = capabilities_table[func]
exceptions = capabilities['exceptions']
reason = capabilities['reason']
if capabilities['cpu_only']:
marks.append(pytest.mark.skip_xp_backends(
cpu_only=True, exceptions=exceptions, reason=reason))
if capabilities['np_only']:
marks.append(pytest.mark.skip_xp_backends(
np_only=True, exceptions=exceptions, reason=reason))
for mod_name, reason in capabilities['skip_backends']:
marks.append(pytest.mark.skip_xp_backends(mod_name, reason=reason))
for mod_name, reason in capabilities['xfail_backends']:
marks.append(pytest.mark.xfail_xp_backends(mod_name, reason=reason))
lazy_kwargs = {k: capabilities[k]
for k in ('allow_dask_compute', 'jax_jit')}
lazy_xp_function(func, **lazy_kwargs)
return marks
# Is it OK to have a dictionary that is mutated (once upon import) in many places?
xp_capabilities_table = {} # type: ignore[var-annotated]
def xp_device_type(a: Array) -> Literal["cpu", "cuda", None]:
if is_numpy_array(a):
return "cpu"
if is_cupy_array(a):
return "cuda"
if is_torch_array(a):
# TODO this can return other backends e.g. tpu but they're unsupported in scipy
return a.device.type
if is_jax_array(a):
# TODO this can return other backends e.g. tpu but they're unsupported in scipy
return "cuda" if (p := a.device.platform) == "gpu" else p
if is_dask_array(a):
return xp_device_type(a._meta)
# array-api-strict is a stand-in for unknown libraries; don't special-case it
return None123456789# DO NOT RENAME THIS FILE
# This is a hook for array_api_extra/src/array_api_extra/_lib/_compat.py
# to override functions of array_api_compat.
from .array_api_compat import * # noqa: F403
from ._array_api_override import array_namespace as scipy_array_namespace
# overrides array_api_compat.array_namespace inside array-api-extra
array_namespace = scipy_array_namespace # type: ignore[assignment]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294"""Generate flat tables showing Array API capabilities for use in docs.
These tables are intended for presenting Array API capabilities across
a wide number of functions at once. Rows correspond to functions and
columns correspond to library/device/option combinations.
"""
from collections import defaultdict
from enum import auto, Enum
from importlib import import_module
from types import ModuleType
from scipy._lib._array_api import xp_capabilities_table
from scipy._lib._array_api import _make_sphinx_capabilities
# For undocumented aliases of public functions which are kept around for
# backwards compatibility reasons. These should be excluded from the
# tables since they would be redundant. There are also no docs pages to
# link entries to.
ALIASES = {
"scipy.linalg": {
# Alias of scipy.linalg.solve_continuous_lyapunov
"solve_lyapunov",
},
"scipy.ndimage": {
# Alias of scipy.ndimage.sum_labels
"sum",
},
"scipy.special": {
# Alias of scipy.special.jv
"jn",
# Alias of scipy.special.roots_legendre
"p_roots",
# Alias of scipy.special.roots_chebyt
"t_roots",
# Alias of scipy.special.roots_chebyu
"u_roots",
# Alias of scipy.special.roots_chebyc
"c_roots",
# Alias of scipy.special.roots_chebys
"s_roots",
# Alias of scipy.special.roots_jacobi
"j_roots",
# Alias of scipy.special.roots_laguerre
"l_roots",
# Alias of scipy.special.roots_genlaguerre
"la_roots",
# Alias of scipy.special.roots_hermite
"h_roots",
# Alias of scipy.special.roots_hermitenorm
"he_roots",
# Alias of scipy.special.roots_gegenbauer
"cg_roots",
# Alias of scipy.special.roots_sh_legendre
"ps_roots",
# Alias of scipy.special.roots_sh_chebyt
"ts_roots",
# Alias of scipy.special.roots_chebyu
"us_roots",
# Alias of scipy.special.roots_sh_jacobi
"js_roots",
}
}
# Shortened names for use in table.
BACKEND_NAMES_MAP = {
"jax.numpy": "jax",
"dask.array": "dask",
}
class BackendSupportStatus(Enum):
YES = auto()
NO = auto()
OUT_OF_SCOPE = auto()
UNKNOWN = auto()
def _process_capabilities_table_entry(entry: dict | None) -> dict[str, dict[str, bool]]:
"""Returns dict showing alternative backend support in easy to consume form.
Parameters
----------
entry : Optional[dict]
A dict with the structure of the values of the dict
scipy._lib._array_api.xp_capabilities_table. If None, it is
assumped that no alternative backends are supported.
Default: None.
Returns
-------
dict[str, dict[str, bool]]
The output dict currently has keys "cpu", "gpu", "jit" and "lazy".
The value associated to each key is itself a dict. The keys of
the inner dicts correspond to backends, with bool values stating
whether or not the backend is supported with a given device or
mode. Inapplicable backends do not appear in the inner dicts
(e.g. since cupy is gpu-only, it does not appear in the inner
dict keyed on "cpu"). Only alternative backends to NumPy are
included since NumPY support should be guaranteed.
"""
# This is a template for the output format. If more backends and
# backend options are added, it will need to be updated manually.
# Entries start as boolean, but upon returning, will take values
# from the BackendSupportStatus Enum.
output = {
"cpu": {"torch": False, "jax": False, "dask": False},
"gpu": {"cupy": False, "torch": False, "jax": False},
"jit": {"jax": False},
"lazy": {"dask": False},
}
S = BackendSupportStatus
if entry is None:
# If there is no entry, assume no alternative backends are supported.
# If the list of supported backends will grows, this hard-coded dict
# will need to be updated.
return {
outer_key: {inner_key: S.UNKNOWN for inner_key in outer_value}
for outer_key, outer_value in output.items()
}
if entry["out_of_scope"]:
# None is used to signify out-of-scope functions.
return {
outer_key: {inner_key: S.OUT_OF_SCOPE for inner_key in outer_value}
for outer_key, outer_value in output.items()
}
# For now, use _make_sphinx_capabilities because that's where
# the relevant logic for determining what is and isn't
# supported based on xp_capabilities_table entries lives.
# Perhaps this logic should be decoupled from sphinx.
for backend, capabilities in _make_sphinx_capabilities(**entry).items():
if backend in {"array_api_strict", "numpy"}:
continue
backend = BACKEND_NAMES_MAP.get(backend, backend)
cpu, gpu = capabilities.cpu, capabilities.gpu
if cpu is not None:
if backend not in output["cpu"]:
raise ValueError(
"Input capabilities table entry contains unhandled"
f" backend {backend} on cpu."
)
output["cpu"][backend] = cpu
if gpu is not None:
if backend not in output["gpu"]:
raise ValueError(
"Input capabilities table entry contains unhandled"
f" backend {backend} on gpu."
)
output["gpu"][backend] = gpu
if backend == "jax":
output["jit"]["jax"] = entry["jax_jit"] and output["cpu"]["jax"]
if backend == "dask.array":
support_lazy = not entry["allow_dask_compute"] and output["dask"]
output["lazy"]["dask"] = support_lazy
return {
outer_key: {
inner_key: S.YES if inner_value else S.NO
for inner_key, inner_value in outer_value.items()
}
for outer_key, outer_value in output.items()
}
def is_named_function_like_object(obj):
return (
not isinstance(obj, ModuleType | type)
and callable(obj) and hasattr(obj, "__name__")
)
def make_flat_capabilities_table(
modules: str | list[str],
backend_type: str,
/,
*,
capabilities_table: list[str] | None = None,
) -> list[dict[str, str]]:
"""Generate full table of array api capabilities across public functions.
Parameters
----------
modules : str | list[str]
A string containing single SciPy module, (e.g `scipy.stats`, `scipy.fft`)
or a list of such strings.
backend_type : {'cpu', 'gpu', 'jit', 'lazy'}
capabilities_table : Optional[list[str]]
Table in the form of `scipy._lib._array_api.xp_capabilities_table`.
If None, uses `scipy._lib._array_api.xp_capabilities_table`.
Default: None.
Returns
-------
output : list[dict[str, str]]
`output` is a table in dict format
(keys corresponding to column names). The first column is "module".
The other columns correspond to supported backends for the given
`backend_type`, e.g. jax.numpy, torch, and dask on cpu.
numpy is excluded because it should always be supported.
See the helper function
`_process_capabilities_table_entry` above).
"""
if backend_type not in {"cpu", "gpu", "jit", "lazy"}:
raise ValueError(f"Received unhandled backend type {backend_type}")
if isinstance(modules, str):
modules = [modules]
if capabilities_table is None:
capabilities_table = xp_capabilities_table
output = []
for module_name in modules:
module = import_module(module_name)
public_things = module.__all__
for name in public_things:
if name in ALIASES.get(module_name, {}):
# Skip undocumented aliases that are kept
# for backwards compatibility reasons.
continue
thing = getattr(module, name)
if not is_named_function_like_object(thing):
continue
entry = xp_capabilities_table.get(thing, None)
capabilities = _process_capabilities_table_entry(entry)[backend_type]
row = {"module": module_name}
row.update({"function": name})
row.update(capabilities)
output.append(row)
return output
def calculate_table_statistics(
flat_table: list[dict[str, str]]
) -> dict[str, tuple[dict[str, str], bool]]:
"""Get counts of what is supported per module.
Parameters
----------
flat_table : list[dict[str, str]]
A table as returned by `make_flat_capabilities_table`
Returns
-------
dict[str, tuple[dict[str, str], bool]]
dict mapping module names to 2-tuples containing an inner dict and a
bool. The inner dicts have a key "total" along with keys for each
backend column of the supplied flat capabilities table. The value
corresponding to total is the total count of functions in the given
module, and the value associated to the other keys is the count of
functions that support that particular backend. The bool is False if
the calculation may be innacurate due to missing xp_capabilities
decorators, and True if all functions for that particular module have
been decorated with xp_capabilities.
"""
if not flat_table:
return []
counter = defaultdict(lambda: defaultdict(int))
S = BackendSupportStatus
# Keep track of which modules have functions with missing xp_capabilities
# decorators so this information can be passed back to the caller.
missing_xp_capabilities = set()
for entry in flat_table:
entry = entry.copy()
entry.pop("function")
module = entry.pop("module")
current_counter = counter[module]
# By design, all backends and options must be considered out-of-scope
# if one is, so just pick an arbitrary entry here to test if function is
# in-scope.
if next(iter(entry.values())) != S.OUT_OF_SCOPE:
current_counter["total"] += 1
for key, value in entry.items():
# Functions missing xp_capabilities will be tabulated as
# unsupported, but may actually be supported. There is a
# note about this in the documentation and this function is
# set up to return information needed to put asterisks next
# to percentages impacted by missing xp_capabilities decorators.
current_counter[key] += 1 if value == S.YES else 0
if value == S.UNKNOWN:
missing_xp_capabilities.add(module)
return {
key: (dict(value), key not in missing_xp_capabilities)
for key, value in counter.items()
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""
Extra testing functions that forbid 0d-input, see #21044
While the xp_assert_* functions generally aim to follow the conventions of the
underlying `xp` library, NumPy in particular is inconsistent in its handling
of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897.
For example, this means that the following operations (as of v2.0.1) currently
return scalars, even though a 0d-array would often be more appropriate:
import numpy as np
np.array(0) * 2 # scalar, not 0d array
- np.array(0) # scalar, not 0d-array
np.sin(np.array(0)) # scalar, not 0d array
np.mean([1, 2, 3]) # scalar, not 0d array
Libraries like CuPy tend to return a 0d-array in scenarios like those above,
and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality
of the inconsistencies present in NumPy, as well as 20+ years of code on top,
the `xp_assert_*` functions here enforce consistency in the only way that
doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type.
However, when scalars are not generally the expected NumPy return type,
it remains preferable to use the assert functions from
the `scipy._lib._array_api` module, which have less surprising behaviour.
"""
from scipy._lib._array_api import array_namespace, is_numpy
from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base,
xp_assert_equal as xp_assert_equal_base,
xp_assert_less as xp_assert_less_base)
__all__: list[str] = []
def _check_scalar(actual, desired, *, xp=None, **kwargs):
__tracebackhide__ = True # Hide traceback for py.test
if xp is None:
xp = array_namespace(actual)
# necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape
desired = xp.asarray(desired)
# Only NumPy distinguishes between scalars and arrays;
# shape check in xp_assert_* is sufficient except for shape == ()
if not (is_numpy(xp) and desired.shape == ()):
return
_msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow "
"the convention of many NumPy functions, returning a scalar when a "
"0d-array would be correct. The specialized `xp_assert_*` functions "
"in the `scipy._lib._array_api_no_0d` module err on the side of "
"caution and do not accept 0d-arrays by default. If the correct "
"result may legitimately be a 0d-array, pass `check_0d=True`, "
"or use the `xp_assert_*` functions from `scipy._lib._array_api`.")
assert xp.isscalar(actual), _msg
def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs):
# in contrast to xp_assert_equal_base, this defaults to check_0d=False,
# but will do an extra check in that case, which forbids 0d-arrays for `actual`
__tracebackhide__ = True # Hide traceback for py.test
# array-ness (check_0d == True) is taken care of by the *_base functions
if not check_0d:
_check_scalar(actual, desired, **kwargs)
return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs)
def xp_assert_close(actual, desired, *, check_0d=False, **kwargs):
# as for xp_assert_equal
__tracebackhide__ = True
if not check_0d:
_check_scalar(actual, desired, **kwargs)
return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs)
def xp_assert_less(actual, desired, *, check_0d=False, **kwargs):
# as for xp_assert_equal
__tracebackhide__ = True
if not check_0d:
_check_scalar(actual, desired, **kwargs)
return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs)
def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
"""
rtol, atol = 0, 1.5*10**(-decimal)
return xp_assert_close(actual, desired,
atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
*args, **kwds)
def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
"""
rtol, atol = 0, 1.5*10**(-decimal)
return xp_assert_close(actual, desired,
atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
*args, **kwds)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""
Override functions from array_api_compat, for use by array-api-extra
and internally.
See also _array_api_compat_vendor.py
"""
import enum
import os
from functools import lru_cache
from types import ModuleType
from typing import Any, TypeAlias
import numpy as np
import numpy.typing as npt
from scipy._lib import array_api_compat
import scipy._lib.array_api_compat.numpy as np_compat
from scipy._lib.array_api_compat import is_array_api_obj, is_jax_array
from scipy._lib._sparse import SparseABC
Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589)
ArrayLike: TypeAlias = Array | npt.ArrayLike
# To enable array API and strict array-like input validation
SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False)
# To control the default device - for use in the test suite only
SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu")
class _ArrayClsInfo(enum.Enum):
skip = 0
numpy = 1
array_like = 2
unknown = 3
@lru_cache(100)
def _validate_array_cls(cls: type) -> _ArrayClsInfo:
if issubclass(cls, (list, tuple)):
return _ArrayClsInfo.array_like
# this comes from `_util._asarray_validated`
if issubclass(cls, SparseABC):
msg = ('Sparse arrays/matrices are not supported by this function. '
'Perhaps one of the `scipy.sparse.linalg` functions '
'would work instead.')
raise ValueError(msg)
if issubclass(cls, np.ma.MaskedArray):
raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.")
if issubclass(cls, np.matrix):
raise TypeError("Inputs of type `numpy.matrix` are not supported.")
if issubclass(cls, (np.ndarray, np.generic)):
return _ArrayClsInfo.numpy
# Note: this must happen after the test for np.generic, because
# np.float64 and np.complex128 are subclasses of float and complex respectively.
# This matches the behavior of array_api_compat.
if issubclass(cls, (int, float, complex, bool, type(None))):
return _ArrayClsInfo.skip
return _ArrayClsInfo.unknown
def array_namespace(*arrays: Array) -> ModuleType:
"""Get the array API compatible namespace for the arrays xs.
Parameters
----------
*arrays : sequence of array_like
Arrays used to infer the common namespace.
Returns
-------
namespace : module
Common namespace.
Notes
-----
Wrapper around `array_api_compat.array_namespace`.
1. Check for the global switch `SCIPY_ARRAY_API`. If disabled, just
return array_api_compat.numpy namespace and skip all compliance checks.
2. Check for known-bad array classes.
The following subclasses are not supported and raise and error:
- `numpy.ma.MaskedArray`
- `numpy.matrix`
- NumPy arrays which do not have a boolean or numerical dtype
- `scipy.sparse` arrays
3. Coerce array-likes to NumPy arrays and check their dtype.
Note that non-scalar array-likes can't be mixed with non-NumPy Array
API objects; e.g.
- `array_namespace([1, 2])` returns NumPy namespace;
- `array_namespace(np.asarray([1, 2], [3, 4])` returns NumPy namespace;
- `array_namespace(cp.asarray([1, 2], [3, 4])` raises an error.
"""
if not SCIPY_ARRAY_API:
# here we could wrap the namespace if needed
return np_compat
numpy_arrays = []
api_arrays = []
for array in arrays:
arr_info = _validate_array_cls(type(array))
if arr_info is _ArrayClsInfo.skip:
pass
elif arr_info is _ArrayClsInfo.numpy:
if array.dtype.kind in 'iufcb': # Numeric or bool
numpy_arrays.append(array)
elif array.dtype.kind == 'V' and is_jax_array(array):
# Special case for JAX zero gradient arrays;
# see array_api_compat._common._helpers._is_jax_zero_gradient_array
api_arrays.append(array) # JAX zero gradient array
else:
raise TypeError(f"An argument has dtype `{array.dtype!r}`; "
"only boolean and numerical dtypes are supported.")
elif arr_info is _ArrayClsInfo.unknown and is_array_api_obj(array):
api_arrays.append(array)
else:
# list, tuple, or arbitrary object
try:
array = np.asanyarray(array)
except TypeError:
raise TypeError("An argument is neither array API compatible nor "
"coercible by NumPy.")
if array.dtype.kind not in 'iufcb': # Numeric or bool
raise TypeError(f"An argument has dtype `{array.dtype!r}`; "
"only boolean and numerical dtypes are supported.")
numpy_arrays.append(array)
# When there are exclusively NumPy and ArrayLikes, skip calling
# array_api_compat.array_namespace for performance.
if not api_arrays:
return np_compat
# In case of mix of NumPy/ArrayLike and non-NumPy Array API arrays,
# let array_api_compat.array_namespace raise an error.
return array_api_compat.array_namespace(*numpy_arrays, *api_arrays)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229import sys as _sys
from keyword import iskeyword as _iskeyword
def _validate_names(typename, field_names, extra_field_names):
"""
Ensure that all the given names are valid Python identifiers that
do not start with '_'. Also check that there are no duplicates
among field_names + extra_field_names.
"""
for name in [typename] + field_names + extra_field_names:
if not isinstance(name, str):
raise TypeError('typename and all field names must be strings')
if not name.isidentifier():
raise ValueError('typename and all field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('typename and all field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names + extra_field_names:
if name.startswith('_'):
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Duplicate field name: {name!r}')
seen.add(name)
# Note: This code is adapted from CPython:Lib/collections/__init__.py
def _make_tuple_bunch(typename, field_names, extra_field_names=None,
module=None):
"""
Create a namedtuple-like class with additional attributes.
This function creates a subclass of tuple that acts like a namedtuple
and that has additional attributes.
The additional attributes are listed in `extra_field_names`. The
values assigned to these attributes are not part of the tuple.
The reason this function exists is to allow functions in SciPy
that currently return a tuple or a namedtuple to returned objects
that have additional attributes, while maintaining backwards
compatibility.
This should only be used to enhance *existing* functions in SciPy.
New functions are free to create objects as return values without
having to maintain backwards compatibility with an old tuple or
namedtuple return value.
Parameters
----------
typename : str
The name of the type.
field_names : list of str
List of names of the values to be stored in the tuple. These names
will also be attributes of instances, so the values in the tuple
can be accessed by indexing or as attributes. At least one name
is required. See the Notes for additional restrictions.
extra_field_names : list of str, optional
List of names of values that will be stored as attributes of the
object. See the notes for additional restrictions.
Returns
-------
cls : type
The new class.
Notes
-----
There are restrictions on the names that may be used in `field_names`
and `extra_field_names`:
* The names must be unique--no duplicates allowed.
* The names must be valid Python identifiers, and must not begin with
an underscore.
* The names must not be Python keywords (e.g. 'def', 'and', etc., are
not allowed).
Examples
--------
>>> from scipy._lib._bunch import _make_tuple_bunch
Create a class that acts like a namedtuple with length 2 (with field
names `x` and `y`) that will also have the attributes `w` and `beta`:
>>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta'])
`Result` is the new class. We call it with keyword arguments to create
a new instance with given values.
>>> result1 = Result(x=1, y=2, w=99, beta=0.5)
>>> result1
Result(x=1, y=2, w=99, beta=0.5)
`result1` acts like a tuple of length 2:
>>> len(result1)
2
>>> result1[:]
(1, 2)
The values assigned when the instance was created are available as
attributes:
>>> result1.y
2
>>> result1.beta
0.5
"""
if len(field_names) == 0:
raise ValueError('field_names must contain at least one name')
if extra_field_names is None:
extra_field_names = []
_validate_names(typename, field_names, extra_field_names)
typename = _sys.intern(str(typename))
field_names = tuple(map(_sys.intern, field_names))
extra_field_names = tuple(map(_sys.intern, extra_field_names))
all_names = field_names + extra_field_names
arg_list = ', '.join(field_names)
full_list = ', '.join(all_names)
repr_fmt = ''.join(('(',
', '.join(f'{name}=%({name})r' for name in all_names),
')'))
tuple_new = tuple.__new__
_dict, _tuple, _zip = dict, tuple, zip
# Create all the named tuple methods to be added to the class namespace
s = f"""\
def __new__(_cls, {arg_list}, **extra_fields):
return _tuple_new(_cls, ({arg_list},))
def __init__(self, {arg_list}, **extra_fields):
for key in self._extra_fields:
if key not in extra_fields:
raise TypeError("missing keyword argument '%s'" % (key,))
for key, val in extra_fields.items():
if key not in self._extra_fields:
raise TypeError("unexpected keyword argument '%s'" % (key,))
self.__dict__[key] = val
def __setattr__(self, key, val):
if key in {repr(field_names)}:
raise AttributeError("can't set attribute %r of class %r"
% (key, self.__class__.__name__))
else:
self.__dict__[key] = val
"""
del arg_list
namespace = {'_tuple_new': tuple_new,
'__builtins__': dict(TypeError=TypeError,
AttributeError=AttributeError),
'__name__': f'namedtuple_{typename}'}
exec(s, namespace)
__new__ = namespace['__new__']
__new__.__doc__ = f'Create new instance of {typename}({full_list})'
__init__ = namespace['__init__']
__init__.__doc__ = f'Instantiate instance of {typename}({full_list})'
__setattr__ = namespace['__setattr__']
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self._asdict()
def _asdict(self):
'Return a new dict which maps field names to their values.'
out = _dict(_zip(self._fields, self))
out.update(self.__dict__)
return out
def __getnewargs_ex__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self), self.__dict__
# Modify function metadata to help with introspection and debugging
for method in (__new__, __repr__, _asdict, __getnewargs_ex__):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({full_list})',
'_fields': field_names,
'__new__': __new__,
'__init__': __init__,
'__repr__': __repr__,
'__setattr__': __setattr__,
'_asdict': _asdict,
'_extra_fields': extra_field_names,
'__getnewargs_ex__': __getnewargs_ex__,
# _field_defaults and _replace are added to get Polars to detect
# a bunch object as a namedtuple. See gh-22450
'_field_defaults': {},
'_replace': None,
}
for index, name in enumerate(field_names):
def _get(self, index=index):
return self[index]
class_namespace[name] = property(_get)
for name in extra_field_names:
def _get(self, name=name):
return self.__dict__[name]
class_namespace[name] = property(_get)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the
# frame where the named tuple is created. Bypass this step in environments
# where sys._getframe is not defined (Jython for example) or sys._getframe
# is not defined for arguments greater than 0 (IronPython), or where the
# user has specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
__new__.__module__ = module
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251from . import _ccallback_c
import ctypes
PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0]
ffi = None
class CData:
pass
def _import_cffi():
global ffi, CData
if ffi is not None:
return
try:
import cffi
ffi = cffi.FFI()
CData = ffi.CData
except ImportError:
ffi = False
class LowLevelCallable(tuple):
"""
Low-level callback function.
Some functions in SciPy take as arguments callback functions, which
can either be python callables or low-level compiled functions. Using
compiled callback functions can improve performance somewhat by
avoiding wrapping data in Python objects.
Such low-level functions in SciPy are wrapped in `LowLevelCallable`
objects, which can be constructed from function pointers obtained from
ctypes, cffi, Cython, or contained in Python `PyCapsule` objects.
.. seealso::
Functions accepting low-level callables:
`scipy.integrate.quad`, `scipy.ndimage.generic_filter`,
`scipy.ndimage.generic_filter1d`, `scipy.ndimage.geometric_transform`
Usage examples:
:ref:`ndimage-ccallbacks`, :ref:`quad-callbacks`
Parameters
----------
function : {PyCapsule, ctypes function pointer, cffi function pointer}
Low-level callback function.
user_data : {PyCapsule, ctypes void pointer, cffi void pointer}
User data to pass on to the callback function.
signature : str, optional
Signature of the function. If omitted, determined from *function*,
if possible.
Attributes
----------
function
Callback function given.
user_data
User data given.
signature
Signature of the function.
Methods
-------
from_cython
Class method for constructing callables from Cython C-exported
functions.
Notes
-----
The argument ``function`` can be one of:
- PyCapsule, whose name contains the C function signature
- ctypes function pointer
- cffi function pointer
The signature of the low-level callback must match one of those expected
by the routine it is passed to.
If constructing low-level functions from a PyCapsule, the name of the
capsule must be the corresponding signature, in the format::
return_type (arg1_type, arg2_type, ...)
For example::
"void (double)"
"double (double, int *, void *)"
The context of a PyCapsule passed in as ``function`` is used as ``user_data``,
if an explicit value for ``user_data`` was not given.
"""
# Make the class immutable
__slots__ = ()
def __new__(cls, function, user_data=None, signature=None):
# We need to hold a reference to the function & user data,
# to prevent them going out of scope
item = cls._parse_callback(function, user_data, signature)
return tuple.__new__(cls, (item, function, user_data))
def __repr__(self):
return f"LowLevelCallable({self.function!r}, {self.user_data!r})"
@property
def function(self):
return tuple.__getitem__(self, 1)
@property
def user_data(self):
return tuple.__getitem__(self, 2)
@property
def signature(self):
return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0))
def __getitem__(self, idx):
raise ValueError()
@classmethod
def from_cython(cls, module, name, user_data=None, signature=None):
"""
Create a low-level callback function from an exported Cython function.
Parameters
----------
module : module
Cython module where the exported function resides
name : str
Name of the exported function
user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional
User data to pass on to the callback function.
signature : str, optional
Signature of the function. If omitted, determined from *function*.
"""
try:
function = module.__pyx_capi__[name]
except AttributeError as e:
message = "Given module is not a Cython module with __pyx_capi__ attribute"
raise ValueError(message) from e
except KeyError as e:
message = f"No function {name!r} found in __pyx_capi__ of the module"
raise ValueError(message) from e
return cls(function, user_data, signature)
@classmethod
def _parse_callback(cls, obj, user_data=None, signature=None):
_import_cffi()
if isinstance(obj, LowLevelCallable):
func = tuple.__getitem__(obj, 0)
elif isinstance(obj, PyCFuncPtr):
func, signature = _get_ctypes_func(obj, signature)
elif isinstance(obj, CData):
func, signature = _get_cffi_func(obj, signature)
elif _ccallback_c.check_capsule(obj):
func = obj
else:
raise ValueError("Given input is not a callable or a "
"low-level callable (pycapsule/ctypes/cffi)")
if isinstance(user_data, ctypes.c_void_p):
context = _get_ctypes_data(user_data)
elif isinstance(user_data, CData):
context = _get_cffi_data(user_data)
elif user_data is None:
context = 0
elif _ccallback_c.check_capsule(user_data):
context = user_data
else:
raise ValueError("Given user data is not a valid "
"low-level void* pointer (pycapsule/ctypes/cffi)")
return _ccallback_c.get_raw_capsule(func, signature, context)
#
# ctypes helpers
#
def _get_ctypes_func(func, signature=None):
# Get function pointer
func_ptr = ctypes.cast(func, ctypes.c_void_p).value
# Construct function signature
if signature is None:
signature = _typename_from_ctypes(func.restype) + " ("
for j, arg in enumerate(func.argtypes):
if j == 0:
signature += _typename_from_ctypes(arg)
else:
signature += ", " + _typename_from_ctypes(arg)
signature += ")"
return func_ptr, signature
def _typename_from_ctypes(item):
if item is None:
return "void"
elif item is ctypes.c_void_p:
return "void *"
name = item.__name__
pointer_level = 0
while name.startswith("LP_"):
pointer_level += 1
name = name[3:]
if name.startswith('c_'):
name = name[2:]
if pointer_level > 0:
name += " " + "*"*pointer_level
return name
def _get_ctypes_data(data):
# Get voidp pointer
return ctypes.cast(data, ctypes.c_void_p).value
#
# CFFI helpers
#
def _get_cffi_func(func, signature=None):
# Get function pointer
func_ptr = ffi.cast('uintptr_t', func)
# Get signature
if signature is None:
signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ')
return func_ptr, signature
def _get_cffi_data(data):
# Get pointer
return ffi.cast('uintptr_t', data)123version https://git-lfs.github.com/spec/v1oid sha256:509d2e681897f4253263c063ad8a2aa0c2459b85ce3d86754b401d42ab26dc9asize 105472123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""
Disjoint set data structure
"""
class DisjointSet:
""" Disjoint set data structure for incremental connectivity queries.
.. versionadded:: 1.6.0
Attributes
----------
n_subsets : int
The number of subsets.
Methods
-------
add
merge
connected
subset
subset_size
subsets
__getitem__
Notes
-----
This class implements the disjoint set [1]_, also known as the *union-find*
or *merge-find* data structure. The *find* operation (implemented in
`__getitem__`) implements the *path halving* variant. The *merge* method
implements the *merge by size* variant.
References
----------
.. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure
Examples
--------
>>> from scipy.cluster.hierarchy import DisjointSet
Initialize a disjoint set:
>>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b'])
Merge some subsets:
>>> disjoint_set.merge(1, 2)
True
>>> disjoint_set.merge(3, 'a')
True
>>> disjoint_set.merge('a', 'b')
True
>>> disjoint_set.merge('b', 'b')
False
Find root elements:
>>> disjoint_set[2]
1
>>> disjoint_set['b']
3
Test connectivity:
>>> disjoint_set.connected(1, 2)
True
>>> disjoint_set.connected(1, 'b')
False
List elements in disjoint set:
>>> list(disjoint_set)
[1, 2, 3, 'a', 'b']
Get the subset containing 'a':
>>> disjoint_set.subset('a')
{'a', 3, 'b'}
Get the size of the subset containing 'a' (without actually instantiating
the subset):
>>> disjoint_set.subset_size('a')
3
Get all subsets in the disjoint set:
>>> disjoint_set.subsets()
[{1, 2}, {'a', 3, 'b'}]
"""
def __init__(self, elements=None):
self.n_subsets = 0
self._sizes = {}
self._parents = {}
# _nbrs is a circular linked list which links connected elements.
self._nbrs = {}
# _indices tracks the element insertion order in `__iter__`.
self._indices = {}
if elements is not None:
for x in elements:
self.add(x)
def __iter__(self):
"""Returns an iterator of the elements in the disjoint set.
Elements are ordered by insertion order.
"""
return iter(self._indices)
def __len__(self):
return len(self._indices)
def __contains__(self, x):
return x in self._indices
def __getitem__(self, x):
"""Find the root element of `x`.
Parameters
----------
x : hashable object
Input element.
Returns
-------
root : hashable object
Root element of `x`.
"""
if x not in self._indices:
raise KeyError(x)
# find by "path halving"
parents = self._parents
while self._indices[x] != self._indices[parents[x]]:
parents[x] = parents[parents[x]]
x = parents[x]
return x
def add(self, x):
"""Add element `x` to disjoint set
"""
if x in self._indices:
return
self._sizes[x] = 1
self._parents[x] = x
self._nbrs[x] = x
self._indices[x] = len(self._indices)
self.n_subsets += 1
def merge(self, x, y):
"""Merge the subsets of `x` and `y`.
The smaller subset (the child) is merged into the larger subset (the
parent). If the subsets are of equal size, the root element which was
first inserted into the disjoint set is selected as the parent.
Parameters
----------
x, y : hashable object
Elements to merge.
Returns
-------
merged : bool
True if `x` and `y` were in disjoint sets, False otherwise.
"""
xr = self[x]
yr = self[y]
if self._indices[xr] == self._indices[yr]:
return False
sizes = self._sizes
if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]):
xr, yr = yr, xr
self._parents[yr] = xr
self._sizes[xr] += self._sizes[yr]
self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr]
self.n_subsets -= 1
return True
def connected(self, x, y):
"""Test whether `x` and `y` are in the same subset.
Parameters
----------
x, y : hashable object
Elements to test.
Returns
-------
result : bool
True if `x` and `y` are in the same set, False otherwise.
"""
return self._indices[self[x]] == self._indices[self[y]]
def subset(self, x):
"""Get the subset containing `x`.
Parameters
----------
x : hashable object
Input element.
Returns
-------
result : set
Subset containing `x`.
"""
if x not in self._indices:
raise KeyError(x)
result = [x]
nxt = self._nbrs[x]
while self._indices[nxt] != self._indices[x]:
result.append(nxt)
nxt = self._nbrs[nxt]
return set(result)
def subset_size(self, x):
"""Get the size of the subset containing `x`.
Note that this method is faster than ``len(self.subset(x))`` because
the size is directly read off an internal field, without the need to
instantiate the full subset.
Parameters
----------
x : hashable object
Input element.
Returns
-------
result : int
Size of the subset containing `x`.
"""
return self._sizes[self[x]]
def subsets(self):
"""Get all the subsets in the disjoint set.
Returns
-------
result : list
Subsets in the disjoint set.
"""
result = []
visited = set()
for x in self:
if x not in visited:
xset = self.subset(x)
visited.update(xset)
result.append(xset)
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761# copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2
"""Extract reference documentation from the NumPy source tree."""
import copy
import inspect
import pydoc
import re
import sys
import textwrap
from collections import namedtuple
from collections.abc import Callable, Mapping
from functools import cached_property
from warnings import warn
def strip_blank_lines(l):
"Remove leading and trailing blank lines from a list of lines"
while l and not l[0].strip():
del l[0]
while l and not l[-1].strip():
del l[-1]
return l
class Reader:
"""A line-based string reader."""
def __init__(self, data):
"""
Parameters
----------
data : str
String with lines separated by '\\n'.
"""
if isinstance(data, list):
self._str = data
else:
self._str = data.split("\n") # store string as list of lines
self.reset()
def __getitem__(self, n):
return self._str[n]
def reset(self):
self._l = 0 # current line nr
def read(self):
if not self.eof():
out = self[self._l]
self._l += 1
return out
else:
return ""
def seek_next_non_empty_line(self):
for l in self[self._l :]:
if l.strip():
break
else:
self._l += 1
def eof(self):
return self._l >= len(self._str)
def read_to_condition(self, condition_func):
start = self._l
for line in self[start:]:
if condition_func(line):
return self[start : self._l]
self._l += 1
if self.eof():
return self[start : self._l + 1]
return []
def read_to_next_empty_line(self):
self.seek_next_non_empty_line()
def is_empty(line):
return not line.strip()
return self.read_to_condition(is_empty)
def read_to_next_unindented_line(self):
def is_unindented(line):
return line.strip() and (len(line.lstrip()) == len(line))
return self.read_to_condition(is_unindented)
def peek(self, n=0):
if self._l + n < len(self._str):
return self[self._l + n]
else:
return ""
def is_empty(self):
return not "".join(self._str).strip()
class ParseError(Exception):
def __str__(self):
message = self.args[0]
if hasattr(self, "docstring"):
message = f"{message} in {self.docstring!r}"
return message
Parameter = namedtuple("Parameter", ["name", "type", "desc"])
class NumpyDocString(Mapping):
"""Parses a numpydoc string to an abstract representation
Instances define a mapping from section title to structured data.
"""
sections = {
"Signature": "",
"Summary": [""],
"Extended Summary": [],
"Parameters": [],
"Attributes": [],
"Methods": [],
"Returns": [],
"Yields": [],
"Receives": [],
"Other Parameters": [],
"Raises": [],
"Warns": [],
"Warnings": [],
"See Also": [],
"Notes": [],
"References": "",
"Examples": "",
"index": {},
}
def __init__(self, docstring, config=None):
orig_docstring = docstring
docstring = textwrap.dedent(docstring).split("\n")
self._doc = Reader(docstring)
self._parsed_data = copy.deepcopy(self.sections)
try:
self._parse()
except ParseError as e:
e.docstring = orig_docstring
raise
def __getitem__(self, key):
return self._parsed_data[key]
def __setitem__(self, key, val):
if key not in self._parsed_data:
self._error_location(f"Unknown section {key}", error=False)
else:
self._parsed_data[key] = val
def __iter__(self):
return iter(self._parsed_data)
def __len__(self):
return len(self._parsed_data)
def _is_at_section(self):
self._doc.seek_next_non_empty_line()
if self._doc.eof():
return False
l1 = self._doc.peek().strip() # e.g. Parameters
if l1.startswith(".. index::"):
return True
l2 = self._doc.peek(1).strip() # ---------- or ==========
if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1):
snip = "\n".join(self._doc._str[:2]) + "..."
self._error_location(
f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}",
error=False,
)
return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1))
def _strip(self, doc):
i = 0
j = 0
for i, line in enumerate(doc):
if line.strip():
break
for j, line in enumerate(doc[::-1]):
if line.strip():
break
return doc[i : len(doc) - j]
def _read_to_next_section(self):
section = self._doc.read_to_next_empty_line()
while not self._is_at_section() and not self._doc.eof():
if not self._doc.peek(-1).strip(): # previous line was empty
section += [""]
section += self._doc.read_to_next_empty_line()
return section
def _read_sections(self):
while not self._doc.eof():
data = self._read_to_next_section()
name = data[0].strip()
if name.startswith(".."): # index section
yield name, data[1:]
elif len(data) < 2:
yield StopIteration
else:
yield name, self._strip(data[2:])
def _parse_param_list(self, content, single_element_is_type=False):
content = dedent_lines(content)
r = Reader(content)
params = []
while not r.eof():
header = r.read().strip()
if " : " in header:
arg_name, arg_type = header.split(" : ", maxsplit=1)
else:
# NOTE: param line with single element should never have a
# a " :" before the description line, so this should probably
# warn.
if header.endswith(" :"):
header = header[:-2]
if single_element_is_type:
arg_name, arg_type = "", header
else:
arg_name, arg_type = header, ""
desc = r.read_to_next_unindented_line()
desc = dedent_lines(desc)
desc = strip_blank_lines(desc)
params.append(Parameter(arg_name, arg_type, desc))
return params
# See also supports the following formats.
#
# <FUNCNAME>
# <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE*
# <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE*
# <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE*
# <FUNCNAME> is one of
# <PLAIN_FUNCNAME>
# COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK
# where
# <PLAIN_FUNCNAME> is a legal function name, and
# <ROLE> is any nonempty sequence of word characters.
# Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`
# <DESC> is a string describing the function.
_role = r":(?P<role>(py:)?\w+):"
_funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`"
_funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)"
_funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")"
_funcnamenext = _funcname.replace("role", "rolenext")
_funcnamenext = _funcnamenext.replace("name", "namenext")
_description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$"
_func_rgx = re.compile(r"^\s*" + _funcname + r"\s*")
_line_rgx = re.compile(
r"^\s*"
+ r"(?P<allfuncs>"
+ _funcname # group for all function names
+ r"(?P<morefuncs>([,]\s+"
+ _funcnamenext
+ r")*)"
+ r")"
+ r"(?P<trailing>[,\.])?" # end of "allfuncs"
+ _description # Some function lists have a trailing comma (or period) '\s*'
)
# Empty <DESC> elements are replaced with '..'
empty_description = ".."
def _parse_see_also(self, content):
"""
func_name : Descriptive text
continued text
another_func_name : Descriptive text
func_name1, func_name2, :meth:`func_name`, func_name3
"""
content = dedent_lines(content)
items = []
def parse_item_name(text):
"""Match ':role:`name`' or 'name'."""
m = self._func_rgx.match(text)
if not m:
self._error_location(f"Error parsing See Also entry {line!r}")
role = m.group("role")
name = m.group("name") if role else m.group("name2")
return name, role, m.end()
rest = []
for line in content:
if not line.strip():
continue
line_match = self._line_rgx.match(line)
description = None
if line_match:
description = line_match.group("desc")
if line_match.group("trailing") and description:
self._error_location(
"Unexpected comma or period after function list at index %d of "
'line "%s"' % (line_match.end("trailing"), line),
error=False,
)
if not description and line.startswith(" "):
rest.append(line.strip())
elif line_match:
funcs = []
text = line_match.group("allfuncs")
while True:
if not text.strip():
break
name, role, match_end = parse_item_name(text)
funcs.append((name, role))
text = text[match_end:].strip()
if text and text[0] == ",":
text = text[1:].strip()
rest = list(filter(None, [description]))
items.append((funcs, rest))
else:
self._error_location(f"Error parsing See Also entry {line!r}")
return items
def _parse_index(self, section, content):
"""
.. index:: default
:refguide: something, else, and more
"""
def strip_each_in(lst):
return [s.strip() for s in lst]
out = {}
section = section.split("::")
if len(section) > 1:
out["default"] = strip_each_in(section[1].split(","))[0]
for line in content:
line = line.split(":")
if len(line) > 2:
out[line[1]] = strip_each_in(line[2].split(","))
return out
def _parse_summary(self):
"""Grab signature (if given) and summary"""
if self._is_at_section():
return
# If several signatures present, take the last one
while True:
summary = self._doc.read_to_next_empty_line()
summary_str = " ".join([s.strip() for s in summary]).strip()
compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$")
if compiled.match(summary_str):
self["Signature"] = summary_str
if not self._is_at_section():
continue
break
if summary is not None:
self["Summary"] = summary
if not self._is_at_section():
self["Extended Summary"] = self._read_to_next_section()
def _parse(self):
self._doc.reset()
self._parse_summary()
sections = list(self._read_sections())
section_names = {section for section, content in sections}
has_yields = "Yields" in section_names
# We could do more tests, but we are not. Arbitrarily.
if not has_yields and "Receives" in section_names:
msg = "Docstring contains a Receives section but not Yields."
raise ValueError(msg)
for section, content in sections:
if not section.startswith(".."):
section = (s.capitalize() for s in section.split(" "))
section = " ".join(section)
if self.get(section):
self._error_location(
"The section %s appears twice in %s"
% (section, "\n".join(self._doc._str))
)
if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):
self[section] = self._parse_param_list(content)
elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"):
self[section] = self._parse_param_list(
content, single_element_is_type=True
)
elif section.startswith(".. index::"):
self["index"] = self._parse_index(section, content)
elif section == "See Also":
self["See Also"] = self._parse_see_also(content)
else:
self[section] = content
@property
def _obj(self):
if hasattr(self, "_cls"):
return self._cls
elif hasattr(self, "_f"):
return self._f
return None
def _error_location(self, msg, error=True):
if self._obj is not None:
# we know where the docs came from:
try:
filename = inspect.getsourcefile(self._obj)
except TypeError:
filename = None
# Make UserWarning more descriptive via object introspection.
# Skip if introspection fails
name = getattr(self._obj, "__name__", None)
if name is None:
name = getattr(getattr(self._obj, "__class__", None), "__name__", None)
if name is not None:
msg += f" in the docstring of {name}"
msg += f" in {filename}." if filename else ""
if error:
raise ValueError(msg)
else:
warn(msg, stacklevel=3)
# string conversion routines
def _str_header(self, name, symbol="-"):
return [name, len(name) * symbol]
def _str_indent(self, doc, indent=4):
return [" " * indent + line for line in doc]
def _str_signature(self):
if self["Signature"]:
return [self["Signature"].replace("*", r"\*")] + [""]
return [""]
def _str_summary(self):
if self["Summary"]:
return self["Summary"] + [""]
return []
def _str_extended_summary(self):
if self["Extended Summary"]:
return self["Extended Summary"] + [""]
return []
def _str_param_list(self, name):
out = []
if self[name]:
out += self._str_header(name)
for param in self[name]:
parts = []
if param.name:
parts.append(param.name)
if param.type:
parts.append(param.type)
out += [" : ".join(parts)]
if param.desc and "".join(param.desc).strip():
out += self._str_indent(param.desc)
out += [""]
return out
def _str_section(self, name):
out = []
if self[name]:
out += self._str_header(name)
out += self[name]
out += [""]
return out
def _str_see_also(self, func_role):
if not self["See Also"]:
return []
out = []
out += self._str_header("See Also")
out += [""]
last_had_desc = True
for funcs, desc in self["See Also"]:
assert isinstance(funcs, list)
links = []
for func, role in funcs:
if role:
link = f":{role}:`{func}`"
elif func_role:
link = f":{func_role}:`{func}`"
else:
link = f"`{func}`_"
links.append(link)
link = ", ".join(links)
out += [link]
if desc:
out += self._str_indent([" ".join(desc)])
last_had_desc = True
else:
last_had_desc = False
out += self._str_indent([self.empty_description])
if last_had_desc:
out += [""]
out += [""]
return out
def _str_index(self):
idx = self["index"]
out = []
output_index = False
default_index = idx.get("default", "")
if default_index:
output_index = True
out += [f".. index:: {default_index}"]
for section, references in idx.items():
if section == "default":
continue
output_index = True
out += [f" :{section}: {', '.join(references)}"]
if output_index:
return out
return ""
def __str__(self, func_role=""):
out = []
out += self._str_signature()
out += self._str_summary()
out += self._str_extended_summary()
out += self._str_param_list("Parameters")
for param_list in ("Attributes", "Methods"):
out += self._str_param_list(param_list)
for param_list in (
"Returns",
"Yields",
"Receives",
"Other Parameters",
"Raises",
"Warns",
):
out += self._str_param_list(param_list)
out += self._str_section("Warnings")
out += self._str_see_also(func_role)
for s in ("Notes", "References", "Examples"):
out += self._str_section(s)
out += self._str_index()
return "\n".join(out)
def dedent_lines(lines):
"""Deindent a list of lines maximally"""
return textwrap.dedent("\n".join(lines)).split("\n")
class FunctionDoc(NumpyDocString):
def __init__(self, func, role="func", doc=None, config=None):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdoc(func) or ""
if config is None:
config = {}
NumpyDocString.__init__(self, doc, config)
def get_func(self):
func_name = getattr(self._f, "__name__", self.__class__.__name__)
if inspect.isclass(self._f):
func = getattr(self._f, "__call__", self._f.__init__)
else:
func = self._f
return func, func_name
def __str__(self):
out = ""
func, func_name = self.get_func()
roles = {"func": "function", "meth": "method"}
if self._role:
if self._role not in roles:
print(f"Warning: invalid role {self._role}")
out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
out += super().__str__(func_role=self._role)
return out
class ObjDoc(NumpyDocString):
def __init__(self, obj, doc=None, config=None):
self._f = obj
if config is None:
config = {}
NumpyDocString.__init__(self, doc, config=config)
class ClassDoc(NumpyDocString):
extra_public_methods = ["__call__"]
def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
if not inspect.isclass(cls) and cls is not None:
raise ValueError(f"Expected a class or None, but got {cls!r}")
self._cls = cls
if "sphinx" in sys.modules:
from sphinx.ext.autodoc import ALL
else:
ALL = object()
if config is None:
config = {}
self.show_inherited_members = config.get("show_inherited_class_members", True)
if modulename and not modulename.endswith("."):
modulename += "."
self._mod = modulename
if doc is None:
if cls is None:
raise ValueError("No class or documentation string given")
doc = pydoc.getdoc(cls)
NumpyDocString.__init__(self, doc)
_members = config.get("members", [])
if _members is ALL:
_members = None
_exclude = config.get("exclude-members", [])
if config.get("show_class_members", True) and _exclude is not ALL:
def splitlines_x(s):
if not s:
return []
else:
return s.splitlines()
for field, items in [
("Methods", self.methods),
("Attributes", self.properties),
]:
if not self[field]:
doc_list = []
for name in sorted(items):
if name in _exclude or (_members and name not in _members):
continue
try:
doc_item = pydoc.getdoc(getattr(self._cls, name))
doc_list.append(Parameter(name, "", splitlines_x(doc_item)))
except AttributeError:
pass # method doesn't exist
self[field] = doc_list
@property
def methods(self):
if self._cls is None:
return []
return [
name
for name, func in inspect.getmembers(self._cls)
if (
(not name.startswith("_") or name in self.extra_public_methods)
and isinstance(func, Callable)
and self._is_show_member(name)
)
]
@property
def properties(self):
if self._cls is None:
return []
return [
name
for name, func in inspect.getmembers(self._cls)
if (
not name.startswith("_")
and not self._should_skip_member(name, self._cls)
and (
func is None
or isinstance(func, property | cached_property)
or inspect.isdatadescriptor(func)
)
and self._is_show_member(name)
)
]
@staticmethod
def _should_skip_member(name, klass):
return (
# Namedtuples should skip everything in their ._fields as the
# docstrings for each of the members is: "Alias for field number X"
issubclass(klass, tuple)
and hasattr(klass, "_asdict")
and hasattr(klass, "_fields")
and name in klass._fields
)
def _is_show_member(self, name):
return (
# show all class members
self.show_inherited_members
# or class member is not inherited
or name in self._cls.__dict__
)
def get_doc_object(
obj,
what=None,
doc=None,
config=None,
class_doc=ClassDoc,
func_doc=FunctionDoc,
obj_doc=ObjDoc,
):
if what is None:
if inspect.isclass(obj):
what = "class"
elif inspect.ismodule(obj):
what = "module"
elif isinstance(obj, Callable):
what = "function"
else:
what = "object"
if config is None:
config = {}
if what == "class":
return class_doc(obj, func_doc=func_doc, doc=doc, config=config)
elif what in ("function", "method"):
return func_doc(obj, doc=doc, config=config)
else:
if doc is None:
doc = pydoc.getdoc(obj)
return obj_doc(obj, doc, config=config)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346# `_elementwise_iterative_method.py` includes tools for writing functions that
# - are vectorized to work elementwise on arrays,
# - implement non-trivial, iterative algorithms with a callback interface, and
# - return rich objects with iteration count, termination status, etc.
#
# Examples include:
# `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding,
# `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization,
# `scipy.optimize._differentiate._differentiate for numerical differentiation,
# `scipy.optimize._bracket._bracket_root for finding rootfinding brackets,
# `scipy.optimize._bracket._bracket_minimize for finding minimization brackets,
# `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature,
# `scipy.differentiate.derivative` for finite difference based differentiation.
import math
import numpy as np
from ._util import _RichResult, _call_callback_maybe_halt
from ._array_api import array_namespace, xp_size, xp_result_type
import scipy._lib.array_api_extra as xpx
_ESIGNERR = -1
_ECONVERR = -2
_EVALUEERR = -3
_ECALLBACK = -4
_EINPUTERR = -5
_ECONVERGED = 0
_EINPROGRESS = 1
def _initialize(func, xs, args, complex_ok=False, preserve_shape=None, xp=None):
"""Initialize abscissa, function, and args arrays for elementwise function
Parameters
----------
func : callable
An elementwise function with signature
func(x: ndarray, *args) -> ndarray
where each element of ``x`` is a finite real and ``args`` is a tuple,
which may contain an arbitrary number of arrays that are broadcastable
with ``x``.
xs : tuple of arrays
Finite real abscissa arrays. Must be broadcastable.
args : tuple, optional
Additional positional arguments to be passed to `func`.
preserve_shape : bool, default:False
When ``preserve_shape=False`` (default), `func` may be passed
arguments of any shape; `_scalar_optimization_loop` is permitted
to reshape and compress arguments at will. When
``preserve_shape=False``, arguments passed to `func` must have shape
`shape` or ``shape + (n,)``, where ``n`` is any integer.
xp : namespace
Namespace of array arguments in `xs`.
Returns
-------
xs, fs, args : tuple of arrays
Broadcasted, writeable, 1D abscissa and function value arrays (or
NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are
`xfat`; the dtype of the `args` are unchanged.
shape : tuple of ints
Original shape of broadcasted arrays.
xfat : NumPy dtype
Result dtype of abscissae, function values, and args determined using
`np.result_type`, except integer types are promoted to `np.float64`.
Raises
------
ValueError
If the result dtype is not that of a real scalar
Notes
-----
Useful for initializing the input of SciPy functions that accept
an elementwise callable, abscissae, and arguments; e.g.
`scipy.optimize._chandrupatla`.
"""
nx = len(xs)
xp = array_namespace(*xs) if xp is None else xp
# Try to preserve `dtype`, but we need to ensure that the arguments are at
# least floats before passing them into the function; integers can overflow
# and cause failure.
# There might be benefit to combining the `xs` into a single array and
# calling `func` once on the combined array. For now, keep them separate.
xat = xp_result_type(*xs, force_floating=True, xp=xp)
xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename
xs, args = xas[:nx], xas[nx:]
xs = [xp.asarray(x, dtype=xat) for x in xs] # use copy=False when implemented
fs = [xp.asarray(func(x, *args)) for x in xs]
shape = xs[0].shape
fshape = fs[0].shape
if preserve_shape:
# bind original shape/func now to avoid late-binding gotcha
def func(x, *args, shape=shape, func=func, **kwargs):
i = (0,)*(len(fshape) - len(shape))
return func(x[i], *args, **kwargs)
shape = np.broadcast_shapes(fshape, shape) # just shapes; use of NumPy OK
xs = [xp.broadcast_to(x, shape) for x in xs]
args = [xp.broadcast_to(arg, shape) for arg in args]
message = ("The shape of the array returned by `func` must be the same as "
"the broadcasted shape of `x` and all other `args`.")
if preserve_shape is not None: # only in tanhsinh for now
message = f"When `preserve_shape=False`, {message.lower()}"
shapes_equal = [f.shape == shape for f in fs]
if not all(shapes_equal): # use Python all to reduce overhead
raise ValueError(message)
# These algorithms tend to mix the dtypes of the abscissae and function
# values, so figure out what the result will be and convert them all to
# that type from the outset.
xfat = xp.result_type(*([f.dtype for f in fs] + [xat]))
if not complex_ok and not xp.isdtype(xfat, "real floating"):
raise ValueError("Abscissae and function output must be real numbers.")
xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs]
fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs]
# To ensure that we can do indexing, we'll work with at least 1d arrays,
# but remember the appropriate shape of the output.
xs = [xp.reshape(x, (-1,)) for x in xs]
fs = [xp.reshape(f, (-1,)) for f in fs]
args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args]
return func, xs, fs, args, shape, xfat, xp
def _loop(work, callback, shape, maxiter, func, args, dtype, pre_func_eval,
post_func_eval, check_termination, post_termination_check,
customize_result, res_work_pairs, xp, preserve_shape=False):
"""Main loop of a vectorized scalar optimization algorithm
Parameters
----------
work : _RichResult
All variables that need to be retained between iterations. Must
contain attributes `nit`, `nfev`, and `success`. All arrays are
subject to being "compressed" if `preserve_shape is False`; nest
arrays that should not be compressed inside another object (e.g.
`dict` or `_RichResult`).
callback : callable
User-specified callback function
shape : tuple of ints
The shape of all output arrays
maxiter :
Maximum number of iterations of the algorithm
func : callable
The user-specified callable that is being optimized or solved
args : tuple
Additional positional arguments to be passed to `func`.
dtype : NumPy dtype
The common dtype of all abscissae and function values
pre_func_eval : callable
A function that accepts `work` and returns `x`, the active elements
of `x` at which `func` will be evaluated. May modify attributes
of `work` with any algorithmic steps that need to happen
at the beginning of an iteration, before `func` is evaluated,
post_func_eval : callable
A function that accepts `x`, `func(x)`, and `work`. May modify
attributes of `work` with any algorithmic steps that need to happen
in the middle of an iteration, after `func` is evaluated but before
the termination check.
check_termination : callable
A function that accepts `work` and returns `stop`, a boolean array
indicating which of the active elements have met a termination
condition.
post_termination_check : callable
A function that accepts `work`. May modify `work` with any algorithmic
steps that need to happen after the termination check and before the
end of the iteration.
customize_result : callable
A function that accepts `res` and `shape` and returns `shape`. May
modify `res` (in-place) according to preferences (e.g. rearrange
elements between attributes) and modify `shape` if needed.
res_work_pairs : list of (str, str)
Identifies correspondence between attributes of `res` and attributes
of `work`; i.e., attributes of active elements of `work` will be
copied to the appropriate indices of `res` when appropriate. The order
determines the order in which _RichResult attributes will be
pretty-printed.
preserve_shape : bool, default: False
Whether to compress the attributes of `work` (to avoid unnecessary
computation on elements that have already converged).
Returns
-------
res : _RichResult
The final result object
Notes
-----
Besides providing structure, this framework provides several important
services for a vectorized optimization algorithm.
- It handles common tasks involving iteration count, function evaluation
count, a user-specified callback, and associated termination conditions.
- It compresses the attributes of `work` to eliminate unnecessary
computation on elements that have already converged.
"""
if xp is None:
raise NotImplementedError("Must provide xp.")
cb_terminate = False
# Initialize the result object and active element index array
n_elements = math.prod(shape)
active = xp.arange(n_elements) # in-progress element indices
res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs}
res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool)
res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32)
res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32)
res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32)
res = _RichResult(res_dict)
work.args = args
active = _check_termination(work, res, res_work_pairs, active,
check_termination, preserve_shape, xp)
if callback is not None:
temp = _prepare_result(work, res, res_work_pairs, active, shape,
customize_result, preserve_shape, xp)
if _call_callback_maybe_halt(callback, temp):
cb_terminate = True
while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements:
x = pre_func_eval(work)
if work.args and work.args[0].ndim != x.ndim:
# `x` always starts as 1D. If the SciPy function that uses
# _loop added dimensions to `x`, we need to
# add them to the elements of `args`.
args = []
for arg in work.args:
n_new_dims = x.ndim - arg.ndim
new_shape = arg.shape + (1,)*n_new_dims
args.append(xp.reshape(arg, new_shape))
work.args = args
x_shape = x.shape
if preserve_shape:
x = xp.reshape(x, (shape + (-1,)))
f = func(x, *work.args)
f = xp.asarray(f, dtype=dtype)
if preserve_shape:
x = xp.reshape(x, x_shape)
f = xp.reshape(f, x_shape)
work.nfev += 1 if x.ndim == 1 else x.shape[-1]
post_func_eval(x, f, work)
work.nit += 1
active = _check_termination(work, res, res_work_pairs, active,
check_termination, preserve_shape, xp)
if callback is not None:
temp = _prepare_result(work, res, res_work_pairs, active, shape,
customize_result, preserve_shape, xp)
if _call_callback_maybe_halt(callback, temp):
cb_terminate = True
break
if xp_size(active) == 0:
break
post_termination_check(work)
work.status = xpx.at(work.status)[:].set(_ECALLBACK if cb_terminate else _ECONVERR)
return _prepare_result(work, res, res_work_pairs, active, shape,
customize_result, preserve_shape, xp)
def _check_termination(work, res, res_work_pairs, active, check_termination,
preserve_shape, xp):
# Checks termination conditions, updates elements of `res` with
# corresponding elements of `work`, and compresses `work`.
stop = check_termination(work)
if xp.any(stop):
# update the active elements of the result object with the active
# elements for which a termination condition has been met
_update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp)
if preserve_shape:
stop = stop[active]
proceed = ~stop
active = active[proceed]
if not preserve_shape:
# compress the arrays to avoid unnecessary computation
for key, val in work.items():
# `continued_fraction` hacks `n`; improve if this becomes a problem
if key in {'args', 'n'}:
continue
work[key] = val[proceed] if getattr(val, 'ndim', 0) > 0 else val
work.args = [arg[proceed] for arg in work.args]
return active
def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp):
# Update `active` indices of the arrays in result object `res` with the
# contents of the scalars and arrays in `update_dict`. When provided,
# `mask` is a boolean array applied both to the arrays in `update_dict`
# that are to be used and to the arrays in `res` that are to be updated.
update_dict = {key1: work[key2] for key1, key2 in res_work_pairs}
update_dict['success'] = work.status == 0
if mask is not None:
if preserve_shape:
active_mask = xp.zeros_like(mask)
active_mask = xpx.at(active_mask)[active].set(True)
active_mask = active_mask & mask
for key, val in update_dict.items():
val = val[active_mask] if getattr(val, 'ndim', 0) > 0 else val
res[key] = xpx.at(res[key])[active_mask].set(val)
else:
active_mask = active[mask]
for key, val in update_dict.items():
val = val[mask] if getattr(val, 'ndim', 0) > 0 else val
res[key] = xpx.at(res[key])[active_mask].set(val)
else:
for key, val in update_dict.items():
if preserve_shape and getattr(val, 'ndim', 0) > 0:
val = val[active]
res[key] = xpx.at(res[key])[active].set(val)
def _prepare_result(work, res, res_work_pairs, active, shape, customize_result,
preserve_shape, xp):
# Prepare the result object `res` by creating a copy, copying the latest
# data from work, running the provided result customization function,
# and reshaping the data to the original shapes.
res = res.copy()
_update_active(work, res, res_work_pairs, active, None, preserve_shape, xp)
shape = customize_result(res, shape)
for key, val in res.items():
# this looks like it won't work for xp != np if val is not numeric
temp = xp.reshape(val, shape)
res[key] = temp[()] if temp.ndim == 0 else temp
res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs]
return _RichResult(**res)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""
Module for testing automatic garbage collection of objects
.. autosummary::
:toctree: generated/
set_gc_state - enable or disable garbage collection
gc_state - context manager for given state of garbage collector
assert_deallocated - context manager to check for circular references on object
"""
import weakref
import gc
from contextlib import contextmanager
from platform import python_implementation
__all__ = ['set_gc_state', 'gc_state', 'assert_deallocated']
IS_PYPY = python_implementation() == 'PyPy'
class ReferenceError(AssertionError):
pass
def set_gc_state(state):
""" Set status of garbage collector """
if gc.isenabled() == state:
return
if state:
gc.enable()
else:
gc.disable()
@contextmanager
def gc_state(state):
""" Context manager to set state of garbage collector to `state`
Parameters
----------
state : bool
True for gc enabled, False for disabled
Examples
--------
>>> with gc_state(False):
... assert not gc.isenabled()
>>> with gc_state(True):
... assert gc.isenabled()
"""
orig_state = gc.isenabled()
set_gc_state(state)
yield
set_gc_state(orig_state)
@contextmanager
def assert_deallocated(func, *args, **kwargs):
"""Context manager to check that object is deallocated
This is useful for checking that an object can be freed directly by
reference counting, without requiring gc to break reference cycles.
GC is disabled inside the context manager.
This check is not available on PyPy.
Parameters
----------
func : callable
Callable to create object to check
\\*args : sequence
positional arguments to `func` in order to create object to check
\\*\\*kwargs : dict
keyword arguments to `func` in order to create object to check
Examples
--------
>>> class C: pass
>>> with assert_deallocated(C) as c:
... # do something
... del c
>>> class C:
... def __init__(self):
... self._circular = self # Make circular reference
>>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL
... # do something
... del c
Traceback (most recent call last):
...
ReferenceError: Remaining reference(s) to object
"""
if IS_PYPY:
raise RuntimeError("assert_deallocated is unavailable on PyPy")
with gc_state(False):
obj = func(*args, **kwargs)
ref = weakref.ref(obj)
yield obj
del obj
if ref() is not None:
raise ReferenceError("Remaining reference(s) to object")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487"""Utility to compare pep440 compatible version strings.
The LooseVersion and StrictVersion classes that distutils provides don't
work; they don't recognize anything like alpha/beta/rc/dev versions.
"""
# Copyright (c) Donald Stufft and individual contributors.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import collections
import itertools
import re
__all__ = [
"parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
]
# BEGIN packaging/_structures.py
class Infinity:
def __repr__(self):
return "Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return False
def __le__(self, other):
return False
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not isinstance(other, self.__class__)
def __gt__(self, other):
return True
def __ge__(self, other):
return True
def __neg__(self):
return NegativeInfinity
Infinity = Infinity()
class NegativeInfinity:
def __repr__(self):
return "-Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return True
def __le__(self, other):
return True
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not isinstance(other, self.__class__)
def __gt__(self, other):
return False
def __ge__(self, other):
return False
def __neg__(self):
return Infinity
# BEGIN packaging/version.py
NegativeInfinity = NegativeInfinity()
_Version = collections.namedtuple(
"_Version",
["epoch", "release", "dev", "pre", "post", "local"],
)
def parse(version):
"""
Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version.
"""
try:
return Version(version)
except InvalidVersion:
return LegacyVersion(version)
class InvalidVersion(ValueError):
"""
An invalid version was found, users should refer to PEP 440.
"""
class _BaseVersion:
def __hash__(self):
return hash(self._key)
def __lt__(self, other):
return self._compare(other, lambda s, o: s < o)
def __le__(self, other):
return self._compare(other, lambda s, o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s, o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s, o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s, o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s, o: s != o)
def _compare(self, other, method):
if not isinstance(other, _BaseVersion):
return NotImplemented
return method(self._key, other._key)
class LegacyVersion(_BaseVersion):
def __init__(self, version):
self._version = str(version)
self._key = _legacy_cmpkey(self._version)
def __str__(self):
return self._version
def __repr__(self):
return f"<LegacyVersion({repr(str(self))})>"
@property
def public(self):
return self._version
@property
def base_version(self):
return self._version
@property
def local(self):
return None
@property
def is_prerelease(self):
return False
@property
def is_postrelease(self):
return False
_legacy_version_component_re = re.compile(
r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
)
_legacy_version_replacement_map = {
"pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
}
def _parse_version_parts(s):
for part in _legacy_version_component_re.split(s):
part = _legacy_version_replacement_map.get(part, part)
if not part or part == ".":
continue
if part[:1] in "0123456789":
# pad for numeric comparison
yield part.zfill(8)
else:
yield "*" + part
# ensure that alpha/beta/candidate are before final
yield "*final"
def _legacy_cmpkey(version):
# We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch
# greater than or equal to 0. This will effectively put the LegacyVersion,
# which uses the defacto standard originally implemented by setuptools,
# as before all PEP 440 versions.
epoch = -1
# This scheme is taken from pkg_resources.parse_version setuptools prior to
# its adoption of the packaging library.
parts = []
for part in _parse_version_parts(version.lower()):
if part.startswith("*"):
# remove "-" before a prerelease tag
if part < "*final":
while parts and parts[-1] == "*final-":
parts.pop()
# remove trailing zeros from each series of numeric parts
while parts and parts[-1] == "00000000":
parts.pop()
parts.append(part)
parts = tuple(parts)
return epoch, parts
# Deliberately not anchored to the start and end of the string, to make it
# easier for 3rd party code to reuse
VERSION_PATTERN = r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
class Version(_BaseVersion):
_regex = re.compile(
r"^\s*" + VERSION_PATTERN + r"\s*$",
re.VERBOSE | re.IGNORECASE,
)
def __init__(self, version):
# Validate the version and parse it into pieces
match = self._regex.search(version)
if not match:
raise InvalidVersion(f"Invalid version: '{version}'")
# Store the parsed out pieces of the version
self._version = _Version(
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
release=tuple(int(i) for i in match.group("release").split(".")),
pre=_parse_letter_version(
match.group("pre_l"),
match.group("pre_n"),
),
post=_parse_letter_version(
match.group("post_l"),
match.group("post_n1") or match.group("post_n2"),
),
dev=_parse_letter_version(
match.group("dev_l"),
match.group("dev_n"),
),
local=_parse_local_version(match.group("local")),
)
# Generate a key which will be used for sorting
self._key = _cmpkey(
self._version.epoch,
self._version.release,
self._version.pre,
self._version.post,
self._version.dev,
self._version.local,
)
def __repr__(self):
return f"<Version({repr(str(self))})>"
def __str__(self):
parts = []
# Epoch
if self._version.epoch != 0:
parts.append(f"{self._version.epoch}!")
# Release segment
parts.append(".".join(str(x) for x in self._version.release))
# Pre-release
if self._version.pre is not None:
parts.append("".join(str(x) for x in self._version.pre))
# Post-release
if self._version.post is not None:
parts.append(f".post{self._version.post[1]}")
# Development release
if self._version.dev is not None:
parts.append(f".dev{self._version.dev[1]}")
# Local version segment
if self._version.local is not None:
parts.append(
"+{}".format(".".join(str(x) for x in self._version.local))
)
return "".join(parts)
@property
def public(self):
return str(self).split("+", 1)[0]
@property
def base_version(self):
parts = []
# Epoch
if self._version.epoch != 0:
parts.append(f"{self._version.epoch}!")
# Release segment
parts.append(".".join(str(x) for x in self._version.release))
return "".join(parts)
@property
def local(self):
version_string = str(self)
if "+" in version_string:
return version_string.split("+", 1)[1]
@property
def is_prerelease(self):
return bool(self._version.dev or self._version.pre)
@property
def is_postrelease(self):
return bool(self._version.post)
def _parse_letter_version(letter, number):
if letter:
# We assume there is an implicit 0 in a pre-release if there is
# no numeral associated with it.
if number is None:
number = 0
# We normalize any letters to their lower-case form
letter = letter.lower()
# We consider some words to be alternate spellings of other words and
# in those cases we want to normalize the spellings to our preferred
# spelling.
if letter == "alpha":
letter = "a"
elif letter == "beta":
letter = "b"
elif letter in ["c", "pre", "preview"]:
letter = "rc"
elif letter in ["rev", "r"]:
letter = "post"
return letter, int(number)
if not letter and number:
# We assume that if we are given a number but not given a letter,
# then this is using the implicit post release syntax (e.g., 1.0-1)
letter = "post"
return letter, int(number)
_local_version_seperators = re.compile(r"[\._-]")
def _parse_local_version(local):
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_seperators.split(local)
)
def _cmpkey(epoch, release, pre, post, dev, local):
# When we compare a release version, we want to compare it with all of the
# trailing zeros removed. So we'll use a reverse the list, drop all the now
# leading zeros until we come to something non-zero, then take the rest,
# re-reverse it back into the correct order, and make it a tuple and use
# that for our sorting key.
release = tuple(
reversed(list(
itertools.dropwhile(
lambda x: x == 0,
reversed(release),
)
))
)
# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
# We'll do this by abusing the pre-segment, but we _only_ want to do this
# if there is no pre- or a post-segment. If we have one of those, then
# the normal sorting rules will handle this case correctly.
if pre is None and post is None and dev is not None:
pre = -Infinity
# Versions without a pre-release (except as noted above) should sort after
# those with one.
elif pre is None:
pre = Infinity
# Versions without a post-segment should sort before those with one.
if post is None:
post = -Infinity
# Versions without a development segment should sort after those with one.
if dev is None:
dev = Infinity
if local is None:
# Versions without a local segment should sort before those with one.
local = -Infinity
else:
# Versions with a local segment need that segment parsed to implement
# the sorting rules in PEP440.
# - Alphanumeric segments sort before numeric segments
# - Alphanumeric segments sort lexicographically
# - Numeric segments sort numerically
# - Shorter versions sort before longer versions when the prefixes
# match exactly
local = tuple(
(i, "") if isinstance(i, int) else (-Infinity, i)
for i in local
)
return epoch, release, pre, post, dev, local1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""PUBLIC_MODULES was once included in scipy._lib.tests.test_public_api.
It has been separated into this file so that this list of public modules
could be used when generating tables showing support for alternative
array API backends across modules in
scipy/doc/source/array_api_capabilities.py.
"""
# Historically SciPy has not used leading underscores for private submodules
# much. This has resulted in lots of things that look like public modules
# (i.e. things that can be imported as `import scipy.somesubmodule.somefile`),
# but were never intended to be public. The PUBLIC_MODULES list contains
# modules that are either public because they were meant to be, or because they
# contain public functions/objects that aren't present in any other namespace
# for whatever reason and therefore should be treated as public.
PUBLIC_MODULES = ["scipy." + s for s in [
"cluster",
"cluster.vq",
"cluster.hierarchy",
"constants",
"datasets",
"differentiate",
"fft",
"fftpack",
"integrate",
"interpolate",
"io",
"io.arff",
"io.matlab",
"io.wavfile",
"linalg",
"linalg.blas",
"linalg.cython_blas",
"linalg.lapack",
"linalg.cython_lapack",
"linalg.interpolative",
"ndimage",
"odr",
"optimize",
"optimize.elementwise",
"signal",
"signal.windows",
"sparse",
"sparse.linalg",
"sparse.csgraph",
"spatial",
"spatial.distance",
"spatial.transform",
"special",
"stats",
"stats.contingency",
"stats.distributions",
"stats.mstats",
"stats.qmc",
"stats.sampling"
]]1234567891011121314151617181920212223242526272829303132333435363738394041from abc import ABC
__all__ = ["SparseABC", "issparse"]
class SparseABC(ABC):
pass
def issparse(x):
"""Is `x` of a sparse array or sparse matrix type?
Parameters
----------
x
object to check for being a sparse array or sparse matrix
Returns
-------
bool
True if `x` is a sparse array or a sparse matrix, False otherwise
Notes
-----
Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.
Examples
--------
>>> import numpy as np
>>> from scipy.sparse import csr_array, csr_matrix, issparse
>>> issparse(csr_matrix([[5]]))
True
>>> issparse(csr_array([[5]]))
True
>>> issparse(np.array([[5]]))
False
>>> issparse(5)
False
"""
return isinstance(x, SparseABC).gitattributes+7
loan-advisor-agent/.venv/Lib/site-packages/scipy/__config__.pyAdded+173
loan-advisor-agent/.venv/Lib/site-packages/scipy/__init__.pyAdded+150
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__config__.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/__init__.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/__pycache__/version.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.dll.aAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_cyutility.cp312-win_amd64.pydAdded+3
loan-advisor-agent/.venv/Lib/site-packages/scipy/_distributor_init.pyAdded+18
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__init__.pyAdded+14
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pycAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api.pyAdded+1036
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_compat_vendor.pyAdded+9
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_docs_tables.pyAdded+294
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_no_0d.pyAdded+103
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_array_api_override.pyAdded+150
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_bunch.pyAdded+229
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback.pyAdded+251
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.aAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.pydAdded+3
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_disjoint_set.pyAdded+254
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_docscrape.pyAdded+761
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.pyAdded+346
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.aAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.pydAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_gcutils.pyAdded+105
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_pep440.pyAdded+487
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_public_api.pyAdded+56
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_sparse.pyAdded+41
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.aAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.pydAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.aAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.pydAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.aAdded
loan-advisor-agent/.venv/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.pydAdded