ADAPT-Chase commited on
Commit
9c31fe9
·
verified ·
1 Parent(s): 906d8f1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +23 -0
  2. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py +14 -0
  3. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py +931 -0
  4. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_compat_vendor.py +9 -0
  5. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py +103 -0
  6. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py +229 -0
  7. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py +251 -0
  8. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py +254 -0
  10. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py +761 -0
  11. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py +346 -0
  12. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so +0 -0
  13. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py +105 -0
  14. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_pep440.py +487 -0
  15. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py +41 -0
  16. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so +0 -0
  17. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py +373 -0
  20. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_threadsafety.py +58 -0
  21. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_tmpdirs.py +86 -0
  22. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py +1283 -0
  23. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/decorator.py +399 -0
  24. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py +274 -0
  25. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py +366 -0
  26. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so +0 -0
  27. tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py +31 -0
  28. tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py +31 -0
  29. tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so +3 -0
  30. tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so +3 -0
  31. tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so +3 -0
  32. tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy.py +0 -0
  33. tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/vq.py +832 -0
  34. tool_server/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py +358 -0
  35. tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py +0 -0
  36. tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py +369 -0
  37. tool_server/.venv/lib/python3.12/site-packages/scipy/constants/codata.py +21 -0
  38. tool_server/.venv/lib/python3.12/site-packages/scipy/constants/constants.py +53 -0
  39. tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py +90 -0
  40. tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py +71 -0
  41. tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py +225 -0
  42. tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py +26 -0
  43. tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py +81 -0
  44. tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py +27 -0
  45. tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py +1129 -0
  46. tool_server/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py +114 -0
  47. tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py +196 -0
  48. tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py +1650 -0
  49. tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py +197 -0
  50. tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py +22 -0
.gitattributes CHANGED
@@ -4207,3 +4207,26 @@ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/cuobjd
4207
  tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
4208
  tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
4209
  tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/ptxas-blackwell filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4207
  tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
4208
  tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
4209
  tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/ptxas-blackwell filter=lfs diff=lfs merge=lfs -text
4210
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/libdevice.10.bc filter=lfs diff=lfs merge=lfs -text
4211
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text
4212
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so filter=lfs diff=lfs merge=lfs -text
4213
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
4214
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.0 filter=lfs diff=lfs merge=lfs -text
4215
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a filter=lfs diff=lfs merge=lfs -text
4216
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so filter=lfs diff=lfs merge=lfs -text
4217
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a filter=lfs diff=lfs merge=lfs -text
4218
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text
4219
+ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text
4220
+ tool_server/.venv/lib/python3.12/site-packages/triton/language/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4221
+ tool_server/.venv/lib/python3.12/site-packages/triton/language/__pycache__/semantic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4222
+ tool_server/.venv/lib/python3.12/site-packages/triton/runtime/__pycache__/interpreter.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4223
+ tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4224
+ tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4225
+ tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4226
+ tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4227
+ tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4228
+ tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4229
+ tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4230
+ tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4231
+ tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4232
+ tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module containing private utility functions
3
+ ===========================================
4
+
5
+ The ``scipy._lib`` namespace is empty (for now). Tests for all
6
+ utilities in submodules of ``_lib`` can be run with::
7
+
8
+ from scipy import _lib
9
+ _lib.test()
10
+
11
+ """
12
+ from scipy._lib._testutils import PytestTester
13
+ test = PytestTester(__name__)
14
+ del PytestTester
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py ADDED
@@ -0,0 +1,931 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility functions to use Python Array API compatible libraries.
2
+
3
+ For the context about the Array API see:
4
+ https://data-apis.org/array-api/latest/purpose_and_scope.html
5
+
6
+ The SciPy use case of the Array API is described on the following page:
7
+ https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy
8
+ """
9
+ import contextlib
10
+ import dataclasses
11
+ import functools
12
+ import os
13
+ import textwrap
14
+
15
+ from collections.abc import Generator, Iterable, Iterator
16
+ from contextlib import contextmanager
17
+ from contextvars import ContextVar
18
+ from types import ModuleType
19
+ from typing import Any, Literal, TypeAlias
20
+
21
+ import numpy as np
22
+ import numpy.typing as npt
23
+
24
+ from scipy._lib import array_api_compat
25
+ from scipy._lib.array_api_compat import (
26
+ is_array_api_obj,
27
+ is_lazy_array,
28
+ size as xp_size,
29
+ numpy as np_compat,
30
+ device as xp_device,
31
+ is_numpy_namespace as is_numpy,
32
+ is_cupy_namespace as is_cupy,
33
+ is_torch_namespace as is_torch,
34
+ is_jax_namespace as is_jax,
35
+ is_dask_namespace as is_dask,
36
+ is_array_api_strict_namespace as is_array_api_strict
37
+ )
38
+ from scipy._lib._sparse import issparse
39
+ from scipy._lib._docscrape import FunctionDoc
40
+
41
+ __all__ = [
42
+ '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal',
43
+ 'default_xp', 'eager_warns', 'is_lazy_array', 'is_marray',
44
+ 'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch',
45
+ 'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for',
46
+ 'xp_assert_close', 'xp_assert_equal', 'xp_assert_less',
47
+ 'xp_copy', 'xp_device', 'xp_ravel', 'xp_size',
48
+ 'xp_unsupported_param_msg', 'xp_vector_norm', 'xp_capabilities',
49
+ 'xp_result_type', 'xp_promote'
50
+ ]
51
+
52
+
53
+ # To enable array API and strict array-like input validation
54
+ SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False)
55
+ # To control the default device - for use in the test suite only
56
+ SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu")
57
+
58
+ _GLOBAL_CONFIG = {
59
+ "SCIPY_ARRAY_API": SCIPY_ARRAY_API,
60
+ "SCIPY_DEVICE": SCIPY_DEVICE,
61
+ }
62
+
63
+
64
+ Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589)
65
+ ArrayLike: TypeAlias = Array | npt.ArrayLike
66
+
67
+
68
+ def _compliance_scipy(arrays: Iterable[ArrayLike]) -> Iterator[Array]:
69
+ """Raise exceptions on known-bad subclasses. Discard 0-dimensional ArrayLikes
70
+ and convert 1+-dimensional ArrayLikes to numpy.
71
+
72
+ The following subclasses are not supported and raise and error:
73
+ - `numpy.ma.MaskedArray`
74
+ - `numpy.matrix`
75
+ - NumPy arrays which do not have a boolean or numerical dtype
76
+ - Any array-like which is neither array API compatible nor coercible by NumPy
77
+ - Any array-like which is coerced by NumPy to an unsupported dtype
78
+ """
79
+ for array in arrays:
80
+ if array is None:
81
+ continue
82
+
83
+ # this comes from `_util._asarray_validated`
84
+ if issparse(array):
85
+ msg = ('Sparse arrays/matrices are not supported by this function. '
86
+ 'Perhaps one of the `scipy.sparse.linalg` functions '
87
+ 'would work instead.')
88
+ raise ValueError(msg)
89
+
90
+ if isinstance(array, np.ma.MaskedArray):
91
+ raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.")
92
+
93
+ if isinstance(array, np.matrix):
94
+ raise TypeError("Inputs of type `numpy.matrix` are not supported.")
95
+
96
+ if isinstance(array, np.ndarray | np.generic):
97
+ dtype = array.dtype
98
+ if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)):
99
+ raise TypeError(f"An argument has dtype `{dtype!r}`; "
100
+ f"only boolean and numerical dtypes are supported.")
101
+
102
+ if is_array_api_obj(array):
103
+ yield array
104
+ else:
105
+ try:
106
+ array = np.asanyarray(array)
107
+ except TypeError:
108
+ raise TypeError("An argument is neither array API compatible nor "
109
+ "coercible by NumPy.")
110
+ dtype = array.dtype
111
+ if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)):
112
+ message = (
113
+ f"An argument was coerced to an unsupported dtype `{dtype!r}`; "
114
+ f"only boolean and numerical dtypes are supported."
115
+ )
116
+ raise TypeError(message)
117
+ # Ignore 0-dimensional arrays, coherently with array-api-compat.
118
+ # Raise if there are 1+-dimensional array-likes mixed with non-numpy
119
+ # Array API objects.
120
+ if array.ndim:
121
+ yield array
122
+
123
+
124
+ def _check_finite(array: Array, xp: ModuleType) -> None:
125
+ """Check for NaNs or Infs."""
126
+ if not xp.all(xp.isfinite(array)):
127
+ msg = "array must not contain infs or NaNs"
128
+ raise ValueError(msg)
129
+
130
+
131
+ def array_namespace(*arrays: Array) -> ModuleType:
132
+ """Get the array API compatible namespace for the arrays xs.
133
+
134
+ Parameters
135
+ ----------
136
+ *arrays : sequence of array_like
137
+ Arrays used to infer the common namespace.
138
+
139
+ Returns
140
+ -------
141
+ namespace : module
142
+ Common namespace.
143
+
144
+ Notes
145
+ -----
146
+ Thin wrapper around `array_api_compat.array_namespace`.
147
+
148
+ 1. Check for the global switch: SCIPY_ARRAY_API. This can also be accessed
149
+ dynamically through ``_GLOBAL_CONFIG['SCIPY_ARRAY_API']``.
150
+ 2. `_compliance_scipy` raise exceptions on known-bad subclasses. See
151
+ its definition for more details.
152
+
153
+ When the global switch is False, it defaults to the `numpy` namespace.
154
+ In that case, there is no compliance check. This is a convenience to
155
+ ease the adoption. Otherwise, arrays must comply with the new rules.
156
+ """
157
+ if not _GLOBAL_CONFIG["SCIPY_ARRAY_API"]:
158
+ # here we could wrap the namespace if needed
159
+ return np_compat
160
+
161
+ api_arrays = list(_compliance_scipy(arrays))
162
+ # In case of a mix of array API compliant arrays and scalars, return
163
+ # the array API namespace. If there are only ArrayLikes (e.g. lists),
164
+ # return NumPy (wrapped by array-api-compat).
165
+ if api_arrays:
166
+ return array_api_compat.array_namespace(*api_arrays)
167
+ return np_compat
168
+
169
+
170
+ def _asarray(
171
+ array: ArrayLike,
172
+ dtype: Any = None,
173
+ order: Literal['K', 'A', 'C', 'F'] | None = None,
174
+ copy: bool | None = None,
175
+ *,
176
+ xp: ModuleType | None = None,
177
+ check_finite: bool = False,
178
+ subok: bool = False,
179
+ ) -> Array:
180
+ """SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and
181
+ `subok`.
182
+
183
+ Memory layout parameter `order` is not exposed in the Array API standard.
184
+ `order` is only enforced if the input array implementation
185
+ is NumPy based, otherwise `order` is just silently ignored.
186
+
187
+ `check_finite` is also not a keyword in the array API standard; included
188
+ here for convenience rather than that having to be a separate function
189
+ call inside SciPy functions.
190
+
191
+ `subok` is included to allow this function to preserve the behaviour of
192
+ `np.asanyarray` for NumPy based inputs.
193
+ """
194
+ if xp is None:
195
+ xp = array_namespace(array)
196
+ if is_numpy(xp):
197
+ # Use NumPy API to support order
198
+ if copy is True:
199
+ array = np.array(array, order=order, dtype=dtype, subok=subok)
200
+ elif subok:
201
+ array = np.asanyarray(array, order=order, dtype=dtype)
202
+ else:
203
+ array = np.asarray(array, order=order, dtype=dtype)
204
+ else:
205
+ try:
206
+ array = xp.asarray(array, dtype=dtype, copy=copy)
207
+ except TypeError:
208
+ coerced_xp = array_namespace(xp.asarray(3))
209
+ array = coerced_xp.asarray(array, dtype=dtype, copy=copy)
210
+
211
+ if check_finite:
212
+ _check_finite(array, xp)
213
+
214
+ return array
215
+
216
+
217
+ def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array:
218
+ """
219
+ Copies an array.
220
+
221
+ Parameters
222
+ ----------
223
+ x : array
224
+
225
+ xp : array_namespace
226
+
227
+ Returns
228
+ -------
229
+ copy : array
230
+ Copied array
231
+
232
+ Notes
233
+ -----
234
+ This copy function does not offer all the semantics of `np.copy`, i.e. the
235
+ `subok` and `order` keywords are not used.
236
+ """
237
+ # Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg,
238
+ # so this uses our other helper `_asarray`.
239
+ if xp is None:
240
+ xp = array_namespace(x)
241
+
242
+ return _asarray(x, copy=True, xp=xp)
243
+
244
+
245
+ _default_xp_ctxvar: ContextVar[ModuleType] = ContextVar("_default_xp")
246
+
247
+ @contextmanager
248
+ def default_xp(xp: ModuleType) -> Generator[None, None, None]:
249
+ """In all ``xp_assert_*`` and ``assert_*`` function calls executed within this
250
+ context manager, test by default that the array namespace is
251
+ the provided across all arrays, unless one explicitly passes the ``xp=``
252
+ parameter or ``check_namespace=False``.
253
+
254
+ Without this context manager, the default value for `xp` is the namespace
255
+ for the desired array (the second parameter of the tests).
256
+ """
257
+ token = _default_xp_ctxvar.set(xp)
258
+ try:
259
+ yield
260
+ finally:
261
+ _default_xp_ctxvar.reset(token)
262
+
263
+
264
+ def eager_warns(x, warning_type, match=None):
265
+ """pytest.warns context manager, but only if x is not a lazy array."""
266
+ import pytest
267
+ # This attribute is interpreted by pytest-run-parallel, ensuring that tests that use
268
+ # `eager_warns` aren't run in parallel (since pytest.warns isn't thread-safe).
269
+ __thread_safe__ = False # noqa: F841
270
+ if is_lazy_array(x):
271
+ return contextlib.nullcontext()
272
+ return pytest.warns(warning_type, match=match)
273
+
274
+
275
+ def _strict_check(actual, desired, xp, *,
276
+ check_namespace=True, check_dtype=True, check_shape=True,
277
+ check_0d=True):
278
+ __tracebackhide__ = True # Hide traceback for py.test
279
+
280
+ if xp is None:
281
+ try:
282
+ xp = _default_xp_ctxvar.get()
283
+ except LookupError:
284
+ xp = array_namespace(desired)
285
+
286
+ if check_namespace:
287
+ _assert_matching_namespace(actual, desired, xp)
288
+
289
+ # only NumPy distinguishes between scalars and arrays; we do if check_0d=True.
290
+ # do this first so we can then cast to array (and thus use the array API) below.
291
+ if is_numpy(xp) and check_0d:
292
+ _msg = ("Array-ness does not match:\n Actual: "
293
+ f"{type(actual)}\n Desired: {type(desired)}")
294
+ assert ((xp.isscalar(actual) and xp.isscalar(desired))
295
+ or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg
296
+
297
+ actual = xp.asarray(actual)
298
+ desired = xp.asarray(desired)
299
+
300
+ if check_dtype:
301
+ _msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}"
302
+ assert actual.dtype == desired.dtype, _msg
303
+
304
+ if check_shape:
305
+ if is_dask(xp):
306
+ actual.compute_chunk_sizes()
307
+ desired.compute_chunk_sizes()
308
+ _msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}"
309
+ assert actual.shape == desired.shape, _msg
310
+
311
+ desired = xp.broadcast_to(desired, actual.shape)
312
+ return actual, desired, xp
313
+
314
+
315
+ def _assert_matching_namespace(actual, desired, xp):
316
+ __tracebackhide__ = True # Hide traceback for py.test
317
+
318
+ desired_arr_space = array_namespace(desired)
319
+ _msg = ("Namespace of desired array does not match expectations "
320
+ "set by the `default_xp` context manager or by the `xp`"
321
+ "pytest fixture.\n"
322
+ f"Desired array's space: {desired_arr_space.__name__}\n"
323
+ f"Expected namespace: {xp.__name__}")
324
+ assert desired_arr_space == xp, _msg
325
+
326
+ actual_arr_space = array_namespace(actual)
327
+ _msg = ("Namespace of actual and desired arrays do not match.\n"
328
+ f"Actual: {actual_arr_space.__name__}\n"
329
+ f"Desired: {xp.__name__}")
330
+ assert actual_arr_space == xp, _msg
331
+
332
+
333
+ def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True,
334
+ check_shape=True, check_0d=True, err_msg='', xp=None):
335
+ __tracebackhide__ = True # Hide traceback for py.test
336
+
337
+ actual, desired, xp = _strict_check(
338
+ actual, desired, xp, check_namespace=check_namespace,
339
+ check_dtype=check_dtype, check_shape=check_shape,
340
+ check_0d=check_0d
341
+ )
342
+
343
+ if is_cupy(xp):
344
+ return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg)
345
+ elif is_torch(xp):
346
+ # PyTorch recommends using `rtol=0, atol=0` like this
347
+ # to test for exact equality
348
+ err_msg = None if err_msg == '' else err_msg
349
+ return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True,
350
+ check_dtype=False, msg=err_msg)
351
+ # JAX uses `np.testing`
352
+ return np.testing.assert_array_equal(actual, desired, err_msg=err_msg)
353
+
354
+
355
+ def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True,
356
+ check_dtype=True, check_shape=True, check_0d=True,
357
+ err_msg='', xp=None):
358
+ __tracebackhide__ = True # Hide traceback for py.test
359
+
360
+ actual, desired, xp = _strict_check(
361
+ actual, desired, xp,
362
+ check_namespace=check_namespace, check_dtype=check_dtype,
363
+ check_shape=check_shape, check_0d=check_0d
364
+ )
365
+
366
+ floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating'))
367
+ if rtol is None and floating:
368
+ # multiplier of 4 is used as for `np.float64` this puts the default `rtol`
369
+ # roughly half way between sqrt(eps) and the default for
370
+ # `numpy.testing.assert_allclose`, 1e-7
371
+ rtol = xp.finfo(actual.dtype).eps**0.5 * 4
372
+ elif rtol is None:
373
+ rtol = 1e-7
374
+
375
+ if is_cupy(xp):
376
+ return xp.testing.assert_allclose(actual, desired, rtol=rtol,
377
+ atol=atol, err_msg=err_msg)
378
+ elif is_torch(xp):
379
+ err_msg = None if err_msg == '' else err_msg
380
+ return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol,
381
+ equal_nan=True, check_dtype=False, msg=err_msg)
382
+ # JAX uses `np.testing`
383
+ return np.testing.assert_allclose(actual, desired, rtol=rtol,
384
+ atol=atol, err_msg=err_msg)
385
+
386
+
387
+ def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True,
388
+ check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None):
389
+ __tracebackhide__ = True # Hide traceback for py.test
390
+
391
+ actual, desired, xp = _strict_check(
392
+ actual, desired, xp, check_namespace=check_namespace,
393
+ check_dtype=check_dtype, check_shape=check_shape,
394
+ check_0d=check_0d
395
+ )
396
+
397
+ if is_cupy(xp):
398
+ return xp.testing.assert_array_less(actual, desired,
399
+ err_msg=err_msg, verbose=verbose)
400
+ elif is_torch(xp):
401
+ if actual.device.type != 'cpu':
402
+ actual = actual.cpu()
403
+ if desired.device.type != 'cpu':
404
+ desired = desired.cpu()
405
+ # JAX uses `np.testing`
406
+ return np.testing.assert_array_less(actual, desired,
407
+ err_msg=err_msg, verbose=verbose)
408
+
409
+
410
+ def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
411
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
412
+ """
413
+ rtol, atol = 0, 1.5*10**(-decimal)
414
+ return xp_assert_close(actual, desired,
415
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
416
+ *args, **kwds)
417
+
418
+
419
+ def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
420
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
421
+ """
422
+ rtol, atol = 0, 1.5*10**(-decimal)
423
+ return xp_assert_close(actual, desired,
424
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
425
+ *args, **kwds)
426
+
427
+
428
+ def xp_unsupported_param_msg(param: Any) -> str:
429
+ return f'Providing {param!r} is only supported for numpy arrays.'
430
+
431
+
432
+ def is_complex(x: Array, xp: ModuleType) -> bool:
433
+ return xp.isdtype(x.dtype, 'complex floating')
434
+
435
+
436
+ def scipy_namespace_for(xp: ModuleType) -> ModuleType | None:
437
+ """Return the `scipy`-like namespace of a non-NumPy backend
438
+
439
+ That is, return the namespace corresponding with backend `xp` that contains
440
+ `scipy` sub-namespaces like `linalg` and `special`. If no such namespace
441
+ exists, return ``None``. Useful for dispatching.
442
+ """
443
+
444
+ if is_cupy(xp):
445
+ import cupyx # type: ignore[import-not-found,import-untyped]
446
+ return cupyx.scipy
447
+
448
+ if is_jax(xp):
449
+ import jax # type: ignore[import-not-found]
450
+ return jax.scipy
451
+
452
+ if is_torch(xp):
453
+ return xp
454
+
455
+ return None
456
+
457
+
458
+ # maybe use `scipy.linalg` if/when array API support is added
459
+ def xp_vector_norm(x: Array, /, *,
460
+ axis: int | tuple[int] | None = None,
461
+ keepdims: bool = False,
462
+ ord: int | float = 2,
463
+ xp: ModuleType | None = None) -> Array:
464
+ xp = array_namespace(x) if xp is None else xp
465
+
466
+ if SCIPY_ARRAY_API:
467
+ # check for optional `linalg` extension
468
+ if hasattr(xp, 'linalg'):
469
+ return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord)
470
+ else:
471
+ if ord != 2:
472
+ raise ValueError(
473
+ "only the Euclidean norm (`ord=2`) is currently supported in "
474
+ "`xp_vector_norm` for backends not implementing the `linalg` "
475
+ "extension."
476
+ )
477
+ # return (x @ x)**0.5
478
+ # or to get the right behavior with nd, complex arrays
479
+ return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5
480
+ else:
481
+ # to maintain backwards compatibility
482
+ return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims)
483
+
484
+
485
+ def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array:
486
+ # Equivalent of np.ravel written in terms of array API
487
+ # Even though it's one line, it comes up so often that it's worth having
488
+ # this function for readability
489
+ xp = array_namespace(x) if xp is None else xp
490
+ return xp.reshape(x, (-1,))
491
+
492
+
493
+ def xp_swapaxes(a, axis1, axis2, xp=None):
494
+ # Equivalent of np.swapaxes written in terms of array API
495
+ xp = array_namespace(a) if xp is None else xp
496
+ axes = list(range(a.ndim))
497
+ axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
498
+ a = xp.permute_dims(a, axes)
499
+ return a
500
+
501
+
502
+ # utility to find common dtype with option to force floating
503
+ def xp_result_type(*args, force_floating=False, xp):
504
+ """
505
+ Returns the dtype that results from applying type promotion rules
506
+ (see Array API Standard Type Promotion Rules) to the arguments. Augments
507
+ standard `result_type` in a few ways:
508
+
509
+ - There is a `force_floating` argument that ensures that the result type
510
+ is floating point, even when all args are integer.
511
+ - When a TypeError is raised (e.g. due to an unsupported promotion)
512
+ and `force_floating=True`, we define a custom rule: use the result type
513
+ of the default float and any other floats passed. See
514
+ https://github.com/scipy/scipy/pull/22695/files#r1997905891
515
+ for rationale.
516
+ - This function accepts array-like iterables, which are immediately converted
517
+ to the namespace's arrays before result type calculation. Consequently, the
518
+ result dtype may be different when an argument is `1.` vs `[1.]`.
519
+
520
+ Typically, this function will be called shortly after `array_namespace`
521
+ on a subset of the arguments passed to `array_namespace`.
522
+ """
523
+ args = [(_asarray(arg, subok=True, xp=xp) if np.iterable(arg) else arg)
524
+ for arg in args]
525
+ args_not_none = [arg for arg in args if arg is not None]
526
+ if force_floating:
527
+ args_not_none.append(1.0)
528
+
529
+ if is_numpy(xp) and xp.__version__ < '2.0':
530
+ # Follow NEP 50 promotion rules anyway
531
+ args_not_none = [arg.dtype if getattr(arg, 'size', 0) == 1 else arg
532
+ for arg in args_not_none]
533
+ return xp.result_type(*args_not_none)
534
+
535
+ try: # follow library's preferred promotion rules
536
+ return xp.result_type(*args_not_none)
537
+ except TypeError: # mixed type promotion isn't defined
538
+ if not force_floating:
539
+ raise
540
+ # use `result_type` of default floating point type and any floats present
541
+ # This can be revisited, but right now, the only backends that get here
542
+ # are array-api-strict (which is not for production use) and PyTorch
543
+ # (due to data-apis/array-api-compat#279).
544
+ float_args = []
545
+ for arg in args_not_none:
546
+ arg_array = xp.asarray(arg) if np.isscalar(arg) else arg
547
+ dtype = getattr(arg_array, 'dtype', arg)
548
+ if xp.isdtype(dtype, ('real floating', 'complex floating')):
549
+ float_args.append(arg)
550
+ return xp.result_type(*float_args, xp_default_dtype(xp))
551
+
552
+
553
+ def xp_promote(*args, broadcast=False, force_floating=False, xp):
554
+ """
555
+ Promotes elements of *args to result dtype, ignoring `None`s.
556
+ Includes options for forcing promotion to floating point and
557
+ broadcasting the arrays, again ignoring `None`s.
558
+ Type promotion rules follow `xp_result_type` instead of `xp.result_type`.
559
+
560
+ Typically, this function will be called shortly after `array_namespace`
561
+ on a subset of the arguments passed to `array_namespace`.
562
+
563
+ This function accepts array-like iterables, which are immediately converted
564
+ to the namespace's arrays before result type calculation. Consequently, the
565
+ result dtype may be different when an argument is `1.` vs `[1.]`.
566
+
567
+ See Also
568
+ --------
569
+ xp_result_type
570
+ """
571
+ args = [(_asarray(arg, subok=True, xp=xp) if np.iterable(arg) else arg)
572
+ for arg in args] # solely to prevent double conversion of iterable to array
573
+
574
+ dtype = xp_result_type(*args, force_floating=force_floating, xp=xp)
575
+
576
+ args = [(_asarray(arg, dtype=dtype, subok=True, xp=xp) if arg is not None else arg)
577
+ for arg in args]
578
+
579
+ if not broadcast:
580
+ return args[0] if len(args)==1 else tuple(args)
581
+
582
+ args_not_none = [arg for arg in args if arg is not None]
583
+
584
+ # determine result shape
585
+ shapes = {arg.shape for arg in args_not_none}
586
+ try:
587
+ shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1
588
+ else args_not_none[0].shape)
589
+ except ValueError as e:
590
+ message = "Array shapes are incompatible for broadcasting."
591
+ raise ValueError(message) from e
592
+
593
+ out = []
594
+ for arg in args:
595
+ if arg is None:
596
+ out.append(arg)
597
+ continue
598
+
599
+ # broadcast only if needed
600
+ # Even if two arguments need broadcasting, this is faster than
601
+ # `broadcast_arrays`, especially since we've already determined `shape`
602
+ if arg.shape != shape:
603
+ kwargs = {'subok': True} if is_numpy(xp) else {}
604
+ arg = xp.broadcast_to(arg, shape, **kwargs)
605
+
606
+ # This is much faster than xp.astype(arg, dtype, copy=False)
607
+ if arg.dtype != dtype:
608
+ arg = xp.astype(arg, dtype)
609
+
610
+ out.append(arg)
611
+
612
+ return out[0] if len(out)==1 else tuple(out)
613
+
614
+
615
+ def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array:
616
+ xp = array_namespace(arr) if xp is None else xp
617
+ arr_dtype = arr.dtype
618
+ # The standard float dtypes are float32 and float64.
619
+ # Convert float32 to complex64,
620
+ # and float64 (and non-standard real dtypes) to complex128
621
+ if xp.isdtype(arr_dtype, xp.float32):
622
+ arr = xp.astype(arr, xp.complex64)
623
+ elif xp.isdtype(arr_dtype, 'real floating'):
624
+ arr = xp.astype(arr, xp.complex128)
625
+
626
+ return arr
627
+
628
+
629
+ def xp_default_dtype(xp):
630
+ """Query the namespace-dependent default floating-point dtype.
631
+ """
632
+ if is_torch(xp):
633
+ # historically, we allow pytorch to keep its default of float32
634
+ return xp.get_default_dtype()
635
+ else:
636
+ # we default to float64
637
+ return xp.float64
638
+
639
+
640
+ def xp_result_device(*args):
641
+ """Return the device of an array in `args`, for the purpose of
642
+ input-output device propagation.
643
+ If there are multiple devices, return an arbitrary one.
644
+ If there are no arrays, return None (this typically happens only on NumPy).
645
+ """
646
+ for arg in args:
647
+ # Do not do a duck-type test for the .device attribute, as many backends today
648
+ # don't have it yet. See workarouunds in array_api_compat.device().
649
+ if is_array_api_obj(arg):
650
+ return xp_device(arg)
651
+ return None
652
+
653
+
654
+ def is_marray(xp):
655
+ """Returns True if `xp` is an MArray namespace; False otherwise."""
656
+ return "marray" in xp.__name__
657
+
658
+
659
+ @dataclasses.dataclass(repr=False)
660
+ class _XPSphinxCapability:
661
+ cpu: bool | None # None if not applicable
662
+ gpu: bool | None
663
+ warnings: list[str] = dataclasses.field(default_factory=list)
664
+
665
+ def _render(self, value):
666
+ if value is None:
667
+ return "n/a"
668
+ if not value:
669
+ return "⛔"
670
+ if self.warnings:
671
+ res = "⚠️ " + '; '.join(self.warnings)
672
+ assert len(res) <= 20, "Warnings too long"
673
+ return res
674
+ return "✅"
675
+
676
+ def __str__(self):
677
+ cpu = self._render(self.cpu)
678
+ gpu = self._render(self.gpu)
679
+ return f"{cpu:20} {gpu:20}"
680
+
681
+
682
+ def _make_sphinx_capabilities(
683
+ # lists of tuples [(module name, reason), ...]
684
+ skip_backends=(), xfail_backends=(),
685
+ # @pytest.mark.skip/xfail_xp_backends kwargs
686
+ cpu_only=False, np_only=False, exceptions=(),
687
+ # xpx.lazy_xp_backends kwargs
688
+ allow_dask_compute=False, jax_jit=True,
689
+ # list of tuples [(module name, reason), ...]
690
+ warnings = (),
691
+ # unused in documentation
692
+ reason=None,
693
+ ):
694
+ exceptions = set(exceptions)
695
+
696
+ # Default capabilities
697
+ capabilities = {
698
+ "numpy": _XPSphinxCapability(cpu=True, gpu=None),
699
+ "array_api_strict": _XPSphinxCapability(cpu=True, gpu=None),
700
+ "cupy": _XPSphinxCapability(cpu=None, gpu=True),
701
+ "torch": _XPSphinxCapability(cpu=True, gpu=True),
702
+ "jax.numpy": _XPSphinxCapability(cpu=True, gpu=True,
703
+ warnings=[] if jax_jit else ["no JIT"]),
704
+ # Note: Dask+CuPy is currently untested and unsupported
705
+ "dask.array": _XPSphinxCapability(cpu=True, gpu=None,
706
+ warnings=["computes graph"] if allow_dask_compute else []),
707
+ }
708
+
709
+ # documentation doesn't display the reason
710
+ for module, _ in list(skip_backends) + list(xfail_backends):
711
+ backend = capabilities[module]
712
+ if backend.cpu is not None:
713
+ backend.cpu = False
714
+ if backend.gpu is not None:
715
+ backend.gpu = False
716
+
717
+ for module, backend in capabilities.items():
718
+ if np_only and module not in exceptions | {"numpy"}:
719
+ if backend.cpu is not None:
720
+ backend.cpu = False
721
+ if backend.gpu is not None:
722
+ backend.gpu = False
723
+ elif cpu_only and module not in exceptions and backend.gpu is not None:
724
+ backend.gpu = False
725
+
726
+ for module, warning in warnings:
727
+ backend = capabilities[module]
728
+ backend.warnings.append(warning)
729
+
730
+ return capabilities
731
+
732
+
733
+ def _make_capabilities_note(fun_name, capabilities):
734
+ # Note: deliberately not documenting array-api-strict
735
+ note = f"""
736
+ `{fun_name}` has experimental support for Python Array API Standard compatible
737
+ backends in addition to NumPy. Please consider testing these features
738
+ by setting an environment variable ``SCIPY_ARRAY_API=1`` and providing
739
+ CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following
740
+ combinations of backend and device (or other capability) are supported.
741
+
742
+ ==================== ==================== ====================
743
+ Library CPU GPU
744
+ ==================== ==================== ====================
745
+ NumPy {capabilities['numpy'] }
746
+ CuPy {capabilities['cupy'] }
747
+ PyTorch {capabilities['torch'] }
748
+ JAX {capabilities['jax.numpy'] }
749
+ Dask {capabilities['dask.array'] }
750
+ ==================== ==================== ====================
751
+
752
+ See :ref:`dev-arrayapi` for more information.
753
+ """
754
+ return textwrap.dedent(note)
755
+
756
+
757
+ def xp_capabilities(
758
+ *,
759
+ # Alternative capabilities table.
760
+ # Used only for testing this decorator.
761
+ capabilities_table=None,
762
+ # Generate pytest.mark.skip/xfail_xp_backends.
763
+ # See documentation in conftest.py.
764
+ # lists of tuples [(module name, reason), ...]
765
+ skip_backends=(), xfail_backends=(),
766
+ cpu_only=False, np_only=False, reason=None, exceptions=(),
767
+ # lists of tuples [(module name, reason), ...]
768
+ warnings=(),
769
+ # xpx.testing.lazy_xp_function kwargs.
770
+ # Refer to array-api-extra documentation.
771
+ allow_dask_compute=False, jax_jit=True,
772
+ ):
773
+ """Decorator for a function that states its support among various
774
+ Array API compatible backends.
775
+
776
+ This decorator has two effects:
777
+ 1. It allows tagging tests with ``@make_xp_test_case`` or
778
+ ``make_xp_pytest_param`` (see below) to automatically generate
779
+ SKIP/XFAIL markers and perform additional backend-specific
780
+ testing, such as extra validation for Dask and JAX;
781
+ 2. It automatically adds a note to the function's docstring, containing
782
+ a table matching what has been tested.
783
+
784
+ See Also
785
+ --------
786
+ make_xp_test_case
787
+ make_xp_pytest_param
788
+ array_api_extra.testing.lazy_xp_function
789
+ """
790
+ capabilities_table = (xp_capabilities_table if capabilities_table is None
791
+ else capabilities_table)
792
+
793
+ capabilities = dict(
794
+ skip_backends=skip_backends,
795
+ xfail_backends=xfail_backends,
796
+ cpu_only=cpu_only,
797
+ np_only=np_only,
798
+ reason=reason,
799
+ exceptions=exceptions,
800
+ allow_dask_compute=allow_dask_compute,
801
+ jax_jit=jax_jit,
802
+ warnings=warnings,
803
+ )
804
+ sphinx_capabilities = _make_sphinx_capabilities(**capabilities)
805
+
806
+ def decorator(f):
807
+ # Don't use a wrapper, as in some cases @xp_capabilities is
808
+ # applied to a ufunc
809
+ capabilities_table[f] = capabilities
810
+ note = _make_capabilities_note(f.__name__, sphinx_capabilities)
811
+ doc = FunctionDoc(f)
812
+ doc['Notes'].append(note)
813
+ doc = str(doc).split("\n", 1)[1] # remove signature
814
+ try:
815
+ f.__doc__ = doc
816
+ except AttributeError:
817
+ # Can't update __doc__ on ufuncs if SciPy
818
+ # was compiled against NumPy < 2.2.
819
+ pass
820
+
821
+ return f
822
+ return decorator
823
+
824
+
825
+ def _make_xp_pytest_marks(*funcs, capabilities_table=None):
826
+ capabilities_table = (xp_capabilities_table if capabilities_table is None
827
+ else capabilities_table)
828
+ import pytest
829
+ from scipy._lib.array_api_extra.testing import lazy_xp_function
830
+
831
+ marks = []
832
+ for func in funcs:
833
+ capabilities = capabilities_table[func]
834
+ exceptions = capabilities['exceptions']
835
+ reason = capabilities['reason']
836
+
837
+ if capabilities['cpu_only']:
838
+ marks.append(pytest.mark.skip_xp_backends(
839
+ cpu_only=True, exceptions=exceptions, reason=reason))
840
+ if capabilities['np_only']:
841
+ marks.append(pytest.mark.skip_xp_backends(
842
+ np_only=True, exceptions=exceptions, reason=reason))
843
+
844
+ for mod_name, reason in capabilities['skip_backends']:
845
+ marks.append(pytest.mark.skip_xp_backends(mod_name, reason=reason))
846
+ for mod_name, reason in capabilities['xfail_backends']:
847
+ marks.append(pytest.mark.xfail_xp_backends(mod_name, reason=reason))
848
+
849
+ lazy_kwargs = {k: capabilities[k]
850
+ for k in ('allow_dask_compute', 'jax_jit')}
851
+ lazy_xp_function(func, **lazy_kwargs)
852
+
853
+ return marks
854
+
855
+
856
+ def make_xp_test_case(*funcs, capabilities_table=None):
857
+ capabilities_table = (xp_capabilities_table if capabilities_table is None
858
+ else capabilities_table)
859
+ """Generate pytest decorator for a test function that tests functionality
860
+ of one or more Array API compatible functions.
861
+
862
+ Read the parameters of the ``@xp_capabilities`` decorator applied to the
863
+ listed functions and:
864
+
865
+ - Generate the ``@pytest.mark.skip_xp_backends`` and
866
+ ``@pytest.mark.xfail_xp_backends`` decorators
867
+ for the decorated test function
868
+ - Tag the function with `xpx.testing.lazy_xp_function`
869
+
870
+ See Also
871
+ --------
872
+ xp_capabilities
873
+ make_xp_pytest_param
874
+ array_api_extra.testing.lazy_xp_function
875
+ """
876
+ marks = _make_xp_pytest_marks(*funcs, capabilities_table=capabilities_table)
877
+ return lambda func: functools.reduce(lambda f, g: g(f), marks, func)
878
+
879
+
880
+ def make_xp_pytest_param(func, *args, capabilities_table=None):
881
+ """Variant of ``make_xp_test_case`` that returns a pytest.param for a function,
882
+ with all necessary skip_xp_backends and xfail_xp_backends marks applied::
883
+
884
+ @pytest.mark.parametrize(
885
+ "func", [make_xp_pytest_param(f1), make_xp_pytest_param(f2)]
886
+ )
887
+ def test(func, xp):
888
+ ...
889
+
890
+ The above is equivalent to::
891
+
892
+ @pytest.mark.parametrize(
893
+ "func", [
894
+ pytest.param(f1, marks=[
895
+ pytest.mark.skip_xp_backends(...),
896
+ pytest.mark.xfail_xp_backends(...), ...]),
897
+ pytest.param(f2, marks=[
898
+ pytest.mark.skip_xp_backends(...),
899
+ pytest.mark.xfail_xp_backends(...), ...]),
900
+ )
901
+ def test(func, xp):
902
+ ...
903
+
904
+ Parameters
905
+ ----------
906
+ func : Callable
907
+ Function to be tested. It must be decorated with ``@xp_capabilities``.
908
+ *args : Any, optional
909
+ Extra pytest parameters for the use case, e.g.::
910
+
911
+ @pytest.mark.parametrize("func,verb", [
912
+ make_xp_pytest_param(f1, "hello"),
913
+ make_xp_pytest_param(f2, "world")])
914
+ def test(func, verb, xp):
915
+ # iterates on (func=f1, verb="hello")
916
+ # and (func=f2, verb="world")
917
+
918
+ See Also
919
+ --------
920
+ xp_capabilities
921
+ make_xp_test_case
922
+ array_api_extra.testing.lazy_xp_function
923
+ """
924
+ import pytest
925
+
926
+ marks = _make_xp_pytest_marks(func, capabilities_table=capabilities_table)
927
+ return pytest.param(func, *args, marks=marks, id=func.__name__)
928
+
929
+
930
+ # Is it OK to have a dictionary that is mutated (once upon import) in many places?
931
+ xp_capabilities_table = {} # type: ignore[var-annotated]
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_compat_vendor.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # DO NOT RENAME THIS FILE
2
+ # This is a hook for array_api_extra/src/array_api_extra/_lib/_compat.py
3
+ # to override functions of array_api_compat.
4
+
5
+ from .array_api_compat import * # noqa: F403
6
+ from ._array_api import array_namespace as scipy_array_namespace
7
+
8
+ # overrides array_api_compat.array_namespace inside array-api-extra
9
+ array_namespace = scipy_array_namespace # type: ignore[assignment]
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Extra testing functions that forbid 0d-input, see #21044
3
+
4
+ While the xp_assert_* functions generally aim to follow the conventions of the
5
+ underlying `xp` library, NumPy in particular is inconsistent in its handling
6
+ of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897.
7
+
8
+ For example, this means that the following operations (as of v2.0.1) currently
9
+ return scalars, even though a 0d-array would often be more appropriate:
10
+
11
+ import numpy as np
12
+ np.array(0) * 2 # scalar, not 0d array
13
+ - np.array(0) # scalar, not 0d-array
14
+ np.sin(np.array(0)) # scalar, not 0d array
15
+ np.mean([1, 2, 3]) # scalar, not 0d array
16
+
17
+ Libraries like CuPy tend to return a 0d-array in scenarios like those above,
18
+ and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality
19
+ of the inconsistencies present in NumPy, as well as 20+ years of code on top,
20
+ the `xp_assert_*` functions here enforce consistency in the only way that
21
+ doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type.
22
+
23
+ However, when scalars are not generally the expected NumPy return type,
24
+ it remains preferable to use the assert functions from
25
+ the `scipy._lib._array_api` module, which have less surprising behaviour.
26
+ """
27
+ from scipy._lib._array_api import array_namespace, is_numpy
28
+ from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base,
29
+ xp_assert_equal as xp_assert_equal_base,
30
+ xp_assert_less as xp_assert_less_base)
31
+
32
+ __all__: list[str] = []
33
+
34
+
35
+ def _check_scalar(actual, desired, *, xp=None, **kwargs):
36
+ __tracebackhide__ = True # Hide traceback for py.test
37
+
38
+ if xp is None:
39
+ xp = array_namespace(actual)
40
+
41
+ # necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape
42
+ desired = xp.asarray(desired)
43
+
44
+ # Only NumPy distinguishes between scalars and arrays;
45
+ # shape check in xp_assert_* is sufficient except for shape == ()
46
+ if not (is_numpy(xp) and desired.shape == ()):
47
+ return
48
+
49
+ _msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow "
50
+ "the convention of many NumPy functions, returning a scalar when a "
51
+ "0d-array would be correct. The specialized `xp_assert_*` functions "
52
+ "in the `scipy._lib._array_api_no_0d` module err on the side of "
53
+ "caution and do not accept 0d-arrays by default. If the correct "
54
+ "result may legitimately be a 0d-array, pass `check_0d=True`, "
55
+ "or use the `xp_assert_*` functions from `scipy._lib._array_api`.")
56
+ assert xp.isscalar(actual), _msg
57
+
58
+
59
+ def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs):
60
+ # in contrast to xp_assert_equal_base, this defaults to check_0d=False,
61
+ # but will do an extra check in that case, which forbids 0d-arrays for `actual`
62
+ __tracebackhide__ = True # Hide traceback for py.test
63
+
64
+ # array-ness (check_0d == True) is taken care of by the *_base functions
65
+ if not check_0d:
66
+ _check_scalar(actual, desired, **kwargs)
67
+ return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs)
68
+
69
+
70
+ def xp_assert_close(actual, desired, *, check_0d=False, **kwargs):
71
+ # as for xp_assert_equal
72
+ __tracebackhide__ = True
73
+
74
+ if not check_0d:
75
+ _check_scalar(actual, desired, **kwargs)
76
+ return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs)
77
+
78
+
79
+ def xp_assert_less(actual, desired, *, check_0d=False, **kwargs):
80
+ # as for xp_assert_equal
81
+ __tracebackhide__ = True
82
+
83
+ if not check_0d:
84
+ _check_scalar(actual, desired, **kwargs)
85
+ return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs)
86
+
87
+
88
+ def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
89
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
90
+ """
91
+ rtol, atol = 0, 1.5*10**(-decimal)
92
+ return xp_assert_close(actual, desired,
93
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
94
+ *args, **kwds)
95
+
96
+
97
+ def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
98
+ """Backwards compatible replacement. In new code, use xp_assert_close instead.
99
+ """
100
+ rtol, atol = 0, 1.5*10**(-decimal)
101
+ return xp_assert_close(actual, desired,
102
+ atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
103
+ *args, **kwds)
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys as _sys
2
+ from keyword import iskeyword as _iskeyword
3
+
4
+
5
+ def _validate_names(typename, field_names, extra_field_names):
6
+ """
7
+ Ensure that all the given names are valid Python identifiers that
8
+ do not start with '_'. Also check that there are no duplicates
9
+ among field_names + extra_field_names.
10
+ """
11
+ for name in [typename] + field_names + extra_field_names:
12
+ if not isinstance(name, str):
13
+ raise TypeError('typename and all field names must be strings')
14
+ if not name.isidentifier():
15
+ raise ValueError('typename and all field names must be valid '
16
+ f'identifiers: {name!r}')
17
+ if _iskeyword(name):
18
+ raise ValueError('typename and all field names cannot be a '
19
+ f'keyword: {name!r}')
20
+
21
+ seen = set()
22
+ for name in field_names + extra_field_names:
23
+ if name.startswith('_'):
24
+ raise ValueError('Field names cannot start with an underscore: '
25
+ f'{name!r}')
26
+ if name in seen:
27
+ raise ValueError(f'Duplicate field name: {name!r}')
28
+ seen.add(name)
29
+
30
+
31
+ # Note: This code is adapted from CPython:Lib/collections/__init__.py
32
+ def _make_tuple_bunch(typename, field_names, extra_field_names=None,
33
+ module=None):
34
+ """
35
+ Create a namedtuple-like class with additional attributes.
36
+
37
+ This function creates a subclass of tuple that acts like a namedtuple
38
+ and that has additional attributes.
39
+
40
+ The additional attributes are listed in `extra_field_names`. The
41
+ values assigned to these attributes are not part of the tuple.
42
+
43
+ The reason this function exists is to allow functions in SciPy
44
+ that currently return a tuple or a namedtuple to returned objects
45
+ that have additional attributes, while maintaining backwards
46
+ compatibility.
47
+
48
+ This should only be used to enhance *existing* functions in SciPy.
49
+ New functions are free to create objects as return values without
50
+ having to maintain backwards compatibility with an old tuple or
51
+ namedtuple return value.
52
+
53
+ Parameters
54
+ ----------
55
+ typename : str
56
+ The name of the type.
57
+ field_names : list of str
58
+ List of names of the values to be stored in the tuple. These names
59
+ will also be attributes of instances, so the values in the tuple
60
+ can be accessed by indexing or as attributes. At least one name
61
+ is required. See the Notes for additional restrictions.
62
+ extra_field_names : list of str, optional
63
+ List of names of values that will be stored as attributes of the
64
+ object. See the notes for additional restrictions.
65
+
66
+ Returns
67
+ -------
68
+ cls : type
69
+ The new class.
70
+
71
+ Notes
72
+ -----
73
+ There are restrictions on the names that may be used in `field_names`
74
+ and `extra_field_names`:
75
+
76
+ * The names must be unique--no duplicates allowed.
77
+ * The names must be valid Python identifiers, and must not begin with
78
+ an underscore.
79
+ * The names must not be Python keywords (e.g. 'def', 'and', etc., are
80
+ not allowed).
81
+
82
+ Examples
83
+ --------
84
+ >>> from scipy._lib._bunch import _make_tuple_bunch
85
+
86
+ Create a class that acts like a namedtuple with length 2 (with field
87
+ names `x` and `y`) that will also have the attributes `w` and `beta`:
88
+
89
+ >>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta'])
90
+
91
+ `Result` is the new class. We call it with keyword arguments to create
92
+ a new instance with given values.
93
+
94
+ >>> result1 = Result(x=1, y=2, w=99, beta=0.5)
95
+ >>> result1
96
+ Result(x=1, y=2, w=99, beta=0.5)
97
+
98
+ `result1` acts like a tuple of length 2:
99
+
100
+ >>> len(result1)
101
+ 2
102
+ >>> result1[:]
103
+ (1, 2)
104
+
105
+ The values assigned when the instance was created are available as
106
+ attributes:
107
+
108
+ >>> result1.y
109
+ 2
110
+ >>> result1.beta
111
+ 0.5
112
+ """
113
+ if len(field_names) == 0:
114
+ raise ValueError('field_names must contain at least one name')
115
+
116
+ if extra_field_names is None:
117
+ extra_field_names = []
118
+ _validate_names(typename, field_names, extra_field_names)
119
+
120
+ typename = _sys.intern(str(typename))
121
+ field_names = tuple(map(_sys.intern, field_names))
122
+ extra_field_names = tuple(map(_sys.intern, extra_field_names))
123
+
124
+ all_names = field_names + extra_field_names
125
+ arg_list = ', '.join(field_names)
126
+ full_list = ', '.join(all_names)
127
+ repr_fmt = ''.join(('(',
128
+ ', '.join(f'{name}=%({name})r' for name in all_names),
129
+ ')'))
130
+ tuple_new = tuple.__new__
131
+ _dict, _tuple, _zip = dict, tuple, zip
132
+
133
+ # Create all the named tuple methods to be added to the class namespace
134
+
135
+ s = f"""\
136
+ def __new__(_cls, {arg_list}, **extra_fields):
137
+ return _tuple_new(_cls, ({arg_list},))
138
+
139
+ def __init__(self, {arg_list}, **extra_fields):
140
+ for key in self._extra_fields:
141
+ if key not in extra_fields:
142
+ raise TypeError("missing keyword argument '%s'" % (key,))
143
+ for key, val in extra_fields.items():
144
+ if key not in self._extra_fields:
145
+ raise TypeError("unexpected keyword argument '%s'" % (key,))
146
+ self.__dict__[key] = val
147
+
148
+ def __setattr__(self, key, val):
149
+ if key in {repr(field_names)}:
150
+ raise AttributeError("can't set attribute %r of class %r"
151
+ % (key, self.__class__.__name__))
152
+ else:
153
+ self.__dict__[key] = val
154
+ """
155
+ del arg_list
156
+ namespace = {'_tuple_new': tuple_new,
157
+ '__builtins__': dict(TypeError=TypeError,
158
+ AttributeError=AttributeError),
159
+ '__name__': f'namedtuple_{typename}'}
160
+ exec(s, namespace)
161
+ __new__ = namespace['__new__']
162
+ __new__.__doc__ = f'Create new instance of {typename}({full_list})'
163
+ __init__ = namespace['__init__']
164
+ __init__.__doc__ = f'Instantiate instance of {typename}({full_list})'
165
+ __setattr__ = namespace['__setattr__']
166
+
167
+ def __repr__(self):
168
+ 'Return a nicely formatted representation string'
169
+ return self.__class__.__name__ + repr_fmt % self._asdict()
170
+
171
+ def _asdict(self):
172
+ 'Return a new dict which maps field names to their values.'
173
+ out = _dict(_zip(self._fields, self))
174
+ out.update(self.__dict__)
175
+ return out
176
+
177
+ def __getnewargs_ex__(self):
178
+ 'Return self as a plain tuple. Used by copy and pickle.'
179
+ return _tuple(self), self.__dict__
180
+
181
+ # Modify function metadata to help with introspection and debugging
182
+ for method in (__new__, __repr__, _asdict, __getnewargs_ex__):
183
+ method.__qualname__ = f'{typename}.{method.__name__}'
184
+
185
+ # Build-up the class namespace dictionary
186
+ # and use type() to build the result class
187
+ class_namespace = {
188
+ '__doc__': f'{typename}({full_list})',
189
+ '_fields': field_names,
190
+ '__new__': __new__,
191
+ '__init__': __init__,
192
+ '__repr__': __repr__,
193
+ '__setattr__': __setattr__,
194
+ '_asdict': _asdict,
195
+ '_extra_fields': extra_field_names,
196
+ '__getnewargs_ex__': __getnewargs_ex__,
197
+ # _field_defaults and _replace are added to get Polars to detect
198
+ # a bunch object as a namedtuple. See gh-22450
199
+ '_field_defaults': {},
200
+ '_replace': None,
201
+ }
202
+ for index, name in enumerate(field_names):
203
+
204
+ def _get(self, index=index):
205
+ return self[index]
206
+ class_namespace[name] = property(_get)
207
+ for name in extra_field_names:
208
+
209
+ def _get(self, name=name):
210
+ return self.__dict__[name]
211
+ class_namespace[name] = property(_get)
212
+
213
+ result = type(typename, (tuple,), class_namespace)
214
+
215
+ # For pickling to work, the __module__ variable needs to be set to the
216
+ # frame where the named tuple is created. Bypass this step in environments
217
+ # where sys._getframe is not defined (Jython for example) or sys._getframe
218
+ # is not defined for arguments greater than 0 (IronPython), or where the
219
+ # user has specified a particular module.
220
+ if module is None:
221
+ try:
222
+ module = _sys._getframe(1).f_globals.get('__name__', '__main__')
223
+ except (AttributeError, ValueError):
224
+ pass
225
+ if module is not None:
226
+ result.__module__ = module
227
+ __new__.__module__ = module
228
+
229
+ return result
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import _ccallback_c
2
+
3
+ import ctypes
4
+
5
+ PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0]
6
+
7
+ ffi = None
8
+
9
+ class CData:
10
+ pass
11
+
12
+ def _import_cffi():
13
+ global ffi, CData
14
+
15
+ if ffi is not None:
16
+ return
17
+
18
+ try:
19
+ import cffi
20
+ ffi = cffi.FFI()
21
+ CData = ffi.CData
22
+ except ImportError:
23
+ ffi = False
24
+
25
+
26
+ class LowLevelCallable(tuple):
27
+ """
28
+ Low-level callback function.
29
+
30
+ Some functions in SciPy take as arguments callback functions, which
31
+ can either be python callables or low-level compiled functions. Using
32
+ compiled callback functions can improve performance somewhat by
33
+ avoiding wrapping data in Python objects.
34
+
35
+ Such low-level functions in SciPy are wrapped in `LowLevelCallable`
36
+ objects, which can be constructed from function pointers obtained from
37
+ ctypes, cffi, Cython, or contained in Python `PyCapsule` objects.
38
+
39
+ .. seealso::
40
+
41
+ Functions accepting low-level callables:
42
+
43
+ `scipy.integrate.quad`, `scipy.ndimage.generic_filter`,
44
+ `scipy.ndimage.generic_filter1d`, `scipy.ndimage.geometric_transform`
45
+
46
+ Usage examples:
47
+
48
+ :ref:`ndimage-ccallbacks`, :ref:`quad-callbacks`
49
+
50
+ Parameters
51
+ ----------
52
+ function : {PyCapsule, ctypes function pointer, cffi function pointer}
53
+ Low-level callback function.
54
+ user_data : {PyCapsule, ctypes void pointer, cffi void pointer}
55
+ User data to pass on to the callback function.
56
+ signature : str, optional
57
+ Signature of the function. If omitted, determined from *function*,
58
+ if possible.
59
+
60
+ Attributes
61
+ ----------
62
+ function
63
+ Callback function given.
64
+ user_data
65
+ User data given.
66
+ signature
67
+ Signature of the function.
68
+
69
+ Methods
70
+ -------
71
+ from_cython
72
+ Class method for constructing callables from Cython C-exported
73
+ functions.
74
+
75
+ Notes
76
+ -----
77
+ The argument ``function`` can be one of:
78
+
79
+ - PyCapsule, whose name contains the C function signature
80
+ - ctypes function pointer
81
+ - cffi function pointer
82
+
83
+ The signature of the low-level callback must match one of those expected
84
+ by the routine it is passed to.
85
+
86
+ If constructing low-level functions from a PyCapsule, the name of the
87
+ capsule must be the corresponding signature, in the format::
88
+
89
+ return_type (arg1_type, arg2_type, ...)
90
+
91
+ For example::
92
+
93
+ "void (double)"
94
+ "double (double, int *, void *)"
95
+
96
+ The context of a PyCapsule passed in as ``function`` is used as ``user_data``,
97
+ if an explicit value for ``user_data`` was not given.
98
+
99
+ """
100
+
101
+ # Make the class immutable
102
+ __slots__ = ()
103
+
104
+ def __new__(cls, function, user_data=None, signature=None):
105
+ # We need to hold a reference to the function & user data,
106
+ # to prevent them going out of scope
107
+ item = cls._parse_callback(function, user_data, signature)
108
+ return tuple.__new__(cls, (item, function, user_data))
109
+
110
+ def __repr__(self):
111
+ return f"LowLevelCallable({self.function!r}, {self.user_data!r})"
112
+
113
+ @property
114
+ def function(self):
115
+ return tuple.__getitem__(self, 1)
116
+
117
+ @property
118
+ def user_data(self):
119
+ return tuple.__getitem__(self, 2)
120
+
121
+ @property
122
+ def signature(self):
123
+ return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0))
124
+
125
+ def __getitem__(self, idx):
126
+ raise ValueError()
127
+
128
+ @classmethod
129
+ def from_cython(cls, module, name, user_data=None, signature=None):
130
+ """
131
+ Create a low-level callback function from an exported Cython function.
132
+
133
+ Parameters
134
+ ----------
135
+ module : module
136
+ Cython module where the exported function resides
137
+ name : str
138
+ Name of the exported function
139
+ user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional
140
+ User data to pass on to the callback function.
141
+ signature : str, optional
142
+ Signature of the function. If omitted, determined from *function*.
143
+
144
+ """
145
+ try:
146
+ function = module.__pyx_capi__[name]
147
+ except AttributeError as e:
148
+ message = "Given module is not a Cython module with __pyx_capi__ attribute"
149
+ raise ValueError(message) from e
150
+ except KeyError as e:
151
+ message = f"No function {name!r} found in __pyx_capi__ of the module"
152
+ raise ValueError(message) from e
153
+ return cls(function, user_data, signature)
154
+
155
+ @classmethod
156
+ def _parse_callback(cls, obj, user_data=None, signature=None):
157
+ _import_cffi()
158
+
159
+ if isinstance(obj, LowLevelCallable):
160
+ func = tuple.__getitem__(obj, 0)
161
+ elif isinstance(obj, PyCFuncPtr):
162
+ func, signature = _get_ctypes_func(obj, signature)
163
+ elif isinstance(obj, CData):
164
+ func, signature = _get_cffi_func(obj, signature)
165
+ elif _ccallback_c.check_capsule(obj):
166
+ func = obj
167
+ else:
168
+ raise ValueError("Given input is not a callable or a "
169
+ "low-level callable (pycapsule/ctypes/cffi)")
170
+
171
+ if isinstance(user_data, ctypes.c_void_p):
172
+ context = _get_ctypes_data(user_data)
173
+ elif isinstance(user_data, CData):
174
+ context = _get_cffi_data(user_data)
175
+ elif user_data is None:
176
+ context = 0
177
+ elif _ccallback_c.check_capsule(user_data):
178
+ context = user_data
179
+ else:
180
+ raise ValueError("Given user data is not a valid "
181
+ "low-level void* pointer (pycapsule/ctypes/cffi)")
182
+
183
+ return _ccallback_c.get_raw_capsule(func, signature, context)
184
+
185
+
186
+ #
187
+ # ctypes helpers
188
+ #
189
+
190
+ def _get_ctypes_func(func, signature=None):
191
+ # Get function pointer
192
+ func_ptr = ctypes.cast(func, ctypes.c_void_p).value
193
+
194
+ # Construct function signature
195
+ if signature is None:
196
+ signature = _typename_from_ctypes(func.restype) + " ("
197
+ for j, arg in enumerate(func.argtypes):
198
+ if j == 0:
199
+ signature += _typename_from_ctypes(arg)
200
+ else:
201
+ signature += ", " + _typename_from_ctypes(arg)
202
+ signature += ")"
203
+
204
+ return func_ptr, signature
205
+
206
+
207
+ def _typename_from_ctypes(item):
208
+ if item is None:
209
+ return "void"
210
+ elif item is ctypes.c_void_p:
211
+ return "void *"
212
+
213
+ name = item.__name__
214
+
215
+ pointer_level = 0
216
+ while name.startswith("LP_"):
217
+ pointer_level += 1
218
+ name = name[3:]
219
+
220
+ if name.startswith('c_'):
221
+ name = name[2:]
222
+
223
+ if pointer_level > 0:
224
+ name += " " + "*"*pointer_level
225
+
226
+ return name
227
+
228
+
229
+ def _get_ctypes_data(data):
230
+ # Get voidp pointer
231
+ return ctypes.cast(data, ctypes.c_void_p).value
232
+
233
+
234
+ #
235
+ # CFFI helpers
236
+ #
237
+
238
+ def _get_cffi_func(func, signature=None):
239
+ # Get function pointer
240
+ func_ptr = ffi.cast('uintptr_t', func)
241
+
242
+ # Get signature
243
+ if signature is None:
244
+ signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ')
245
+
246
+ return func_ptr, signature
247
+
248
+
249
+ def _get_cffi_data(data):
250
+ # Get pointer
251
+ return ffi.cast('uintptr_t', data)
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (99.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Disjoint set data structure
3
+ """
4
+
5
+
6
+ class DisjointSet:
7
+ """ Disjoint set data structure for incremental connectivity queries.
8
+
9
+ .. versionadded:: 1.6.0
10
+
11
+ Attributes
12
+ ----------
13
+ n_subsets : int
14
+ The number of subsets.
15
+
16
+ Methods
17
+ -------
18
+ add
19
+ merge
20
+ connected
21
+ subset
22
+ subset_size
23
+ subsets
24
+ __getitem__
25
+
26
+ Notes
27
+ -----
28
+ This class implements the disjoint set [1]_, also known as the *union-find*
29
+ or *merge-find* data structure. The *find* operation (implemented in
30
+ `__getitem__`) implements the *path halving* variant. The *merge* method
31
+ implements the *merge by size* variant.
32
+
33
+ References
34
+ ----------
35
+ .. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure
36
+
37
+ Examples
38
+ --------
39
+ >>> from scipy.cluster.hierarchy import DisjointSet
40
+
41
+ Initialize a disjoint set:
42
+
43
+ >>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b'])
44
+
45
+ Merge some subsets:
46
+
47
+ >>> disjoint_set.merge(1, 2)
48
+ True
49
+ >>> disjoint_set.merge(3, 'a')
50
+ True
51
+ >>> disjoint_set.merge('a', 'b')
52
+ True
53
+ >>> disjoint_set.merge('b', 'b')
54
+ False
55
+
56
+ Find root elements:
57
+
58
+ >>> disjoint_set[2]
59
+ 1
60
+ >>> disjoint_set['b']
61
+ 3
62
+
63
+ Test connectivity:
64
+
65
+ >>> disjoint_set.connected(1, 2)
66
+ True
67
+ >>> disjoint_set.connected(1, 'b')
68
+ False
69
+
70
+ List elements in disjoint set:
71
+
72
+ >>> list(disjoint_set)
73
+ [1, 2, 3, 'a', 'b']
74
+
75
+ Get the subset containing 'a':
76
+
77
+ >>> disjoint_set.subset('a')
78
+ {'a', 3, 'b'}
79
+
80
+ Get the size of the subset containing 'a' (without actually instantiating
81
+ the subset):
82
+
83
+ >>> disjoint_set.subset_size('a')
84
+ 3
85
+
86
+ Get all subsets in the disjoint set:
87
+
88
+ >>> disjoint_set.subsets()
89
+ [{1, 2}, {'a', 3, 'b'}]
90
+ """
91
+ def __init__(self, elements=None):
92
+ self.n_subsets = 0
93
+ self._sizes = {}
94
+ self._parents = {}
95
+ # _nbrs is a circular linked list which links connected elements.
96
+ self._nbrs = {}
97
+ # _indices tracks the element insertion order in `__iter__`.
98
+ self._indices = {}
99
+ if elements is not None:
100
+ for x in elements:
101
+ self.add(x)
102
+
103
+ def __iter__(self):
104
+ """Returns an iterator of the elements in the disjoint set.
105
+
106
+ Elements are ordered by insertion order.
107
+ """
108
+ return iter(self._indices)
109
+
110
+ def __len__(self):
111
+ return len(self._indices)
112
+
113
+ def __contains__(self, x):
114
+ return x in self._indices
115
+
116
+ def __getitem__(self, x):
117
+ """Find the root element of `x`.
118
+
119
+ Parameters
120
+ ----------
121
+ x : hashable object
122
+ Input element.
123
+
124
+ Returns
125
+ -------
126
+ root : hashable object
127
+ Root element of `x`.
128
+ """
129
+ if x not in self._indices:
130
+ raise KeyError(x)
131
+
132
+ # find by "path halving"
133
+ parents = self._parents
134
+ while self._indices[x] != self._indices[parents[x]]:
135
+ parents[x] = parents[parents[x]]
136
+ x = parents[x]
137
+ return x
138
+
139
+ def add(self, x):
140
+ """Add element `x` to disjoint set
141
+ """
142
+ if x in self._indices:
143
+ return
144
+
145
+ self._sizes[x] = 1
146
+ self._parents[x] = x
147
+ self._nbrs[x] = x
148
+ self._indices[x] = len(self._indices)
149
+ self.n_subsets += 1
150
+
151
+ def merge(self, x, y):
152
+ """Merge the subsets of `x` and `y`.
153
+
154
+ The smaller subset (the child) is merged into the larger subset (the
155
+ parent). If the subsets are of equal size, the root element which was
156
+ first inserted into the disjoint set is selected as the parent.
157
+
158
+ Parameters
159
+ ----------
160
+ x, y : hashable object
161
+ Elements to merge.
162
+
163
+ Returns
164
+ -------
165
+ merged : bool
166
+ True if `x` and `y` were in disjoint sets, False otherwise.
167
+ """
168
+ xr = self[x]
169
+ yr = self[y]
170
+ if self._indices[xr] == self._indices[yr]:
171
+ return False
172
+
173
+ sizes = self._sizes
174
+ if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]):
175
+ xr, yr = yr, xr
176
+ self._parents[yr] = xr
177
+ self._sizes[xr] += self._sizes[yr]
178
+ self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr]
179
+ self.n_subsets -= 1
180
+ return True
181
+
182
+ def connected(self, x, y):
183
+ """Test whether `x` and `y` are in the same subset.
184
+
185
+ Parameters
186
+ ----------
187
+ x, y : hashable object
188
+ Elements to test.
189
+
190
+ Returns
191
+ -------
192
+ result : bool
193
+ True if `x` and `y` are in the same set, False otherwise.
194
+ """
195
+ return self._indices[self[x]] == self._indices[self[y]]
196
+
197
+ def subset(self, x):
198
+ """Get the subset containing `x`.
199
+
200
+ Parameters
201
+ ----------
202
+ x : hashable object
203
+ Input element.
204
+
205
+ Returns
206
+ -------
207
+ result : set
208
+ Subset containing `x`.
209
+ """
210
+ if x not in self._indices:
211
+ raise KeyError(x)
212
+
213
+ result = [x]
214
+ nxt = self._nbrs[x]
215
+ while self._indices[nxt] != self._indices[x]:
216
+ result.append(nxt)
217
+ nxt = self._nbrs[nxt]
218
+ return set(result)
219
+
220
+ def subset_size(self, x):
221
+ """Get the size of the subset containing `x`.
222
+
223
+ Note that this method is faster than ``len(self.subset(x))`` because
224
+ the size is directly read off an internal field, without the need to
225
+ instantiate the full subset.
226
+
227
+ Parameters
228
+ ----------
229
+ x : hashable object
230
+ Input element.
231
+
232
+ Returns
233
+ -------
234
+ result : int
235
+ Size of the subset containing `x`.
236
+ """
237
+ return self._sizes[self[x]]
238
+
239
+ def subsets(self):
240
+ """Get all the subsets in the disjoint set.
241
+
242
+ Returns
243
+ -------
244
+ result : list
245
+ Subsets in the disjoint set.
246
+ """
247
+ result = []
248
+ visited = set()
249
+ for x in self:
250
+ if x not in visited:
251
+ xset = self.subset(x)
252
+ visited.update(xset)
253
+ result.append(xset)
254
+ return result
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2
2
+ """Extract reference documentation from the NumPy source tree."""
3
+
4
+ import copy
5
+ import inspect
6
+ import pydoc
7
+ import re
8
+ import sys
9
+ import textwrap
10
+ from collections import namedtuple
11
+ from collections.abc import Callable, Mapping
12
+ from functools import cached_property
13
+ from warnings import warn
14
+
15
+
16
+ def strip_blank_lines(l):
17
+ "Remove leading and trailing blank lines from a list of lines"
18
+ while l and not l[0].strip():
19
+ del l[0]
20
+ while l and not l[-1].strip():
21
+ del l[-1]
22
+ return l
23
+
24
+
25
+ class Reader:
26
+ """A line-based string reader."""
27
+
28
+ def __init__(self, data):
29
+ """
30
+ Parameters
31
+ ----------
32
+ data : str
33
+ String with lines separated by '\\n'.
34
+
35
+ """
36
+ if isinstance(data, list):
37
+ self._str = data
38
+ else:
39
+ self._str = data.split("\n") # store string as list of lines
40
+
41
+ self.reset()
42
+
43
+ def __getitem__(self, n):
44
+ return self._str[n]
45
+
46
+ def reset(self):
47
+ self._l = 0 # current line nr
48
+
49
+ def read(self):
50
+ if not self.eof():
51
+ out = self[self._l]
52
+ self._l += 1
53
+ return out
54
+ else:
55
+ return ""
56
+
57
+ def seek_next_non_empty_line(self):
58
+ for l in self[self._l :]:
59
+ if l.strip():
60
+ break
61
+ else:
62
+ self._l += 1
63
+
64
+ def eof(self):
65
+ return self._l >= len(self._str)
66
+
67
+ def read_to_condition(self, condition_func):
68
+ start = self._l
69
+ for line in self[start:]:
70
+ if condition_func(line):
71
+ return self[start : self._l]
72
+ self._l += 1
73
+ if self.eof():
74
+ return self[start : self._l + 1]
75
+ return []
76
+
77
+ def read_to_next_empty_line(self):
78
+ self.seek_next_non_empty_line()
79
+
80
+ def is_empty(line):
81
+ return not line.strip()
82
+
83
+ return self.read_to_condition(is_empty)
84
+
85
+ def read_to_next_unindented_line(self):
86
+ def is_unindented(line):
87
+ return line.strip() and (len(line.lstrip()) == len(line))
88
+
89
+ return self.read_to_condition(is_unindented)
90
+
91
+ def peek(self, n=0):
92
+ if self._l + n < len(self._str):
93
+ return self[self._l + n]
94
+ else:
95
+ return ""
96
+
97
+ def is_empty(self):
98
+ return not "".join(self._str).strip()
99
+
100
+
101
+ class ParseError(Exception):
102
+ def __str__(self):
103
+ message = self.args[0]
104
+ if hasattr(self, "docstring"):
105
+ message = f"{message} in {self.docstring!r}"
106
+ return message
107
+
108
+
109
+ Parameter = namedtuple("Parameter", ["name", "type", "desc"])
110
+
111
+
112
+ class NumpyDocString(Mapping):
113
+ """Parses a numpydoc string to an abstract representation
114
+
115
+ Instances define a mapping from section title to structured data.
116
+
117
+ """
118
+
119
+ sections = {
120
+ "Signature": "",
121
+ "Summary": [""],
122
+ "Extended Summary": [],
123
+ "Parameters": [],
124
+ "Attributes": [],
125
+ "Methods": [],
126
+ "Returns": [],
127
+ "Yields": [],
128
+ "Receives": [],
129
+ "Other Parameters": [],
130
+ "Raises": [],
131
+ "Warns": [],
132
+ "Warnings": [],
133
+ "See Also": [],
134
+ "Notes": [],
135
+ "References": "",
136
+ "Examples": "",
137
+ "index": {},
138
+ }
139
+
140
+ def __init__(self, docstring, config=None):
141
+ orig_docstring = docstring
142
+ docstring = textwrap.dedent(docstring).split("\n")
143
+
144
+ self._doc = Reader(docstring)
145
+ self._parsed_data = copy.deepcopy(self.sections)
146
+
147
+ try:
148
+ self._parse()
149
+ except ParseError as e:
150
+ e.docstring = orig_docstring
151
+ raise
152
+
153
+ def __getitem__(self, key):
154
+ return self._parsed_data[key]
155
+
156
+ def __setitem__(self, key, val):
157
+ if key not in self._parsed_data:
158
+ self._error_location(f"Unknown section {key}", error=False)
159
+ else:
160
+ self._parsed_data[key] = val
161
+
162
+ def __iter__(self):
163
+ return iter(self._parsed_data)
164
+
165
+ def __len__(self):
166
+ return len(self._parsed_data)
167
+
168
+ def _is_at_section(self):
169
+ self._doc.seek_next_non_empty_line()
170
+
171
+ if self._doc.eof():
172
+ return False
173
+
174
+ l1 = self._doc.peek().strip() # e.g. Parameters
175
+
176
+ if l1.startswith(".. index::"):
177
+ return True
178
+
179
+ l2 = self._doc.peek(1).strip() # ---------- or ==========
180
+ if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1):
181
+ snip = "\n".join(self._doc._str[:2]) + "..."
182
+ self._error_location(
183
+ f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}",
184
+ error=False,
185
+ )
186
+ return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1))
187
+
188
+ def _strip(self, doc):
189
+ i = 0
190
+ j = 0
191
+ for i, line in enumerate(doc):
192
+ if line.strip():
193
+ break
194
+
195
+ for j, line in enumerate(doc[::-1]):
196
+ if line.strip():
197
+ break
198
+
199
+ return doc[i : len(doc) - j]
200
+
201
+ def _read_to_next_section(self):
202
+ section = self._doc.read_to_next_empty_line()
203
+
204
+ while not self._is_at_section() and not self._doc.eof():
205
+ if not self._doc.peek(-1).strip(): # previous line was empty
206
+ section += [""]
207
+
208
+ section += self._doc.read_to_next_empty_line()
209
+
210
+ return section
211
+
212
+ def _read_sections(self):
213
+ while not self._doc.eof():
214
+ data = self._read_to_next_section()
215
+ name = data[0].strip()
216
+
217
+ if name.startswith(".."): # index section
218
+ yield name, data[1:]
219
+ elif len(data) < 2:
220
+ yield StopIteration
221
+ else:
222
+ yield name, self._strip(data[2:])
223
+
224
+ def _parse_param_list(self, content, single_element_is_type=False):
225
+ content = dedent_lines(content)
226
+ r = Reader(content)
227
+ params = []
228
+ while not r.eof():
229
+ header = r.read().strip()
230
+ if " : " in header:
231
+ arg_name, arg_type = header.split(" : ", maxsplit=1)
232
+ else:
233
+ # NOTE: param line with single element should never have a
234
+ # a " :" before the description line, so this should probably
235
+ # warn.
236
+ if header.endswith(" :"):
237
+ header = header[:-2]
238
+ if single_element_is_type:
239
+ arg_name, arg_type = "", header
240
+ else:
241
+ arg_name, arg_type = header, ""
242
+
243
+ desc = r.read_to_next_unindented_line()
244
+ desc = dedent_lines(desc)
245
+ desc = strip_blank_lines(desc)
246
+
247
+ params.append(Parameter(arg_name, arg_type, desc))
248
+
249
+ return params
250
+
251
+ # See also supports the following formats.
252
+ #
253
+ # <FUNCNAME>
254
+ # <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE*
255
+ # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE*
256
+ # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE*
257
+
258
+ # <FUNCNAME> is one of
259
+ # <PLAIN_FUNCNAME>
260
+ # COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK
261
+ # where
262
+ # <PLAIN_FUNCNAME> is a legal function name, and
263
+ # <ROLE> is any nonempty sequence of word characters.
264
+ # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`
265
+ # <DESC> is a string describing the function.
266
+
267
+ _role = r":(?P<role>(py:)?\w+):"
268
+ _funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`"
269
+ _funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)"
270
+ _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")"
271
+ _funcnamenext = _funcname.replace("role", "rolenext")
272
+ _funcnamenext = _funcnamenext.replace("name", "namenext")
273
+ _description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$"
274
+ _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*")
275
+ _line_rgx = re.compile(
276
+ r"^\s*"
277
+ + r"(?P<allfuncs>"
278
+ + _funcname # group for all function names
279
+ + r"(?P<morefuncs>([,]\s+"
280
+ + _funcnamenext
281
+ + r")*)"
282
+ + r")"
283
+ + r"(?P<trailing>[,\.])?" # end of "allfuncs"
284
+ + _description # Some function lists have a trailing comma (or period) '\s*'
285
+ )
286
+
287
+ # Empty <DESC> elements are replaced with '..'
288
+ empty_description = ".."
289
+
290
+ def _parse_see_also(self, content):
291
+ """
292
+ func_name : Descriptive text
293
+ continued text
294
+ another_func_name : Descriptive text
295
+ func_name1, func_name2, :meth:`func_name`, func_name3
296
+
297
+ """
298
+
299
+ content = dedent_lines(content)
300
+
301
+ items = []
302
+
303
+ def parse_item_name(text):
304
+ """Match ':role:`name`' or 'name'."""
305
+ m = self._func_rgx.match(text)
306
+ if not m:
307
+ self._error_location(f"Error parsing See Also entry {line!r}")
308
+ role = m.group("role")
309
+ name = m.group("name") if role else m.group("name2")
310
+ return name, role, m.end()
311
+
312
+ rest = []
313
+ for line in content:
314
+ if not line.strip():
315
+ continue
316
+
317
+ line_match = self._line_rgx.match(line)
318
+ description = None
319
+ if line_match:
320
+ description = line_match.group("desc")
321
+ if line_match.group("trailing") and description:
322
+ self._error_location(
323
+ "Unexpected comma or period after function list at index %d of "
324
+ 'line "%s"' % (line_match.end("trailing"), line),
325
+ error=False,
326
+ )
327
+ if not description and line.startswith(" "):
328
+ rest.append(line.strip())
329
+ elif line_match:
330
+ funcs = []
331
+ text = line_match.group("allfuncs")
332
+ while True:
333
+ if not text.strip():
334
+ break
335
+ name, role, match_end = parse_item_name(text)
336
+ funcs.append((name, role))
337
+ text = text[match_end:].strip()
338
+ if text and text[0] == ",":
339
+ text = text[1:].strip()
340
+ rest = list(filter(None, [description]))
341
+ items.append((funcs, rest))
342
+ else:
343
+ self._error_location(f"Error parsing See Also entry {line!r}")
344
+ return items
345
+
346
+ def _parse_index(self, section, content):
347
+ """
348
+ .. index:: default
349
+ :refguide: something, else, and more
350
+
351
+ """
352
+
353
+ def strip_each_in(lst):
354
+ return [s.strip() for s in lst]
355
+
356
+ out = {}
357
+ section = section.split("::")
358
+ if len(section) > 1:
359
+ out["default"] = strip_each_in(section[1].split(","))[0]
360
+ for line in content:
361
+ line = line.split(":")
362
+ if len(line) > 2:
363
+ out[line[1]] = strip_each_in(line[2].split(","))
364
+ return out
365
+
366
+ def _parse_summary(self):
367
+ """Grab signature (if given) and summary"""
368
+ if self._is_at_section():
369
+ return
370
+
371
+ # If several signatures present, take the last one
372
+ while True:
373
+ summary = self._doc.read_to_next_empty_line()
374
+ summary_str = " ".join([s.strip() for s in summary]).strip()
375
+ compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$")
376
+ if compiled.match(summary_str):
377
+ self["Signature"] = summary_str
378
+ if not self._is_at_section():
379
+ continue
380
+ break
381
+
382
+ if summary is not None:
383
+ self["Summary"] = summary
384
+
385
+ if not self._is_at_section():
386
+ self["Extended Summary"] = self._read_to_next_section()
387
+
388
+ def _parse(self):
389
+ self._doc.reset()
390
+ self._parse_summary()
391
+
392
+ sections = list(self._read_sections())
393
+ section_names = {section for section, content in sections}
394
+
395
+ has_yields = "Yields" in section_names
396
+ # We could do more tests, but we are not. Arbitrarily.
397
+ if not has_yields and "Receives" in section_names:
398
+ msg = "Docstring contains a Receives section but not Yields."
399
+ raise ValueError(msg)
400
+
401
+ for section, content in sections:
402
+ if not section.startswith(".."):
403
+ section = (s.capitalize() for s in section.split(" "))
404
+ section = " ".join(section)
405
+ if self.get(section):
406
+ self._error_location(
407
+ "The section %s appears twice in %s"
408
+ % (section, "\n".join(self._doc._str))
409
+ )
410
+
411
+ if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):
412
+ self[section] = self._parse_param_list(content)
413
+ elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"):
414
+ self[section] = self._parse_param_list(
415
+ content, single_element_is_type=True
416
+ )
417
+ elif section.startswith(".. index::"):
418
+ self["index"] = self._parse_index(section, content)
419
+ elif section == "See Also":
420
+ self["See Also"] = self._parse_see_also(content)
421
+ else:
422
+ self[section] = content
423
+
424
+ @property
425
+ def _obj(self):
426
+ if hasattr(self, "_cls"):
427
+ return self._cls
428
+ elif hasattr(self, "_f"):
429
+ return self._f
430
+ return None
431
+
432
+ def _error_location(self, msg, error=True):
433
+ if self._obj is not None:
434
+ # we know where the docs came from:
435
+ try:
436
+ filename = inspect.getsourcefile(self._obj)
437
+ except TypeError:
438
+ filename = None
439
+ # Make UserWarning more descriptive via object introspection.
440
+ # Skip if introspection fails
441
+ name = getattr(self._obj, "__name__", None)
442
+ if name is None:
443
+ name = getattr(getattr(self._obj, "__class__", None), "__name__", None)
444
+ if name is not None:
445
+ msg += f" in the docstring of {name}"
446
+ msg += f" in {filename}." if filename else ""
447
+ if error:
448
+ raise ValueError(msg)
449
+ else:
450
+ warn(msg, stacklevel=3)
451
+
452
+ # string conversion routines
453
+
454
+ def _str_header(self, name, symbol="-"):
455
+ return [name, len(name) * symbol]
456
+
457
+ def _str_indent(self, doc, indent=4):
458
+ return [" " * indent + line for line in doc]
459
+
460
+ def _str_signature(self):
461
+ if self["Signature"]:
462
+ return [self["Signature"].replace("*", r"\*")] + [""]
463
+ return [""]
464
+
465
+ def _str_summary(self):
466
+ if self["Summary"]:
467
+ return self["Summary"] + [""]
468
+ return []
469
+
470
+ def _str_extended_summary(self):
471
+ if self["Extended Summary"]:
472
+ return self["Extended Summary"] + [""]
473
+ return []
474
+
475
+ def _str_param_list(self, name):
476
+ out = []
477
+ if self[name]:
478
+ out += self._str_header(name)
479
+ for param in self[name]:
480
+ parts = []
481
+ if param.name:
482
+ parts.append(param.name)
483
+ if param.type:
484
+ parts.append(param.type)
485
+ out += [" : ".join(parts)]
486
+ if param.desc and "".join(param.desc).strip():
487
+ out += self._str_indent(param.desc)
488
+ out += [""]
489
+ return out
490
+
491
+ def _str_section(self, name):
492
+ out = []
493
+ if self[name]:
494
+ out += self._str_header(name)
495
+ out += self[name]
496
+ out += [""]
497
+ return out
498
+
499
+ def _str_see_also(self, func_role):
500
+ if not self["See Also"]:
501
+ return []
502
+ out = []
503
+ out += self._str_header("See Also")
504
+ out += [""]
505
+ last_had_desc = True
506
+ for funcs, desc in self["See Also"]:
507
+ assert isinstance(funcs, list)
508
+ links = []
509
+ for func, role in funcs:
510
+ if role:
511
+ link = f":{role}:`{func}`"
512
+ elif func_role:
513
+ link = f":{func_role}:`{func}`"
514
+ else:
515
+ link = f"`{func}`_"
516
+ links.append(link)
517
+ link = ", ".join(links)
518
+ out += [link]
519
+ if desc:
520
+ out += self._str_indent([" ".join(desc)])
521
+ last_had_desc = True
522
+ else:
523
+ last_had_desc = False
524
+ out += self._str_indent([self.empty_description])
525
+
526
+ if last_had_desc:
527
+ out += [""]
528
+ out += [""]
529
+ return out
530
+
531
+ def _str_index(self):
532
+ idx = self["index"]
533
+ out = []
534
+ output_index = False
535
+ default_index = idx.get("default", "")
536
+ if default_index:
537
+ output_index = True
538
+ out += [f".. index:: {default_index}"]
539
+ for section, references in idx.items():
540
+ if section == "default":
541
+ continue
542
+ output_index = True
543
+ out += [f" :{section}: {', '.join(references)}"]
544
+ if output_index:
545
+ return out
546
+ return ""
547
+
548
+ def __str__(self, func_role=""):
549
+ out = []
550
+ out += self._str_signature()
551
+ out += self._str_summary()
552
+ out += self._str_extended_summary()
553
+ out += self._str_param_list("Parameters")
554
+ for param_list in ("Attributes", "Methods"):
555
+ out += self._str_param_list(param_list)
556
+ for param_list in (
557
+ "Returns",
558
+ "Yields",
559
+ "Receives",
560
+ "Other Parameters",
561
+ "Raises",
562
+ "Warns",
563
+ ):
564
+ out += self._str_param_list(param_list)
565
+ out += self._str_section("Warnings")
566
+ out += self._str_see_also(func_role)
567
+ for s in ("Notes", "References", "Examples"):
568
+ out += self._str_section(s)
569
+ out += self._str_index()
570
+ return "\n".join(out)
571
+
572
+
573
+ def dedent_lines(lines):
574
+ """Deindent a list of lines maximally"""
575
+ return textwrap.dedent("\n".join(lines)).split("\n")
576
+
577
+
578
+ class FunctionDoc(NumpyDocString):
579
+ def __init__(self, func, role="func", doc=None, config=None):
580
+ self._f = func
581
+ self._role = role # e.g. "func" or "meth"
582
+
583
+ if doc is None:
584
+ if func is None:
585
+ raise ValueError("No function or docstring given")
586
+ doc = inspect.getdoc(func) or ""
587
+ if config is None:
588
+ config = {}
589
+ NumpyDocString.__init__(self, doc, config)
590
+
591
+ def get_func(self):
592
+ func_name = getattr(self._f, "__name__", self.__class__.__name__)
593
+ if inspect.isclass(self._f):
594
+ func = getattr(self._f, "__call__", self._f.__init__)
595
+ else:
596
+ func = self._f
597
+ return func, func_name
598
+
599
+ def __str__(self):
600
+ out = ""
601
+
602
+ func, func_name = self.get_func()
603
+
604
+ roles = {"func": "function", "meth": "method"}
605
+
606
+ if self._role:
607
+ if self._role not in roles:
608
+ print(f"Warning: invalid role {self._role}")
609
+ out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
610
+
611
+ out += super().__str__(func_role=self._role)
612
+ return out
613
+
614
+
615
+ class ObjDoc(NumpyDocString):
616
+ def __init__(self, obj, doc=None, config=None):
617
+ self._f = obj
618
+ if config is None:
619
+ config = {}
620
+ NumpyDocString.__init__(self, doc, config=config)
621
+
622
+
623
+ class ClassDoc(NumpyDocString):
624
+ extra_public_methods = ["__call__"]
625
+
626
+ def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
627
+ if not inspect.isclass(cls) and cls is not None:
628
+ raise ValueError(f"Expected a class or None, but got {cls!r}")
629
+ self._cls = cls
630
+
631
+ if "sphinx" in sys.modules:
632
+ from sphinx.ext.autodoc import ALL
633
+ else:
634
+ ALL = object()
635
+
636
+ if config is None:
637
+ config = {}
638
+ self.show_inherited_members = config.get("show_inherited_class_members", True)
639
+
640
+ if modulename and not modulename.endswith("."):
641
+ modulename += "."
642
+ self._mod = modulename
643
+
644
+ if doc is None:
645
+ if cls is None:
646
+ raise ValueError("No class or documentation string given")
647
+ doc = pydoc.getdoc(cls)
648
+
649
+ NumpyDocString.__init__(self, doc)
650
+
651
+ _members = config.get("members", [])
652
+ if _members is ALL:
653
+ _members = None
654
+ _exclude = config.get("exclude-members", [])
655
+
656
+ if config.get("show_class_members", True) and _exclude is not ALL:
657
+
658
+ def splitlines_x(s):
659
+ if not s:
660
+ return []
661
+ else:
662
+ return s.splitlines()
663
+
664
+ for field, items in [
665
+ ("Methods", self.methods),
666
+ ("Attributes", self.properties),
667
+ ]:
668
+ if not self[field]:
669
+ doc_list = []
670
+ for name in sorted(items):
671
+ if name in _exclude or (_members and name not in _members):
672
+ continue
673
+ try:
674
+ doc_item = pydoc.getdoc(getattr(self._cls, name))
675
+ doc_list.append(Parameter(name, "", splitlines_x(doc_item)))
676
+ except AttributeError:
677
+ pass # method doesn't exist
678
+ self[field] = doc_list
679
+
680
+ @property
681
+ def methods(self):
682
+ if self._cls is None:
683
+ return []
684
+ return [
685
+ name
686
+ for name, func in inspect.getmembers(self._cls)
687
+ if (
688
+ (not name.startswith("_") or name in self.extra_public_methods)
689
+ and isinstance(func, Callable)
690
+ and self._is_show_member(name)
691
+ )
692
+ ]
693
+
694
+ @property
695
+ def properties(self):
696
+ if self._cls is None:
697
+ return []
698
+ return [
699
+ name
700
+ for name, func in inspect.getmembers(self._cls)
701
+ if (
702
+ not name.startswith("_")
703
+ and not self._should_skip_member(name, self._cls)
704
+ and (
705
+ func is None
706
+ or isinstance(func, property | cached_property)
707
+ or inspect.isdatadescriptor(func)
708
+ )
709
+ and self._is_show_member(name)
710
+ )
711
+ ]
712
+
713
+ @staticmethod
714
+ def _should_skip_member(name, klass):
715
+ return (
716
+ # Namedtuples should skip everything in their ._fields as the
717
+ # docstrings for each of the members is: "Alias for field number X"
718
+ issubclass(klass, tuple)
719
+ and hasattr(klass, "_asdict")
720
+ and hasattr(klass, "_fields")
721
+ and name in klass._fields
722
+ )
723
+
724
+ def _is_show_member(self, name):
725
+ return (
726
+ # show all class members
727
+ self.show_inherited_members
728
+ # or class member is not inherited
729
+ or name in self._cls.__dict__
730
+ )
731
+
732
+
733
+ def get_doc_object(
734
+ obj,
735
+ what=None,
736
+ doc=None,
737
+ config=None,
738
+ class_doc=ClassDoc,
739
+ func_doc=FunctionDoc,
740
+ obj_doc=ObjDoc,
741
+ ):
742
+ if what is None:
743
+ if inspect.isclass(obj):
744
+ what = "class"
745
+ elif inspect.ismodule(obj):
746
+ what = "module"
747
+ elif isinstance(obj, Callable):
748
+ what = "function"
749
+ else:
750
+ what = "object"
751
+ if config is None:
752
+ config = {}
753
+
754
+ if what == "class":
755
+ return class_doc(obj, func_doc=func_doc, doc=doc, config=config)
756
+ elif what in ("function", "method"):
757
+ return func_doc(obj, doc=doc, config=config)
758
+ else:
759
+ if doc is None:
760
+ doc = pydoc.getdoc(obj)
761
+ return obj_doc(obj, doc, config=config)
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `_elementwise_iterative_method.py` includes tools for writing functions that
2
+ # - are vectorized to work elementwise on arrays,
3
+ # - implement non-trivial, iterative algorithms with a callback interface, and
4
+ # - return rich objects with iteration count, termination status, etc.
5
+ #
6
+ # Examples include:
7
+ # `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding,
8
+ # `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization,
9
+ # `scipy.optimize._differentiate._differentiate for numerical differentiation,
10
+ # `scipy.optimize._bracket._bracket_root for finding rootfinding brackets,
11
+ # `scipy.optimize._bracket._bracket_minimize for finding minimization brackets,
12
+ # `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature,
13
+ # `scipy.differentiate.derivative` for finite difference based differentiation.
14
+
15
+ import math
16
+ import numpy as np
17
+ from ._util import _RichResult, _call_callback_maybe_halt
18
+ from ._array_api import array_namespace, xp_size, xp_result_type
19
+ import scipy._lib.array_api_extra as xpx
20
+
21
+ _ESIGNERR = -1
22
+ _ECONVERR = -2
23
+ _EVALUEERR = -3
24
+ _ECALLBACK = -4
25
+ _EINPUTERR = -5
26
+ _ECONVERGED = 0
27
+ _EINPROGRESS = 1
28
+
29
+ def _initialize(func, xs, args, complex_ok=False, preserve_shape=None, xp=None):
30
+ """Initialize abscissa, function, and args arrays for elementwise function
31
+
32
+ Parameters
33
+ ----------
34
+ func : callable
35
+ An elementwise function with signature
36
+
37
+ func(x: ndarray, *args) -> ndarray
38
+
39
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
40
+ which may contain an arbitrary number of arrays that are broadcastable
41
+ with ``x``.
42
+ xs : tuple of arrays
43
+ Finite real abscissa arrays. Must be broadcastable.
44
+ args : tuple, optional
45
+ Additional positional arguments to be passed to `func`.
46
+ preserve_shape : bool, default:False
47
+ When ``preserve_shape=False`` (default), `func` may be passed
48
+ arguments of any shape; `_scalar_optimization_loop` is permitted
49
+ to reshape and compress arguments at will. When
50
+ ``preserve_shape=False``, arguments passed to `func` must have shape
51
+ `shape` or ``shape + (n,)``, where ``n`` is any integer.
52
+ xp : namespace
53
+ Namespace of array arguments in `xs`.
54
+
55
+ Returns
56
+ -------
57
+ xs, fs, args : tuple of arrays
58
+ Broadcasted, writeable, 1D abscissa and function value arrays (or
59
+ NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are
60
+ `xfat`; the dtype of the `args` are unchanged.
61
+ shape : tuple of ints
62
+ Original shape of broadcasted arrays.
63
+ xfat : NumPy dtype
64
+ Result dtype of abscissae, function values, and args determined using
65
+ `np.result_type`, except integer types are promoted to `np.float64`.
66
+
67
+ Raises
68
+ ------
69
+ ValueError
70
+ If the result dtype is not that of a real scalar
71
+
72
+ Notes
73
+ -----
74
+ Useful for initializing the input of SciPy functions that accept
75
+ an elementwise callable, abscissae, and arguments; e.g.
76
+ `scipy.optimize._chandrupatla`.
77
+ """
78
+ nx = len(xs)
79
+ xp = array_namespace(*xs) if xp is None else xp
80
+
81
+ # Try to preserve `dtype`, but we need to ensure that the arguments are at
82
+ # least floats before passing them into the function; integers can overflow
83
+ # and cause failure.
84
+ # There might be benefit to combining the `xs` into a single array and
85
+ # calling `func` once on the combined array. For now, keep them separate.
86
+ xat = xp_result_type(*xs, force_floating=True, xp=xp)
87
+ xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename
88
+ xs, args = xas[:nx], xas[nx:]
89
+ xs = [xp.asarray(x, dtype=xat) for x in xs] # use copy=False when implemented
90
+ fs = [xp.asarray(func(x, *args)) for x in xs]
91
+ shape = xs[0].shape
92
+ fshape = fs[0].shape
93
+
94
+ if preserve_shape:
95
+ # bind original shape/func now to avoid late-binding gotcha
96
+ def func(x, *args, shape=shape, func=func, **kwargs):
97
+ i = (0,)*(len(fshape) - len(shape))
98
+ return func(x[i], *args, **kwargs)
99
+ shape = np.broadcast_shapes(fshape, shape) # just shapes; use of NumPy OK
100
+ xs = [xp.broadcast_to(x, shape) for x in xs]
101
+ args = [xp.broadcast_to(arg, shape) for arg in args]
102
+
103
+ message = ("The shape of the array returned by `func` must be the same as "
104
+ "the broadcasted shape of `x` and all other `args`.")
105
+ if preserve_shape is not None: # only in tanhsinh for now
106
+ message = f"When `preserve_shape=False`, {message.lower()}"
107
+ shapes_equal = [f.shape == shape for f in fs]
108
+ if not all(shapes_equal): # use Python all to reduce overhead
109
+ raise ValueError(message)
110
+
111
+ # These algorithms tend to mix the dtypes of the abscissae and function
112
+ # values, so figure out what the result will be and convert them all to
113
+ # that type from the outset.
114
+ xfat = xp.result_type(*([f.dtype for f in fs] + [xat]))
115
+ if not complex_ok and not xp.isdtype(xfat, "real floating"):
116
+ raise ValueError("Abscissae and function output must be real numbers.")
117
+ xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs]
118
+ fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs]
119
+
120
+ # To ensure that we can do indexing, we'll work with at least 1d arrays,
121
+ # but remember the appropriate shape of the output.
122
+ xs = [xp.reshape(x, (-1,)) for x in xs]
123
+ fs = [xp.reshape(f, (-1,)) for f in fs]
124
+ args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args]
125
+ return func, xs, fs, args, shape, xfat, xp
126
+
127
+
128
+ def _loop(work, callback, shape, maxiter, func, args, dtype, pre_func_eval,
129
+ post_func_eval, check_termination, post_termination_check,
130
+ customize_result, res_work_pairs, xp, preserve_shape=False):
131
+ """Main loop of a vectorized scalar optimization algorithm
132
+
133
+ Parameters
134
+ ----------
135
+ work : _RichResult
136
+ All variables that need to be retained between iterations. Must
137
+ contain attributes `nit`, `nfev`, and `success`. All arrays are
138
+ subject to being "compressed" if `preserve_shape is False`; nest
139
+ arrays that should not be compressed inside another object (e.g.
140
+ `dict` or `_RichResult`).
141
+ callback : callable
142
+ User-specified callback function
143
+ shape : tuple of ints
144
+ The shape of all output arrays
145
+ maxiter :
146
+ Maximum number of iterations of the algorithm
147
+ func : callable
148
+ The user-specified callable that is being optimized or solved
149
+ args : tuple
150
+ Additional positional arguments to be passed to `func`.
151
+ dtype : NumPy dtype
152
+ The common dtype of all abscissae and function values
153
+ pre_func_eval : callable
154
+ A function that accepts `work` and returns `x`, the active elements
155
+ of `x` at which `func` will be evaluated. May modify attributes
156
+ of `work` with any algorithmic steps that need to happen
157
+ at the beginning of an iteration, before `func` is evaluated,
158
+ post_func_eval : callable
159
+ A function that accepts `x`, `func(x)`, and `work`. May modify
160
+ attributes of `work` with any algorithmic steps that need to happen
161
+ in the middle of an iteration, after `func` is evaluated but before
162
+ the termination check.
163
+ check_termination : callable
164
+ A function that accepts `work` and returns `stop`, a boolean array
165
+ indicating which of the active elements have met a termination
166
+ condition.
167
+ post_termination_check : callable
168
+ A function that accepts `work`. May modify `work` with any algorithmic
169
+ steps that need to happen after the termination check and before the
170
+ end of the iteration.
171
+ customize_result : callable
172
+ A function that accepts `res` and `shape` and returns `shape`. May
173
+ modify `res` (in-place) according to preferences (e.g. rearrange
174
+ elements between attributes) and modify `shape` if needed.
175
+ res_work_pairs : list of (str, str)
176
+ Identifies correspondence between attributes of `res` and attributes
177
+ of `work`; i.e., attributes of active elements of `work` will be
178
+ copied to the appropriate indices of `res` when appropriate. The order
179
+ determines the order in which _RichResult attributes will be
180
+ pretty-printed.
181
+ preserve_shape : bool, default: False
182
+ Whether to compress the attributes of `work` (to avoid unnecessary
183
+ computation on elements that have already converged).
184
+
185
+ Returns
186
+ -------
187
+ res : _RichResult
188
+ The final result object
189
+
190
+ Notes
191
+ -----
192
+ Besides providing structure, this framework provides several important
193
+ services for a vectorized optimization algorithm.
194
+
195
+ - It handles common tasks involving iteration count, function evaluation
196
+ count, a user-specified callback, and associated termination conditions.
197
+ - It compresses the attributes of `work` to eliminate unnecessary
198
+ computation on elements that have already converged.
199
+
200
+ """
201
+ if xp is None:
202
+ raise NotImplementedError("Must provide xp.")
203
+
204
+ cb_terminate = False
205
+
206
+ # Initialize the result object and active element index array
207
+ n_elements = math.prod(shape)
208
+ active = xp.arange(n_elements) # in-progress element indices
209
+ res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs}
210
+ res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool)
211
+ res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32)
212
+ res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32)
213
+ res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32)
214
+ res = _RichResult(res_dict)
215
+ work.args = args
216
+
217
+ active = _check_termination(work, res, res_work_pairs, active,
218
+ check_termination, preserve_shape, xp)
219
+
220
+ if callback is not None:
221
+ temp = _prepare_result(work, res, res_work_pairs, active, shape,
222
+ customize_result, preserve_shape, xp)
223
+ if _call_callback_maybe_halt(callback, temp):
224
+ cb_terminate = True
225
+
226
+ while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements:
227
+ x = pre_func_eval(work)
228
+
229
+ if work.args and work.args[0].ndim != x.ndim:
230
+ # `x` always starts as 1D. If the SciPy function that uses
231
+ # _loop added dimensions to `x`, we need to
232
+ # add them to the elements of `args`.
233
+ args = []
234
+ for arg in work.args:
235
+ n_new_dims = x.ndim - arg.ndim
236
+ new_shape = arg.shape + (1,)*n_new_dims
237
+ args.append(xp.reshape(arg, new_shape))
238
+ work.args = args
239
+
240
+ x_shape = x.shape
241
+ if preserve_shape:
242
+ x = xp.reshape(x, (shape + (-1,)))
243
+ f = func(x, *work.args)
244
+ f = xp.asarray(f, dtype=dtype)
245
+ if preserve_shape:
246
+ x = xp.reshape(x, x_shape)
247
+ f = xp.reshape(f, x_shape)
248
+ work.nfev += 1 if x.ndim == 1 else x.shape[-1]
249
+
250
+ post_func_eval(x, f, work)
251
+
252
+ work.nit += 1
253
+ active = _check_termination(work, res, res_work_pairs, active,
254
+ check_termination, preserve_shape, xp)
255
+
256
+ if callback is not None:
257
+ temp = _prepare_result(work, res, res_work_pairs, active, shape,
258
+ customize_result, preserve_shape, xp)
259
+ if _call_callback_maybe_halt(callback, temp):
260
+ cb_terminate = True
261
+ break
262
+ if xp_size(active) == 0:
263
+ break
264
+
265
+ post_termination_check(work)
266
+
267
+ work.status = xpx.at(work.status)[:].set(_ECALLBACK if cb_terminate else _ECONVERR)
268
+ return _prepare_result(work, res, res_work_pairs, active, shape,
269
+ customize_result, preserve_shape, xp)
270
+
271
+
272
+ def _check_termination(work, res, res_work_pairs, active, check_termination,
273
+ preserve_shape, xp):
274
+ # Checks termination conditions, updates elements of `res` with
275
+ # corresponding elements of `work`, and compresses `work`.
276
+
277
+ stop = check_termination(work)
278
+
279
+ if xp.any(stop):
280
+ # update the active elements of the result object with the active
281
+ # elements for which a termination condition has been met
282
+ _update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp)
283
+
284
+ if preserve_shape:
285
+ stop = stop[active]
286
+
287
+ proceed = ~stop
288
+ active = active[proceed]
289
+
290
+ if not preserve_shape:
291
+ # compress the arrays to avoid unnecessary computation
292
+ for key, val in work.items():
293
+ # `continued_fraction` hacks `n`; improve if this becomes a problem
294
+ if key in {'args', 'n'}:
295
+ continue
296
+ work[key] = val[proceed] if getattr(val, 'ndim', 0) > 0 else val
297
+ work.args = [arg[proceed] for arg in work.args]
298
+
299
+ return active
300
+
301
+
302
+ def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp):
303
+ # Update `active` indices of the arrays in result object `res` with the
304
+ # contents of the scalars and arrays in `update_dict`. When provided,
305
+ # `mask` is a boolean array applied both to the arrays in `update_dict`
306
+ # that are to be used and to the arrays in `res` that are to be updated.
307
+ update_dict = {key1: work[key2] for key1, key2 in res_work_pairs}
308
+ update_dict['success'] = work.status == 0
309
+
310
+ if mask is not None:
311
+ if preserve_shape:
312
+ active_mask = xp.zeros_like(mask)
313
+ active_mask = xpx.at(active_mask)[active].set(True)
314
+ active_mask = active_mask & mask
315
+ for key, val in update_dict.items():
316
+ val = val[active_mask] if getattr(val, 'ndim', 0) > 0 else val
317
+ res[key] = xpx.at(res[key])[active_mask].set(val)
318
+ else:
319
+ active_mask = active[mask]
320
+ for key, val in update_dict.items():
321
+ val = val[mask] if getattr(val, 'ndim', 0) > 0 else val
322
+ res[key] = xpx.at(res[key])[active_mask].set(val)
323
+ else:
324
+ for key, val in update_dict.items():
325
+ if preserve_shape and getattr(val, 'ndim', 0) > 0:
326
+ val = val[active]
327
+ res[key] = xpx.at(res[key])[active].set(val)
328
+
329
+
330
+ def _prepare_result(work, res, res_work_pairs, active, shape, customize_result,
331
+ preserve_shape, xp):
332
+ # Prepare the result object `res` by creating a copy, copying the latest
333
+ # data from work, running the provided result customization function,
334
+ # and reshaping the data to the original shapes.
335
+ res = res.copy()
336
+ _update_active(work, res, res_work_pairs, active, None, preserve_shape, xp)
337
+
338
+ shape = customize_result(res, shape)
339
+
340
+ for key, val in res.items():
341
+ # this looks like it won't work for xp != np if val is not numeric
342
+ temp = xp.reshape(val, shape)
343
+ res[key] = temp[()] if temp.ndim == 0 else temp
344
+
345
+ res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs]
346
+ return _RichResult(**res)
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (16.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module for testing automatic garbage collection of objects
3
+
4
+ .. autosummary::
5
+ :toctree: generated/
6
+
7
+ set_gc_state - enable or disable garbage collection
8
+ gc_state - context manager for given state of garbage collector
9
+ assert_deallocated - context manager to check for circular references on object
10
+
11
+ """
12
+ import weakref
13
+ import gc
14
+
15
+ from contextlib import contextmanager
16
+ from platform import python_implementation
17
+
18
+ __all__ = ['set_gc_state', 'gc_state', 'assert_deallocated']
19
+
20
+
21
+ IS_PYPY = python_implementation() == 'PyPy'
22
+
23
+
24
+ class ReferenceError(AssertionError):
25
+ pass
26
+
27
+
28
+ def set_gc_state(state):
29
+ """ Set status of garbage collector """
30
+ if gc.isenabled() == state:
31
+ return
32
+ if state:
33
+ gc.enable()
34
+ else:
35
+ gc.disable()
36
+
37
+
38
+ @contextmanager
39
+ def gc_state(state):
40
+ """ Context manager to set state of garbage collector to `state`
41
+
42
+ Parameters
43
+ ----------
44
+ state : bool
45
+ True for gc enabled, False for disabled
46
+
47
+ Examples
48
+ --------
49
+ >>> with gc_state(False):
50
+ ... assert not gc.isenabled()
51
+ >>> with gc_state(True):
52
+ ... assert gc.isenabled()
53
+ """
54
+ orig_state = gc.isenabled()
55
+ set_gc_state(state)
56
+ yield
57
+ set_gc_state(orig_state)
58
+
59
+
60
+ @contextmanager
61
+ def assert_deallocated(func, *args, **kwargs):
62
+ """Context manager to check that object is deallocated
63
+
64
+ This is useful for checking that an object can be freed directly by
65
+ reference counting, without requiring gc to break reference cycles.
66
+ GC is disabled inside the context manager.
67
+
68
+ This check is not available on PyPy.
69
+
70
+ Parameters
71
+ ----------
72
+ func : callable
73
+ Callable to create object to check
74
+ \\*args : sequence
75
+ positional arguments to `func` in order to create object to check
76
+ \\*\\*kwargs : dict
77
+ keyword arguments to `func` in order to create object to check
78
+
79
+ Examples
80
+ --------
81
+ >>> class C: pass
82
+ >>> with assert_deallocated(C) as c:
83
+ ... # do something
84
+ ... del c
85
+
86
+ >>> class C:
87
+ ... def __init__(self):
88
+ ... self._circular = self # Make circular reference
89
+ >>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL
90
+ ... # do something
91
+ ... del c
92
+ Traceback (most recent call last):
93
+ ...
94
+ ReferenceError: Remaining reference(s) to object
95
+ """
96
+ if IS_PYPY:
97
+ raise RuntimeError("assert_deallocated is unavailable on PyPy")
98
+
99
+ with gc_state(False):
100
+ obj = func(*args, **kwargs)
101
+ ref = weakref.ref(obj)
102
+ yield obj
103
+ del obj
104
+ if ref() is not None:
105
+ raise ReferenceError("Remaining reference(s) to object")
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_pep440.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility to compare pep440 compatible version strings.
2
+
3
+ The LooseVersion and StrictVersion classes that distutils provides don't
4
+ work; they don't recognize anything like alpha/beta/rc/dev versions.
5
+ """
6
+
7
+ # Copyright (c) Donald Stufft and individual contributors.
8
+ # All rights reserved.
9
+
10
+ # Redistribution and use in source and binary forms, with or without
11
+ # modification, are permitted provided that the following conditions are met:
12
+
13
+ # 1. Redistributions of source code must retain the above copyright notice,
14
+ # this list of conditions and the following disclaimer.
15
+
16
+ # 2. Redistributions in binary form must reproduce the above copyright
17
+ # notice, this list of conditions and the following disclaimer in the
18
+ # documentation and/or other materials provided with the distribution.
19
+
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ # POSSIBILITY OF SUCH DAMAGE.
31
+
32
+ import collections
33
+ import itertools
34
+ import re
35
+
36
+
37
+ __all__ = [
38
+ "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
39
+ ]
40
+
41
+
42
+ # BEGIN packaging/_structures.py
43
+
44
+
45
+ class Infinity:
46
+ def __repr__(self):
47
+ return "Infinity"
48
+
49
+ def __hash__(self):
50
+ return hash(repr(self))
51
+
52
+ def __lt__(self, other):
53
+ return False
54
+
55
+ def __le__(self, other):
56
+ return False
57
+
58
+ def __eq__(self, other):
59
+ return isinstance(other, self.__class__)
60
+
61
+ def __ne__(self, other):
62
+ return not isinstance(other, self.__class__)
63
+
64
+ def __gt__(self, other):
65
+ return True
66
+
67
+ def __ge__(self, other):
68
+ return True
69
+
70
+ def __neg__(self):
71
+ return NegativeInfinity
72
+
73
+
74
+ Infinity = Infinity()
75
+
76
+
77
+ class NegativeInfinity:
78
+ def __repr__(self):
79
+ return "-Infinity"
80
+
81
+ def __hash__(self):
82
+ return hash(repr(self))
83
+
84
+ def __lt__(self, other):
85
+ return True
86
+
87
+ def __le__(self, other):
88
+ return True
89
+
90
+ def __eq__(self, other):
91
+ return isinstance(other, self.__class__)
92
+
93
+ def __ne__(self, other):
94
+ return not isinstance(other, self.__class__)
95
+
96
+ def __gt__(self, other):
97
+ return False
98
+
99
+ def __ge__(self, other):
100
+ return False
101
+
102
+ def __neg__(self):
103
+ return Infinity
104
+
105
+
106
+ # BEGIN packaging/version.py
107
+
108
+
109
+ NegativeInfinity = NegativeInfinity()
110
+
111
+ _Version = collections.namedtuple(
112
+ "_Version",
113
+ ["epoch", "release", "dev", "pre", "post", "local"],
114
+ )
115
+
116
+
117
+ def parse(version):
118
+ """
119
+ Parse the given version string and return either a :class:`Version` object
120
+ or a :class:`LegacyVersion` object depending on if the given version is
121
+ a valid PEP 440 version or a legacy version.
122
+ """
123
+ try:
124
+ return Version(version)
125
+ except InvalidVersion:
126
+ return LegacyVersion(version)
127
+
128
+
129
+ class InvalidVersion(ValueError):
130
+ """
131
+ An invalid version was found, users should refer to PEP 440.
132
+ """
133
+
134
+
135
+ class _BaseVersion:
136
+
137
+ def __hash__(self):
138
+ return hash(self._key)
139
+
140
+ def __lt__(self, other):
141
+ return self._compare(other, lambda s, o: s < o)
142
+
143
+ def __le__(self, other):
144
+ return self._compare(other, lambda s, o: s <= o)
145
+
146
+ def __eq__(self, other):
147
+ return self._compare(other, lambda s, o: s == o)
148
+
149
+ def __ge__(self, other):
150
+ return self._compare(other, lambda s, o: s >= o)
151
+
152
+ def __gt__(self, other):
153
+ return self._compare(other, lambda s, o: s > o)
154
+
155
+ def __ne__(self, other):
156
+ return self._compare(other, lambda s, o: s != o)
157
+
158
+ def _compare(self, other, method):
159
+ if not isinstance(other, _BaseVersion):
160
+ return NotImplemented
161
+
162
+ return method(self._key, other._key)
163
+
164
+
165
+ class LegacyVersion(_BaseVersion):
166
+
167
+ def __init__(self, version):
168
+ self._version = str(version)
169
+ self._key = _legacy_cmpkey(self._version)
170
+
171
+ def __str__(self):
172
+ return self._version
173
+
174
+ def __repr__(self):
175
+ return f"<LegacyVersion({repr(str(self))})>"
176
+
177
+ @property
178
+ def public(self):
179
+ return self._version
180
+
181
+ @property
182
+ def base_version(self):
183
+ return self._version
184
+
185
+ @property
186
+ def local(self):
187
+ return None
188
+
189
+ @property
190
+ def is_prerelease(self):
191
+ return False
192
+
193
+ @property
194
+ def is_postrelease(self):
195
+ return False
196
+
197
+
198
+ _legacy_version_component_re = re.compile(
199
+ r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
200
+ )
201
+
202
+ _legacy_version_replacement_map = {
203
+ "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
204
+ }
205
+
206
+
207
+ def _parse_version_parts(s):
208
+ for part in _legacy_version_component_re.split(s):
209
+ part = _legacy_version_replacement_map.get(part, part)
210
+
211
+ if not part or part == ".":
212
+ continue
213
+
214
+ if part[:1] in "0123456789":
215
+ # pad for numeric comparison
216
+ yield part.zfill(8)
217
+ else:
218
+ yield "*" + part
219
+
220
+ # ensure that alpha/beta/candidate are before final
221
+ yield "*final"
222
+
223
+
224
+ def _legacy_cmpkey(version):
225
+ # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch
226
+ # greater than or equal to 0. This will effectively put the LegacyVersion,
227
+ # which uses the defacto standard originally implemented by setuptools,
228
+ # as before all PEP 440 versions.
229
+ epoch = -1
230
+
231
+ # This scheme is taken from pkg_resources.parse_version setuptools prior to
232
+ # its adoption of the packaging library.
233
+ parts = []
234
+ for part in _parse_version_parts(version.lower()):
235
+ if part.startswith("*"):
236
+ # remove "-" before a prerelease tag
237
+ if part < "*final":
238
+ while parts and parts[-1] == "*final-":
239
+ parts.pop()
240
+
241
+ # remove trailing zeros from each series of numeric parts
242
+ while parts and parts[-1] == "00000000":
243
+ parts.pop()
244
+
245
+ parts.append(part)
246
+ parts = tuple(parts)
247
+
248
+ return epoch, parts
249
+
250
+
251
+ # Deliberately not anchored to the start and end of the string, to make it
252
+ # easier for 3rd party code to reuse
253
+ VERSION_PATTERN = r"""
254
+ v?
255
+ (?:
256
+ (?:(?P<epoch>[0-9]+)!)? # epoch
257
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
258
+ (?P<pre> # pre-release
259
+ [-_\.]?
260
+ (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
261
+ [-_\.]?
262
+ (?P<pre_n>[0-9]+)?
263
+ )?
264
+ (?P<post> # post release
265
+ (?:-(?P<post_n1>[0-9]+))
266
+ |
267
+ (?:
268
+ [-_\.]?
269
+ (?P<post_l>post|rev|r)
270
+ [-_\.]?
271
+ (?P<post_n2>[0-9]+)?
272
+ )
273
+ )?
274
+ (?P<dev> # dev release
275
+ [-_\.]?
276
+ (?P<dev_l>dev)
277
+ [-_\.]?
278
+ (?P<dev_n>[0-9]+)?
279
+ )?
280
+ )
281
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
282
+ """
283
+
284
+
285
+ class Version(_BaseVersion):
286
+
287
+ _regex = re.compile(
288
+ r"^\s*" + VERSION_PATTERN + r"\s*$",
289
+ re.VERBOSE | re.IGNORECASE,
290
+ )
291
+
292
+ def __init__(self, version):
293
+ # Validate the version and parse it into pieces
294
+ match = self._regex.search(version)
295
+ if not match:
296
+ raise InvalidVersion(f"Invalid version: '{version}'")
297
+
298
+ # Store the parsed out pieces of the version
299
+ self._version = _Version(
300
+ epoch=int(match.group("epoch")) if match.group("epoch") else 0,
301
+ release=tuple(int(i) for i in match.group("release").split(".")),
302
+ pre=_parse_letter_version(
303
+ match.group("pre_l"),
304
+ match.group("pre_n"),
305
+ ),
306
+ post=_parse_letter_version(
307
+ match.group("post_l"),
308
+ match.group("post_n1") or match.group("post_n2"),
309
+ ),
310
+ dev=_parse_letter_version(
311
+ match.group("dev_l"),
312
+ match.group("dev_n"),
313
+ ),
314
+ local=_parse_local_version(match.group("local")),
315
+ )
316
+
317
+ # Generate a key which will be used for sorting
318
+ self._key = _cmpkey(
319
+ self._version.epoch,
320
+ self._version.release,
321
+ self._version.pre,
322
+ self._version.post,
323
+ self._version.dev,
324
+ self._version.local,
325
+ )
326
+
327
+ def __repr__(self):
328
+ return f"<Version({repr(str(self))})>"
329
+
330
+ def __str__(self):
331
+ parts = []
332
+
333
+ # Epoch
334
+ if self._version.epoch != 0:
335
+ parts.append(f"{self._version.epoch}!")
336
+
337
+ # Release segment
338
+ parts.append(".".join(str(x) for x in self._version.release))
339
+
340
+ # Pre-release
341
+ if self._version.pre is not None:
342
+ parts.append("".join(str(x) for x in self._version.pre))
343
+
344
+ # Post-release
345
+ if self._version.post is not None:
346
+ parts.append(f".post{self._version.post[1]}")
347
+
348
+ # Development release
349
+ if self._version.dev is not None:
350
+ parts.append(f".dev{self._version.dev[1]}")
351
+
352
+ # Local version segment
353
+ if self._version.local is not None:
354
+ parts.append(
355
+ "+{}".format(".".join(str(x) for x in self._version.local))
356
+ )
357
+
358
+ return "".join(parts)
359
+
360
+ @property
361
+ def public(self):
362
+ return str(self).split("+", 1)[0]
363
+
364
+ @property
365
+ def base_version(self):
366
+ parts = []
367
+
368
+ # Epoch
369
+ if self._version.epoch != 0:
370
+ parts.append(f"{self._version.epoch}!")
371
+
372
+ # Release segment
373
+ parts.append(".".join(str(x) for x in self._version.release))
374
+
375
+ return "".join(parts)
376
+
377
+ @property
378
+ def local(self):
379
+ version_string = str(self)
380
+ if "+" in version_string:
381
+ return version_string.split("+", 1)[1]
382
+
383
+ @property
384
+ def is_prerelease(self):
385
+ return bool(self._version.dev or self._version.pre)
386
+
387
+ @property
388
+ def is_postrelease(self):
389
+ return bool(self._version.post)
390
+
391
+
392
+ def _parse_letter_version(letter, number):
393
+ if letter:
394
+ # We assume there is an implicit 0 in a pre-release if there is
395
+ # no numeral associated with it.
396
+ if number is None:
397
+ number = 0
398
+
399
+ # We normalize any letters to their lower-case form
400
+ letter = letter.lower()
401
+
402
+ # We consider some words to be alternate spellings of other words and
403
+ # in those cases we want to normalize the spellings to our preferred
404
+ # spelling.
405
+ if letter == "alpha":
406
+ letter = "a"
407
+ elif letter == "beta":
408
+ letter = "b"
409
+ elif letter in ["c", "pre", "preview"]:
410
+ letter = "rc"
411
+ elif letter in ["rev", "r"]:
412
+ letter = "post"
413
+
414
+ return letter, int(number)
415
+ if not letter and number:
416
+ # We assume that if we are given a number but not given a letter,
417
+ # then this is using the implicit post release syntax (e.g., 1.0-1)
418
+ letter = "post"
419
+
420
+ return letter, int(number)
421
+
422
+
423
+ _local_version_seperators = re.compile(r"[\._-]")
424
+
425
+
426
+ def _parse_local_version(local):
427
+ """
428
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
429
+ """
430
+ if local is not None:
431
+ return tuple(
432
+ part.lower() if not part.isdigit() else int(part)
433
+ for part in _local_version_seperators.split(local)
434
+ )
435
+
436
+
437
+ def _cmpkey(epoch, release, pre, post, dev, local):
438
+ # When we compare a release version, we want to compare it with all of the
439
+ # trailing zeros removed. So we'll use a reverse the list, drop all the now
440
+ # leading zeros until we come to something non-zero, then take the rest,
441
+ # re-reverse it back into the correct order, and make it a tuple and use
442
+ # that for our sorting key.
443
+ release = tuple(
444
+ reversed(list(
445
+ itertools.dropwhile(
446
+ lambda x: x == 0,
447
+ reversed(release),
448
+ )
449
+ ))
450
+ )
451
+
452
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
453
+ # We'll do this by abusing the pre-segment, but we _only_ want to do this
454
+ # if there is no pre- or a post-segment. If we have one of those, then
455
+ # the normal sorting rules will handle this case correctly.
456
+ if pre is None and post is None and dev is not None:
457
+ pre = -Infinity
458
+ # Versions without a pre-release (except as noted above) should sort after
459
+ # those with one.
460
+ elif pre is None:
461
+ pre = Infinity
462
+
463
+ # Versions without a post-segment should sort before those with one.
464
+ if post is None:
465
+ post = -Infinity
466
+
467
+ # Versions without a development segment should sort after those with one.
468
+ if dev is None:
469
+ dev = Infinity
470
+
471
+ if local is None:
472
+ # Versions without a local segment should sort before those with one.
473
+ local = -Infinity
474
+ else:
475
+ # Versions with a local segment need that segment parsed to implement
476
+ # the sorting rules in PEP440.
477
+ # - Alphanumeric segments sort before numeric segments
478
+ # - Alphanumeric segments sort lexicographically
479
+ # - Numeric segments sort numerically
480
+ # - Shorter versions sort before longer versions when the prefixes
481
+ # match exactly
482
+ local = tuple(
483
+ (i, "") if isinstance(i, int) else (-Infinity, i)
484
+ for i in local
485
+ )
486
+
487
+ return epoch, release, pre, post, dev, local
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+
3
+ __all__ = ["SparseABC", "issparse"]
4
+
5
+
6
+ class SparseABC(ABC):
7
+ pass
8
+
9
+
10
+ def issparse(x):
11
+ """Is `x` of a sparse array or sparse matrix type?
12
+
13
+ Parameters
14
+ ----------
15
+ x
16
+ object to check for being a sparse array or sparse matrix
17
+
18
+ Returns
19
+ -------
20
+ bool
21
+ True if `x` is a sparse array or a sparse matrix, False otherwise
22
+
23
+ Notes
24
+ -----
25
+ Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
26
+ Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.
27
+
28
+ Examples
29
+ --------
30
+ >>> import numpy as np
31
+ >>> from scipy.sparse import csr_array, csr_matrix, issparse
32
+ >>> issparse(csr_matrix([[5]]))
33
+ True
34
+ >>> issparse(csr_array([[5]]))
35
+ True
36
+ >>> issparse(np.array([[5]]))
37
+ False
38
+ >>> issparse(5)
39
+ False
40
+ """
41
+ return isinstance(x, SparseABC)
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (23.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (45.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (29.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generic test utilities.
3
+
4
+ """
5
+
6
+ import inspect
7
+ import os
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import sysconfig
13
+ import threading
14
+ from importlib.util import module_from_spec, spec_from_file_location
15
+
16
+ import numpy as np
17
+ import scipy
18
+
19
+ try:
20
+ # Need type: ignore[import-untyped] for mypy >= 1.6
21
+ import cython # type: ignore[import-untyped]
22
+ from Cython.Compiler.Version import ( # type: ignore[import-untyped]
23
+ version as cython_version,
24
+ )
25
+ except ImportError:
26
+ cython = None
27
+ else:
28
+ from scipy._lib import _pep440
29
+ required_version = '3.0.8'
30
+ if _pep440.parse(cython_version) < _pep440.Version(required_version):
31
+ # too old or wrong cython, skip Cython API tests
32
+ cython = None
33
+
34
+
35
+ __all__ = ['PytestTester', 'check_free_memory', '_TestPythranFunc', 'IS_MUSL']
36
+
37
+
38
+ IS_MUSL = False
39
+ # alternate way is
40
+ # from packaging.tags import sys_tags
41
+ # _tags = list(sys_tags())
42
+ # if 'musllinux' in _tags[0].platform:
43
+ _v = sysconfig.get_config_var('HOST_GNU_TYPE') or ''
44
+ if 'musl' in _v:
45
+ IS_MUSL = True
46
+
47
+
48
+ IS_EDITABLE = 'editable' in scipy.__path__[0]
49
+
50
+
51
+ class FPUModeChangeWarning(RuntimeWarning):
52
+ """Warning about FPU mode change"""
53
+ pass
54
+
55
+
56
+ class PytestTester:
57
+ """
58
+ Run tests for this namespace
59
+
60
+ ``scipy.test()`` runs tests for all of SciPy, with the default settings.
61
+ When used from a submodule (e.g., ``scipy.cluster.test()``, only the tests
62
+ for that namespace are run.
63
+
64
+ Parameters
65
+ ----------
66
+ label : {'fast', 'full'}, optional
67
+ Whether to run only the fast tests, or also those marked as slow.
68
+ Default is 'fast'.
69
+ verbose : int, optional
70
+ Test output verbosity. Default is 1.
71
+ extra_argv : list, optional
72
+ Arguments to pass through to Pytest.
73
+ doctests : bool, optional
74
+ Whether to run doctests or not. Default is False.
75
+ coverage : bool, optional
76
+ Whether to run tests with code coverage measurements enabled.
77
+ Default is False.
78
+ tests : list of str, optional
79
+ List of module names to run tests for. By default, uses the module
80
+ from which the ``test`` function is called.
81
+ parallel : int, optional
82
+ Run tests in parallel with pytest-xdist, if number given is larger than
83
+ 1. Default is 1.
84
+
85
+ """
86
+ def __init__(self, module_name):
87
+ self.module_name = module_name
88
+
89
+ def __call__(self, label="fast", verbose=1, extra_argv=None, doctests=False,
90
+ coverage=False, tests=None, parallel=None):
91
+ import pytest
92
+
93
+ module = sys.modules[self.module_name]
94
+ module_path = os.path.abspath(module.__path__[0])
95
+
96
+ pytest_args = ['--showlocals', '--tb=short']
97
+
98
+ if extra_argv is None:
99
+ extra_argv = []
100
+ pytest_args += extra_argv
101
+ if any(arg == "-m" or arg == "--markers" for arg in extra_argv):
102
+ # Likely conflict with default --mode=fast
103
+ raise ValueError("Must specify -m before --")
104
+
105
+ if verbose and int(verbose) > 1:
106
+ pytest_args += ["-" + "v"*(int(verbose)-1)]
107
+
108
+ if coverage:
109
+ pytest_args += ["--cov=" + module_path]
110
+
111
+ if label == "fast":
112
+ pytest_args += ["-m", "not slow"]
113
+ elif label != "full":
114
+ pytest_args += ["-m", label]
115
+
116
+ if tests is None:
117
+ tests = [self.module_name]
118
+
119
+ if parallel is not None and parallel > 1:
120
+ if _pytest_has_xdist():
121
+ pytest_args += ['-n', str(parallel)]
122
+ else:
123
+ import warnings
124
+ warnings.warn('Could not run tests in parallel because '
125
+ 'pytest-xdist plugin is not available.',
126
+ stacklevel=2)
127
+
128
+ pytest_args += ['--pyargs'] + list(tests)
129
+
130
+ try:
131
+ code = pytest.main(pytest_args)
132
+ except SystemExit as exc:
133
+ code = exc.code
134
+
135
+ return (code == 0)
136
+
137
+
138
+ class _TestPythranFunc:
139
+ '''
140
+ These are situations that can be tested in our pythran tests:
141
+ - A function with multiple array arguments and then
142
+ other positional and keyword arguments.
143
+ - A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
144
+ Note: list/tuple input is not yet tested!
145
+
146
+ `self.arguments`: A dictionary which key is the index of the argument,
147
+ value is tuple(array value, all supported dtypes)
148
+ `self.partialfunc`: A function used to freeze some non-array argument
149
+ that of no interests in the original function
150
+ '''
151
+ ALL_INTEGER = [np.int8, np.int16, np.int32, np.int64, np.intc, np.intp]
152
+ ALL_FLOAT = [np.float32, np.float64]
153
+ ALL_COMPLEX = [np.complex64, np.complex128]
154
+
155
+ def setup_method(self):
156
+ self.arguments = {}
157
+ self.partialfunc = None
158
+ self.expected = None
159
+
160
+ def get_optional_args(self, func):
161
+ # get optional arguments with its default value,
162
+ # used for testing keywords
163
+ signature = inspect.signature(func)
164
+ optional_args = {}
165
+ for k, v in signature.parameters.items():
166
+ if v.default is not inspect.Parameter.empty:
167
+ optional_args[k] = v.default
168
+ return optional_args
169
+
170
+ def get_max_dtype_list_length(self):
171
+ # get the max supported dtypes list length in all arguments
172
+ max_len = 0
173
+ for arg_idx in self.arguments:
174
+ cur_len = len(self.arguments[arg_idx][1])
175
+ if cur_len > max_len:
176
+ max_len = cur_len
177
+ return max_len
178
+
179
+ def get_dtype(self, dtype_list, dtype_idx):
180
+ # get the dtype from dtype_list via index
181
+ # if the index is out of range, then return the last dtype
182
+ if dtype_idx > len(dtype_list)-1:
183
+ return dtype_list[-1]
184
+ else:
185
+ return dtype_list[dtype_idx]
186
+
187
+ def test_all_dtypes(self):
188
+ for type_idx in range(self.get_max_dtype_list_length()):
189
+ args_array = []
190
+ for arg_idx in self.arguments:
191
+ new_dtype = self.get_dtype(self.arguments[arg_idx][1],
192
+ type_idx)
193
+ args_array.append(self.arguments[arg_idx][0].astype(new_dtype))
194
+ self.pythranfunc(*args_array)
195
+
196
+ def test_views(self):
197
+ args_array = []
198
+ for arg_idx in self.arguments:
199
+ args_array.append(self.arguments[arg_idx][0][::-1][::-1])
200
+ self.pythranfunc(*args_array)
201
+
202
+ def test_strided(self):
203
+ args_array = []
204
+ for arg_idx in self.arguments:
205
+ args_array.append(np.repeat(self.arguments[arg_idx][0],
206
+ 2, axis=0)[::2])
207
+ self.pythranfunc(*args_array)
208
+
209
+
210
+ def _pytest_has_xdist():
211
+ """
212
+ Check if the pytest-xdist plugin is installed, providing parallel tests
213
+ """
214
+ # Check xdist exists without importing, otherwise pytests emits warnings
215
+ from importlib.util import find_spec
216
+ return find_spec('xdist') is not None
217
+
218
+
219
+ def check_free_memory(free_mb):
220
+ """
221
+ Check *free_mb* of memory is available, otherwise do pytest.skip
222
+ """
223
+ import pytest
224
+
225
+ try:
226
+ mem_free = _parse_size(os.environ['SCIPY_AVAILABLE_MEM'])
227
+ msg = '{} MB memory required, but environment SCIPY_AVAILABLE_MEM={}'.format(
228
+ free_mb, os.environ['SCIPY_AVAILABLE_MEM'])
229
+ except KeyError:
230
+ mem_free = _get_mem_available()
231
+ if mem_free is None:
232
+ pytest.skip("Could not determine available memory; set SCIPY_AVAILABLE_MEM "
233
+ "variable to free memory in MB to run the test.")
234
+ msg = f'{free_mb} MB memory required, but {mem_free/1e6} MB available'
235
+
236
+ if mem_free < free_mb * 1e6:
237
+ pytest.skip(msg)
238
+
239
+
240
+ def _parse_size(size_str):
241
+ suffixes = {'': 1e6,
242
+ 'b': 1.0,
243
+ 'k': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12,
244
+ 'kb': 1e3, 'Mb': 1e6, 'Gb': 1e9, 'Tb': 1e12,
245
+ 'kib': 1024.0, 'Mib': 1024.0**2, 'Gib': 1024.0**3, 'Tib': 1024.0**4}
246
+ m = re.match(r'^\s*(\d+)\s*({})\s*$'.format('|'.join(suffixes.keys())),
247
+ size_str,
248
+ re.I)
249
+ if not m or m.group(2) not in suffixes:
250
+ raise ValueError("Invalid size string")
251
+
252
+ return float(m.group(1)) * suffixes[m.group(2)]
253
+
254
+
255
+ def _get_mem_available():
256
+ """
257
+ Get information about memory available, not counting swap.
258
+ """
259
+ try:
260
+ import psutil
261
+ return psutil.virtual_memory().available
262
+ except (ImportError, AttributeError):
263
+ pass
264
+
265
+ if sys.platform.startswith('linux'):
266
+ info = {}
267
+ with open('/proc/meminfo') as f:
268
+ for line in f:
269
+ p = line.split()
270
+ info[p[0].strip(':').lower()] = float(p[1]) * 1e3
271
+
272
+ if 'memavailable' in info:
273
+ # Linux >= 3.14
274
+ return info['memavailable']
275
+ else:
276
+ return info['memfree'] + info['cached']
277
+
278
+ return None
279
+
280
+ def _test_cython_extension(tmp_path, srcdir):
281
+ """
282
+ Helper function to test building and importing Cython modules that
283
+ make use of the Cython APIs for BLAS, LAPACK, optimize, and special.
284
+ """
285
+ import pytest
286
+ try:
287
+ subprocess.check_call(["meson", "--version"])
288
+ except FileNotFoundError:
289
+ pytest.skip("No usable 'meson' found")
290
+
291
+ # Make safe for being called by multiple threads within one test
292
+ tmp_path = tmp_path / str(threading.get_ident())
293
+
294
+ # build the examples in a temporary directory
295
+ mod_name = os.path.split(srcdir)[1]
296
+ shutil.copytree(srcdir, tmp_path / mod_name)
297
+ build_dir = tmp_path / mod_name / 'tests' / '_cython_examples'
298
+ target_dir = build_dir / 'build'
299
+ os.makedirs(target_dir, exist_ok=True)
300
+
301
+ # Ensure we use the correct Python interpreter even when `meson` is
302
+ # installed in a different Python environment (see numpy#24956)
303
+ native_file = str(build_dir / 'interpreter-native-file.ini')
304
+ with open(native_file, 'w') as f:
305
+ f.write("[binaries]\n")
306
+ f.write(f"python = '{sys.executable}'")
307
+
308
+ if sys.platform == "win32":
309
+ subprocess.check_call(["meson", "setup",
310
+ "--buildtype=release",
311
+ "--native-file", native_file,
312
+ "--vsenv", str(build_dir)],
313
+ cwd=target_dir,
314
+ )
315
+ else:
316
+ subprocess.check_call(["meson", "setup",
317
+ "--native-file", native_file, str(build_dir)],
318
+ cwd=target_dir
319
+ )
320
+ subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
321
+
322
+ # import without adding the directory to sys.path
323
+ suffix = sysconfig.get_config_var('EXT_SUFFIX')
324
+
325
+ def load(modname):
326
+ so = (target_dir / modname).with_suffix(suffix)
327
+ spec = spec_from_file_location(modname, so)
328
+ mod = module_from_spec(spec)
329
+ spec.loader.exec_module(mod)
330
+ return mod
331
+
332
+ # test that the module can be imported
333
+ return load("extending"), load("extending_cpp")
334
+
335
+
336
+ def _run_concurrent_barrier(n_workers, fn, *args, **kwargs):
337
+ """
338
+ Run a given function concurrently across a given number of threads.
339
+
340
+ This is equivalent to using a ThreadPoolExecutor, but using the threading
341
+ primitives instead. This function ensures that the closure passed by
342
+ parameter gets called concurrently by setting up a barrier before it gets
343
+ called before any of the threads.
344
+
345
+ Arguments
346
+ ---------
347
+ n_workers: int
348
+ Number of concurrent threads to spawn.
349
+ fn: callable
350
+ Function closure to execute concurrently. Its first argument will
351
+ be the thread id.
352
+ *args: tuple
353
+ Variable number of positional arguments to pass to the function.
354
+ **kwargs: dict
355
+ Keyword arguments to pass to the function.
356
+ """
357
+ barrier = threading.Barrier(n_workers)
358
+
359
+ def closure(i, *args, **kwargs):
360
+ barrier.wait()
361
+ fn(i, *args, **kwargs)
362
+
363
+ workers = []
364
+ for i in range(0, n_workers):
365
+ workers.append(threading.Thread(
366
+ target=closure,
367
+ args=(i,) + args, kwargs=kwargs))
368
+
369
+ for worker in workers:
370
+ worker.start()
371
+
372
+ for worker in workers:
373
+ worker.join()
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_threadsafety.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+
3
+ import scipy._lib.decorator
4
+
5
+
6
+ __all__ = ['ReentrancyError', 'ReentrancyLock', 'non_reentrant']
7
+
8
+
9
+ class ReentrancyError(RuntimeError):
10
+ pass
11
+
12
+
13
+ class ReentrancyLock:
14
+ """
15
+ Threading lock that raises an exception for reentrant calls.
16
+
17
+ Calls from different threads are serialized, and nested calls from the
18
+ same thread result to an error.
19
+
20
+ The object can be used as a context manager or to decorate functions
21
+ via the decorate() method.
22
+
23
+ """
24
+
25
+ def __init__(self, err_msg):
26
+ self._rlock = threading.RLock()
27
+ self._entered = False
28
+ self._err_msg = err_msg
29
+
30
+ def __enter__(self):
31
+ self._rlock.acquire()
32
+ if self._entered:
33
+ self._rlock.release()
34
+ raise ReentrancyError(self._err_msg)
35
+ self._entered = True
36
+
37
+ def __exit__(self, type, value, traceback):
38
+ self._entered = False
39
+ self._rlock.release()
40
+
41
+ def decorate(self, func):
42
+ def caller(func, *a, **kw):
43
+ with self:
44
+ return func(*a, **kw)
45
+ return scipy._lib.decorator.decorate(func, caller)
46
+
47
+
48
+ def non_reentrant(err_msg=None):
49
+ """
50
+ Decorate a function with a threading lock and prevent reentrant calls.
51
+ """
52
+ def decorator(func):
53
+ msg = err_msg
54
+ if msg is None:
55
+ msg = f"{func.__name__} is not re-entrant"
56
+ lock = ReentrancyLock(msg)
57
+ return lock.decorate(func)
58
+ return decorator
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_tmpdirs.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ''' Contexts for *with* statement providing temporary directories
2
+ '''
3
+ import os
4
+ from contextlib import contextmanager
5
+ from shutil import rmtree
6
+ from tempfile import mkdtemp
7
+
8
+
9
+ @contextmanager
10
+ def tempdir():
11
+ """Create and return a temporary directory. This has the same
12
+ behavior as mkdtemp but can be used as a context manager.
13
+
14
+ Upon exiting the context, the directory and everything contained
15
+ in it are removed.
16
+
17
+ Examples
18
+ --------
19
+ >>> import os
20
+ >>> with tempdir() as tmpdir:
21
+ ... fname = os.path.join(tmpdir, 'example_file.txt')
22
+ ... with open(fname, 'wt') as fobj:
23
+ ... _ = fobj.write('a string\\n')
24
+ >>> os.path.exists(tmpdir)
25
+ False
26
+ """
27
+ d = mkdtemp()
28
+ yield d
29
+ rmtree(d)
30
+
31
+
32
+ @contextmanager
33
+ def in_tempdir():
34
+ ''' Create, return, and change directory to a temporary directory
35
+
36
+ Examples
37
+ --------
38
+ >>> import os
39
+ >>> my_cwd = os.getcwd()
40
+ >>> with in_tempdir() as tmpdir:
41
+ ... _ = open('test.txt', 'wt').write('some text')
42
+ ... assert os.path.isfile('test.txt')
43
+ ... assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
44
+ >>> os.path.exists(tmpdir)
45
+ False
46
+ >>> os.getcwd() == my_cwd
47
+ True
48
+ '''
49
+ pwd = os.getcwd()
50
+ d = mkdtemp()
51
+ os.chdir(d)
52
+ yield d
53
+ os.chdir(pwd)
54
+ rmtree(d)
55
+
56
+
57
+ @contextmanager
58
+ def in_dir(dir=None):
59
+ """ Change directory to given directory for duration of ``with`` block
60
+
61
+ Useful when you want to use `in_tempdir` for the final test, but
62
+ you are still debugging. For example, you may want to do this in the end:
63
+
64
+ >>> with in_tempdir() as tmpdir:
65
+ ... # do something complicated which might break
66
+ ... pass
67
+
68
+ But, indeed, the complicated thing does break, and meanwhile, the
69
+ ``in_tempdir`` context manager wiped out the directory with the
70
+ temporary files that you wanted for debugging. So, while debugging, you
71
+ replace with something like:
72
+
73
+ >>> with in_dir() as tmpdir: # Use working directory by default
74
+ ... # do something complicated which might break
75
+ ... pass
76
+
77
+ You can then look at the temporary file outputs to debug what is happening,
78
+ fix, and finally replace ``in_dir`` with ``in_tempdir`` again.
79
+ """
80
+ cwd = os.getcwd()
81
+ if dir is None:
82
+ yield cwd
83
+ return
84
+ os.chdir(dir)
85
+ yield dir
86
+ os.chdir(cwd)
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py ADDED
@@ -0,0 +1,1283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from contextlib import contextmanager
3
+ import functools
4
+ import operator
5
+ import warnings
6
+ import numbers
7
+ from collections import namedtuple
8
+ import inspect
9
+ import math
10
+ from types import ModuleType
11
+ from typing import Literal, TypeAlias, TypeVar
12
+
13
+ import numpy as np
14
+ from scipy._lib._array_api import (Array, array_namespace, is_lazy_array,
15
+ is_numpy, is_marray, xp_result_device,
16
+ xp_size, xp_result_type)
17
+ from scipy._lib._docscrape import FunctionDoc, Parameter
18
+ from scipy._lib._sparse import issparse
19
+
20
+ from numpy.exceptions import AxisError
21
+
22
+
23
+ np_long: type
24
+ np_ulong: type
25
+
26
+ if np.lib.NumpyVersion(np.__version__) >= "2.0.0.dev0":
27
+ try:
28
+ with warnings.catch_warnings():
29
+ warnings.filterwarnings(
30
+ "ignore",
31
+ r".*In the future `np\.long` will be defined as.*",
32
+ FutureWarning,
33
+ )
34
+ np_long = np.long # type: ignore[attr-defined]
35
+ np_ulong = np.ulong # type: ignore[attr-defined]
36
+ except AttributeError:
37
+ np_long = np.int_
38
+ np_ulong = np.uint
39
+ else:
40
+ np_long = np.int_
41
+ np_ulong = np.uint
42
+
43
+ IntNumber = int | np.integer
44
+ DecimalNumber = float | np.floating | np.integer
45
+
46
+ copy_if_needed: bool | None
47
+
48
+ if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
49
+ copy_if_needed = None
50
+ elif np.lib.NumpyVersion(np.__version__) < "1.28.0":
51
+ copy_if_needed = False
52
+ else:
53
+ # 2.0.0 dev versions, handle cases where copy may or may not exist
54
+ try:
55
+ np.array([1]).__array__(copy=None) # type: ignore[call-overload]
56
+ copy_if_needed = None
57
+ except TypeError:
58
+ copy_if_needed = False
59
+
60
+
61
+ _RNG: TypeAlias = np.random.Generator | np.random.RandomState
62
+ SeedType: TypeAlias = IntNumber | _RNG | None
63
+
64
+ GeneratorType = TypeVar("GeneratorType", bound=_RNG)
65
+
66
+ # Since Generator was introduced in numpy 1.17, the following condition is needed for
67
+ # backward compatibility
68
+ try:
69
+ from numpy.random import Generator as Generator
70
+ except ImportError:
71
+ class Generator: # type: ignore[no-redef]
72
+ pass
73
+
74
+
75
+ def _lazyselect(condlist, choicelist, arrays, default=0):
76
+ """
77
+ Mimic `np.select(condlist, choicelist)`.
78
+
79
+ Notice, it assumes that all `arrays` are of the same shape or can be
80
+ broadcasted together.
81
+
82
+ All functions in `choicelist` must accept array arguments in the order
83
+ given in `arrays` and must return an array of the same shape as broadcasted
84
+ `arrays`.
85
+
86
+ Examples
87
+ --------
88
+ >>> import numpy as np
89
+ >>> x = np.arange(6)
90
+ >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
91
+ array([ 0, 1, 4, 0, 64, 125])
92
+
93
+ >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
94
+ array([ 0., 1., 4., 0., 64., 125.])
95
+
96
+ >>> a = -np.ones_like(x)
97
+ >>> _lazyselect([x < 3, x > 3],
98
+ ... [lambda x, a: x**2, lambda x, a: a * x**3],
99
+ ... (x, a), default=np.nan)
100
+ array([ 0., 1., 4., nan, -64., -125.])
101
+
102
+ """
103
+ arrays = np.broadcast_arrays(*arrays)
104
+ tcode = np.mintypecode([a.dtype.char for a in arrays])
105
+ out = np.full(np.shape(arrays[0]), fill_value=default, dtype=tcode)
106
+ for func, cond in zip(choicelist, condlist):
107
+ if np.all(cond is False):
108
+ continue
109
+ cond, _ = np.broadcast_arrays(cond, arrays[0])
110
+ temp = tuple(np.extract(cond, arr) for arr in arrays)
111
+ np.place(out, cond, func(*temp))
112
+ return out
113
+
114
+
115
+ def _aligned_zeros(shape, dtype=float, order="C", align=None):
116
+ """Allocate a new ndarray with aligned memory.
117
+
118
+ Primary use case for this currently is working around a f2py issue
119
+ in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
120
+ not necessarily create arrays aligned up to it.
121
+
122
+ """
123
+ dtype = np.dtype(dtype)
124
+ if align is None:
125
+ align = dtype.alignment
126
+ if not hasattr(shape, '__len__'):
127
+ shape = (shape,)
128
+ size = functools.reduce(operator.mul, shape) * dtype.itemsize
129
+ buf = np.empty(size + align + 1, np.uint8)
130
+ offset = buf.__array_interface__['data'][0] % align
131
+ if offset != 0:
132
+ offset = align - offset
133
+ # Note: slices producing 0-size arrays do not necessarily change
134
+ # data pointer --- so we use and allocate size+1
135
+ buf = buf[offset:offset+size+1][:-1]
136
+ data = np.ndarray(shape, dtype, buf, order=order)
137
+ data.fill(0)
138
+ return data
139
+
140
+
141
+ def _prune_array(array):
142
+ """Return an array equivalent to the input array. If the input
143
+ array is a view of a much larger array, copy its contents to a
144
+ newly allocated array. Otherwise, return the input unchanged.
145
+ """
146
+ if array.base is not None and array.size < array.base.size // 2:
147
+ return array.copy()
148
+ return array
149
+
150
+
151
+ def float_factorial(n: int) -> float:
152
+ """Compute the factorial and return as a float
153
+
154
+ Returns infinity when result is too large for a double
155
+ """
156
+ return float(math.factorial(n)) if n < 171 else np.inf
157
+
158
+
159
+ _rng_desc = (
160
+ r"""If `rng` is passed by keyword, types other than `numpy.random.Generator` are
161
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
162
+ If `rng` is already a ``Generator`` instance, then the provided instance is
163
+ used. Specify `rng` for repeatable function behavior.
164
+
165
+ If this argument is passed by position or `{old_name}` is passed by keyword,
166
+ legacy behavior for the argument `{old_name}` applies:
167
+
168
+ - If `{old_name}` is None (or `numpy.random`), the `numpy.random.RandomState`
169
+ singleton is used.
170
+ - If `{old_name}` is an int, a new ``RandomState`` instance is used,
171
+ seeded with `{old_name}`.
172
+ - If `{old_name}` is already a ``Generator`` or ``RandomState`` instance then
173
+ that instance is used.
174
+
175
+ .. versionchanged:: 1.15.0
176
+ As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
177
+ transition from use of `numpy.random.RandomState` to
178
+ `numpy.random.Generator`, this keyword was changed from `{old_name}` to `rng`.
179
+ For an interim period, both keywords will continue to work, although only one
180
+ may be specified at a time. After the interim period, function calls using the
181
+ `{old_name}` keyword will emit warnings. The behavior of both `{old_name}` and
182
+ `rng` are outlined above, but only the `rng` keyword should be used in new code.
183
+ """
184
+ )
185
+
186
+
187
+ # SPEC 7
188
+ def _transition_to_rng(old_name, *, position_num=None, end_version=None,
189
+ replace_doc=True):
190
+ """Example decorator to transition from old PRNG usage to new `rng` behavior
191
+
192
+ Suppose the decorator is applied to a function that used to accept parameter
193
+ `old_name='random_state'` either by keyword or as a positional argument at
194
+ `position_num=1`. At the time of application, the name of the argument in the
195
+ function signature is manually changed to the new name, `rng`. If positional
196
+ use was allowed before, this is not changed.*
197
+
198
+ - If the function is called with both `random_state` and `rng`, the decorator
199
+ raises an error.
200
+ - If `random_state` is provided as a keyword argument, the decorator passes
201
+ `random_state` to the function's `rng` argument as a keyword. If `end_version`
202
+ is specified, the decorator will emit a `DeprecationWarning` about the
203
+ deprecation of keyword `random_state`.
204
+ - If `random_state` is provided as a positional argument, the decorator passes
205
+ `random_state` to the function's `rng` argument by position. If `end_version`
206
+ is specified, the decorator will emit a `FutureWarning` about the changing
207
+ interpretation of the argument.
208
+ - If `rng` is provided as a keyword argument, the decorator validates `rng` using
209
+ `numpy.random.default_rng` before passing it to the function.
210
+ - If `end_version` is specified and neither `random_state` nor `rng` is provided
211
+ by the user, the decorator checks whether `np.random.seed` has been used to set
212
+ the global seed. If so, it emits a `FutureWarning`, noting that usage of
213
+ `numpy.random.seed` will eventually have no effect. Either way, the decorator
214
+ calls the function without explicitly passing the `rng` argument.
215
+
216
+ If `end_version` is specified, a user must pass `rng` as a keyword to avoid
217
+ warnings.
218
+
219
+ After the deprecation period, the decorator can be removed, and the function
220
+ can simply validate the `rng` argument by calling `np.random.default_rng(rng)`.
221
+
222
+ * A `FutureWarning` is emitted when the PRNG argument is used by
223
+ position. It indicates that the "Hinsen principle" (same
224
+ code yielding different results in two versions of the software)
225
+ will be violated, unless positional use is deprecated. Specifically:
226
+
227
+ - If `None` is passed by position and `np.random.seed` has been used,
228
+ the function will change from being seeded to being unseeded.
229
+ - If an integer is passed by position, the random stream will change.
230
+ - If `np.random` or an instance of `RandomState` is passed by position,
231
+ an error will be raised.
232
+
233
+ We suggest that projects consider deprecating positional use of
234
+ `random_state`/`rng` (i.e., change their function signatures to
235
+ ``def my_func(..., *, rng=None)``); that might not make sense
236
+ for all projects, so this SPEC does not make that
237
+ recommendation, neither does this decorator enforce it.
238
+
239
+ Parameters
240
+ ----------
241
+ old_name : str
242
+ The old name of the PRNG argument (e.g. `seed` or `random_state`).
243
+ position_num : int, optional
244
+ The (0-indexed) position of the old PRNG argument (if accepted by position).
245
+ Maintainers are welcome to eliminate this argument and use, for example,
246
+ `inspect`, if preferred.
247
+ end_version : str, optional
248
+ The full version number of the library when the behavior described in
249
+ `DeprecationWarning`s and `FutureWarning`s will take effect. If left
250
+ unspecified, no warnings will be emitted by the decorator.
251
+ replace_doc : bool, default: True
252
+ Whether the decorator should replace the documentation for parameter `rng` with
253
+ `_rng_desc` (defined above), which documents both new `rng` keyword behavior
254
+ and typical legacy `random_state`/`seed` behavior. If True, manually replace
255
+ the first paragraph of the function's old `random_state`/`seed` documentation
256
+ with the desired *final* `rng` documentation; this way, no changes to
257
+ documentation are needed when the decorator is removed. Documentation of `rng`
258
+ after the first blank line is preserved. Use False if the function's old
259
+ `random_state`/`seed` behavior does not match that described by `_rng_desc`.
260
+
261
+ """
262
+ NEW_NAME = "rng"
263
+
264
+ cmn_msg = (
265
+ "To silence this warning and ensure consistent behavior in SciPy "
266
+ f"{end_version}, control the RNG using argument `{NEW_NAME}`. Arguments passed "
267
+ f"to keyword `{NEW_NAME}` will be validated by `np.random.default_rng`, so the "
268
+ "behavior corresponding with a given value may change compared to use of "
269
+ f"`{old_name}`. For example, "
270
+ "1) `None` will result in unpredictable random numbers, "
271
+ "2) an integer will result in a different stream of random numbers, (with the "
272
+ "same distribution), and "
273
+ "3) `np.random` or `RandomState` instances will result in an error. "
274
+ "See the documentation of `default_rng` for more information."
275
+ )
276
+
277
+ def decorator(fun):
278
+ @functools.wraps(fun)
279
+ def wrapper(*args, **kwargs):
280
+ # Determine how PRNG was passed
281
+ as_old_kwarg = old_name in kwargs
282
+ as_new_kwarg = NEW_NAME in kwargs
283
+ as_pos_arg = position_num is not None and len(args) >= position_num + 1
284
+ emit_warning = end_version is not None
285
+
286
+ # Can only specify PRNG one of the three ways
287
+ if int(as_old_kwarg) + int(as_new_kwarg) + int(as_pos_arg) > 1:
288
+ message = (
289
+ f"{fun.__name__}() got multiple values for "
290
+ f"argument now known as `{NEW_NAME}`. Specify one of "
291
+ f"`{NEW_NAME}` or `{old_name}`."
292
+ )
293
+ raise TypeError(message)
294
+
295
+ # Check whether global random state has been set
296
+ global_seed_set = np.random.mtrand._rand._bit_generator._seed_seq is None
297
+
298
+ if as_old_kwarg: # warn about deprecated use of old kwarg
299
+ kwargs[NEW_NAME] = kwargs.pop(old_name)
300
+ if emit_warning:
301
+ message = (
302
+ f"Use of keyword argument `{old_name}` is "
303
+ f"deprecated and replaced by `{NEW_NAME}`. "
304
+ f"Support for `{old_name}` will be removed "
305
+ f"in SciPy {end_version}. "
306
+ ) + cmn_msg
307
+ warnings.warn(message, DeprecationWarning, stacklevel=2)
308
+
309
+ elif as_pos_arg:
310
+ # Warn about changing meaning of positional arg
311
+
312
+ # Note that this decorator does not deprecate positional use of the
313
+ # argument; it only warns that the behavior will change in the future.
314
+ # Simultaneously transitioning to keyword-only use is another option.
315
+
316
+ arg = args[position_num]
317
+ # If the argument is None and the global seed wasn't set, or if the
318
+ # argument is one of a few new classes, the user will not notice change
319
+ # in behavior.
320
+ ok_classes = (
321
+ np.random.Generator,
322
+ np.random.SeedSequence,
323
+ np.random.BitGenerator,
324
+ )
325
+ if (arg is None and not global_seed_set) or isinstance(arg, ok_classes):
326
+ pass
327
+ elif emit_warning:
328
+ message = (
329
+ f"Positional use of `{NEW_NAME}` (formerly known as "
330
+ f"`{old_name}`) is still allowed, but the behavior is "
331
+ "changing: the argument will be normalized using "
332
+ f"`np.random.default_rng` beginning in SciPy {end_version}, "
333
+ "and the resulting `Generator` will be used to generate "
334
+ "random numbers."
335
+ ) + cmn_msg
336
+ warnings.warn(message, FutureWarning, stacklevel=2)
337
+
338
+ elif as_new_kwarg: # no warnings; this is the preferred use
339
+ # After the removal of the decorator, normalization with
340
+ # np.random.default_rng will be done inside the decorated function
341
+ kwargs[NEW_NAME] = np.random.default_rng(kwargs[NEW_NAME])
342
+
343
+ elif global_seed_set and emit_warning:
344
+ # Emit FutureWarning if `np.random.seed` was used and no PRNG was passed
345
+ message = (
346
+ "The NumPy global RNG was seeded by calling "
347
+ f"`np.random.seed`. Beginning in {end_version}, this "
348
+ "function will no longer use the global RNG."
349
+ ) + cmn_msg
350
+ warnings.warn(message, FutureWarning, stacklevel=2)
351
+
352
+ return fun(*args, **kwargs)
353
+
354
+ # Add the old parameter name to the function signature
355
+ wrapped_signature = inspect.signature(fun)
356
+ wrapper.__signature__ = wrapped_signature.replace(parameters=[
357
+ *wrapped_signature.parameters.values(),
358
+ inspect.Parameter(old_name, inspect.Parameter.KEYWORD_ONLY, default=None),
359
+ ])
360
+
361
+ if replace_doc:
362
+ doc = FunctionDoc(wrapper)
363
+ parameter_names = [param.name for param in doc['Parameters']]
364
+ if 'rng' in parameter_names:
365
+ _type = "{None, int, `numpy.random.Generator`}, optional"
366
+ _desc = _rng_desc.replace("{old_name}", old_name)
367
+ old_doc = doc['Parameters'][parameter_names.index('rng')].desc
368
+ old_doc_keep = old_doc[old_doc.index("") + 1:] if "" in old_doc else []
369
+ new_doc = [_desc] + old_doc_keep
370
+ _rng_parameter_doc = Parameter('rng', _type, new_doc)
371
+ doc['Parameters'][parameter_names.index('rng')] = _rng_parameter_doc
372
+ doc = str(doc).split("\n", 1)[1] # remove signature
373
+ wrapper.__doc__ = str(doc)
374
+ return wrapper
375
+
376
+ return decorator
377
+
378
+
379
+ # copy-pasted from scikit-learn utils/validation.py
380
+ def check_random_state(seed):
381
+ """Turn `seed` into a `np.random.RandomState` instance.
382
+
383
+ Parameters
384
+ ----------
385
+ seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
386
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
387
+ singleton is used.
388
+ If `seed` is an int, a new ``RandomState`` instance is used,
389
+ seeded with `seed`.
390
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
391
+ that instance is used.
392
+
393
+ Returns
394
+ -------
395
+ seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
396
+ Random number generator.
397
+
398
+ """
399
+ if seed is None or seed is np.random:
400
+ return np.random.mtrand._rand
401
+ if isinstance(seed, numbers.Integral | np.integer):
402
+ return np.random.RandomState(seed)
403
+ if isinstance(seed, np.random.RandomState | np.random.Generator):
404
+ return seed
405
+
406
+ raise ValueError(f"'{seed}' cannot be used to seed a numpy.random.RandomState"
407
+ " instance")
408
+
409
+
410
+ def _asarray_validated(a, check_finite=True,
411
+ sparse_ok=False, objects_ok=False, mask_ok=False,
412
+ as_inexact=False):
413
+ """
414
+ Helper function for SciPy argument validation.
415
+
416
+ Many SciPy linear algebra functions do support arbitrary array-like
417
+ input arguments. Examples of commonly unsupported inputs include
418
+ matrices containing inf/nan, sparse matrix representations, and
419
+ matrices with complicated elements.
420
+
421
+ Parameters
422
+ ----------
423
+ a : array_like
424
+ The array-like input.
425
+ check_finite : bool, optional
426
+ Whether to check that the input matrices contain only finite numbers.
427
+ Disabling may give a performance gain, but may result in problems
428
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
429
+ Default: True
430
+ sparse_ok : bool, optional
431
+ True if scipy sparse matrices are allowed.
432
+ objects_ok : bool, optional
433
+ True if arrays with dype('O') are allowed.
434
+ mask_ok : bool, optional
435
+ True if masked arrays are allowed.
436
+ as_inexact : bool, optional
437
+ True to convert the input array to a np.inexact dtype.
438
+
439
+ Returns
440
+ -------
441
+ ret : ndarray
442
+ The converted validated array.
443
+
444
+ """
445
+ if not sparse_ok:
446
+ if issparse(a):
447
+ msg = ('Sparse arrays/matrices are not supported by this function. '
448
+ 'Perhaps one of the `scipy.sparse.linalg` functions '
449
+ 'would work instead.')
450
+ raise ValueError(msg)
451
+ if not mask_ok:
452
+ if np.ma.isMaskedArray(a):
453
+ raise ValueError('masked arrays are not supported')
454
+ toarray = np.asarray_chkfinite if check_finite else np.asarray
455
+ a = toarray(a)
456
+ if not objects_ok:
457
+ if a.dtype is np.dtype('O'):
458
+ raise ValueError('object arrays are not supported')
459
+ if as_inexact:
460
+ if not np.issubdtype(a.dtype, np.inexact):
461
+ a = toarray(a, dtype=np.float64)
462
+ return a
463
+
464
+
465
+ def _validate_int(k, name, minimum=None):
466
+ """
467
+ Validate a scalar integer.
468
+
469
+ This function can be used to validate an argument to a function
470
+ that expects the value to be an integer. It uses `operator.index`
471
+ to validate the value (so, for example, k=2.0 results in a
472
+ TypeError).
473
+
474
+ Parameters
475
+ ----------
476
+ k : int
477
+ The value to be validated.
478
+ name : str
479
+ The name of the parameter.
480
+ minimum : int, optional
481
+ An optional lower bound.
482
+ """
483
+ try:
484
+ k = operator.index(k)
485
+ except TypeError:
486
+ raise TypeError(f'{name} must be an integer.') from None
487
+ if minimum is not None and k < minimum:
488
+ raise ValueError(f'{name} must be an integer not less '
489
+ f'than {minimum}') from None
490
+ return k
491
+
492
+
493
+ # Add a replacement for inspect.getfullargspec()/
494
+ # The version below is borrowed from Django,
495
+ # https://github.com/django/django/pull/4846.
496
+
497
+ # Note an inconsistency between inspect.getfullargspec(func) and
498
+ # inspect.signature(func). If `func` is a bound method, the latter does *not*
499
+ # list `self` as a first argument, while the former *does*.
500
+ # Hence, cook up a common ground replacement: `getfullargspec_no_self` which
501
+ # mimics `inspect.getfullargspec` but does not list `self`.
502
+ #
503
+ # This way, the caller code does not need to know whether it uses a legacy
504
+ # .getfullargspec or a bright and shiny .signature.
505
+
506
+ FullArgSpec = namedtuple('FullArgSpec',
507
+ ['args', 'varargs', 'varkw', 'defaults',
508
+ 'kwonlyargs', 'kwonlydefaults', 'annotations'])
509
+
510
+
511
+ def getfullargspec_no_self(func):
512
+ """inspect.getfullargspec replacement using inspect.signature.
513
+
514
+ If func is a bound method, do not list the 'self' parameter.
515
+
516
+ Parameters
517
+ ----------
518
+ func : callable
519
+ A callable to inspect
520
+
521
+ Returns
522
+ -------
523
+ fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
524
+ kwonlydefaults, annotations)
525
+
526
+ NOTE: if the first argument of `func` is self, it is *not*, I repeat
527
+ *not*, included in fullargspec.args.
528
+ This is done for consistency between inspect.getargspec() under
529
+ Python 2.x, and inspect.signature() under Python 3.x.
530
+
531
+ """
532
+ sig = inspect.signature(func)
533
+ args = [
534
+ p.name for p in sig.parameters.values()
535
+ if p.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD,
536
+ inspect.Parameter.POSITIONAL_ONLY]
537
+ ]
538
+ varargs = [
539
+ p.name for p in sig.parameters.values()
540
+ if p.kind == inspect.Parameter.VAR_POSITIONAL
541
+ ]
542
+ varargs = varargs[0] if varargs else None
543
+ varkw = [
544
+ p.name for p in sig.parameters.values()
545
+ if p.kind == inspect.Parameter.VAR_KEYWORD
546
+ ]
547
+ varkw = varkw[0] if varkw else None
548
+ defaults = tuple(
549
+ p.default for p in sig.parameters.values()
550
+ if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and
551
+ p.default is not p.empty)
552
+ ) or None
553
+ kwonlyargs = [
554
+ p.name for p in sig.parameters.values()
555
+ if p.kind == inspect.Parameter.KEYWORD_ONLY
556
+ ]
557
+ kwdefaults = {p.name: p.default for p in sig.parameters.values()
558
+ if p.kind == inspect.Parameter.KEYWORD_ONLY and
559
+ p.default is not p.empty}
560
+ annotations = {p.name: p.annotation for p in sig.parameters.values()
561
+ if p.annotation is not p.empty}
562
+ return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
563
+ kwdefaults or None, annotations)
564
+
565
+
566
+ class _FunctionWrapper:
567
+ """
568
+ Object to wrap user's function, allowing picklability
569
+ """
570
+ def __init__(self, f, args):
571
+ self.f = f
572
+ self.args = [] if args is None else args
573
+
574
+ def __call__(self, x):
575
+ return self.f(x, *self.args)
576
+
577
+
578
+ class _ScalarFunctionWrapper:
579
+ """
580
+ Object to wrap scalar user function, allowing picklability
581
+ """
582
+ def __init__(self, f, args=None):
583
+ self.f = f
584
+ self.args = [] if args is None else args
585
+ self.nfev = 0
586
+
587
+ def __call__(self, x):
588
+ # Send a copy because the user may overwrite it.
589
+ # The user of this class might want `x` to remain unchanged.
590
+ fx = self.f(np.copy(x), *self.args)
591
+ self.nfev += 1
592
+
593
+ # Make sure the function returns a true scalar
594
+ if not np.isscalar(fx):
595
+ try:
596
+ fx = np.asarray(fx).item()
597
+ except (TypeError, ValueError) as e:
598
+ raise ValueError(
599
+ "The user-provided objective function "
600
+ "must return a scalar value."
601
+ ) from e
602
+ return fx
603
+
604
+ class MapWrapper:
605
+ """
606
+ Parallelisation wrapper for working with map-like callables, such as
607
+ `multiprocessing.Pool.map`.
608
+
609
+ Parameters
610
+ ----------
611
+ pool : int or map-like callable
612
+ If `pool` is an integer, then it specifies the number of threads to
613
+ use for parallelization. If ``int(pool) == 1``, then no parallel
614
+ processing is used and the map builtin is used.
615
+ If ``pool == -1``, then the pool will utilize all available CPUs.
616
+ If `pool` is a map-like callable that follows the same
617
+ calling sequence as the built-in map function, then this callable is
618
+ used for parallelization.
619
+ """
620
+ def __init__(self, pool=1):
621
+ self.pool = None
622
+ self._mapfunc = map
623
+ self._own_pool = False
624
+
625
+ if callable(pool):
626
+ self.pool = pool
627
+ self._mapfunc = self.pool
628
+ else:
629
+ from multiprocessing import Pool
630
+ # user supplies a number
631
+ if int(pool) == -1:
632
+ # use as many processors as possible
633
+ self.pool = Pool()
634
+ self._mapfunc = self.pool.map
635
+ self._own_pool = True
636
+ elif int(pool) == 1:
637
+ pass
638
+ elif int(pool) > 1:
639
+ # use the number of processors requested
640
+ self.pool = Pool(processes=int(pool))
641
+ self._mapfunc = self.pool.map
642
+ self._own_pool = True
643
+ else:
644
+ raise RuntimeError("Number of workers specified must be -1,"
645
+ " an int >= 1, or an object with a 'map' "
646
+ "method")
647
+
648
+ def __enter__(self):
649
+ return self
650
+
651
+ def terminate(self):
652
+ if self._own_pool:
653
+ self.pool.terminate()
654
+
655
+ def join(self):
656
+ if self._own_pool:
657
+ self.pool.join()
658
+
659
+ def close(self):
660
+ if self._own_pool:
661
+ self.pool.close()
662
+
663
+ def __exit__(self, exc_type, exc_value, traceback):
664
+ if self._own_pool:
665
+ self.pool.close()
666
+ self.pool.terminate()
667
+
668
+ def __call__(self, func, iterable):
669
+ # only accept one iterable because that's all Pool.map accepts
670
+ try:
671
+ return self._mapfunc(func, iterable)
672
+ except TypeError as e:
673
+ # wrong number of arguments
674
+ raise TypeError("The map-like callable must be of the"
675
+ " form f(func, iterable)") from e
676
+
677
+
678
+ def _workers_wrapper(func):
679
+ """
680
+ Wrapper to deal with setup-cleanup of workers outside a user function via a
681
+ ContextManager. It saves having to do the setup/tear down with within that
682
+ function, which can be messy.
683
+ """
684
+ @functools.wraps(func)
685
+ def inner(*args, **kwds):
686
+ kwargs = kwds.copy()
687
+ if 'workers' not in kwargs:
688
+ _workers = map
689
+ elif 'workers' in kwargs and kwargs['workers'] is None:
690
+ _workers = map
691
+ else:
692
+ _workers = kwargs['workers']
693
+
694
+ with MapWrapper(_workers) as mf:
695
+ kwargs['workers'] = mf
696
+ return func(*args, **kwargs)
697
+
698
+ return inner
699
+
700
+
701
+ def rng_integers(gen, low, high=None, size=None, dtype='int64',
702
+ endpoint=False):
703
+ """
704
+ Return random integers from low (inclusive) to high (exclusive), or if
705
+ endpoint=True, low (inclusive) to high (inclusive). Replaces
706
+ `RandomState.randint` (with endpoint=False) and
707
+ `RandomState.random_integers` (with endpoint=True).
708
+
709
+ Return random integers from the "discrete uniform" distribution of the
710
+ specified dtype. If high is None (the default), then results are from
711
+ 0 to low.
712
+
713
+ Parameters
714
+ ----------
715
+ gen : {None, np.random.RandomState, np.random.Generator}
716
+ Random number generator. If None, then the np.random.RandomState
717
+ singleton is used.
718
+ low : int or array-like of ints
719
+ Lowest (signed) integers to be drawn from the distribution (unless
720
+ high=None, in which case this parameter is 0 and this value is used
721
+ for high).
722
+ high : int or array-like of ints
723
+ If provided, one above the largest (signed) integer to be drawn from
724
+ the distribution (see above for behavior if high=None). If array-like,
725
+ must contain integer values.
726
+ size : array-like of ints, optional
727
+ Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
728
+ samples are drawn. Default is None, in which case a single value is
729
+ returned.
730
+ dtype : {str, dtype}, optional
731
+ Desired dtype of the result. All dtypes are determined by their name,
732
+ i.e., 'int64', 'int', etc, so byteorder is not available and a specific
733
+ precision may have different C types depending on the platform.
734
+ The default value is 'int64'.
735
+ endpoint : bool, optional
736
+ If True, sample from the interval [low, high] instead of the default
737
+ [low, high) Defaults to False.
738
+
739
+ Returns
740
+ -------
741
+ out: int or ndarray of ints
742
+ size-shaped array of random integers from the appropriate distribution,
743
+ or a single such random int if size not provided.
744
+ """
745
+ if isinstance(gen, Generator):
746
+ return gen.integers(low, high=high, size=size, dtype=dtype,
747
+ endpoint=endpoint)
748
+ else:
749
+ if gen is None:
750
+ # default is RandomState singleton used by np.random.
751
+ gen = np.random.mtrand._rand
752
+ if endpoint:
753
+ # inclusive of endpoint
754
+ # remember that low and high can be arrays, so don't modify in
755
+ # place
756
+ if high is None:
757
+ return gen.randint(low + 1, size=size, dtype=dtype)
758
+ if high is not None:
759
+ return gen.randint(low, high=high + 1, size=size, dtype=dtype)
760
+
761
+ # exclusive
762
+ return gen.randint(low, high=high, size=size, dtype=dtype)
763
+
764
+
765
+ @contextmanager
766
+ def _fixed_default_rng(seed=1638083107694713882823079058616272161):
767
+ """Context with a fixed np.random.default_rng seed."""
768
+ orig_fun = np.random.default_rng
769
+ np.random.default_rng = lambda seed=seed: orig_fun(seed)
770
+ try:
771
+ yield
772
+ finally:
773
+ np.random.default_rng = orig_fun
774
+
775
+
776
+ def _rng_html_rewrite(func):
777
+ """Rewrite the HTML rendering of ``np.random.default_rng``.
778
+
779
+ This is intended to decorate
780
+ ``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.
781
+
782
+ Examples are only run by Sphinx when there are plot involved. Even so,
783
+ it does not change the result values getting printed.
784
+ """
785
+ # hexadecimal or number seed, case-insensitive
786
+ pattern = re.compile(r'np.random.default_rng\((0x[0-9A-F]+|\d+)\)', re.I)
787
+
788
+ def _wrapped(*args, **kwargs):
789
+ res = func(*args, **kwargs)
790
+ lines = [
791
+ re.sub(pattern, 'np.random.default_rng()', line)
792
+ for line in res
793
+ ]
794
+ return lines
795
+
796
+ return _wrapped
797
+
798
+
799
+ def _argmin(a, keepdims=False, axis=None):
800
+ """
801
+ argmin with a `keepdims` parameter.
802
+
803
+ See https://github.com/numpy/numpy/issues/8710
804
+
805
+ If axis is not None, a.shape[axis] must be greater than 0.
806
+ """
807
+ res = np.argmin(a, axis=axis)
808
+ if keepdims and axis is not None:
809
+ res = np.expand_dims(res, axis=axis)
810
+ return res
811
+
812
+
813
+ def _first_nonnan(a, axis):
814
+ """
815
+ Return the first non-nan value along the given axis.
816
+
817
+ If a slice is all nan, nan is returned for that slice.
818
+
819
+ The shape of the return value corresponds to ``keepdims=True``.
820
+
821
+ Examples
822
+ --------
823
+ >>> import numpy as np
824
+ >>> nan = np.nan
825
+ >>> a = np.array([[ 3., 3., nan, 3.],
826
+ [ 1., nan, 2., 4.],
827
+ [nan, nan, 9., -1.],
828
+ [nan, 5., 4., 3.],
829
+ [ 2., 2., 2., 2.],
830
+ [nan, nan, nan, nan]])
831
+ >>> _first_nonnan(a, axis=0)
832
+ array([[3., 3., 2., 3.]])
833
+ >>> _first_nonnan(a, axis=1)
834
+ array([[ 3.],
835
+ [ 1.],
836
+ [ 9.],
837
+ [ 5.],
838
+ [ 2.],
839
+ [nan]])
840
+ """
841
+ k = _argmin(np.isnan(a), axis=axis, keepdims=True)
842
+ return np.take_along_axis(a, k, axis=axis)
843
+
844
+
845
+ def _nan_allsame(a, axis, keepdims=False):
846
+ """
847
+ Determine if the values along an axis are all the same.
848
+
849
+ nan values are ignored.
850
+
851
+ `a` must be a numpy array.
852
+
853
+ `axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.
854
+
855
+ For an axis of length 0, the result is True. That is, we adopt the
856
+ convention that ``allsame([])`` is True. (There are no values in the
857
+ input that are different.)
858
+
859
+ `True` is returned for slices that are all nan--not because all the
860
+ values are the same, but because this is equivalent to ``allsame([])``.
861
+
862
+ Examples
863
+ --------
864
+ >>> from numpy import nan, array
865
+ >>> a = array([[ 3., 3., nan, 3.],
866
+ ... [ 1., nan, 2., 4.],
867
+ ... [nan, nan, 9., -1.],
868
+ ... [nan, 5., 4., 3.],
869
+ ... [ 2., 2., 2., 2.],
870
+ ... [nan, nan, nan, nan]])
871
+ >>> _nan_allsame(a, axis=1, keepdims=True)
872
+ array([[ True],
873
+ [False],
874
+ [False],
875
+ [False],
876
+ [ True],
877
+ [ True]])
878
+ """
879
+ if axis is None:
880
+ if a.size == 0:
881
+ return True
882
+ a = a.ravel()
883
+ axis = 0
884
+ else:
885
+ shp = a.shape
886
+ if shp[axis] == 0:
887
+ shp = shp[:axis] + (1,)*keepdims + shp[axis + 1:]
888
+ return np.full(shp, fill_value=True, dtype=bool)
889
+ a0 = _first_nonnan(a, axis=axis)
890
+ return ((a0 == a) | np.isnan(a)).all(axis=axis, keepdims=keepdims)
891
+
892
+
893
+ def _contains_nan(
894
+ a: Array,
895
+ nan_policy: Literal["propagate", "raise", "omit"] = "propagate",
896
+ *,
897
+ xp_omit_okay: bool = False,
898
+ xp: ModuleType | None = None,
899
+ ) -> Array | bool:
900
+ # Regarding `xp_omit_okay`: Temporarily, while `_axis_nan_policy` does not
901
+ # handle non-NumPy arrays, most functions that call `_contains_nan` want
902
+ # it to raise an error if `nan_policy='omit'` and `xp` is not `np`.
903
+ # Some functions support `nan_policy='omit'` natively, so setting this to
904
+ # `True` prevents the error from being raised.
905
+ policies = {"propagate", "raise", "omit"}
906
+ if nan_policy not in policies:
907
+ msg = f"nan_policy must be one of {policies}."
908
+ raise ValueError(msg)
909
+
910
+ if xp_size(a) == 0:
911
+ return False
912
+
913
+ if xp is None:
914
+ xp = array_namespace(a)
915
+
916
+ if xp.isdtype(a.dtype, "real floating"):
917
+ # Faster and less memory-intensive than xp.any(xp.isnan(a)), and unlike other
918
+ # reductions, `max`/`min` won't return NaN unless there is a NaN in the data.
919
+ contains_nan = xp.isnan(xp.max(a))
920
+ elif xp.isdtype(a.dtype, "complex floating"):
921
+ # Typically `real` and `imag` produce views; otherwise, `xp.any(xp.isnan(a))`
922
+ # would be more efficient.
923
+ contains_nan = xp.isnan(xp.max(xp.real(a))) | xp.isnan(xp.max(xp.imag(a)))
924
+ elif is_numpy(xp) and np.issubdtype(a.dtype, object):
925
+ contains_nan = False
926
+ for el in a.ravel():
927
+ # isnan doesn't work on non-numeric elements
928
+ if np.issubdtype(type(el), np.number) and np.isnan(el):
929
+ contains_nan = True
930
+ break
931
+ else:
932
+ # Only `object` and `inexact` arrays can have NaNs
933
+ return False
934
+
935
+ # The implicit call to bool(contains_nan) must happen after testing
936
+ # nan_policy to prevent lazy and device-bound xps from raising in the
937
+ # default policy='propagate' case.
938
+ if nan_policy == 'raise':
939
+ if is_lazy_array(a):
940
+ msg = "nan_policy='raise' is not supported for lazy arrays."
941
+ raise TypeError(msg)
942
+ if contains_nan:
943
+ msg = "The input contains nan values"
944
+ raise ValueError(msg)
945
+ elif nan_policy == 'omit' and not xp_omit_okay and not is_numpy(xp):
946
+ if is_lazy_array(a):
947
+ msg = "nan_policy='omit' is not supported for lazy arrays."
948
+ raise TypeError(msg)
949
+ if contains_nan:
950
+ msg = "nan_policy='omit' is incompatible with non-NumPy arrays."
951
+ raise ValueError(msg)
952
+
953
+ return contains_nan
954
+
955
+
956
+ def _rename_parameter(old_name, new_name, dep_version=None):
957
+ """
958
+ Generate decorator for backward-compatible keyword renaming.
959
+
960
+ Apply the decorator generated by `_rename_parameter` to functions with a
961
+ recently renamed parameter to maintain backward-compatibility.
962
+
963
+ After decoration, the function behaves as follows:
964
+ If only the new parameter is passed into the function, behave as usual.
965
+ If only the old parameter is passed into the function (as a keyword), raise
966
+ a DeprecationWarning if `dep_version` is provided, and behave as usual
967
+ otherwise.
968
+ If both old and new parameters are passed into the function, raise a
969
+ DeprecationWarning if `dep_version` is provided, and raise the appropriate
970
+ TypeError (function got multiple values for argument).
971
+
972
+ Parameters
973
+ ----------
974
+ old_name : str
975
+ Old name of parameter
976
+ new_name : str
977
+ New name of parameter
978
+ dep_version : str, optional
979
+ Version of SciPy in which old parameter was deprecated in the format
980
+ 'X.Y.Z'. If supplied, the deprecation message will indicate that
981
+ support for the old parameter will be removed in version 'X.Y+2.Z'
982
+
983
+ Notes
984
+ -----
985
+ Untested with functions that accept *args. Probably won't work as written.
986
+
987
+ """
988
+ def decorator(fun):
989
+ @functools.wraps(fun)
990
+ def wrapper(*args, **kwargs):
991
+ if old_name in kwargs:
992
+ if dep_version:
993
+ end_version = dep_version.split('.')
994
+ end_version[1] = str(int(end_version[1]) + 2)
995
+ end_version = '.'.join(end_version)
996
+ message = (f"Use of keyword argument `{old_name}` is "
997
+ f"deprecated and replaced by `{new_name}`. "
998
+ f"Support for `{old_name}` will be removed "
999
+ f"in SciPy {end_version}.")
1000
+ warnings.warn(message, DeprecationWarning, stacklevel=2)
1001
+ if new_name in kwargs:
1002
+ message = (f"{fun.__name__}() got multiple values for "
1003
+ f"argument now known as `{new_name}`")
1004
+ raise TypeError(message)
1005
+ kwargs[new_name] = kwargs.pop(old_name)
1006
+ return fun(*args, **kwargs)
1007
+ return wrapper
1008
+ return decorator
1009
+
1010
+
1011
+ def _rng_spawn(rng, n_children):
1012
+ # spawns independent RNGs from a parent RNG
1013
+ bg = rng._bit_generator
1014
+ ss = bg._seed_seq
1015
+ child_rngs = [np.random.Generator(type(bg)(child_ss))
1016
+ for child_ss in ss.spawn(n_children)]
1017
+ return child_rngs
1018
+
1019
+
1020
+ def _get_nan(*data, shape=(), xp=None):
1021
+ xp = array_namespace(*data) if xp is None else xp
1022
+ # Get NaN of appropriate dtype for data
1023
+ dtype = xp_result_type(*data, force_floating=True, xp=xp)
1024
+ device = xp_result_device(*data)
1025
+ res = xp.full(shape, xp.nan, dtype=dtype, device=device)
1026
+ if not shape:
1027
+ res = res[()]
1028
+ # whenever mdhaber/marray#89 is resolved, could just return `res`
1029
+ return res.data if is_marray(xp) else res
1030
+
1031
+
1032
+ def normalize_axis_index(axis, ndim):
1033
+ # Check if `axis` is in the correct range and normalize it
1034
+ if axis < -ndim or axis >= ndim:
1035
+ msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
1036
+ raise AxisError(msg)
1037
+
1038
+ if axis < 0:
1039
+ axis = axis + ndim
1040
+ return axis
1041
+
1042
+
1043
+ def _call_callback_maybe_halt(callback, res):
1044
+ """Call wrapped callback; return True if algorithm should stop.
1045
+
1046
+ Parameters
1047
+ ----------
1048
+ callback : callable or None
1049
+ A user-provided callback wrapped with `_wrap_callback`
1050
+ res : OptimizeResult
1051
+ Information about the current iterate
1052
+
1053
+ Returns
1054
+ -------
1055
+ halt : bool
1056
+ True if minimization should stop
1057
+
1058
+ """
1059
+ if callback is None:
1060
+ return False
1061
+ try:
1062
+ callback(res)
1063
+ return False
1064
+ except StopIteration:
1065
+ callback.stop_iteration = True
1066
+ return True
1067
+
1068
+
1069
+ class _RichResult(dict):
1070
+ """ Container for multiple outputs with pretty-printing """
1071
+ def __getattr__(self, name):
1072
+ try:
1073
+ return self[name]
1074
+ except KeyError as e:
1075
+ raise AttributeError(name) from e
1076
+
1077
+ __setattr__ = dict.__setitem__ # type: ignore[assignment]
1078
+ __delattr__ = dict.__delitem__ # type: ignore[assignment]
1079
+
1080
+ def __repr__(self):
1081
+ order_keys = ['message', 'success', 'status', 'fun', 'funl', 'x', 'xl',
1082
+ 'col_ind', 'nit', 'lower', 'upper', 'eqlin', 'ineqlin',
1083
+ 'converged', 'flag', 'function_calls', 'iterations',
1084
+ 'root']
1085
+ order_keys = getattr(self, '_order_keys', order_keys)
1086
+ # 'slack', 'con' are redundant with residuals
1087
+ # 'crossover_nit' is probably not interesting to most users
1088
+ omit_keys = {'slack', 'con', 'crossover_nit', '_order_keys'}
1089
+
1090
+ def key(item):
1091
+ try:
1092
+ return order_keys.index(item[0].lower())
1093
+ except ValueError: # item not in list
1094
+ return np.inf
1095
+
1096
+ def omit_redundant(items):
1097
+ for item in items:
1098
+ if item[0] in omit_keys:
1099
+ continue
1100
+ yield item
1101
+
1102
+ def item_sorter(d):
1103
+ return sorted(omit_redundant(d.items()), key=key)
1104
+
1105
+ if self.keys():
1106
+ return _dict_formatter(self, sorter=item_sorter)
1107
+ else:
1108
+ return self.__class__.__name__ + "()"
1109
+
1110
+ def __dir__(self):
1111
+ return list(self.keys())
1112
+
1113
+
1114
+ def _indenter(s, n=0):
1115
+ """
1116
+ Ensures that lines after the first are indented by the specified amount
1117
+ """
1118
+ split = s.split("\n")
1119
+ indent = " "*n
1120
+ return ("\n" + indent).join(split)
1121
+
1122
+
1123
+ def _float_formatter_10(x):
1124
+ """
1125
+ Returns a string representation of a float with exactly ten characters
1126
+ """
1127
+ if np.isposinf(x):
1128
+ return " inf"
1129
+ elif np.isneginf(x):
1130
+ return " -inf"
1131
+ elif np.isnan(x):
1132
+ return " nan"
1133
+ return np.format_float_scientific(x, precision=3, pad_left=2, unique=False)
1134
+
1135
+
1136
+ def _dict_formatter(d, n=0, mplus=1, sorter=None):
1137
+ """
1138
+ Pretty printer for dictionaries
1139
+
1140
+ `n` keeps track of the starting indentation;
1141
+ lines are indented by this much after a line break.
1142
+ `mplus` is additional left padding applied to keys
1143
+ """
1144
+ if isinstance(d, dict):
1145
+ m = max(map(len, list(d.keys()))) + mplus # width to print keys
1146
+ s = '\n'.join([k.rjust(m) + ': ' + # right justified, width m
1147
+ _indenter(_dict_formatter(v, m+n+2, 0, sorter), m+2)
1148
+ for k, v in sorter(d)]) # +2 for ': '
1149
+ else:
1150
+ # By default, NumPy arrays print with linewidth=76. `n` is
1151
+ # the indent at which a line begins printing, so it is subtracted
1152
+ # from the default to avoid exceeding 76 characters total.
1153
+ # `edgeitems` is the number of elements to include before and after
1154
+ # ellipses when arrays are not shown in full.
1155
+ # `threshold` is the maximum number of elements for which an
1156
+ # array is shown in full.
1157
+ # These values tend to work well for use with OptimizeResult.
1158
+ with np.printoptions(linewidth=76-n, edgeitems=2, threshold=12,
1159
+ formatter={'float_kind': _float_formatter_10}):
1160
+ s = str(d)
1161
+ return s
1162
+
1163
+
1164
+ _batch_note = """
1165
+ The documentation is written assuming array arguments are of specified
1166
+ "core" shapes. However, array argument(s) of this function may have additional
1167
+ "batch" dimensions prepended to the core shape. In this case, the array is treated
1168
+ as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
1169
+ """
1170
+
1171
+
1172
+ def _apply_over_batch(*argdefs):
1173
+ """
1174
+ Factory for decorator that applies a function over batched arguments.
1175
+
1176
+ Array arguments may have any number of core dimensions (typically 0,
1177
+ 1, or 2) and any broadcastable batch shapes. There may be any
1178
+ number of array outputs of any number of dimensions. Assumptions
1179
+ right now - which are satisfied by all functions of interest in `linalg` -
1180
+ are that all array inputs are consecutive keyword or positional arguments,
1181
+ and that the wrapped function returns either a single array or a tuple of
1182
+ arrays. It's only as general as it needs to be right now - it can be extended.
1183
+
1184
+ Parameters
1185
+ ----------
1186
+ *argdefs : tuple of (str, int)
1187
+ Definitions of array arguments: the keyword name of the argument, and
1188
+ the number of core dimensions.
1189
+
1190
+ Example:
1191
+ --------
1192
+ `linalg.eig` accepts two matrices as the first two arguments `a` and `b`, where
1193
+ `b` is optional, and returns one array or a tuple of arrays, depending on the
1194
+ values of other positional or keyword arguments. To generate a wrapper that applies
1195
+ the function over batches of `a` and optionally `b` :
1196
+
1197
+ >>> _apply_over_batch(('a', 2), ('b', 2))
1198
+ """
1199
+ names, ndims = list(zip(*argdefs))
1200
+ n_arrays = len(names)
1201
+
1202
+ def decorator(f):
1203
+ @functools.wraps(f)
1204
+ def wrapper(*args, **kwargs):
1205
+ args = list(args)
1206
+
1207
+ # Ensure all arrays in `arrays`, other arguments in `other_args`/`kwargs`
1208
+ arrays, other_args = args[:n_arrays], args[n_arrays:]
1209
+ for i, name in enumerate(names):
1210
+ if name in kwargs:
1211
+ if i + 1 <= len(args):
1212
+ raise ValueError(f'{f.__name__}() got multiple values '
1213
+ f'for argument `{name}`.')
1214
+ else:
1215
+ arrays.append(kwargs.pop(name))
1216
+
1217
+ # Determine core and batch shapes
1218
+ batch_shapes = []
1219
+ core_shapes = []
1220
+ for i, (array, ndim) in enumerate(zip(arrays, ndims)):
1221
+ array = None if array is None else np.asarray(array)
1222
+ shape = () if array is None else array.shape
1223
+
1224
+ if ndim == "1|2": # special case for `solve`, etc.
1225
+ ndim = 2 if array.ndim >= 2 else 1
1226
+
1227
+ arrays[i] = array
1228
+ batch_shapes.append(shape[:-ndim] if ndim > 0 else shape)
1229
+ core_shapes.append(shape[-ndim:] if ndim > 0 else ())
1230
+
1231
+ # Early exit if call is not batched
1232
+ if not any(batch_shapes):
1233
+ return f(*arrays, *other_args, **kwargs)
1234
+
1235
+ # Determine broadcasted batch shape
1236
+ batch_shape = np.broadcast_shapes(*batch_shapes) # Gives OK error message
1237
+
1238
+ # Broadcast arrays to appropriate shape
1239
+ for i, (array, core_shape) in enumerate(zip(arrays, core_shapes)):
1240
+ if array is None:
1241
+ continue
1242
+ arrays[i] = np.broadcast_to(array, batch_shape + core_shape)
1243
+
1244
+ # Main loop
1245
+ results = []
1246
+ for index in np.ndindex(batch_shape):
1247
+ result = f(*(array[index] for array in arrays), *other_args, **kwargs)
1248
+ # Assume `result` is either a tuple or single array. This is easily
1249
+ # generalized by allowing the contributor to pass an `unpack_result`
1250
+ # callable to the decorator factory.
1251
+ result = (result,) if not isinstance(result, tuple) else result
1252
+ results.append(result)
1253
+ results = list(zip(*results))
1254
+
1255
+ # Reshape results
1256
+ for i, result in enumerate(results):
1257
+ result = np.stack(result)
1258
+ core_shape = result.shape[1:]
1259
+ results[i] = np.reshape(result, batch_shape + core_shape)
1260
+
1261
+ # Assume `result` should be a single array if there is only one element or
1262
+ # a `tuple` otherwise. This is easily generalized by allowing the
1263
+ # contributor to pass an `pack_result` callable to the decorator factory.
1264
+ return results[0] if len(results) == 1 else results
1265
+
1266
+ doc = FunctionDoc(wrapper)
1267
+ doc['Extended Summary'].append(_batch_note.rstrip())
1268
+ wrapper.__doc__ = str(doc).split("\n", 1)[1] # remove signature
1269
+
1270
+ return wrapper
1271
+ return decorator
1272
+
1273
+
1274
+ def np_vecdot(x1, x2, /, *, axis=-1):
1275
+ # `np.vecdot` has advantages (e.g. see gh-22462), so let's use it when
1276
+ # available. As functions are translated to Array API, `np_vecdot` can be
1277
+ # replaced with `xp.vecdot`.
1278
+ if np.__version__ > "2.0":
1279
+ return np.vecdot(x1, x2, axis=axis)
1280
+ else:
1281
+ # of course there are other fancy ways of doing this (e.g. `einsum`)
1282
+ # but let's keep it simple since it's temporary
1283
+ return np.sum(x1 * x2, axis=axis)
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/decorator.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ######################### LICENSE ############################ #
2
+
3
+ # Copyright (c) 2005-2015, Michele Simionato
4
+ # All rights reserved.
5
+
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are
8
+ # met:
9
+
10
+ # Redistributions of source code must retain the above copyright
11
+ # notice, this list of conditions and the following disclaimer.
12
+ # Redistributions in bytecode form must reproduce the above copyright
13
+ # notice, this list of conditions and the following disclaimer in
14
+ # the documentation and/or other materials provided with the
15
+ # distribution.
16
+
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ # HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24
+ # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25
+ # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
26
+ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27
+ # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28
+ # DAMAGE.
29
+
30
+ """
31
+ Decorator module, see https://pypi.python.org/pypi/decorator
32
+ for the documentation.
33
+ """
34
+ import re
35
+ import sys
36
+ import inspect
37
+ import operator
38
+ import itertools
39
+ import collections
40
+
41
+ from inspect import getfullargspec
42
+
43
+ __version__ = '4.0.5'
44
+
45
+
46
+ def get_init(cls):
47
+ return cls.__init__
48
+
49
+
50
+ # getargspec has been deprecated in Python 3.5
51
+ ArgSpec = collections.namedtuple(
52
+ 'ArgSpec', 'args varargs varkw defaults')
53
+
54
+
55
+ def getargspec(f):
56
+ """A replacement for inspect.getargspec"""
57
+ spec = getfullargspec(f)
58
+ return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
59
+
60
+
61
+ DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
62
+
63
+
64
+ # basic functionality
65
+ class FunctionMaker:
66
+ """
67
+ An object with the ability to create functions with a given signature.
68
+ It has attributes name, doc, module, signature, defaults, dict, and
69
+ methods update and make.
70
+ """
71
+
72
+ # Atomic get-and-increment provided by the GIL
73
+ _compile_count = itertools.count()
74
+
75
+ def __init__(self, func=None, name=None, signature=None,
76
+ defaults=None, doc=None, module=None, funcdict=None):
77
+ self.shortsignature = signature
78
+ if func:
79
+ # func can be a class or a callable, but not an instance method
80
+ self.name = func.__name__
81
+ if self.name == '<lambda>': # small hack for lambda functions
82
+ self.name = '_lambda_'
83
+ self.doc = func.__doc__
84
+ self.module = func.__module__
85
+ if inspect.isfunction(func):
86
+ argspec = getfullargspec(func)
87
+ self.annotations = getattr(func, '__annotations__', {})
88
+ for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
89
+ 'kwonlydefaults'):
90
+ setattr(self, a, getattr(argspec, a))
91
+ for i, arg in enumerate(self.args):
92
+ setattr(self, f'arg{i}', arg)
93
+ allargs = list(self.args)
94
+ allshortargs = list(self.args)
95
+ if self.varargs:
96
+ allargs.append('*' + self.varargs)
97
+ allshortargs.append('*' + self.varargs)
98
+ elif self.kwonlyargs:
99
+ allargs.append('*') # single star syntax
100
+ for a in self.kwonlyargs:
101
+ allargs.append(f'{a}=None')
102
+ allshortargs.append(f'{a}={a}')
103
+ if self.varkw:
104
+ allargs.append('**' + self.varkw)
105
+ allshortargs.append('**' + self.varkw)
106
+ self.signature = ', '.join(allargs)
107
+ self.shortsignature = ', '.join(allshortargs)
108
+ self.dict = func.__dict__.copy()
109
+ # func=None happens when decorating a caller
110
+ if name:
111
+ self.name = name
112
+ if signature is not None:
113
+ self.signature = signature
114
+ if defaults:
115
+ self.defaults = defaults
116
+ if doc:
117
+ self.doc = doc
118
+ if module:
119
+ self.module = module
120
+ if funcdict:
121
+ self.dict = funcdict
122
+ # check existence required attributes
123
+ assert hasattr(self, 'name')
124
+ if not hasattr(self, 'signature'):
125
+ raise TypeError(f'You are decorating a non-function: {func}')
126
+
127
+ def update(self, func, **kw):
128
+ "Update the signature of func with the data in self"
129
+ func.__name__ = self.name
130
+ func.__doc__ = getattr(self, 'doc', None)
131
+ func.__dict__ = getattr(self, 'dict', {})
132
+ func.__defaults__ = getattr(self, 'defaults', ())
133
+ func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
134
+ func.__annotations__ = getattr(self, 'annotations', None)
135
+ try:
136
+ frame = sys._getframe(3)
137
+ except AttributeError: # for IronPython and similar implementations
138
+ callermodule = '?'
139
+ else:
140
+ callermodule = frame.f_globals.get('__name__', '?')
141
+ func.__module__ = getattr(self, 'module', callermodule)
142
+ func.__dict__.update(kw)
143
+
144
+ def make(self, src_templ, evaldict=None, addsource=False, **attrs):
145
+ "Make a new function from a given template and update the signature"
146
+ src = src_templ % vars(self) # expand name and signature
147
+ evaldict = evaldict or {}
148
+ mo = DEF.match(src)
149
+ if mo is None:
150
+ raise SyntaxError(f'not a valid function template\n{src}')
151
+ name = mo.group(1) # extract the function name
152
+ names = set([name] + [arg.strip(' *') for arg in
153
+ self.shortsignature.split(',')])
154
+ for n in names:
155
+ if n in ('_func_', '_call_'):
156
+ raise NameError(f'{n} is overridden in\n{src}')
157
+ if not src.endswith('\n'): # add a newline just for safety
158
+ src += '\n' # this is needed in old versions of Python
159
+
160
+ # Ensure each generated function has a unique filename for profilers
161
+ # (such as cProfile) that depend on the tuple of (<filename>,
162
+ # <definition line>, <function name>) being unique.
163
+ filename = f'<decorator-gen-{next(self._compile_count)}>'
164
+ try:
165
+ code = compile(src, filename, 'single')
166
+ exec(code, evaldict)
167
+ except: # noqa: E722
168
+ print('Error in generated code:', file=sys.stderr)
169
+ print(src, file=sys.stderr)
170
+ raise
171
+ func = evaldict[name]
172
+ if addsource:
173
+ attrs['__source__'] = src
174
+ self.update(func, **attrs)
175
+ return func
176
+
177
+ @classmethod
178
+ def create(cls, obj, body, evaldict, defaults=None,
179
+ doc=None, module=None, addsource=True, **attrs):
180
+ """
181
+ Create a function from the strings name, signature, and body.
182
+ evaldict is the evaluation dictionary. If addsource is true, an
183
+ attribute __source__ is added to the result. The attributes attrs
184
+ are added, if any.
185
+ """
186
+ if isinstance(obj, str): # "name(signature)"
187
+ name, rest = obj.strip().split('(', 1)
188
+ signature = rest[:-1] # strip a right parens
189
+ func = None
190
+ else: # a function
191
+ name = None
192
+ signature = None
193
+ func = obj
194
+ self = cls(func, name, signature, defaults, doc, module)
195
+ ibody = '\n'.join(' ' + line for line in body.splitlines())
196
+ return self.make('def %(name)s(%(signature)s):\n' + ibody,
197
+ evaldict, addsource, **attrs)
198
+
199
+
200
+ def decorate(func, caller):
201
+ """
202
+ decorate(func, caller) decorates a function using a caller.
203
+ """
204
+ evaldict = func.__globals__.copy()
205
+ evaldict['_call_'] = caller
206
+ evaldict['_func_'] = func
207
+ fun = FunctionMaker.create(
208
+ func, "return _call_(_func_, %(shortsignature)s)",
209
+ evaldict, __wrapped__=func)
210
+ if hasattr(func, '__qualname__'):
211
+ fun.__qualname__ = func.__qualname__
212
+ return fun
213
+
214
+
215
+ def decorator(caller, _func=None):
216
+ """decorator(caller) converts a caller function into a decorator"""
217
+ if _func is not None: # return a decorated function
218
+ # this is obsolete behavior; you should use decorate instead
219
+ return decorate(_func, caller)
220
+ # else return a decorator function
221
+ if inspect.isclass(caller):
222
+ name = caller.__name__.lower()
223
+ callerfunc = get_init(caller)
224
+ doc = (f'decorator({caller.__name__}) converts functions/generators into '
225
+ f'factories of {caller.__name__} objects')
226
+ elif inspect.isfunction(caller):
227
+ if caller.__name__ == '<lambda>':
228
+ name = '_lambda_'
229
+ else:
230
+ name = caller.__name__
231
+ callerfunc = caller
232
+ doc = caller.__doc__
233
+ else: # assume caller is an object with a __call__ method
234
+ name = caller.__class__.__name__.lower()
235
+ callerfunc = caller.__call__.__func__
236
+ doc = caller.__call__.__doc__
237
+ evaldict = callerfunc.__globals__.copy()
238
+ evaldict['_call_'] = caller
239
+ evaldict['_decorate_'] = decorate
240
+ return FunctionMaker.create(
241
+ f'{name}(func)', 'return _decorate_(func, _call_)',
242
+ evaldict, doc=doc, module=caller.__module__,
243
+ __wrapped__=caller)
244
+
245
+
246
+ # ####################### contextmanager ####################### #
247
+
248
+ try: # Python >= 3.2
249
+ from contextlib import _GeneratorContextManager
250
+ except ImportError: # Python >= 2.5
251
+ from contextlib import GeneratorContextManager as _GeneratorContextManager
252
+
253
+
254
+ class ContextManager(_GeneratorContextManager):
255
+ def __call__(self, func):
256
+ """Context manager decorator"""
257
+ return FunctionMaker.create(
258
+ func, "with _self_: return _func_(%(shortsignature)s)",
259
+ dict(_self_=self, _func_=func), __wrapped__=func)
260
+
261
+
262
+ init = getfullargspec(_GeneratorContextManager.__init__)
263
+ n_args = len(init.args)
264
+ if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7
265
+ def __init__(self, g, *a, **k):
266
+ return _GeneratorContextManager.__init__(self, g(*a, **k))
267
+ ContextManager.__init__ = __init__
268
+ elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4
269
+ pass
270
+ elif n_args == 4: # (self, gen, args, kwds) Python 3.5
271
+ def __init__(self, g, *a, **k):
272
+ return _GeneratorContextManager.__init__(self, g, a, k)
273
+ ContextManager.__init__ = __init__
274
+
275
+ contextmanager = decorator(ContextManager)
276
+
277
+
278
+ # ############################ dispatch_on ############################ #
279
+
280
+ def append(a, vancestors):
281
+ """
282
+ Append ``a`` to the list of the virtual ancestors, unless it is already
283
+ included.
284
+ """
285
+ add = True
286
+ for j, va in enumerate(vancestors):
287
+ if issubclass(va, a):
288
+ add = False
289
+ break
290
+ if issubclass(a, va):
291
+ vancestors[j] = a
292
+ add = False
293
+ if add:
294
+ vancestors.append(a)
295
+
296
+
297
+ # inspired from simplegeneric by P.J. Eby and functools.singledispatch
298
+ def dispatch_on(*dispatch_args):
299
+ """
300
+ Factory of decorators turning a function into a generic function
301
+ dispatching on the given arguments.
302
+ """
303
+ assert dispatch_args, 'No dispatch args passed'
304
+ dispatch_str = f"({', '.join(dispatch_args)},)"
305
+
306
+ def check(arguments, wrong=operator.ne, msg=''):
307
+ """Make sure one passes the expected number of arguments"""
308
+ if wrong(len(arguments), len(dispatch_args)):
309
+ raise TypeError(f'Expected {len(dispatch_args)} arguments, '
310
+ 'got {len(arguments)}{msg}')
311
+
312
+ def gen_func_dec(func):
313
+ """Decorator turning a function into a generic function"""
314
+
315
+ # first check the dispatch arguments
316
+ argset = set(getfullargspec(func).args)
317
+ if not set(dispatch_args) <= argset:
318
+ raise NameError(f'Unknown dispatch arguments {dispatch_str}')
319
+
320
+ typemap = {}
321
+
322
+ def vancestors(*types):
323
+ """
324
+ Get a list of sets of virtual ancestors for the given types
325
+ """
326
+ check(types)
327
+ ras = [[] for _ in range(len(dispatch_args))]
328
+ for types_ in typemap:
329
+ for t, type_, ra in zip(types, types_, ras):
330
+ if issubclass(t, type_) and type_ not in t.__mro__:
331
+ append(type_, ra)
332
+ return [set(ra) for ra in ras]
333
+
334
+ def ancestors(*types):
335
+ """
336
+ Get a list of virtual MROs, one for each type
337
+ """
338
+ check(types)
339
+ lists = []
340
+ for t, vas in zip(types, vancestors(*types)):
341
+ n_vas = len(vas)
342
+ if n_vas > 1:
343
+ raise RuntimeError(
344
+ f'Ambiguous dispatch for {t}: {vas}')
345
+ elif n_vas == 1:
346
+ va, = vas
347
+ mro = type('t', (t, va), {}).__mro__[1:]
348
+ else:
349
+ mro = t.__mro__
350
+ lists.append(mro[:-1]) # discard t and object
351
+ return lists
352
+
353
+ def register(*types):
354
+ """
355
+ Decorator to register an implementation for the given types
356
+ """
357
+ check(types)
358
+
359
+ def dec(f):
360
+ check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
361
+ typemap[types] = f
362
+ return f
363
+ return dec
364
+
365
+ def dispatch_info(*types):
366
+ """
367
+ An utility to introspect the dispatch algorithm
368
+ """
369
+ check(types)
370
+ lst = [tuple(a.__name__ for a in anc)
371
+ for anc in itertools.product(*ancestors(*types))]
372
+ return lst
373
+
374
+ def _dispatch(dispatch_args, *args, **kw):
375
+ types = tuple(type(arg) for arg in dispatch_args)
376
+ try: # fast path
377
+ f = typemap[types]
378
+ except KeyError:
379
+ pass
380
+ else:
381
+ return f(*args, **kw)
382
+ combinations = itertools.product(*ancestors(*types))
383
+ next(combinations) # the first one has been already tried
384
+ for types_ in combinations:
385
+ f = typemap.get(types_)
386
+ if f is not None:
387
+ return f(*args, **kw)
388
+
389
+ # else call the default implementation
390
+ return func(*args, **kw)
391
+
392
+ return FunctionMaker.create(
393
+ func, f'return _f_({dispatch_str}, %%(shortsignature)s)',
394
+ dict(_f_=_dispatch), register=register, default=func,
395
+ typemap=typemap, vancestors=vancestors, ancestors=ancestors,
396
+ dispatch_info=dispatch_info, __wrapped__=func)
397
+
398
+ gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
399
+ return gen_func_dec
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from inspect import Parameter, signature
2
+ import functools
3
+ import warnings
4
+ from importlib import import_module
5
+ from scipy._lib._docscrape import FunctionDoc
6
+
7
+
8
+ __all__ = ["_deprecated"]
9
+
10
+
11
+ # Object to use as default value for arguments to be deprecated. This should
12
+ # be used over 'None' as the user could parse 'None' as a positional argument
13
+ _NoValue = object()
14
+
15
+ def _sub_module_deprecation(*, sub_package, module, private_modules, all,
16
+ attribute, correct_module=None, dep_version="1.16.0"):
17
+ """Helper function for deprecating modules that are public but were
18
+ intended to be private.
19
+
20
+ Parameters
21
+ ----------
22
+ sub_package : str
23
+ Subpackage the module belongs to eg. stats
24
+ module : str
25
+ Public but intended private module to deprecate
26
+ private_modules : list
27
+ Private replacement(s) for `module`; should contain the
28
+ content of ``all``, possibly spread over several modules.
29
+ all : list
30
+ ``__all__`` belonging to `module`
31
+ attribute : str
32
+ The attribute in `module` being accessed
33
+ correct_module : str, optional
34
+ Module in `sub_package` that `attribute` should be imported from.
35
+ Default is that `attribute` should be imported from ``scipy.sub_package``.
36
+ dep_version : str, optional
37
+ Version in which deprecated attributes will be removed.
38
+ """
39
+ if correct_module is not None:
40
+ correct_import = f"scipy.{sub_package}.{correct_module}"
41
+ else:
42
+ correct_import = f"scipy.{sub_package}"
43
+
44
+ if attribute not in all:
45
+ raise AttributeError(
46
+ f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
47
+ f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
48
+ f"and will be removed in SciPy 2.0.0."
49
+ )
50
+
51
+ attr = getattr(import_module(correct_import), attribute, None)
52
+
53
+ if attr is not None:
54
+ message = (
55
+ f"Please import `{attribute}` from the `{correct_import}` namespace; "
56
+ f"the `scipy.{sub_package}.{module}` namespace is deprecated "
57
+ f"and will be removed in SciPy 2.0.0."
58
+ )
59
+ else:
60
+ message = (
61
+ f"`scipy.{sub_package}.{module}.{attribute}` is deprecated along with "
62
+ f"the `scipy.{sub_package}.{module}` namespace. "
63
+ f"`scipy.{sub_package}.{module}.{attribute}` will be removed "
64
+ f"in SciPy {dep_version}, and the `scipy.{sub_package}.{module}` namespace "
65
+ f"will be removed in SciPy 2.0.0."
66
+ )
67
+
68
+ warnings.warn(message, category=DeprecationWarning, stacklevel=3)
69
+
70
+ for module in private_modules:
71
+ try:
72
+ return getattr(import_module(f"scipy.{sub_package}.{module}"), attribute)
73
+ except AttributeError as e:
74
+ # still raise an error if the attribute isn't in any of the expected
75
+ # private modules
76
+ if module == private_modules[-1]:
77
+ raise e
78
+ continue
79
+
80
+
81
+ def _deprecated(msg, stacklevel=2):
82
+ """Deprecate a function by emitting a warning on use."""
83
+ def wrap(fun):
84
+ if isinstance(fun, type):
85
+ warnings.warn(
86
+ f"Trying to deprecate class {fun!r}",
87
+ category=RuntimeWarning, stacklevel=2)
88
+ return fun
89
+
90
+ @functools.wraps(fun)
91
+ def call(*args, **kwargs):
92
+ warnings.warn(msg, category=DeprecationWarning,
93
+ stacklevel=stacklevel)
94
+ return fun(*args, **kwargs)
95
+ call.__doc__ = fun.__doc__
96
+ return call
97
+
98
+ return wrap
99
+
100
+
101
+ class _DeprecationHelperStr:
102
+ """
103
+ Helper class used by deprecate_cython_api
104
+ """
105
+ def __init__(self, content, message):
106
+ self._content = content
107
+ self._message = message
108
+
109
+ def __hash__(self):
110
+ return hash(self._content)
111
+
112
+ def __eq__(self, other):
113
+ res = (self._content == other)
114
+ if res:
115
+ warnings.warn(self._message, category=DeprecationWarning,
116
+ stacklevel=2)
117
+ return res
118
+
119
+
120
+ def deprecate_cython_api(module, routine_name, new_name=None, message=None):
121
+ """
122
+ Deprecate an exported cdef function in a public Cython API module.
123
+
124
+ Only functions can be deprecated; typedefs etc. cannot.
125
+
126
+ Parameters
127
+ ----------
128
+ module : module
129
+ Public Cython API module (e.g. scipy.linalg.cython_blas).
130
+ routine_name : str
131
+ Name of the routine to deprecate. May also be a fused-type
132
+ routine (in which case its all specializations are deprecated).
133
+ new_name : str
134
+ New name to include in the deprecation warning message
135
+ message : str
136
+ Additional text in the deprecation warning message
137
+
138
+ Examples
139
+ --------
140
+ Usually, this function would be used in the top-level of the
141
+ module ``.pyx`` file:
142
+
143
+ >>> from scipy._lib.deprecation import deprecate_cython_api
144
+ >>> import scipy.linalg.cython_blas as mod
145
+ >>> deprecate_cython_api(mod, "dgemm", "dgemm_new",
146
+ ... message="Deprecated in Scipy 1.5.0")
147
+ >>> del deprecate_cython_api, mod
148
+
149
+ After this, Cython modules that use the deprecated function emit a
150
+ deprecation warning when they are imported.
151
+
152
+ """
153
+ old_name = f"{module.__name__}.{routine_name}"
154
+
155
+ if new_name is None:
156
+ depdoc = f"`{old_name}` is deprecated!"
157
+ else:
158
+ depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
159
+
160
+ if message is not None:
161
+ depdoc += "\n" + message
162
+
163
+ d = module.__pyx_capi__
164
+
165
+ # Check if the function is a fused-type function with a mangled name
166
+ j = 0
167
+ has_fused = False
168
+ while True:
169
+ fused_name = f"__pyx_fuse_{j}{routine_name}"
170
+ if fused_name in d:
171
+ has_fused = True
172
+ d[_DeprecationHelperStr(fused_name, depdoc)] = d.pop(fused_name)
173
+ j += 1
174
+ else:
175
+ break
176
+
177
+ # If not, apply deprecation to the named routine
178
+ if not has_fused:
179
+ d[_DeprecationHelperStr(routine_name, depdoc)] = d.pop(routine_name)
180
+
181
+
182
+ # taken from scikit-learn, see
183
+ # https://github.com/scikit-learn/scikit-learn/blob/1.3.0/sklearn/utils/validation.py#L38
184
+ def _deprecate_positional_args(func=None, *, version=None,
185
+ deprecated_args=None, custom_message=""):
186
+ """Decorator for methods that issues warnings for positional arguments.
187
+
188
+ Using the keyword-only argument syntax in pep 3102, arguments after the
189
+ * will issue a warning when passed as a positional argument.
190
+
191
+ Parameters
192
+ ----------
193
+ func : callable, default=None
194
+ Function to check arguments on.
195
+ version : callable, default=None
196
+ The version when positional arguments will result in error.
197
+ deprecated_args : set of str, optional
198
+ Arguments to deprecate - whether passed by position or keyword.
199
+ custom_message : str, optional
200
+ Custom message to add to deprecation warning and documentation.
201
+ """
202
+ if version is None:
203
+ msg = "Need to specify a version where signature will be changed"
204
+ raise ValueError(msg)
205
+
206
+ deprecated_args = set() if deprecated_args is None else set(deprecated_args)
207
+
208
+ def _inner_deprecate_positional_args(f):
209
+ sig = signature(f)
210
+ kwonly_args = []
211
+ all_args = []
212
+
213
+ for name, param in sig.parameters.items():
214
+ if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
215
+ all_args.append(name)
216
+ elif param.kind == Parameter.KEYWORD_ONLY:
217
+ kwonly_args.append(name)
218
+
219
+ def warn_deprecated_args(kwargs):
220
+ intersection = deprecated_args.intersection(kwargs)
221
+ if intersection:
222
+ message = (f"Arguments {intersection} are deprecated, whether passed "
223
+ "by position or keyword. They will be removed in SciPy "
224
+ f"{version}. ")
225
+ message += custom_message
226
+ warnings.warn(message, category=DeprecationWarning, stacklevel=3)
227
+
228
+ @functools.wraps(f)
229
+ def inner_f(*args, **kwargs):
230
+
231
+ extra_args = len(args) - len(all_args)
232
+ if extra_args <= 0:
233
+ warn_deprecated_args(kwargs)
234
+ return f(*args, **kwargs)
235
+
236
+ # extra_args > 0
237
+ kwonly_extra_args = set(kwonly_args[:extra_args]) - deprecated_args
238
+ args_msg = ", ".join(kwonly_extra_args)
239
+ warnings.warn(
240
+ (
241
+ f"You are passing as positional arguments: {args_msg}. "
242
+ "Please change your invocation to use keyword arguments. "
243
+ f"From SciPy {version}, passing these as positional "
244
+ "arguments will result in an error."
245
+ ),
246
+ DeprecationWarning,
247
+ stacklevel=2,
248
+ )
249
+ kwargs.update(zip(sig.parameters, args))
250
+ warn_deprecated_args(kwargs)
251
+ return f(**kwargs)
252
+
253
+ doc = FunctionDoc(inner_f)
254
+ kwonly_extra_args = set(kwonly_args) - deprecated_args
255
+ admonition = f"""
256
+ .. deprecated:: {version}
257
+ Use of argument(s) ``{kwonly_extra_args}`` by position is deprecated; beginning in
258
+ SciPy {version}, these will be keyword-only. """
259
+ if deprecated_args:
260
+ admonition += (f"Argument(s) ``{deprecated_args}`` are deprecated, whether "
261
+ "passed by position or keyword; they will be removed in "
262
+ f"SciPy {version}. ")
263
+ admonition += custom_message
264
+ doc['Extended Summary'] += [admonition]
265
+
266
+ doc = str(doc).split("\n", 1)[1] # remove signature
267
+ inner_f.__doc__ = str(doc)
268
+
269
+ return inner_f
270
+
271
+ if func is not None:
272
+ return _inner_deprecate_positional_args(func)
273
+
274
+ return _inner_deprecate_positional_args
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities to allow inserting docstring fragments for common
2
+ parameters into function and method docstrings."""
3
+
4
+ from collections.abc import Callable, Iterable, Mapping
5
+ from typing import Protocol, TypeVar
6
+ import sys
7
+
8
+ __all__ = [
9
+ "docformat",
10
+ "inherit_docstring_from",
11
+ "indentcount_lines",
12
+ "filldoc",
13
+ "unindent_dict",
14
+ "unindent_string",
15
+ "extend_notes_in_docstring",
16
+ "replace_notes_in_docstring",
17
+ "doc_replace",
18
+ ]
19
+
20
+ _F = TypeVar("_F", bound=Callable[..., object])
21
+
22
+
23
+ class Decorator(Protocol):
24
+ """A decorator of a function."""
25
+
26
+ def __call__(self, func: _F, /) -> _F: ...
27
+
28
+
29
+ def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str:
30
+ """Fill a function docstring from variables in dictionary.
31
+
32
+ Adapt the indent of the inserted docs
33
+
34
+ Parameters
35
+ ----------
36
+ docstring : str
37
+ A docstring from a function, possibly with dict formatting strings.
38
+ docdict : dict[str, str], optional
39
+ A dictionary with keys that match the dict formatting strings
40
+ and values that are docstring fragments to be inserted. The
41
+ indentation of the inserted docstrings is set to match the
42
+ minimum indentation of the ``docstring`` by adding this
43
+ indentation to all lines of the inserted string, except the
44
+ first.
45
+
46
+ Returns
47
+ -------
48
+ docstring : str
49
+ string with requested ``docdict`` strings inserted.
50
+
51
+ Examples
52
+ --------
53
+ >>> docformat(' Test string with %(value)s', {'value':'inserted value'})
54
+ ' Test string with inserted value'
55
+ >>> docstring = 'First line\\n Second line\\n %(value)s'
56
+ >>> inserted_string = "indented\\nstring"
57
+ >>> docdict = {'value': inserted_string}
58
+ >>> docformat(docstring, docdict)
59
+ 'First line\\n Second line\\n indented\\n string'
60
+ """
61
+ if not docstring:
62
+ return docstring
63
+ if docdict is None:
64
+ docdict = {}
65
+ if not docdict:
66
+ return docstring
67
+ lines = docstring.expandtabs().splitlines()
68
+ # Find the minimum indent of the main docstring, after first line
69
+ if len(lines) < 2:
70
+ icount = 0
71
+ else:
72
+ icount = indentcount_lines(lines[1:])
73
+ indent = " " * icount
74
+ # Insert this indent to dictionary docstrings
75
+ indented = {}
76
+ for name, dstr in docdict.items():
77
+ lines = dstr.expandtabs().splitlines()
78
+ indented[name] = ("\n" + indent).join(lines)
79
+ return docstring % indented
80
+
81
+
82
+ def inherit_docstring_from(cls: object) -> Decorator:
83
+ """This decorator modifies the decorated function's docstring by
84
+ replacing occurrences of '%(super)s' with the docstring of the
85
+ method of the same name from the class `cls`.
86
+
87
+ If the decorated method has no docstring, it is simply given the
88
+ docstring of `cls`s method.
89
+
90
+ Parameters
91
+ ----------
92
+ cls : type or object
93
+ A class with a method with the same name as the decorated method.
94
+ The docstring of the method in this class replaces '%(super)s' in the
95
+ docstring of the decorated method.
96
+
97
+ Returns
98
+ -------
99
+ decfunc : function
100
+ The decorator function that modifies the __doc__ attribute
101
+ of its argument.
102
+
103
+ Examples
104
+ --------
105
+ In the following, the docstring for Bar.func created using the
106
+ docstring of `Foo.func`.
107
+
108
+ >>> class Foo:
109
+ ... def func(self):
110
+ ... '''Do something useful.'''
111
+ ... return
112
+ ...
113
+ >>> class Bar(Foo):
114
+ ... @inherit_docstring_from(Foo)
115
+ ... def func(self):
116
+ ... '''%(super)s
117
+ ... Do it fast.
118
+ ... '''
119
+ ... return
120
+ ...
121
+ >>> b = Bar()
122
+ >>> b.func.__doc__
123
+ 'Do something useful.\n Do it fast.\n '
124
+ """
125
+
126
+ def _doc(func: _F) -> _F:
127
+ cls_docstring = getattr(cls, func.__name__).__doc__
128
+ func_docstring = func.__doc__
129
+ if func_docstring is None:
130
+ func.__doc__ = cls_docstring
131
+ else:
132
+ new_docstring = func_docstring % dict(super=cls_docstring)
133
+ func.__doc__ = new_docstring
134
+ return func
135
+
136
+ return _doc
137
+
138
+
139
+ def extend_notes_in_docstring(cls: object, notes: str) -> Decorator:
140
+ """This decorator replaces the decorated function's docstring
141
+ with the docstring from corresponding method in `cls`.
142
+ It extends the 'Notes' section of that docstring to include
143
+ the given `notes`.
144
+
145
+ Parameters
146
+ ----------
147
+ cls : type or object
148
+ A class with a method with the same name as the decorated method.
149
+ The docstring of the method in this class replaces the docstring of the
150
+ decorated method.
151
+ notes : str
152
+ Additional notes to append to the 'Notes' section of the docstring.
153
+
154
+ Returns
155
+ -------
156
+ decfunc : function
157
+ The decorator function that modifies the __doc__ attribute
158
+ of its argument.
159
+ """
160
+
161
+ def _doc(func: _F) -> _F:
162
+ cls_docstring = getattr(cls, func.__name__).__doc__
163
+ # If python is called with -OO option,
164
+ # there is no docstring
165
+ if cls_docstring is None:
166
+ return func
167
+ end_of_notes = cls_docstring.find(" References\n")
168
+ if end_of_notes == -1:
169
+ end_of_notes = cls_docstring.find(" Examples\n")
170
+ if end_of_notes == -1:
171
+ end_of_notes = len(cls_docstring)
172
+ func.__doc__ = (
173
+ cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:]
174
+ )
175
+ return func
176
+
177
+ return _doc
178
+
179
+
180
+ def replace_notes_in_docstring(cls: object, notes: str) -> Decorator:
181
+ """This decorator replaces the decorated function's docstring
182
+ with the docstring from corresponding method in `cls`.
183
+ It replaces the 'Notes' section of that docstring with
184
+ the given `notes`.
185
+
186
+ Parameters
187
+ ----------
188
+ cls : type or object
189
+ A class with a method with the same name as the decorated method.
190
+ The docstring of the method in this class replaces the docstring of the
191
+ decorated method.
192
+ notes : str
193
+ The notes to replace the existing 'Notes' section with.
194
+
195
+ Returns
196
+ -------
197
+ decfunc : function
198
+ The decorator function that modifies the __doc__ attribute
199
+ of its argument.
200
+ """
201
+
202
+ def _doc(func: _F) -> _F:
203
+ cls_docstring = getattr(cls, func.__name__).__doc__
204
+ notes_header = " Notes\n -----\n"
205
+ # If python is called with -OO option,
206
+ # there is no docstring
207
+ if cls_docstring is None:
208
+ return func
209
+ start_of_notes = cls_docstring.find(notes_header)
210
+ end_of_notes = cls_docstring.find(" References\n")
211
+ if end_of_notes == -1:
212
+ end_of_notes = cls_docstring.find(" Examples\n")
213
+ if end_of_notes == -1:
214
+ end_of_notes = len(cls_docstring)
215
+ func.__doc__ = (
216
+ cls_docstring[: start_of_notes + len(notes_header)]
217
+ + notes
218
+ + cls_docstring[end_of_notes:]
219
+ )
220
+ return func
221
+
222
+ return _doc
223
+
224
+
225
+ def indentcount_lines(lines: Iterable[str]) -> int:
226
+ """Minimum indent for all lines in line list
227
+
228
+ Parameters
229
+ ----------
230
+ lines : Iterable[str]
231
+ The lines to find the minimum indent of.
232
+
233
+ Returns
234
+ -------
235
+ indent : int
236
+ The minimum indent.
237
+
238
+
239
+ Examples
240
+ --------
241
+ >>> lines = [' one', ' two', ' three']
242
+ >>> indentcount_lines(lines)
243
+ 1
244
+ >>> lines = []
245
+ >>> indentcount_lines(lines)
246
+ 0
247
+ >>> lines = [' one']
248
+ >>> indentcount_lines(lines)
249
+ 1
250
+ >>> indentcount_lines([' '])
251
+ 0
252
+ """
253
+ indentno = sys.maxsize
254
+ for line in lines:
255
+ stripped = line.lstrip()
256
+ if stripped:
257
+ indentno = min(indentno, len(line) - len(stripped))
258
+ if indentno == sys.maxsize:
259
+ return 0
260
+ return indentno
261
+
262
+
263
+ def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator:
264
+ """Return docstring decorator using docdict variable dictionary.
265
+
266
+ Parameters
267
+ ----------
268
+ docdict : dict[str, str]
269
+ A dictionary containing name, docstring fragment pairs.
270
+ unindent_params : bool, optional
271
+ If True, strip common indentation from all parameters in docdict.
272
+ Default is False.
273
+
274
+ Returns
275
+ -------
276
+ decfunc : function
277
+ The decorator function that applies dictionary to its
278
+ argument's __doc__ attribute.
279
+ """
280
+ if unindent_params:
281
+ docdict = unindent_dict(docdict)
282
+
283
+ def decorate(func: _F) -> _F:
284
+ # __doc__ may be None for optimized Python (-OO)
285
+ doc = func.__doc__ or ""
286
+ func.__doc__ = docformat(doc, docdict)
287
+ return func
288
+
289
+ return decorate
290
+
291
+
292
+ def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]:
293
+ """Unindent all strings in a docdict.
294
+
295
+ Parameters
296
+ ----------
297
+ docdict : dict[str, str]
298
+ A dictionary with string values to unindent.
299
+
300
+ Returns
301
+ -------
302
+ docdict : dict[str, str]
303
+ The `docdict` dictionary but each of its string values are unindented.
304
+ """
305
+ can_dict: dict[str, str] = {}
306
+ for name, dstr in docdict.items():
307
+ can_dict[name] = unindent_string(dstr)
308
+ return can_dict
309
+
310
+
311
+ def unindent_string(docstring: str) -> str:
312
+ """Set docstring to minimum indent for all lines, including first.
313
+
314
+ Parameters
315
+ ----------
316
+ docstring : str
317
+ The input docstring to unindent.
318
+
319
+ Returns
320
+ -------
321
+ docstring : str
322
+ The unindented docstring.
323
+
324
+ Examples
325
+ --------
326
+ >>> unindent_string(' two')
327
+ 'two'
328
+ >>> unindent_string(' two\\n three')
329
+ 'two\\n three'
330
+ """
331
+ lines = docstring.expandtabs().splitlines()
332
+ icount = indentcount_lines(lines)
333
+ if icount == 0:
334
+ return docstring
335
+ return "\n".join([line[icount:] for line in lines])
336
+
337
+
338
+ def doc_replace(obj: object, oldval: str, newval: str) -> Decorator:
339
+ """Decorator to take the docstring from obj, with oldval replaced by newval
340
+
341
+ Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)``
342
+
343
+ Parameters
344
+ ----------
345
+ obj : object
346
+ A class or object whose docstring will be used as the basis for the
347
+ replacement operation.
348
+ oldval : str
349
+ The string to search for in the docstring.
350
+ newval : str
351
+ The string to replace `oldval` with in the docstring.
352
+
353
+ Returns
354
+ -------
355
+ decfunc : function
356
+ A decorator function that replaces occurrences of `oldval` with `newval`
357
+ in the docstring of the decorated function.
358
+ """
359
+ # __doc__ may be None for optimized Python (-OO)
360
+ doc = (obj.__doc__ or "").replace(oldval, newval)
361
+
362
+ def inner(func: _F) -> _F:
363
+ func.__doc__ = doc
364
+ return func
365
+
366
+ return inner
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (86.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """`uarray` provides functions for generating multimethods that dispatch to
2
+ multiple different backends
3
+
4
+ This should be imported, rather than `_uarray` so that an installed version could
5
+ be used instead, if available. This means that users can call
6
+ `uarray.set_backend` directly instead of going through SciPy.
7
+
8
+ """
9
+
10
+
11
+ # Prefer an installed version of uarray, if available
12
+ try:
13
+ import uarray as _uarray
14
+ except ImportError:
15
+ _has_uarray = False
16
+ else:
17
+ from scipy._lib._pep440 import Version as _Version
18
+
19
+ _has_uarray = _Version(_uarray.__version__) >= _Version("0.8")
20
+ del _uarray
21
+ del _Version
22
+
23
+
24
+ if _has_uarray:
25
+ from uarray import * # noqa: F403
26
+ from uarray import _Function
27
+ else:
28
+ from ._uarray import * # noqa: F403
29
+ from ._uarray import _Function # noqa: F401
30
+
31
+ del _has_uarray
tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =========================================
3
+ Clustering package (:mod:`scipy.cluster`)
4
+ =========================================
5
+
6
+ .. currentmodule:: scipy.cluster
7
+
8
+ Clustering algorithms are useful in information theory, target detection,
9
+ communications, compression, and other areas. The `vq` module only
10
+ supports vector quantization and the k-means algorithms.
11
+
12
+ The `hierarchy` module provides functions for hierarchical and
13
+ agglomerative clustering. Its features include generating hierarchical
14
+ clusters from distance matrices,
15
+ calculating statistics on clusters, cutting linkages
16
+ to generate flat clusters, and visualizing clusters with dendrograms.
17
+
18
+ .. toctree::
19
+ :maxdepth: 1
20
+
21
+ cluster.vq
22
+ cluster.hierarchy
23
+
24
+ """
25
+ __all__ = ['vq', 'hierarchy']
26
+
27
+ from . import vq, hierarchy
28
+
29
+ from scipy._lib._testutils import PytestTester
30
+ test = PytestTester(__name__)
31
+ del PytestTester
tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06d7a371d04ebd6ebffb169e63c62b47c3647e97548f012b942d1cbcb32c1903
3
+ size 300088
tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a07f9f1b9bce7a39f0150194dc8bcacae4f8f53c47af21f9f672d38ed05c67c4
3
+ size 195304
tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54a856896fc3b62956b45b0ec7c29b5fc5e338beb5dc078952e1950aaec24d43
3
+ size 129872
tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy.py ADDED
The diff for this file is too large to render. See raw diff
 
tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/vq.py ADDED
@@ -0,0 +1,832 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ K-means clustering and vector quantization (:mod:`scipy.cluster.vq`)
3
+ ====================================================================
4
+
5
+ Provides routines for k-means clustering, generating code books
6
+ from k-means models and quantizing vectors by comparing them with
7
+ centroids in a code book.
8
+
9
+ .. autosummary::
10
+ :toctree: generated/
11
+
12
+ whiten -- Normalize a group of observations so each feature has unit variance
13
+ vq -- Calculate code book membership of a set of observation vectors
14
+ kmeans -- Perform k-means on a set of observation vectors forming k clusters
15
+ kmeans2 -- A different implementation of k-means with more methods
16
+ -- for initializing centroids
17
+
18
+ Background information
19
+ ----------------------
20
+ The k-means algorithm takes as input the number of clusters to
21
+ generate, k, and a set of observation vectors to cluster. It
22
+ returns a set of centroids, one for each of the k clusters. An
23
+ observation vector is classified with the cluster number or
24
+ centroid index of the centroid closest to it.
25
+
26
+ A vector v belongs to cluster i if it is closer to centroid i than
27
+ any other centroid. If v belongs to i, we say centroid i is the
28
+ dominating centroid of v. The k-means algorithm tries to
29
+ minimize distortion, which is defined as the sum of the squared distances
30
+ between each observation vector and its dominating centroid.
31
+ The minimization is achieved by iteratively reclassifying
32
+ the observations into clusters and recalculating the centroids until
33
+ a configuration is reached in which the centroids are stable. One can
34
+ also define a maximum number of iterations.
35
+
36
+ Since vector quantization is a natural application for k-means,
37
+ information theory terminology is often used. The centroid index
38
+ or cluster index is also referred to as a "code" and the table
39
+ mapping codes to centroids and, vice versa, is often referred to as a
40
+ "code book". The result of k-means, a set of centroids, can be
41
+ used to quantize vectors. Quantization aims to find an encoding of
42
+ vectors that reduces the expected distortion.
43
+
44
+ All routines expect obs to be an M by N array, where the rows are
45
+ the observation vectors. The codebook is a k by N array, where the
46
+ ith row is the centroid of code word i. The observation vectors
47
+ and centroids have the same feature dimension.
48
+
49
+ As an example, suppose we wish to compress a 24-bit color image
50
+ (each pixel is represented by one byte for red, one for blue, and
51
+ one for green) before sending it over the web. By using a smaller
52
+ 8-bit encoding, we can reduce the amount of data by two
53
+ thirds. Ideally, the colors for each of the 256 possible 8-bit
54
+ encoding values should be chosen to minimize distortion of the
55
+ color. Running k-means with k=256 generates a code book of 256
56
+ codes, which fills up all possible 8-bit sequences. Instead of
57
+ sending a 3-byte value for each pixel, the 8-bit centroid index
58
+ (or code word) of the dominating centroid is transmitted. The code
59
+ book is also sent over the wire so each 8-bit code can be
60
+ translated back to a 24-bit pixel value representation. If the
61
+ image of interest was of an ocean, we would expect many 24-bit
62
+ blues to be represented by 8-bit codes. If it was an image of a
63
+ human face, more flesh-tone colors would be represented in the
64
+ code book.
65
+
66
+ """
67
+ import warnings
68
+ import numpy as np
69
+ from collections import deque
70
+ from scipy._lib._array_api import (_asarray, array_namespace, is_lazy_array,
71
+ xp_capabilities, xp_copy, xp_size)
72
+ from scipy._lib._util import (check_random_state, rng_integers,
73
+ _transition_to_rng)
74
+ from scipy._lib import array_api_extra as xpx
75
+ from scipy.spatial.distance import cdist
76
+
77
+ from . import _vq
78
+
79
+ __docformat__ = 'restructuredtext'
80
+
81
+ __all__ = ['whiten', 'vq', 'kmeans', 'kmeans2']
82
+
83
+
84
+ class ClusterError(Exception):
85
+ pass
86
+
87
+
88
+ @xp_capabilities()
89
+ def whiten(obs, check_finite=None):
90
+ """
91
+ Normalize a group of observations on a per feature basis.
92
+
93
+ Before running k-means, it is beneficial to rescale each feature
94
+ dimension of the observation set by its standard deviation (i.e. "whiten"
95
+ it - as in "white noise" where each frequency has equal power).
96
+ Each feature is divided by its standard deviation across all observations
97
+ to give it unit variance.
98
+
99
+ Parameters
100
+ ----------
101
+ obs : ndarray
102
+ Each row of the array is an observation. The
103
+ columns are the features seen during each observation::
104
+
105
+ # f0 f1 f2
106
+ obs = [[ 1., 1., 1.], #o0
107
+ [ 2., 2., 2.], #o1
108
+ [ 3., 3., 3.], #o2
109
+ [ 4., 4., 4.]] #o3
110
+
111
+ check_finite : bool, optional
112
+ Whether to check that the input matrices contain only finite numbers.
113
+ Disabling may give a performance gain, but may result in problems
114
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
115
+ Default: True for eager backends and False for lazy ones.
116
+
117
+ Returns
118
+ -------
119
+ result : ndarray
120
+ Contains the values in `obs` scaled by the standard deviation
121
+ of each column.
122
+
123
+ Examples
124
+ --------
125
+ >>> import numpy as np
126
+ >>> from scipy.cluster.vq import whiten
127
+ >>> features = np.array([[1.9, 2.3, 1.7],
128
+ ... [1.5, 2.5, 2.2],
129
+ ... [0.8, 0.6, 1.7,]])
130
+ >>> whiten(features)
131
+ array([[ 4.17944278, 2.69811351, 7.21248917],
132
+ [ 3.29956009, 2.93273208, 9.33380951],
133
+ [ 1.75976538, 0.7038557 , 7.21248917]])
134
+
135
+ """
136
+ xp = array_namespace(obs)
137
+ if check_finite is None:
138
+ check_finite = not is_lazy_array(obs)
139
+ obs = _asarray(obs, check_finite=check_finite, xp=xp)
140
+ std_dev = xp.std(obs, axis=0)
141
+ zero_std_mask = std_dev == 0
142
+ std_dev = xpx.at(std_dev, zero_std_mask).set(1.0)
143
+ if check_finite and xp.any(zero_std_mask):
144
+ warnings.warn("Some columns have standard deviation zero. "
145
+ "The values of these columns will not change.",
146
+ RuntimeWarning, stacklevel=2)
147
+ return obs / std_dev
148
+
149
+
150
+ @xp_capabilities(cpu_only=True, reason="uses spatial.distance.cdist",
151
+ jax_jit=False, allow_dask_compute=True)
152
+ def vq(obs, code_book, check_finite=True):
153
+ """
154
+ Assign codes from a code book to observations.
155
+
156
+ Assigns a code from a code book to each observation. Each
157
+ observation vector in the 'M' by 'N' `obs` array is compared with the
158
+ centroids in the code book and assigned the code of the closest
159
+ centroid.
160
+
161
+ The features in `obs` should have unit variance, which can be
162
+ achieved by passing them through the whiten function. The code
163
+ book can be created with the k-means algorithm or a different
164
+ encoding algorithm.
165
+
166
+ Parameters
167
+ ----------
168
+ obs : ndarray
169
+ Each row of the 'M' x 'N' array is an observation. The columns are
170
+ the "features" seen during each observation. The features must be
171
+ whitened first using the whiten function or something equivalent.
172
+ code_book : ndarray
173
+ The code book is usually generated using the k-means algorithm.
174
+ Each row of the array holds a different code, and the columns are
175
+ the features of the code::
176
+
177
+ # f0 f1 f2 f3
178
+ code_book = [[ 1., 2., 3., 4.], #c0
179
+ [ 1., 2., 3., 4.], #c1
180
+ [ 1., 2., 3., 4.]] #c2
181
+
182
+ check_finite : bool, optional
183
+ Whether to check that the input matrices contain only finite numbers.
184
+ Disabling may give a performance gain, but may result in problems
185
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
186
+ Default: True
187
+
188
+ Returns
189
+ -------
190
+ code : ndarray
191
+ A length M array holding the code book index for each observation.
192
+ dist : ndarray
193
+ The distortion (distance) between the observation and its nearest
194
+ code.
195
+
196
+ Examples
197
+ --------
198
+ >>> import numpy as np
199
+ >>> from scipy.cluster.vq import vq
200
+ >>> code_book = np.array([[1., 1., 1.],
201
+ ... [2., 2., 2.]])
202
+ >>> features = np.array([[1.9, 2.3, 1.7],
203
+ ... [1.5, 2.5, 2.2],
204
+ ... [0.8, 0.6, 1.7]])
205
+ >>> vq(features, code_book)
206
+ (array([1, 1, 0], dtype=int32), array([0.43588989, 0.73484692, 0.83066239]))
207
+
208
+ """
209
+ xp = array_namespace(obs, code_book)
210
+ obs = _asarray(obs, xp=xp, check_finite=check_finite)
211
+ code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
212
+ ct = xp.result_type(obs, code_book)
213
+
214
+ if xp.isdtype(ct, kind='real floating'):
215
+ c_obs = xp.astype(obs, ct, copy=False)
216
+ c_code_book = xp.astype(code_book, ct, copy=False)
217
+ c_obs = np.asarray(c_obs)
218
+ c_code_book = np.asarray(c_code_book)
219
+ result = _vq.vq(c_obs, c_code_book)
220
+ return xp.asarray(result[0]), xp.asarray(result[1])
221
+ return py_vq(obs, code_book, check_finite=False)
222
+
223
+
224
+ def py_vq(obs, code_book, check_finite=True):
225
+ """ Python version of vq algorithm.
226
+
227
+ The algorithm computes the Euclidean distance between each
228
+ observation and every frame in the code_book.
229
+
230
+ Parameters
231
+ ----------
232
+ obs : ndarray
233
+ Expects a rank 2 array. Each row is one observation.
234
+ code_book : ndarray
235
+ Code book to use. Same format than obs. Should have same number of
236
+ features (e.g., columns) than obs.
237
+ check_finite : bool, optional
238
+ Whether to check that the input matrices contain only finite numbers.
239
+ Disabling may give a performance gain, but may result in problems
240
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
241
+ Default: True
242
+
243
+ Returns
244
+ -------
245
+ code : ndarray
246
+ code[i] gives the label of the ith obversation; its code is
247
+ code_book[code[i]].
248
+ mind_dist : ndarray
249
+ min_dist[i] gives the distance between the ith observation and its
250
+ corresponding code.
251
+
252
+ Notes
253
+ -----
254
+ This function is slower than the C version but works for
255
+ all input types. If the inputs have the wrong types for the
256
+ C versions of the function, this one is called as a last resort.
257
+
258
+ It is about 20 times slower than the C version.
259
+
260
+ """
261
+ xp = array_namespace(obs, code_book)
262
+ obs = _asarray(obs, xp=xp, check_finite=check_finite)
263
+ code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
264
+
265
+ if obs.ndim != code_book.ndim:
266
+ raise ValueError("Observation and code_book should have the same rank")
267
+
268
+ if obs.ndim == 1:
269
+ obs = obs[:, xp.newaxis]
270
+ code_book = code_book[:, xp.newaxis]
271
+
272
+ # Once `cdist` has array API support, this `xp.asarray` call can be removed
273
+ dist = xp.asarray(cdist(obs, code_book))
274
+ code = xp.argmin(dist, axis=1)
275
+ min_dist = xp.min(dist, axis=1)
276
+ return code, min_dist
277
+
278
+
279
+ def _kmeans(obs, guess, thresh=1e-5, xp=None):
280
+ """ "raw" version of k-means.
281
+
282
+ Returns
283
+ -------
284
+ code_book
285
+ The lowest distortion codebook found.
286
+ avg_dist
287
+ The average distance a observation is from a code in the book.
288
+ Lower means the code_book matches the data better.
289
+
290
+ See Also
291
+ --------
292
+ kmeans : wrapper around k-means
293
+
294
+ Examples
295
+ --------
296
+ Note: not whitened in this example.
297
+
298
+ >>> import numpy as np
299
+ >>> from scipy.cluster.vq import _kmeans
300
+ >>> features = np.array([[ 1.9,2.3],
301
+ ... [ 1.5,2.5],
302
+ ... [ 0.8,0.6],
303
+ ... [ 0.4,1.8],
304
+ ... [ 1.0,1.0]])
305
+ >>> book = np.array((features[0],features[2]))
306
+ >>> _kmeans(features,book)
307
+ (array([[ 1.7 , 2.4 ],
308
+ [ 0.73333333, 1.13333333]]), 0.40563916697728591)
309
+
310
+ """
311
+ xp = np if xp is None else xp
312
+ code_book = guess
313
+ diff = xp.inf
314
+ prev_avg_dists = deque([diff], maxlen=2)
315
+
316
+ np_obs = np.asarray(obs)
317
+ while diff > thresh:
318
+ # compute membership and distances between obs and code_book
319
+ obs_code, distort = vq(obs, code_book, check_finite=False)
320
+ prev_avg_dists.append(xp.mean(distort, axis=-1))
321
+ # recalc code_book as centroids of associated obs
322
+ obs_code = np.asarray(obs_code)
323
+ code_book, has_members = _vq.update_cluster_means(np_obs, obs_code,
324
+ code_book.shape[0])
325
+ code_book = code_book[has_members]
326
+ code_book = xp.asarray(code_book)
327
+ diff = xp.abs(prev_avg_dists[0] - prev_avg_dists[1])
328
+
329
+ return code_book, prev_avg_dists[1]
330
+
331
+
332
+ @xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
333
+ @_transition_to_rng("seed")
334
+ def kmeans(obs, k_or_guess, iter=20, thresh=1e-5, check_finite=True,
335
+ *, rng=None):
336
+ """
337
+ Performs k-means on a set of observation vectors forming k clusters.
338
+
339
+ The k-means algorithm adjusts the classification of the observations
340
+ into clusters and updates the cluster centroids until the position of
341
+ the centroids is stable over successive iterations. In this
342
+ implementation of the algorithm, the stability of the centroids is
343
+ determined by comparing the absolute value of the change in the average
344
+ Euclidean distance between the observations and their corresponding
345
+ centroids against a threshold. This yields
346
+ a code book mapping centroids to codes and vice versa.
347
+
348
+ Parameters
349
+ ----------
350
+ obs : ndarray
351
+ Each row of the M by N array is an observation vector. The
352
+ columns are the features seen during each observation.
353
+ The features must be whitened first with the `whiten` function.
354
+
355
+ k_or_guess : int or ndarray
356
+ The number of centroids to generate. A code is assigned to
357
+ each centroid, which is also the row index of the centroid
358
+ in the code_book matrix generated.
359
+
360
+ The initial k centroids are chosen by randomly selecting
361
+ observations from the observation matrix. Alternatively,
362
+ passing a k by N array specifies the initial k centroids.
363
+
364
+ iter : int, optional
365
+ The number of times to run k-means, returning the codebook
366
+ with the lowest distortion. This argument is ignored if
367
+ initial centroids are specified with an array for the
368
+ ``k_or_guess`` parameter. This parameter does not represent the
369
+ number of iterations of the k-means algorithm.
370
+
371
+ thresh : float, optional
372
+ Terminates the k-means algorithm if the change in
373
+ distortion since the last k-means iteration is less than
374
+ or equal to threshold.
375
+
376
+ check_finite : bool, optional
377
+ Whether to check that the input matrices contain only finite numbers.
378
+ Disabling may give a performance gain, but may result in problems
379
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
380
+ Default: True
381
+ rng : `numpy.random.Generator`, optional
382
+ Pseudorandom number generator state. When `rng` is None, a new
383
+ `numpy.random.Generator` is created using entropy from the
384
+ operating system. Types other than `numpy.random.Generator` are
385
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
386
+
387
+ Returns
388
+ -------
389
+ codebook : ndarray
390
+ A k by N array of k centroids. The ith centroid
391
+ codebook[i] is represented with the code i. The centroids
392
+ and codes generated represent the lowest distortion seen,
393
+ not necessarily the globally minimal distortion.
394
+ Note that the number of centroids is not necessarily the same as the
395
+ ``k_or_guess`` parameter, because centroids assigned to no observations
396
+ are removed during iterations.
397
+
398
+ distortion : float
399
+ The mean (non-squared) Euclidean distance between the observations
400
+ passed and the centroids generated. Note the difference to the standard
401
+ definition of distortion in the context of the k-means algorithm, which
402
+ is the sum of the squared distances.
403
+
404
+ See Also
405
+ --------
406
+ kmeans2 : a different implementation of k-means clustering
407
+ with more methods for generating initial centroids but without
408
+ using a distortion change threshold as a stopping criterion.
409
+
410
+ whiten : must be called prior to passing an observation matrix
411
+ to kmeans.
412
+
413
+ Notes
414
+ -----
415
+ For more functionalities or optimal performance, you can use
416
+ `sklearn.cluster.KMeans <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html>`_.
417
+ `This <https://hdbscan.readthedocs.io/en/latest/performance_and_scalability.html#comparison-of-high-performance-implementations>`_
418
+ is a benchmark result of several implementations.
419
+
420
+ Examples
421
+ --------
422
+ >>> import numpy as np
423
+ >>> from scipy.cluster.vq import vq, kmeans, whiten
424
+ >>> import matplotlib.pyplot as plt
425
+ >>> features = np.array([[ 1.9,2.3],
426
+ ... [ 1.5,2.5],
427
+ ... [ 0.8,0.6],
428
+ ... [ 0.4,1.8],
429
+ ... [ 0.1,0.1],
430
+ ... [ 0.2,1.8],
431
+ ... [ 2.0,0.5],
432
+ ... [ 0.3,1.5],
433
+ ... [ 1.0,1.0]])
434
+ >>> whitened = whiten(features)
435
+ >>> book = np.array((whitened[0],whitened[2]))
436
+ >>> kmeans(whitened,book)
437
+ (array([[ 2.3110306 , 2.86287398], # random
438
+ [ 0.93218041, 1.24398691]]), 0.85684700941625547)
439
+
440
+ >>> codes = 3
441
+ >>> kmeans(whitened,codes)
442
+ (array([[ 2.3110306 , 2.86287398], # random
443
+ [ 1.32544402, 0.65607529],
444
+ [ 0.40782893, 2.02786907]]), 0.5196582527686241)
445
+
446
+ >>> # Create 50 datapoints in two clusters a and b
447
+ >>> pts = 50
448
+ >>> rng = np.random.default_rng()
449
+ >>> a = rng.multivariate_normal([0, 0], [[4, 1], [1, 4]], size=pts)
450
+ >>> b = rng.multivariate_normal([30, 10],
451
+ ... [[10, 2], [2, 1]],
452
+ ... size=pts)
453
+ >>> features = np.concatenate((a, b))
454
+ >>> # Whiten data
455
+ >>> whitened = whiten(features)
456
+ >>> # Find 2 clusters in the data
457
+ >>> codebook, distortion = kmeans(whitened, 2)
458
+ >>> # Plot whitened data and cluster centers in red
459
+ >>> plt.scatter(whitened[:, 0], whitened[:, 1])
460
+ >>> plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
461
+ >>> plt.show()
462
+
463
+ """
464
+ if isinstance(k_or_guess, int):
465
+ xp = array_namespace(obs)
466
+ else:
467
+ xp = array_namespace(obs, k_or_guess)
468
+ obs = _asarray(obs, xp=xp, check_finite=check_finite)
469
+ guess = _asarray(k_or_guess, xp=xp, check_finite=check_finite)
470
+ if iter < 1:
471
+ raise ValueError(f"iter must be at least 1, got {iter}")
472
+
473
+ # Determine whether a count (scalar) or an initial guess (array) was passed.
474
+ if xp_size(guess) != 1:
475
+ if xp_size(guess) < 1:
476
+ raise ValueError(f"Asked for 0 clusters. Initial book was {guess}")
477
+ return _kmeans(obs, guess, thresh=thresh, xp=xp)
478
+
479
+ # k_or_guess is a scalar, now verify that it's an integer
480
+ k = int(guess)
481
+ if k != guess:
482
+ raise ValueError("If k_or_guess is a scalar, it must be an integer.")
483
+ if k < 1:
484
+ raise ValueError(f"Asked for {k} clusters.")
485
+
486
+ rng = check_random_state(rng)
487
+
488
+ # initialize best distance value to a large value
489
+ best_dist = xp.inf
490
+ for i in range(iter):
491
+ # the initial code book is randomly selected from observations
492
+ guess = _kpoints(obs, k, rng, xp)
493
+ book, dist = _kmeans(obs, guess, thresh=thresh, xp=xp)
494
+ if dist < best_dist:
495
+ best_book = book
496
+ best_dist = dist
497
+ return best_book, best_dist
498
+
499
+
500
+ def _kpoints(data, k, rng, xp):
501
+ """Pick k points at random in data (one row = one observation).
502
+
503
+ Parameters
504
+ ----------
505
+ data : ndarray
506
+ Expect a rank 1 or 2 array. Rank 1 are assumed to describe one
507
+ dimensional data, rank 2 multidimensional data, in which case one
508
+ row is one observation.
509
+ k : int
510
+ Number of samples to generate.
511
+ rng : `numpy.random.Generator` or `numpy.random.RandomState`
512
+ Random number generator.
513
+
514
+ Returns
515
+ -------
516
+ x : ndarray
517
+ A 'k' by 'N' containing the initial centroids
518
+
519
+ """
520
+ idx = rng.choice(data.shape[0], size=int(k), replace=False)
521
+ # convert to array with default integer dtype (avoids numpy#25607)
522
+ idx = xp.asarray(idx, dtype=xp.asarray([1]).dtype)
523
+ return xp.take(data, idx, axis=0)
524
+
525
+
526
+ def _krandinit(data, k, rng, xp):
527
+ """Returns k samples of a random variable whose parameters depend on data.
528
+
529
+ More precisely, it returns k observations sampled from a Gaussian random
530
+ variable whose mean and covariances are the ones estimated from the data.
531
+
532
+ Parameters
533
+ ----------
534
+ data : ndarray
535
+ Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
536
+ data, rank 2 multidimensional data, in which case one
537
+ row is one observation.
538
+ k : int
539
+ Number of samples to generate.
540
+ rng : `numpy.random.Generator` or `numpy.random.RandomState`
541
+ Random number generator.
542
+
543
+ Returns
544
+ -------
545
+ x : ndarray
546
+ A 'k' by 'N' containing the initial centroids
547
+
548
+ """
549
+ mu = xp.mean(data, axis=0)
550
+ k = np.asarray(k)
551
+
552
+ if data.ndim == 1:
553
+ _cov = xpx.cov(data, xp=xp)
554
+ x = rng.standard_normal(size=k)
555
+ x = xp.asarray(x)
556
+ x *= xp.sqrt(_cov)
557
+ elif data.shape[1] > data.shape[0]:
558
+ # initialize when the covariance matrix is rank deficient
559
+ _, s, vh = xp.linalg.svd(data - mu, full_matrices=False)
560
+ x = rng.standard_normal(size=(k, xp_size(s)))
561
+ x = xp.asarray(x)
562
+ sVh = s[:, None] * vh / xp.sqrt(data.shape[0] - xp.asarray(1.))
563
+ x = x @ sVh
564
+ else:
565
+ _cov = xpx.atleast_nd(xpx.cov(data.T, xp=xp), ndim=2, xp=xp)
566
+
567
+ # k rows, d cols (one row = one obs)
568
+ # Generate k sample of a random variable ~ Gaussian(mu, cov)
569
+ x = rng.standard_normal(size=(k, xp_size(mu)))
570
+ x = xp.asarray(x)
571
+ x = x @ xp.linalg.cholesky(_cov).T
572
+
573
+ x += mu
574
+ return x
575
+
576
+
577
+ def _kpp(data, k, rng, xp):
578
+ """ Picks k points in the data based on the kmeans++ method.
579
+
580
+ Parameters
581
+ ----------
582
+ data : ndarray
583
+ Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
584
+ data, rank 2 multidimensional data, in which case one
585
+ row is one observation.
586
+ k : int
587
+ Number of samples to generate.
588
+ rng : `numpy.random.Generator` or `numpy.random.RandomState`
589
+ Random number generator.
590
+
591
+ Returns
592
+ -------
593
+ init : ndarray
594
+ A 'k' by 'N' containing the initial centroids.
595
+
596
+ References
597
+ ----------
598
+ .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
599
+ careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
600
+ on Discrete Algorithms, 2007.
601
+ """
602
+
603
+ ndim = len(data.shape)
604
+ if ndim == 1:
605
+ data = data[:, None]
606
+
607
+ dims = data.shape[1]
608
+
609
+ init = xp.empty((int(k), dims))
610
+
611
+ for i in range(k):
612
+ if i == 0:
613
+ data_idx = rng_integers(rng, data.shape[0])
614
+ else:
615
+ D2 = cdist(init[:i,:], data, metric='sqeuclidean').min(axis=0)
616
+ probs = D2/D2.sum()
617
+ cumprobs = probs.cumsum()
618
+ r = rng.uniform()
619
+ cumprobs = np.asarray(cumprobs)
620
+ data_idx = int(np.searchsorted(cumprobs, r))
621
+
622
+ init = xpx.at(init)[i, :].set(data[data_idx, :])
623
+
624
+ if ndim == 1:
625
+ init = init[:, 0]
626
+ return init
627
+
628
+
629
+ _valid_init_meth = {'random': _krandinit, 'points': _kpoints, '++': _kpp}
630
+
631
+
632
+ def _missing_warn():
633
+ """Print a warning when called."""
634
+ warnings.warn("One of the clusters is empty. "
635
+ "Re-run kmeans with a different initialization.",
636
+ stacklevel=3)
637
+
638
+
639
+ def _missing_raise():
640
+ """Raise a ClusterError when called."""
641
+ raise ClusterError("One of the clusters is empty. "
642
+ "Re-run kmeans with a different initialization.")
643
+
644
+
645
+ _valid_miss_meth = {'warn': _missing_warn, 'raise': _missing_raise}
646
+
647
+
648
+ @xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
649
+ @_transition_to_rng("seed")
650
+ def kmeans2(data, k, iter=10, thresh=1e-5, minit='random',
651
+ missing='warn', check_finite=True, *, rng=None):
652
+ """
653
+ Classify a set of observations into k clusters using the k-means algorithm.
654
+
655
+ The algorithm attempts to minimize the Euclidean distance between
656
+ observations and centroids. Several initialization methods are
657
+ included.
658
+
659
+ Parameters
660
+ ----------
661
+ data : ndarray
662
+ A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
663
+ 'M' array of 'M' 1-D observations.
664
+ k : int or ndarray
665
+ The number of clusters to form as well as the number of
666
+ centroids to generate. If `minit` initialization string is
667
+ 'matrix', or if a ndarray is given instead, it is
668
+ interpreted as initial cluster to use instead.
669
+ iter : int, optional
670
+ Number of iterations of the k-means algorithm to run. Note
671
+ that this differs in meaning from the iters parameter to
672
+ the kmeans function.
673
+ thresh : float, optional
674
+ (not used yet)
675
+ minit : str, optional
676
+ Method for initialization. Available methods are 'random',
677
+ 'points', '++' and 'matrix':
678
+
679
+ 'random': generate k centroids from a Gaussian with mean and
680
+ variance estimated from the data.
681
+
682
+ 'points': choose k observations (rows) at random from data for
683
+ the initial centroids.
684
+
685
+ '++': choose k observations accordingly to the kmeans++ method
686
+ (careful seeding)
687
+
688
+ 'matrix': interpret the k parameter as a k by M (or length k
689
+ array for 1-D data) array of initial centroids.
690
+ missing : str, optional
691
+ Method to deal with empty clusters. Available methods are
692
+ 'warn' and 'raise':
693
+
694
+ 'warn': give a warning and continue.
695
+
696
+ 'raise': raise an ClusterError and terminate the algorithm.
697
+ check_finite : bool, optional
698
+ Whether to check that the input matrices contain only finite numbers.
699
+ Disabling may give a performance gain, but may result in problems
700
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
701
+ Default: True
702
+ rng : `numpy.random.Generator`, optional
703
+ Pseudorandom number generator state. When `rng` is None, a new
704
+ `numpy.random.Generator` is created using entropy from the
705
+ operating system. Types other than `numpy.random.Generator` are
706
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
707
+
708
+ Returns
709
+ -------
710
+ centroid : ndarray
711
+ A 'k' by 'N' array of centroids found at the last iteration of
712
+ k-means.
713
+ label : ndarray
714
+ label[i] is the code or index of the centroid the
715
+ ith observation is closest to.
716
+
717
+ See Also
718
+ --------
719
+ kmeans
720
+
721
+ References
722
+ ----------
723
+ .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
724
+ careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
725
+ on Discrete Algorithms, 2007.
726
+
727
+ Examples
728
+ --------
729
+ >>> from scipy.cluster.vq import kmeans2
730
+ >>> import matplotlib.pyplot as plt
731
+ >>> import numpy as np
732
+
733
+ Create z, an array with shape (100, 2) containing a mixture of samples
734
+ from three multivariate normal distributions.
735
+
736
+ >>> rng = np.random.default_rng()
737
+ >>> a = rng.multivariate_normal([0, 6], [[2, 1], [1, 1.5]], size=45)
738
+ >>> b = rng.multivariate_normal([2, 0], [[1, -1], [-1, 3]], size=30)
739
+ >>> c = rng.multivariate_normal([6, 4], [[5, 0], [0, 1.2]], size=25)
740
+ >>> z = np.concatenate((a, b, c))
741
+ >>> rng.shuffle(z)
742
+
743
+ Compute three clusters.
744
+
745
+ >>> centroid, label = kmeans2(z, 3, minit='points')
746
+ >>> centroid
747
+ array([[ 2.22274463, -0.61666946], # may vary
748
+ [ 0.54069047, 5.86541444],
749
+ [ 6.73846769, 4.01991898]])
750
+
751
+ How many points are in each cluster?
752
+
753
+ >>> counts = np.bincount(label)
754
+ >>> counts
755
+ array([29, 51, 20]) # may vary
756
+
757
+ Plot the clusters.
758
+
759
+ >>> w0 = z[label == 0]
760
+ >>> w1 = z[label == 1]
761
+ >>> w2 = z[label == 2]
762
+ >>> plt.plot(w0[:, 0], w0[:, 1], 'o', alpha=0.5, label='cluster 0')
763
+ >>> plt.plot(w1[:, 0], w1[:, 1], 'd', alpha=0.5, label='cluster 1')
764
+ >>> plt.plot(w2[:, 0], w2[:, 1], 's', alpha=0.5, label='cluster 2')
765
+ >>> plt.plot(centroid[:, 0], centroid[:, 1], 'k*', label='centroids')
766
+ >>> plt.axis('equal')
767
+ >>> plt.legend(shadow=True)
768
+ >>> plt.show()
769
+
770
+ """
771
+ if int(iter) < 1:
772
+ raise ValueError(f"Invalid iter ({iter}), must be a positive integer.")
773
+ try:
774
+ miss_meth = _valid_miss_meth[missing]
775
+ except KeyError as e:
776
+ raise ValueError(f"Unknown missing method {missing!r}") from e
777
+
778
+ if isinstance(k, int):
779
+ xp = array_namespace(data)
780
+ else:
781
+ xp = array_namespace(data, k)
782
+ data = _asarray(data, xp=xp, check_finite=check_finite)
783
+ code_book = xp_copy(k, xp=xp)
784
+ if data.ndim == 1:
785
+ d = 1
786
+ elif data.ndim == 2:
787
+ d = data.shape[1]
788
+ else:
789
+ raise ValueError("Input of rank > 2 is not supported.")
790
+
791
+ if xp_size(data) < 1 or xp_size(code_book) < 1:
792
+ raise ValueError("Empty input is not supported.")
793
+
794
+ # If k is not a single value, it should be compatible with data's shape
795
+ if minit == 'matrix' or xp_size(code_book) > 1:
796
+ if data.ndim != code_book.ndim:
797
+ raise ValueError("k array doesn't match data rank")
798
+ nc = code_book.shape[0]
799
+ if data.ndim > 1 and code_book.shape[1] != d:
800
+ raise ValueError("k array doesn't match data dimension")
801
+ else:
802
+ nc = int(code_book)
803
+
804
+ if nc < 1:
805
+ raise ValueError(
806
+ f"Cannot ask kmeans2 for {nc} clusters (k was {code_book})"
807
+ )
808
+ elif nc != code_book:
809
+ warnings.warn("k was not an integer, was converted.", stacklevel=2)
810
+
811
+ try:
812
+ init_meth = _valid_init_meth[minit]
813
+ except KeyError as e:
814
+ raise ValueError(f"Unknown init method {minit!r}") from e
815
+ else:
816
+ rng = check_random_state(rng)
817
+ code_book = init_meth(data, code_book, rng, xp)
818
+
819
+ data = np.asarray(data)
820
+ code_book = np.asarray(code_book)
821
+ for _ in range(iter):
822
+ # Compute the nearest neighbor for each obs using the current code book
823
+ label = vq(data, code_book, check_finite=check_finite)[0]
824
+ # Update the code book by computing centroids
825
+ new_code_book, has_members = _vq.update_cluster_means(data, label, nc)
826
+ if not has_members.all():
827
+ miss_meth()
828
+ # Set the empty clusters to their previous positions
829
+ new_code_book[~has_members] = code_book[~has_members]
830
+ code_book = new_code_book
831
+
832
+ return xp.asarray(code_book), xp.asarray(label)
tool_server/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ ==================================
3
+ Constants (:mod:`scipy.constants`)
4
+ ==================================
5
+
6
+ .. currentmodule:: scipy.constants
7
+
8
+ Physical and mathematical constants and units.
9
+
10
+
11
+ Mathematical constants
12
+ ======================
13
+
14
+ ================ =================================================================
15
+ ``pi`` Pi
16
+ ``golden`` Golden ratio
17
+ ``golden_ratio`` Golden ratio
18
+ ================ =================================================================
19
+
20
+
21
+ Physical constants
22
+ ==================
23
+ The following physical constants are available as attributes of `scipy.constants`.
24
+ All units are `SI <https://en.wikipedia.org/wiki/International_System_of_Units>`_.
25
+
26
+ =========================== ================================================================ ===============
27
+ Attribute Quantity Units
28
+ =========================== ================================================================ ===============
29
+ ``c`` speed of light in vacuum m s^-1
30
+ ``speed_of_light`` speed of light in vacuum m s^-1
31
+ ``mu_0`` the magnetic constant :math:`\mu_0` N A^-2
32
+ ``epsilon_0`` the electric constant (vacuum permittivity), :math:`\epsilon_0` F m^-1
33
+ ``h`` the Planck constant :math:`h` J Hz^-1
34
+ ``Planck`` the Planck constant :math:`h` J Hz^-1
35
+ ``hbar`` the reduced Planck constant, :math:`\hbar = h/(2\pi)` J s
36
+ ``G`` Newtonian constant of gravitation m^3 kg^-1 s^-2
37
+ ``gravitational_constant`` Newtonian constant of gravitation m^3 kg^-1 s^-2
38
+ ``g`` standard acceleration of gravity m s^-2
39
+ ``e`` elementary charge C
40
+ ``elementary_charge`` elementary charge C
41
+ ``R`` molar gas constant J mol^-1 K^-1
42
+ ``gas_constant`` molar gas constant J mol^-1 K^-1
43
+ ``alpha`` fine-structure constant (unitless)
44
+ ``fine_structure`` fine-structure constant (unitless)
45
+ ``N_A`` Avogadro constant mol^-1
46
+ ``Avogadro`` Avogadro constant mol^-1
47
+ ``k`` Boltzmann constant J K^-1
48
+ ``Boltzmann`` Boltzmann constant J K^-1
49
+ ``sigma`` Stefan-Boltzmann constant :math:`\sigma` W m^-2 K^-4
50
+ ``Stefan_Boltzmann`` Stefan-Boltzmann constant :math:`\sigma` W m^-2 K^-4
51
+ ``Wien`` Wien wavelength displacement law constant m K
52
+ ``Rydberg`` Rydberg constant m^-1
53
+ ``m_e`` electron mass kg
54
+ ``electron_mass`` electron mass kg
55
+ ``m_p`` proton mass kg
56
+ ``proton_mass`` proton mass kg
57
+ ``m_n`` neutron mass kg
58
+ ``neutron_mass`` neutron mass kg
59
+ =========================== ================================================================ ===============
60
+
61
+
62
+ Constants database
63
+ ------------------
64
+
65
+ In addition to the above variables, :mod:`scipy.constants` also contains the
66
+ 2022 CODATA recommended values [CODATA2022]_ database containing more physical
67
+ constants.
68
+
69
+ .. autosummary::
70
+ :toctree: generated/
71
+
72
+ value -- Value in physical_constants indexed by key
73
+ unit -- Unit in physical_constants indexed by key
74
+ precision -- Relative precision in physical_constants indexed by key
75
+ find -- Return list of physical_constant keys with a given string
76
+ ConstantWarning -- Constant sought not in newest CODATA data set
77
+
78
+ .. data:: physical_constants
79
+
80
+ Dictionary of physical constants, of the format
81
+ ``physical_constants[name] = (value, unit, uncertainty)``.
82
+ The CODATA database uses ellipses to indicate that a value is defined
83
+ (exactly) in terms of others but cannot be represented exactly with the
84
+ allocated number of digits. In these cases, SciPy calculates the derived
85
+ value and reports it to the full precision of a Python ``float``. Although
86
+ ``physical_constants`` lists the uncertainty as ``0.0`` to indicate that
87
+ the CODATA value is exact, the value in ``physical_constants`` is still
88
+ subject to the truncation error inherent in double-precision representation.
89
+
90
+ Available constants:
91
+
92
+ ====================================================================== ====
93
+ %(constant_names)s
94
+ ====================================================================== ====
95
+
96
+
97
+ Units
98
+ =====
99
+
100
+ SI prefixes
101
+ -----------
102
+
103
+ ============ =================================================================
104
+ ``quetta`` :math:`10^{30}`
105
+ ``ronna`` :math:`10^{27}`
106
+ ``yotta`` :math:`10^{24}`
107
+ ``zetta`` :math:`10^{21}`
108
+ ``exa`` :math:`10^{18}`
109
+ ``peta`` :math:`10^{15}`
110
+ ``tera`` :math:`10^{12}`
111
+ ``giga`` :math:`10^{9}`
112
+ ``mega`` :math:`10^{6}`
113
+ ``kilo`` :math:`10^{3}`
114
+ ``hecto`` :math:`10^{2}`
115
+ ``deka`` :math:`10^{1}`
116
+ ``deci`` :math:`10^{-1}`
117
+ ``centi`` :math:`10^{-2}`
118
+ ``milli`` :math:`10^{-3}`
119
+ ``micro`` :math:`10^{-6}`
120
+ ``nano`` :math:`10^{-9}`
121
+ ``pico`` :math:`10^{-12}`
122
+ ``femto`` :math:`10^{-15}`
123
+ ``atto`` :math:`10^{-18}`
124
+ ``zepto`` :math:`10^{-21}`
125
+ ``yocto`` :math:`10^{-24}`
126
+ ``ronto`` :math:`10^{-27}`
127
+ ``quecto`` :math:`10^{-30}`
128
+ ============ =================================================================
129
+
130
+ Binary prefixes
131
+ ---------------
132
+
133
+ ============ =================================================================
134
+ ``kibi`` :math:`2^{10}`
135
+ ``mebi`` :math:`2^{20}`
136
+ ``gibi`` :math:`2^{30}`
137
+ ``tebi`` :math:`2^{40}`
138
+ ``pebi`` :math:`2^{50}`
139
+ ``exbi`` :math:`2^{60}`
140
+ ``zebi`` :math:`2^{70}`
141
+ ``yobi`` :math:`2^{80}`
142
+ ============ =================================================================
143
+
144
+ Mass
145
+ ----
146
+
147
+ ================= ============================================================
148
+ ``gram`` :math:`10^{-3}` kg
149
+ ``metric_ton`` :math:`10^{3}` kg
150
+ ``grain`` one grain in kg
151
+ ``lb`` one pound (avoirdupous) in kg
152
+ ``pound`` one pound (avoirdupous) in kg
153
+ ``blob`` one inch version of a slug in kg (added in 1.0.0)
154
+ ``slinch`` one inch version of a slug in kg (added in 1.0.0)
155
+ ``slug`` one slug in kg (added in 1.0.0)
156
+ ``oz`` one ounce in kg
157
+ ``ounce`` one ounce in kg
158
+ ``stone`` one stone in kg
159
+ ``grain`` one grain in kg
160
+ ``long_ton`` one long ton in kg
161
+ ``short_ton`` one short ton in kg
162
+ ``troy_ounce`` one Troy ounce in kg
163
+ ``troy_pound`` one Troy pound in kg
164
+ ``carat`` one carat in kg
165
+ ``m_u`` atomic mass constant (in kg)
166
+ ``u`` atomic mass constant (in kg)
167
+ ``atomic_mass`` atomic mass constant (in kg)
168
+ ================= ============================================================
169
+
170
+ Angle
171
+ -----
172
+
173
+ ================= ============================================================
174
+ ``degree`` degree in radians
175
+ ``arcmin`` arc minute in radians
176
+ ``arcminute`` arc minute in radians
177
+ ``arcsec`` arc second in radians
178
+ ``arcsecond`` arc second in radians
179
+ ================= ============================================================
180
+
181
+
182
+ Time
183
+ ----
184
+
185
+ ================= ============================================================
186
+ ``minute`` one minute in seconds
187
+ ``hour`` one hour in seconds
188
+ ``day`` one day in seconds
189
+ ``week`` one week in seconds
190
+ ``year`` one year (365 days) in seconds
191
+ ``Julian_year`` one Julian year (365.25 days) in seconds
192
+ ================= ============================================================
193
+
194
+
195
+ Length
196
+ ------
197
+
198
+ ===================== ============================================================
199
+ ``inch`` one inch in meters
200
+ ``foot`` one foot in meters
201
+ ``yard`` one yard in meters
202
+ ``mile`` one mile in meters
203
+ ``mil`` one mil in meters
204
+ ``pt`` one point in meters
205
+ ``point`` one point in meters
206
+ ``survey_foot`` one survey foot in meters
207
+ ``survey_mile`` one survey mile in meters
208
+ ``nautical_mile`` one nautical mile in meters
209
+ ``fermi`` one Fermi in meters
210
+ ``angstrom`` one Angstrom in meters
211
+ ``micron`` one micron in meters
212
+ ``au`` one astronomical unit in meters
213
+ ``astronomical_unit`` one astronomical unit in meters
214
+ ``light_year`` one light year in meters
215
+ ``parsec`` one parsec in meters
216
+ ===================== ============================================================
217
+
218
+ Pressure
219
+ --------
220
+
221
+ ================= ============================================================
222
+ ``atm`` standard atmosphere in pascals
223
+ ``atmosphere`` standard atmosphere in pascals
224
+ ``bar`` one bar in pascals
225
+ ``torr`` one torr (mmHg) in pascals
226
+ ``mmHg`` one torr (mmHg) in pascals
227
+ ``psi`` one psi in pascals
228
+ ================= ============================================================
229
+
230
+ Area
231
+ ----
232
+
233
+ ================= ============================================================
234
+ ``hectare`` one hectare in square meters
235
+ ``acre`` one acre in square meters
236
+ ================= ============================================================
237
+
238
+
239
+ Volume
240
+ ------
241
+
242
+ =================== ========================================================
243
+ ``liter`` one liter in cubic meters
244
+ ``litre`` one liter in cubic meters
245
+ ``gallon`` one gallon (US) in cubic meters
246
+ ``gallon_US`` one gallon (US) in cubic meters
247
+ ``gallon_imp`` one gallon (UK) in cubic meters
248
+ ``fluid_ounce`` one fluid ounce (US) in cubic meters
249
+ ``fluid_ounce_US`` one fluid ounce (US) in cubic meters
250
+ ``fluid_ounce_imp`` one fluid ounce (UK) in cubic meters
251
+ ``bbl`` one barrel in cubic meters
252
+ ``barrel`` one barrel in cubic meters
253
+ =================== ========================================================
254
+
255
+ Speed
256
+ -----
257
+
258
+ ================== ==========================================================
259
+ ``kmh`` kilometers per hour in meters per second
260
+ ``mph`` miles per hour in meters per second
261
+ ``mach`` one Mach (approx., at 15 C, 1 atm) in meters per second
262
+ ``speed_of_sound`` one Mach (approx., at 15 C, 1 atm) in meters per second
263
+ ``knot`` one knot in meters per second
264
+ ================== ==========================================================
265
+
266
+
267
+ Temperature
268
+ -----------
269
+
270
+ ===================== =======================================================
271
+ ``zero_Celsius`` zero of Celsius scale in Kelvin
272
+ ``degree_Fahrenheit`` one Fahrenheit (only differences) in Kelvins
273
+ ===================== =======================================================
274
+
275
+ .. autosummary::
276
+ :toctree: generated/
277
+
278
+ convert_temperature
279
+
280
+ Energy
281
+ ------
282
+
283
+ ==================== =======================================================
284
+ ``eV`` one electron volt in Joules
285
+ ``electron_volt`` one electron volt in Joules
286
+ ``calorie`` one calorie (thermochemical) in Joules
287
+ ``calorie_th`` one calorie (thermochemical) in Joules
288
+ ``calorie_IT`` one calorie (International Steam Table calorie, 1956) in Joules
289
+ ``erg`` one erg in Joules
290
+ ``Btu`` one British thermal unit (International Steam Table) in Joules
291
+ ``Btu_IT`` one British thermal unit (International Steam Table) in Joules
292
+ ``Btu_th`` one British thermal unit (thermochemical) in Joules
293
+ ``ton_TNT`` one ton of TNT in Joules
294
+ ==================== =======================================================
295
+
296
+ Power
297
+ -----
298
+
299
+ ==================== =======================================================
300
+ ``hp`` one horsepower in watts
301
+ ``horsepower`` one horsepower in watts
302
+ ==================== =======================================================
303
+
304
+ Force
305
+ -----
306
+
307
+ ==================== =======================================================
308
+ ``dyn`` one dyne in newtons
309
+ ``dyne`` one dyne in newtons
310
+ ``lbf`` one pound force in newtons
311
+ ``pound_force`` one pound force in newtons
312
+ ``kgf`` one kilogram force in newtons
313
+ ``kilogram_force`` one kilogram force in newtons
314
+ ==================== =======================================================
315
+
316
+ Optics
317
+ ------
318
+
319
+ .. autosummary::
320
+ :toctree: generated/
321
+
322
+ lambda2nu
323
+ nu2lambda
324
+
325
+ References
326
+ ==========
327
+
328
+ .. [CODATA2022] CODATA Recommended Values of the Fundamental
329
+ Physical Constants 2022.
330
+
331
+ https://physics.nist.gov/cuu/Constants/
332
+
333
+ """ # noqa: E501
334
+ # Modules contributed by BasSw (wegwerp@gmail.com)
335
+ from ._codata import *
336
+ from ._constants import *
337
+ from ._codata import _obsolete_constants, physical_constants
338
+
339
+ # Deprecated namespaces, to be removed in v2.0.0
340
+ from . import codata, constants
341
+
342
+ _constant_names_list = [(_k.lower(), _k, _v)
343
+ for _k, _v in physical_constants.items()
344
+ if _k not in _obsolete_constants]
345
+ _constant_names = "\n".join(["``{}``{} {} {}".format(_x[1], " "*(66-len(_x[1])),
346
+ _x[2][0], _x[2][1])
347
+ for _x in sorted(_constant_names_list)])
348
+ if __doc__:
349
+ __doc__ = __doc__ % dict(constant_names=_constant_names)
350
+
351
+ del _constant_names
352
+ del _constant_names_list
353
+
354
+ __all__ = [s for s in dir() if not s.startswith('_')]
355
+
356
+ from scipy._lib._testutils import PytestTester
357
+ test = PytestTester(__name__)
358
+ del PytestTester
tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py ADDED
The diff for this file is too large to render. See raw diff
 
tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Collection of physical constants and conversion factors.
3
+
4
+ Most constants are in SI units, so you can do
5
+ print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
6
+
7
+ The list is not meant to be comprehensive, but just convenient for everyday use.
8
+ """
9
+
10
+ import math as _math
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from ._codata import value as _cd
14
+
15
+ if TYPE_CHECKING:
16
+ import numpy.typing as npt
17
+
18
+ from scipy._lib._array_api import array_namespace, _asarray, xp_capabilities
19
+
20
+
21
+ """
22
+ BasSw 2006
23
+ physical constants: imported from CODATA
24
+ unit conversion: see e.g., NIST special publication 811
25
+ Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
26
+ Some constants exist in a few variants, which are marked with suffixes.
27
+ The ones without any suffix should be the most common ones.
28
+ """
29
+
30
+ __all__ = [
31
+ 'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
32
+ 'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
33
+ 'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
34
+ 'angstrom', 'arcmin', 'arcminute', 'arcsec',
35
+ 'arcsecond', 'astronomical_unit', 'atm',
36
+ 'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
37
+ 'barrel', 'bbl', 'blob', 'c', 'calorie',
38
+ 'calorie_IT', 'calorie_th', 'carat', 'centi',
39
+ 'convert_temperature', 'day', 'deci', 'degree',
40
+ 'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
41
+ 'eV', 'electron_mass', 'electron_volt',
42
+ 'elementary_charge', 'epsilon_0', 'erg',
43
+ 'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
44
+ 'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
45
+ 'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
46
+ 'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
47
+ 'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
48
+ 'hectare', 'hecto', 'horsepower', 'hour', 'hp',
49
+ 'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
50
+ 'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
51
+ 'light_year', 'liter', 'litre', 'long_ton', 'm_e',
52
+ 'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
53
+ 'metric_ton', 'micro', 'micron', 'mil', 'mile',
54
+ 'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
55
+ 'nautical_mile', 'neutron_mass', 'nu2lambda',
56
+ 'ounce', 'oz', 'parsec', 'pebi', 'peta',
57
+ 'pi', 'pico', 'point', 'pound', 'pound_force',
58
+ 'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
59
+ 'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
60
+ 'speed_of_sound', 'stone', 'survey_foot',
61
+ 'survey_mile', 'tebi', 'tera', 'ton_TNT',
62
+ 'torr', 'troy_ounce', 'troy_pound', 'u',
63
+ 'week', 'yard', 'year', 'yobi', 'yocto',
64
+ 'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
65
+ ]
66
+
67
+
68
+ # mathematical constants
69
+ pi = _math.pi
70
+ golden = golden_ratio = (1 + _math.sqrt(5)) / 2
71
+
72
+ # SI prefixes
73
+ quetta = 1e30
74
+ ronna = 1e27
75
+ yotta = 1e24
76
+ zetta = 1e21
77
+ exa = 1e18
78
+ peta = 1e15
79
+ tera = 1e12
80
+ giga = 1e9
81
+ mega = 1e6
82
+ kilo = 1e3
83
+ hecto = 1e2
84
+ deka = 1e1
85
+ deci = 1e-1
86
+ centi = 1e-2
87
+ milli = 1e-3
88
+ micro = 1e-6
89
+ nano = 1e-9
90
+ pico = 1e-12
91
+ femto = 1e-15
92
+ atto = 1e-18
93
+ zepto = 1e-21
94
+ yocto = 1e-24
95
+ ronto = 1e-27
96
+ quecto = 1e-30
97
+
98
+ # binary prefixes
99
+ kibi = 2**10
100
+ mebi = 2**20
101
+ gibi = 2**30
102
+ tebi = 2**40
103
+ pebi = 2**50
104
+ exbi = 2**60
105
+ zebi = 2**70
106
+ yobi = 2**80
107
+
108
+ # physical constants
109
+ c = speed_of_light = _cd('speed of light in vacuum')
110
+ mu_0 = _cd('vacuum mag. permeability')
111
+ epsilon_0 = _cd('vacuum electric permittivity')
112
+ h = Planck = _cd('Planck constant')
113
+ hbar = _cd('reduced Planck constant')
114
+ G = gravitational_constant = _cd('Newtonian constant of gravitation')
115
+ g = _cd('standard acceleration of gravity')
116
+ e = elementary_charge = _cd('elementary charge')
117
+ R = gas_constant = _cd('molar gas constant')
118
+ alpha = fine_structure = _cd('fine-structure constant')
119
+ N_A = Avogadro = _cd('Avogadro constant')
120
+ k = Boltzmann = _cd('Boltzmann constant')
121
+ sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
122
+ Wien = _cd('Wien wavelength displacement law constant')
123
+ Rydberg = _cd('Rydberg constant')
124
+
125
+ # mass in kg
126
+ gram = 1e-3
127
+ metric_ton = 1e3
128
+ grain = 64.79891e-6
129
+ lb = pound = 7000 * grain # avoirdupois
130
+ blob = slinch = pound * g / 0.0254 # lbf*s**2/in (added in 1.0.0)
131
+ slug = blob / 12 # lbf*s**2/foot (added in 1.0.0)
132
+ oz = ounce = pound / 16
133
+ stone = 14 * pound
134
+ long_ton = 2240 * pound
135
+ short_ton = 2000 * pound
136
+
137
+ troy_ounce = 480 * grain # only for metals / gems
138
+ troy_pound = 12 * troy_ounce
139
+ carat = 200e-6
140
+
141
+ m_e = electron_mass = _cd('electron mass')
142
+ m_p = proton_mass = _cd('proton mass')
143
+ m_n = neutron_mass = _cd('neutron mass')
144
+ m_u = u = atomic_mass = _cd('atomic mass constant')
145
+
146
+ # angle in rad
147
+ degree = pi / 180
148
+ arcmin = arcminute = degree / 60
149
+ arcsec = arcsecond = arcmin / 60
150
+
151
+ # time in second
152
+ minute = 60.0
153
+ hour = 60 * minute
154
+ day = 24 * hour
155
+ week = 7 * day
156
+ year = 365 * day
157
+ Julian_year = 365.25 * day
158
+
159
+ # length in meter
160
+ inch = 0.0254
161
+ foot = 12 * inch
162
+ yard = 3 * foot
163
+ mile = 1760 * yard
164
+ mil = inch / 1000
165
+ pt = point = inch / 72 # typography
166
+ survey_foot = 1200.0 / 3937
167
+ survey_mile = 5280 * survey_foot
168
+ nautical_mile = 1852.0
169
+ fermi = 1e-15
170
+ angstrom = 1e-10
171
+ micron = 1e-6
172
+ au = astronomical_unit = 149597870700.0
173
+ light_year = Julian_year * c
174
+ parsec = au / arcsec
175
+
176
+ # pressure in pascal
177
+ atm = atmosphere = _cd('standard atmosphere')
178
+ bar = 1e5
179
+ torr = mmHg = atm / 760
180
+ psi = pound * g / (inch * inch)
181
+
182
+ # area in meter**2
183
+ hectare = 1e4
184
+ acre = 43560 * foot**2
185
+
186
+ # volume in meter**3
187
+ litre = liter = 1e-3
188
+ gallon = gallon_US = 231 * inch**3 # US
189
+ # pint = gallon_US / 8
190
+ fluid_ounce = fluid_ounce_US = gallon_US / 128
191
+ bbl = barrel = 42 * gallon_US # for oil
192
+
193
+ gallon_imp = 4.54609e-3 # UK
194
+ fluid_ounce_imp = gallon_imp / 160
195
+
196
+ # speed in meter per second
197
+ kmh = 1e3 / hour
198
+ mph = mile / hour
199
+ # approx value of mach at 15 degrees in 1 atm. Is this a common value?
200
+ mach = speed_of_sound = 340.5
201
+ knot = nautical_mile / hour
202
+
203
+ # temperature in kelvin
204
+ zero_Celsius = 273.15
205
+ degree_Fahrenheit = 1/1.8 # only for differences
206
+
207
+ # energy in joule
208
+ eV = electron_volt = elementary_charge # * 1 Volt
209
+ calorie = calorie_th = 4.184
210
+ calorie_IT = 4.1868
211
+ erg = 1e-7
212
+ Btu_th = pound * degree_Fahrenheit * calorie_th / gram
213
+ Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
214
+ ton_TNT = 1e9 * calorie_th
215
+ # Wh = watt_hour
216
+
217
+ # power in watt
218
+ hp = horsepower = 550 * foot * pound * g
219
+
220
+ # force in newton
221
+ dyn = dyne = 1e-5
222
+ lbf = pound_force = pound * g
223
+ kgf = kilogram_force = g # * 1 kg
224
+
225
+ # functions for conversions that are not linear
226
+
227
+
228
+ @xp_capabilities()
229
+ def convert_temperature(
230
+ val: "npt.ArrayLike",
231
+ old_scale: str,
232
+ new_scale: str,
233
+ ) -> Any:
234
+ """
235
+ Convert from a temperature scale to another one among Celsius, Kelvin,
236
+ Fahrenheit, and Rankine scales.
237
+
238
+ Parameters
239
+ ----------
240
+ val : array_like
241
+ Value(s) of the temperature(s) to be converted expressed in the
242
+ original scale.
243
+ old_scale : str
244
+ Specifies as a string the original scale from which the temperature
245
+ value(s) will be converted. Supported scales are Celsius ('Celsius',
246
+ 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
247
+ Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
248
+ ('Rankine', 'rankine', 'R', 'r').
249
+ new_scale : str
250
+ Specifies as a string the new scale to which the temperature
251
+ value(s) will be converted. Supported scales are Celsius ('Celsius',
252
+ 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
253
+ Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
254
+ ('Rankine', 'rankine', 'R', 'r').
255
+
256
+ Returns
257
+ -------
258
+ res : float or array of floats
259
+ Value(s) of the converted temperature(s) expressed in the new scale.
260
+
261
+ Notes
262
+ -----
263
+ .. versionadded:: 0.18.0
264
+
265
+ Examples
266
+ --------
267
+ >>> from scipy.constants import convert_temperature
268
+ >>> import numpy as np
269
+ >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
270
+ array([ 233.15, 313.15])
271
+
272
+ """
273
+ xp = array_namespace(val)
274
+ _val = _asarray(val, xp=xp, subok=True)
275
+ # Convert from `old_scale` to Kelvin
276
+ if old_scale.lower() in ['celsius', 'c']:
277
+ tempo = _val + zero_Celsius
278
+ elif old_scale.lower() in ['kelvin', 'k']:
279
+ tempo = _val
280
+ elif old_scale.lower() in ['fahrenheit', 'f']:
281
+ tempo = (_val - 32) * 5 / 9 + zero_Celsius
282
+ elif old_scale.lower() in ['rankine', 'r']:
283
+ tempo = _val * 5 / 9
284
+ else:
285
+ raise NotImplementedError(f"{old_scale=} is unsupported: supported scales "
286
+ "are Celsius, Kelvin, Fahrenheit, and "
287
+ "Rankine")
288
+ # and from Kelvin to `new_scale`.
289
+ if new_scale.lower() in ['celsius', 'c']:
290
+ res = tempo - zero_Celsius
291
+ elif new_scale.lower() in ['kelvin', 'k']:
292
+ res = tempo
293
+ elif new_scale.lower() in ['fahrenheit', 'f']:
294
+ res = (tempo - zero_Celsius) * 9 / 5 + 32
295
+ elif new_scale.lower() in ['rankine', 'r']:
296
+ res = tempo * 9 / 5
297
+ else:
298
+ raise NotImplementedError(f"{new_scale=} is unsupported: supported "
299
+ "scales are 'Celsius', 'Kelvin', "
300
+ "'Fahrenheit', and 'Rankine'")
301
+
302
+ return res
303
+
304
+
305
+ # optics
306
+
307
+
308
+ @xp_capabilities()
309
+ def lambda2nu(lambda_: "npt.ArrayLike") -> Any:
310
+ """
311
+ Convert wavelength to optical frequency
312
+
313
+ Parameters
314
+ ----------
315
+ lambda_ : array_like
316
+ Wavelength(s) to be converted.
317
+
318
+ Returns
319
+ -------
320
+ nu : float or array of floats
321
+ Equivalent optical frequency.
322
+
323
+ Notes
324
+ -----
325
+ Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
326
+ (vacuum) speed of light in meters/second.
327
+
328
+ Examples
329
+ --------
330
+ >>> from scipy.constants import lambda2nu, speed_of_light
331
+ >>> import numpy as np
332
+ >>> lambda2nu(np.array((1, speed_of_light)))
333
+ array([ 2.99792458e+08, 1.00000000e+00])
334
+
335
+ """
336
+ xp = array_namespace(lambda_)
337
+ return c / _asarray(lambda_, xp=xp, subok=True)
338
+
339
+
340
+ @xp_capabilities()
341
+ def nu2lambda(nu: "npt.ArrayLike") -> Any:
342
+ """
343
+ Convert optical frequency to wavelength.
344
+
345
+ Parameters
346
+ ----------
347
+ nu : array_like
348
+ Optical frequency to be converted.
349
+
350
+ Returns
351
+ -------
352
+ lambda : float or array of floats
353
+ Equivalent wavelength(s).
354
+
355
+ Notes
356
+ -----
357
+ Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
358
+ (vacuum) speed of light in meters/second.
359
+
360
+ Examples
361
+ --------
362
+ >>> from scipy.constants import nu2lambda, speed_of_light
363
+ >>> import numpy as np
364
+ >>> nu2lambda(np.array((1, speed_of_light)))
365
+ array([ 2.99792458e+08, 1.00000000e+00])
366
+
367
+ """
368
+ xp = array_namespace(nu)
369
+ return c / _asarray(nu, xp=xp, subok=True)
tool_server/.venv/lib/python3.12/site-packages/scipy/constants/codata.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.constants` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'physical_constants', 'value', 'unit', 'precision', 'find',
9
+ 'ConstantWarning', 'k', 'c',
10
+
11
+ ]
12
+
13
+
14
+ def __dir__():
15
+ return __all__
16
+
17
+
18
+ def __getattr__(name):
19
+ return _sub_module_deprecation(sub_package="constants", module="codata",
20
+ private_modules=["_codata"], all=__all__,
21
+ attribute=name)
tool_server/.venv/lib/python3.12/site-packages/scipy/constants/constants.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.constants` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
10
+ 'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
11
+ 'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
12
+ 'angstrom', 'arcmin', 'arcminute', 'arcsec',
13
+ 'arcsecond', 'astronomical_unit', 'atm',
14
+ 'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
15
+ 'barrel', 'bbl', 'blob', 'c', 'calorie',
16
+ 'calorie_IT', 'calorie_th', 'carat', 'centi',
17
+ 'convert_temperature', 'day', 'deci', 'degree',
18
+ 'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
19
+ 'eV', 'electron_mass', 'electron_volt',
20
+ 'elementary_charge', 'epsilon_0', 'erg',
21
+ 'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
22
+ 'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
23
+ 'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
24
+ 'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
25
+ 'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
26
+ 'hectare', 'hecto', 'horsepower', 'hour', 'hp',
27
+ 'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
28
+ 'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
29
+ 'light_year', 'liter', 'litre', 'long_ton', 'm_e',
30
+ 'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
31
+ 'metric_ton', 'micro', 'micron', 'mil', 'mile',
32
+ 'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
33
+ 'nautical_mile', 'neutron_mass', 'nu2lambda',
34
+ 'ounce', 'oz', 'parsec', 'pebi', 'peta',
35
+ 'pi', 'pico', 'point', 'pound', 'pound_force',
36
+ 'proton_mass', 'psi', 'pt', 'short_ton',
37
+ 'sigma', 'slinch', 'slug', 'speed_of_light',
38
+ 'speed_of_sound', 'stone', 'survey_foot',
39
+ 'survey_mile', 'tebi', 'tera', 'ton_TNT',
40
+ 'torr', 'troy_ounce', 'troy_pound', 'u',
41
+ 'week', 'yard', 'year', 'yobi', 'yocto',
42
+ 'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
43
+ ]
44
+
45
+
46
+ def __dir__():
47
+ return __all__
48
+
49
+
50
+ def __getattr__(name):
51
+ return _sub_module_deprecation(sub_package="constants", module="constants",
52
+ private_modules=["_constants"], all=__all__,
53
+ attribute=name)
tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================
3
+ Datasets (:mod:`scipy.datasets`)
4
+ ================================
5
+
6
+ .. currentmodule:: scipy.datasets
7
+
8
+ Dataset Methods
9
+ ===============
10
+
11
+ .. autosummary::
12
+ :toctree: generated/
13
+
14
+ ascent
15
+ face
16
+ electrocardiogram
17
+
18
+ Utility Methods
19
+ ===============
20
+
21
+ .. autosummary::
22
+ :toctree: generated/
23
+
24
+ download_all -- Download all the dataset files to specified path.
25
+ clear_cache -- Clear cached dataset directory.
26
+
27
+
28
+ Usage of Datasets
29
+ =================
30
+
31
+ SciPy dataset methods can be simply called as follows: ``'<dataset-name>()'``
32
+ This downloads the dataset files over the network once, and saves the cache,
33
+ before returning a `numpy.ndarray` object representing the dataset.
34
+
35
+ Note that the return data structure and data type might be different for
36
+ different dataset methods. For a more detailed example on usage, please look
37
+ into the particular dataset method documentation above.
38
+
39
+
40
+ How dataset retrieval and storage works
41
+ =======================================
42
+
43
+ SciPy dataset files are stored within individual GitHub repositories under the
44
+ SciPy GitHub organization, following a naming convention as
45
+ ``'dataset-<name>'``, for example `scipy.datasets.face` files live at
46
+ https://github.com/scipy/dataset-face. The `scipy.datasets` submodule utilizes
47
+ and depends on `Pooch <https://www.fatiando.org/pooch/latest/>`_, a Python
48
+ package built to simplify fetching data files. Pooch uses these repos to
49
+ retrieve the respective dataset files when calling the dataset function.
50
+
51
+ A registry of all the datasets, essentially a mapping of filenames with their
52
+ SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
53
+ the downloads on function call. After downloading the dataset once, the files
54
+ are saved in the system cache directory under ``'scipy-data'``.
55
+
56
+ Dataset cache locations may vary on different platforms.
57
+
58
+ For macOS::
59
+
60
+ '~/Library/Caches/scipy-data'
61
+
62
+ For Linux and other Unix-like platforms::
63
+
64
+ '~/.cache/scipy-data' # or the value of the XDG_CACHE_HOME env var, if defined
65
+
66
+ For Windows::
67
+
68
+ 'C:\\Users\\<user>\\AppData\\Local\\<AppAuthor>\\scipy-data\\Cache'
69
+
70
+
71
+ In environments with constrained network connectivity for various security
72
+ reasons or on systems without continuous internet connections, one may manually
73
+ load the cache of the datasets by placing the contents of the dataset repo in
74
+ the above mentioned cache directory to avoid fetching dataset errors without
75
+ the internet connectivity.
76
+
77
+ """
78
+
79
+
80
+ from ._fetchers import face, ascent, electrocardiogram
81
+ from ._download_all import download_all
82
+ from ._utils import clear_cache
83
+
84
+ __all__ = ['ascent', 'electrocardiogram', 'face',
85
+ 'download_all', 'clear_cache']
86
+
87
+
88
+ from scipy._lib._testutils import PytestTester
89
+ test = PytestTester(__name__)
90
+ del PytestTester
tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Platform independent script to download all the
3
+ `scipy.datasets` module data files.
4
+ This doesn't require a full scipy build.
5
+
6
+ Run: python _download_all.py <download_dir>
7
+ """
8
+
9
+ import argparse
10
+ try:
11
+ import pooch
12
+ except ImportError:
13
+ pooch = None
14
+
15
+
16
+ if __package__ is None or __package__ == '':
17
+ # Running as python script, use absolute import
18
+ import _registry # type: ignore
19
+ else:
20
+ # Running as python module, use relative import
21
+ from . import _registry
22
+
23
+
24
+ def download_all(path=None):
25
+ """
26
+ Utility method to download all the dataset files
27
+ for `scipy.datasets` module.
28
+
29
+ Parameters
30
+ ----------
31
+ path : str, optional
32
+ Directory path to download all the dataset files.
33
+ If None, default to the system cache_dir detected by pooch.
34
+
35
+ Examples
36
+ --------
37
+ Download the datasets to the default cache location:
38
+
39
+ >>> from scipy import datasets
40
+ >>> datasets.download_all()
41
+
42
+ Download the datasets to the current directory:
43
+
44
+ >>> datasets.download_all(".")
45
+
46
+ """
47
+ if pooch is None:
48
+ raise ImportError("Missing optional dependency 'pooch' required "
49
+ "for scipy.datasets module. Please use pip or "
50
+ "conda to install 'pooch'.")
51
+ if path is None:
52
+ path = pooch.os_cache('scipy-data')
53
+ # https://github.com/scipy/scipy/issues/21879
54
+ downloader = pooch.HTTPDownloader(headers={"User-Agent": "SciPy"})
55
+ for dataset_name, dataset_hash in _registry.registry.items():
56
+ pooch.retrieve(url=_registry.registry_urls[dataset_name],
57
+ known_hash=dataset_hash,
58
+ fname=dataset_name, path=path, downloader=downloader)
59
+
60
+
61
+ def main():
62
+ parser = argparse.ArgumentParser(description='Download SciPy data files.')
63
+ parser.add_argument("path", nargs='?', type=str,
64
+ default=pooch.os_cache('scipy-data'),
65
+ help="Directory path to download all the data files.")
66
+ args = parser.parse_args()
67
+ download_all(args.path)
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from numpy import array, frombuffer, load
4
+ from ._registry import registry, registry_urls
5
+
6
+ try:
7
+ import pooch
8
+ except ImportError:
9
+ pooch = None
10
+ data_fetcher = None
11
+ else:
12
+ data_fetcher = pooch.create(
13
+ # Use the default cache folder for the operating system
14
+ # Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
15
+ # select an appropriate directory for the cache on each platform.
16
+ path=pooch.os_cache("scipy-data"),
17
+
18
+ # The remote data is on Github
19
+ # base_url is a required param, even though we override this
20
+ # using individual urls in the registry.
21
+ base_url="https://github.com/scipy/",
22
+ registry=registry,
23
+ urls=registry_urls
24
+ )
25
+
26
+
27
+ def fetch_data(dataset_name, data_fetcher=data_fetcher):
28
+ if data_fetcher is None:
29
+ raise ImportError("Missing optional dependency 'pooch' required "
30
+ "for scipy.datasets module. Please use pip or "
31
+ "conda to install 'pooch'.")
32
+ # https://github.com/scipy/scipy/issues/21879
33
+ downloader = pooch.HTTPDownloader(
34
+ headers={"User-Agent": f"SciPy {sys.modules['scipy'].__version__}"}
35
+ )
36
+ # The "fetch" method returns the full path to the downloaded data file.
37
+ return data_fetcher.fetch(dataset_name, downloader=downloader)
38
+
39
+
40
+ def ascent():
41
+ """
42
+ Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
43
+ use in demos.
44
+
45
+ The image is derived from
46
+ https://pixnio.com/people/accent-to-the-top
47
+
48
+ Parameters
49
+ ----------
50
+ None
51
+
52
+ Returns
53
+ -------
54
+ ascent : ndarray
55
+ convenient image to use for testing and demonstration
56
+
57
+ Examples
58
+ --------
59
+ >>> import scipy.datasets
60
+ >>> ascent = scipy.datasets.ascent()
61
+ >>> ascent.shape
62
+ (512, 512)
63
+ >>> ascent.max()
64
+ np.uint8(255)
65
+
66
+ >>> import matplotlib.pyplot as plt
67
+ >>> plt.gray()
68
+ >>> plt.imshow(ascent)
69
+ >>> plt.show()
70
+
71
+ """
72
+ import pickle
73
+
74
+ # The file will be downloaded automatically the first time this is run,
75
+ # returning the path to the downloaded file. Afterwards, Pooch finds
76
+ # it in the local cache and doesn't repeat the download.
77
+ fname = fetch_data("ascent.dat")
78
+ # Now we just need to load it with our standard Python tools.
79
+ with open(fname, 'rb') as f:
80
+ ascent = array(pickle.load(f))
81
+ return ascent
82
+
83
+
84
+ def electrocardiogram():
85
+ """
86
+ Load an electrocardiogram as an example for a 1-D signal.
87
+
88
+ The returned signal is a 5 minute long electrocardiogram (ECG), a medical
89
+ recording of the heart's electrical activity, sampled at 360 Hz.
90
+
91
+ Returns
92
+ -------
93
+ ecg : ndarray
94
+ The electrocardiogram in millivolt (mV) sampled at 360 Hz.
95
+
96
+ Notes
97
+ -----
98
+ The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
99
+ (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
100
+ PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
101
+ heartbeats as well as pathological changes.
102
+
103
+ .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
104
+
105
+ .. versionadded:: 1.1.0
106
+
107
+ References
108
+ ----------
109
+ .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
110
+ IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
111
+ (PMID: 11446209); :doi:`10.13026/C2F305`
112
+ .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
113
+ Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
114
+ PhysioToolkit, and PhysioNet: Components of a New Research Resource
115
+ for Complex Physiologic Signals. Circulation 101(23):e215-e220;
116
+ :doi:`10.1161/01.CIR.101.23.e215`
117
+
118
+ Examples
119
+ --------
120
+ >>> from scipy.datasets import electrocardiogram
121
+ >>> ecg = electrocardiogram()
122
+ >>> ecg
123
+ array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
124
+ >>> ecg.shape, ecg.mean(), ecg.std()
125
+ ((108000,), -0.16510875, 0.5992473991177294)
126
+
127
+ As stated the signal features several areas with a different morphology.
128
+ E.g., the first few seconds show the electrical activity of a heart in
129
+ normal sinus rhythm as seen below.
130
+
131
+ >>> import numpy as np
132
+ >>> import matplotlib.pyplot as plt
133
+ >>> fs = 360
134
+ >>> time = np.arange(ecg.size) / fs
135
+ >>> plt.plot(time, ecg)
136
+ >>> plt.xlabel("time in s")
137
+ >>> plt.ylabel("ECG in mV")
138
+ >>> plt.xlim(9, 10.2)
139
+ >>> plt.ylim(-1, 1.5)
140
+ >>> plt.show()
141
+
142
+ After second 16, however, the first premature ventricular contractions,
143
+ also called extrasystoles, appear. These have a different morphology
144
+ compared to typical heartbeats. The difference can easily be observed
145
+ in the following plot.
146
+
147
+ >>> plt.plot(time, ecg)
148
+ >>> plt.xlabel("time in s")
149
+ >>> plt.ylabel("ECG in mV")
150
+ >>> plt.xlim(46.5, 50)
151
+ >>> plt.ylim(-2, 1.5)
152
+ >>> plt.show()
153
+
154
+ At several points large artifacts disturb the recording, e.g.:
155
+
156
+ >>> plt.plot(time, ecg)
157
+ >>> plt.xlabel("time in s")
158
+ >>> plt.ylabel("ECG in mV")
159
+ >>> plt.xlim(207, 215)
160
+ >>> plt.ylim(-2, 3.5)
161
+ >>> plt.show()
162
+
163
+ Finally, examining the power spectrum reveals that most of the biosignal is
164
+ made up of lower frequencies. At 60 Hz the noise induced by the mains
165
+ electricity can be clearly observed.
166
+
167
+ >>> from scipy.signal import welch
168
+ >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
169
+ >>> plt.semilogy(f, Pxx)
170
+ >>> plt.xlabel("Frequency in Hz")
171
+ >>> plt.ylabel("Power spectrum of the ECG in mV**2")
172
+ >>> plt.xlim(f[[0, -1]])
173
+ >>> plt.show()
174
+ """
175
+ fname = fetch_data("ecg.dat")
176
+ with load(fname) as file:
177
+ ecg = file["ecg"].astype(int) # np.uint16 -> int
178
+ # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
179
+ ecg = (ecg - 1024) / 200.0
180
+ return ecg
181
+
182
+
183
+ def face(gray=False):
184
+ """
185
+ Get a 1024 x 768, color image of a raccoon face.
186
+
187
+ The image is derived from
188
+ https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
189
+
190
+ Parameters
191
+ ----------
192
+ gray : bool, optional
193
+ If True return 8-bit grey-scale image, otherwise return a color image
194
+
195
+ Returns
196
+ -------
197
+ face : ndarray
198
+ image of a raccoon face
199
+
200
+ Examples
201
+ --------
202
+ >>> import scipy.datasets
203
+ >>> face = scipy.datasets.face()
204
+ >>> face.shape
205
+ (768, 1024, 3)
206
+ >>> face.max()
207
+ np.uint8(255)
208
+
209
+ >>> import matplotlib.pyplot as plt
210
+ >>> plt.gray()
211
+ >>> plt.imshow(face)
212
+ >>> plt.show()
213
+
214
+ """
215
+ import bz2
216
+ fname = fetch_data("face.dat")
217
+ with open(fname, 'rb') as f:
218
+ rawdata = f.read()
219
+ face_data = bz2.decompress(rawdata)
220
+ face = frombuffer(face_data, dtype='uint8')
221
+ face.shape = (768, 1024, 3)
222
+ if gray is True:
223
+ face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
224
+ 0.07 * face[:, :, 2]).astype('uint8')
225
+ return face
tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ # This file serves as the dataset registry for SciPy Datasets SubModule.
3
+ ##########################################################################
4
+
5
+
6
+ # To generate the SHA256 hash, use the command
7
+ # openssl sha256 <filename>
8
+ registry = {
9
+ "ascent.dat": "03ce124c1afc880f87b55f6b061110e2e1e939679184f5614e38dacc6c1957e2",
10
+ "ecg.dat": "f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf",
11
+ "face.dat": "9d8b0b4d081313e2b485748c770472e5a95ed1738146883d84c7030493e82886"
12
+ }
13
+
14
+ registry_urls = {
15
+ "ascent.dat": "https://raw.githubusercontent.com/scipy/dataset-ascent/main/ascent.dat",
16
+ "ecg.dat": "https://raw.githubusercontent.com/scipy/dataset-ecg/main/ecg.dat",
17
+ "face.dat": "https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat"
18
+ }
19
+
20
+ # dataset method mapping with their associated filenames
21
+ # <method_name> : ["filename1", "filename2", ...]
22
+ method_files_map = {
23
+ "ascent": ["ascent.dat"],
24
+ "electrocardiogram": ["ecg.dat"],
25
+ "face": ["face.dat"]
26
+ }
tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from ._registry import method_files_map
4
+
5
+ try:
6
+ import platformdirs
7
+ except ImportError:
8
+ platformdirs = None # type: ignore[assignment]
9
+
10
+
11
+ def _clear_cache(datasets, cache_dir=None, method_map=None):
12
+ if method_map is None:
13
+ # Use SciPy Datasets method map
14
+ method_map = method_files_map
15
+ if cache_dir is None:
16
+ # Use default cache_dir path
17
+ if platformdirs is None:
18
+ # platformdirs is pooch dependency
19
+ raise ImportError("Missing optional dependency 'pooch' required "
20
+ "for scipy.datasets module. Please use pip or "
21
+ "conda to install 'pooch'.")
22
+ cache_dir = platformdirs.user_cache_dir("scipy-data")
23
+
24
+ if not os.path.exists(cache_dir):
25
+ print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
26
+ return
27
+
28
+ if datasets is None:
29
+ print(f"Cleaning the cache directory {cache_dir}!")
30
+ shutil.rmtree(cache_dir)
31
+ else:
32
+ if not isinstance(datasets, list | tuple):
33
+ # single dataset method passed should be converted to list
34
+ datasets = [datasets, ]
35
+ for dataset in datasets:
36
+ assert callable(dataset)
37
+ dataset_name = dataset.__name__ # Name of the dataset method
38
+ if dataset_name not in method_map:
39
+ raise ValueError(f"Dataset method {dataset_name} doesn't "
40
+ "exist. Please check if the passed dataset "
41
+ "is a subset of the following dataset "
42
+ f"methods: {list(method_map.keys())}")
43
+
44
+ data_files = method_map[dataset_name]
45
+ data_filepaths = [os.path.join(cache_dir, file)
46
+ for file in data_files]
47
+ for data_filepath in data_filepaths:
48
+ if os.path.exists(data_filepath):
49
+ print("Cleaning the file "
50
+ f"{os.path.split(data_filepath)[1]} "
51
+ f"for dataset {dataset_name}")
52
+ os.remove(data_filepath)
53
+ else:
54
+ print(f"Path {data_filepath} doesn't exist. "
55
+ "Nothing to clear.")
56
+
57
+
58
+ def clear_cache(datasets=None):
59
+ """
60
+ Cleans the scipy datasets cache directory.
61
+
62
+ If a scipy.datasets method or a list/tuple of the same is
63
+ provided, then clear_cache removes all the data files
64
+ associated to the passed dataset method callable(s).
65
+
66
+ By default, it removes all the cached data files.
67
+
68
+ Parameters
69
+ ----------
70
+ datasets : callable or list/tuple of callable or None
71
+
72
+ Examples
73
+ --------
74
+ >>> from scipy import datasets
75
+ >>> ascent_array = datasets.ascent()
76
+ >>> ascent_array.shape
77
+ (512, 512)
78
+ >>> datasets.clear_cache([datasets.ascent])
79
+ Cleaning the file ascent.dat for dataset ascent
80
+ """
81
+ _clear_cache(datasets)
tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ==============================================================
3
+ Finite Difference Differentiation (:mod:`scipy.differentiate`)
4
+ ==============================================================
5
+
6
+ .. currentmodule:: scipy.differentiate
7
+
8
+ SciPy ``differentiate`` provides functions for performing finite difference
9
+ numerical differentiation of black-box functions.
10
+
11
+ .. autosummary::
12
+ :toctree: generated/
13
+
14
+ derivative
15
+ jacobian
16
+ hessian
17
+
18
+ """
19
+
20
+
21
+ from ._differentiate import *
22
+
23
+ __all__ = ['derivative', 'jacobian', 'hessian']
24
+
25
+ from scipy._lib._testutils import PytestTester
26
+ test = PytestTester(__name__)
27
+ del PytestTester
tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py ADDED
@@ -0,0 +1,1129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disable-error-code="attr-defined"
2
+ import warnings
3
+ import numpy as np
4
+ import scipy._lib._elementwise_iterative_method as eim
5
+ from scipy._lib._util import _RichResult
6
+ from scipy._lib._array_api import array_namespace, xp_copy, xp_promote
7
+ import scipy._lib.array_api_extra as xpx
8
+
9
+ _EERRORINCREASE = -1 # used in derivative
10
+
11
+ def _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
12
+ step_factor, step_direction, preserve_shape, callback):
13
+ # Input validation for `derivative`
14
+ xp = array_namespace(x)
15
+
16
+ if not callable(f):
17
+ raise ValueError('`f` must be callable.')
18
+
19
+ if not np.iterable(args):
20
+ args = (args,)
21
+
22
+ tolerances = {} if tolerances is None else tolerances
23
+ atol = tolerances.get('atol', None)
24
+ rtol = tolerances.get('rtol', None)
25
+
26
+ # tolerances are floats, not arrays; OK to use NumPy
27
+ message = 'Tolerances and step parameters must be non-negative scalars.'
28
+ tols = np.asarray([atol if atol is not None else 1,
29
+ rtol if rtol is not None else 1,
30
+ step_factor])
31
+ if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
32
+ or np.any(np.isnan(tols)) or tols.shape != (3,)):
33
+ raise ValueError(message)
34
+ step_factor = float(tols[2])
35
+
36
+ maxiter_int = int(maxiter)
37
+ if maxiter != maxiter_int or maxiter <= 0:
38
+ raise ValueError('`maxiter` must be a positive integer.')
39
+
40
+ order_int = int(order)
41
+ if order_int != order or order <= 0:
42
+ raise ValueError('`order` must be a positive integer.')
43
+
44
+ step_direction = xp.asarray(step_direction)
45
+ initial_step = xp.asarray(initial_step)
46
+ temp = xp.broadcast_arrays(x, step_direction, initial_step)
47
+ x, step_direction, initial_step = temp
48
+
49
+ message = '`preserve_shape` must be True or False.'
50
+ if preserve_shape not in {True, False}:
51
+ raise ValueError(message)
52
+
53
+ if callback is not None and not callable(callback):
54
+ raise ValueError('`callback` must be callable.')
55
+
56
+ return (f, x, args, atol, rtol, maxiter_int, order_int, initial_step,
57
+ step_factor, step_direction, preserve_shape, callback)
58
+
59
+
60
+ def derivative(f, x, *, args=(), tolerances=None, maxiter=10,
61
+ order=8, initial_step=0.5, step_factor=2.0,
62
+ step_direction=0, preserve_shape=False, callback=None):
63
+ """Evaluate the derivative of a elementwise, real scalar function numerically.
64
+
65
+ For each element of the output of `f`, `derivative` approximates the first
66
+ derivative of `f` at the corresponding element of `x` using finite difference
67
+ differentiation.
68
+
69
+ This function works elementwise when `x`, `step_direction`, and `args` contain
70
+ (broadcastable) arrays.
71
+
72
+ Parameters
73
+ ----------
74
+ f : callable
75
+ The function whose derivative is desired. The signature must be::
76
+
77
+ f(xi: ndarray, *argsi) -> ndarray
78
+
79
+ where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
80
+ which may contain an arbitrary number of arrays that are broadcastable with
81
+ ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
82
+ must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
83
+ ``xi`` or the arrays in ``argsi``.
84
+ x : float array_like
85
+ Abscissae at which to evaluate the derivative. Must be broadcastable with
86
+ `args` and `step_direction`.
87
+ args : tuple of array_like, optional
88
+ Additional positional array arguments to be passed to `f`. Arrays
89
+ must be broadcastable with one another and the arrays of `init`.
90
+ If the callable for which the root is desired requires arguments that are
91
+ not broadcastable with `x`, wrap that callable with `f` such that `f`
92
+ accepts only `x` and broadcastable ``*args``.
93
+ tolerances : dictionary of floats, optional
94
+ Absolute and relative tolerances. Valid keys of the dictionary are:
95
+
96
+ - ``atol`` - absolute tolerance on the derivative
97
+ - ``rtol`` - relative tolerance on the derivative
98
+
99
+ Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
100
+ `atol` is the smallest normal number of the appropriate dtype, and
101
+ the default `rtol` is the square root of the precision of the
102
+ appropriate dtype.
103
+ order : int, default: 8
104
+ The (positive integer) order of the finite difference formula to be
105
+ used. Odd integers will be rounded up to the next even integer.
106
+ initial_step : float array_like, default: 0.5
107
+ The (absolute) initial step size for the finite difference derivative
108
+ approximation.
109
+ step_factor : float, default: 2.0
110
+ The factor by which the step size is *reduced* in each iteration; i.e.
111
+ the step size in iteration 1 is ``initial_step/step_factor``. If
112
+ ``step_factor < 1``, subsequent steps will be greater than the initial
113
+ step; this may be useful if steps smaller than some threshold are
114
+ undesirable (e.g. due to subtractive cancellation error).
115
+ maxiter : int, default: 10
116
+ The maximum number of iterations of the algorithm to perform. See
117
+ Notes.
118
+ step_direction : integer array_like
119
+ An array representing the direction of the finite difference steps (for
120
+ use when `x` lies near to the boundary of the domain of the function.)
121
+ Must be broadcastable with `x` and all `args`.
122
+ Where 0 (default), central differences are used; where negative (e.g.
123
+ -1), steps are non-positive; and where positive (e.g. 1), all steps are
124
+ non-negative.
125
+ preserve_shape : bool, default: False
126
+ In the following, "arguments of `f`" refers to the array ``xi`` and
127
+ any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
128
+ of `x` and all elements of `args` (which is conceptually
129
+ distinct from ``xi` and ``argsi`` passed into `f`).
130
+
131
+ - When ``preserve_shape=False`` (default), `f` must accept arguments
132
+ of *any* broadcastable shapes.
133
+
134
+ - When ``preserve_shape=True``, `f` must accept arguments of shape
135
+ ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
136
+ abscissae at which the function is being evaluated.
137
+
138
+ In either case, for each scalar element ``xi[j]`` within ``xi``, the array
139
+ returned by `f` must include the scalar ``f(xi[j])`` at the same index.
140
+ Consequently, the shape of the output is always the shape of the input
141
+ ``xi``.
142
+
143
+ See Examples.
144
+ callback : callable, optional
145
+ An optional user-supplied function to be called before the first
146
+ iteration and after each iteration.
147
+ Called as ``callback(res)``, where ``res`` is a ``_RichResult``
148
+ similar to that returned by `derivative` (but containing the current
149
+ iterate's values of all variables). If `callback` raises a
150
+ ``StopIteration``, the algorithm will terminate immediately and
151
+ `derivative` will return a result. `callback` must not mutate
152
+ `res` or its attributes.
153
+
154
+ Returns
155
+ -------
156
+ res : _RichResult
157
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
158
+ following attributes. The descriptions are written as though the values will
159
+ be scalars; however, if `f` returns an array, the outputs will be
160
+ arrays of the same shape.
161
+
162
+ success : bool array
163
+ ``True`` where the algorithm terminated successfully (status ``0``);
164
+ ``False`` otherwise.
165
+ status : int array
166
+ An integer representing the exit status of the algorithm.
167
+
168
+ - ``0`` : The algorithm converged to the specified tolerances.
169
+ - ``-1`` : The error estimate increased, so iteration was terminated.
170
+ - ``-2`` : The maximum number of iterations was reached.
171
+ - ``-3`` : A non-finite value was encountered.
172
+ - ``-4`` : Iteration was terminated by `callback`.
173
+ - ``1`` : The algorithm is proceeding normally (in `callback` only).
174
+
175
+ df : float array
176
+ The derivative of `f` at `x`, if the algorithm terminated
177
+ successfully.
178
+ error : float array
179
+ An estimate of the error: the magnitude of the difference between
180
+ the current estimate of the derivative and the estimate in the
181
+ previous iteration.
182
+ nit : int array
183
+ The number of iterations of the algorithm that were performed.
184
+ nfev : int array
185
+ The number of points at which `f` was evaluated.
186
+ x : float array
187
+ The value at which the derivative of `f` was evaluated
188
+ (after broadcasting with `args` and `step_direction`).
189
+
190
+ See Also
191
+ --------
192
+ jacobian, hessian
193
+
194
+ Notes
195
+ -----
196
+ The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
197
+ DERIVEST [3]_, but the implementation follows the theory of Taylor series
198
+ more straightforwardly (and arguably naively so).
199
+ In the first iteration, the derivative is estimated using a finite
200
+ difference formula of order `order` with maximum step size `initial_step`.
201
+ Each subsequent iteration, the maximum step size is reduced by
202
+ `step_factor`, and the derivative is estimated again until a termination
203
+ condition is reached. The error estimate is the magnitude of the difference
204
+ between the current derivative approximation and that of the previous
205
+ iteration.
206
+
207
+ The stencils of the finite difference formulae are designed such that
208
+ abscissae are "nested": after `f` is evaluated at ``order + 1``
209
+ points in the first iteration, `f` is evaluated at only two new points
210
+ in each subsequent iteration; ``order - 1`` previously evaluated function
211
+ values required by the finite difference formula are reused, and two
212
+ function values (evaluations at the points furthest from `x`) are unused.
213
+
214
+ Step sizes are absolute. When the step size is small relative to the
215
+ magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
216
+ default initial step size of ``0.5`` cannot be resolved. Accordingly,
217
+ consider using larger initial step sizes for large magnitudes of `x`.
218
+
219
+ The default tolerances are challenging to satisfy at points where the
220
+ true derivative is exactly zero. If the derivative may be exactly zero,
221
+ consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
222
+ improve convergence.
223
+
224
+ References
225
+ ----------
226
+ .. [1] Hans Dembinski (@HDembinski). jacobi.
227
+ https://github.com/HDembinski/jacobi
228
+ .. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
229
+ https://numdifftools.readthedocs.io/en/latest/
230
+ .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
231
+ https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
232
+ .. [4] Numerical Differentition. Wikipedia.
233
+ https://en.wikipedia.org/wiki/Numerical_differentiation
234
+
235
+ Examples
236
+ --------
237
+ Evaluate the derivative of ``np.exp`` at several points ``x``.
238
+
239
+ >>> import numpy as np
240
+ >>> from scipy.differentiate import derivative
241
+ >>> f = np.exp
242
+ >>> df = np.exp # true derivative
243
+ >>> x = np.linspace(1, 2, 5)
244
+ >>> res = derivative(f, x)
245
+ >>> res.df # approximation of the derivative
246
+ array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
247
+ >>> res.error # estimate of the error
248
+ array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
249
+ 1.94262384e-11])
250
+ >>> abs(res.df - df(x)) # true error
251
+ array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
252
+ 6.92779167e-14])
253
+
254
+ Show the convergence of the approximation as the step size is reduced.
255
+ Each iteration, the step size is reduced by `step_factor`, so for
256
+ sufficiently small initial step, each iteration reduces the error by a
257
+ factor of ``1/step_factor**order`` until finite precision arithmetic
258
+ inhibits further improvement.
259
+
260
+ >>> import matplotlib.pyplot as plt
261
+ >>> iter = list(range(1, 12)) # maximum iterations
262
+ >>> hfac = 2 # step size reduction per iteration
263
+ >>> hdir = [-1, 0, 1] # compare left-, central-, and right- steps
264
+ >>> order = 4 # order of differentiation formula
265
+ >>> x = 1
266
+ >>> ref = df(x)
267
+ >>> errors = [] # true error
268
+ >>> for i in iter:
269
+ ... res = derivative(f, x, maxiter=i, step_factor=hfac,
270
+ ... step_direction=hdir, order=order,
271
+ ... # prevent early termination
272
+ ... tolerances=dict(atol=0, rtol=0))
273
+ ... errors.append(abs(res.df - ref))
274
+ >>> errors = np.array(errors)
275
+ >>> plt.semilogy(iter, errors[:, 0], label='left differences')
276
+ >>> plt.semilogy(iter, errors[:, 1], label='central differences')
277
+ >>> plt.semilogy(iter, errors[:, 2], label='right differences')
278
+ >>> plt.xlabel('iteration')
279
+ >>> plt.ylabel('error')
280
+ >>> plt.legend()
281
+ >>> plt.show()
282
+ >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
283
+ (0.06215223140159822, 0.0625)
284
+
285
+ The implementation is vectorized over `x`, `step_direction`, and `args`.
286
+ The function is evaluated once before the first iteration to perform input
287
+ validation and standardization, and once per iteration thereafter.
288
+
289
+ >>> def f(x, p):
290
+ ... f.nit += 1
291
+ ... return x**p
292
+ >>> f.nit = 0
293
+ >>> def df(x, p):
294
+ ... return p*x**(p-1)
295
+ >>> x = np.arange(1, 5)
296
+ >>> p = np.arange(1, 6).reshape((-1, 1))
297
+ >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
298
+ >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
299
+ >>> np.allclose(res.df, df(x, p))
300
+ True
301
+ >>> res.df.shape
302
+ (3, 5, 4)
303
+ >>> f.nit
304
+ 2
305
+
306
+ By default, `preserve_shape` is False, and therefore the callable
307
+ `f` may be called with arrays of any broadcastable shapes.
308
+ For example:
309
+
310
+ >>> shapes = []
311
+ >>> def f(x, c):
312
+ ... shape = np.broadcast_shapes(x.shape, c.shape)
313
+ ... shapes.append(shape)
314
+ ... return np.sin(c*x)
315
+ >>>
316
+ >>> c = [1, 5, 10, 20]
317
+ >>> res = derivative(f, 0, args=(c,))
318
+ >>> shapes
319
+ [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]
320
+
321
+ To understand where these shapes are coming from - and to better
322
+ understand how `derivative` computes accurate results - note that
323
+ higher values of ``c`` correspond with higher frequency sinusoids.
324
+ The higher frequency sinusoids make the function's derivative change
325
+ faster, so more function evaluations are required to achieve the target
326
+ accuracy:
327
+
328
+ >>> res.nfev
329
+ array([11, 13, 15, 17], dtype=int32)
330
+
331
+ The initial ``shape``, ``(4,)``, corresponds with evaluating the
332
+ function at a single abscissa and all four frequencies; this is used
333
+ for input validation and to determine the size and dtype of the arrays
334
+ that store results. The next shape corresponds with evaluating the
335
+ function at an initial grid of abscissae and all four frequencies.
336
+ Successive calls to the function evaluate the function at two more
337
+ abscissae, increasing the effective order of the approximation by two.
338
+ However, in later function evaluations, the function is evaluated at
339
+ fewer frequencies because the corresponding derivative has already
340
+ converged to the required tolerance. This saves function evaluations to
341
+ improve performance, but it requires the function to accept arguments of
342
+ any shape.
343
+
344
+ "Vector-valued" functions are unlikely to satisfy this requirement.
345
+ For example, consider
346
+
347
+ >>> def f(x):
348
+ ... return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
349
+
350
+ This integrand is not compatible with `derivative` as written; for instance,
351
+ the shape of the output will not be the same as the shape of ``x``. Such a
352
+ function *could* be converted to a compatible form with the introduction of
353
+ additional parameters, but this would be inconvenient. In such cases,
354
+ a simpler solution would be to use `preserve_shape`.
355
+
356
+ >>> shapes = []
357
+ >>> def f(x):
358
+ ... shapes.append(x.shape)
359
+ ... x0, x1, x2, x3 = x
360
+ ... return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
361
+ >>>
362
+ >>> x = np.zeros(4)
363
+ >>> res = derivative(f, x, preserve_shape=True)
364
+ >>> shapes
365
+ [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
366
+
367
+ Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
368
+ function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
369
+ and this is what we observe.
370
+
371
+ """
372
+ # TODO (followup):
373
+ # - investigate behavior at saddle points
374
+ # - multivariate functions?
375
+ # - relative steps?
376
+ # - show example of `np.vectorize`
377
+
378
+ res = _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
379
+ step_factor, step_direction, preserve_shape, callback)
380
+ (func, x, args, atol, rtol, maxiter, order,
381
+ h0, fac, hdir, preserve_shape, callback) = res
382
+
383
+ # Initialization
384
+ # Since f(x) (no step) is not needed for central differences, it may be
385
+ # possible to eliminate this function evaluation. However, it's useful for
386
+ # input validation and standardization, and everything else is designed to
387
+ # reduce function calls, so let's keep it simple.
388
+ temp = eim._initialize(func, (x,), args, preserve_shape=preserve_shape)
389
+ func, xs, fs, args, shape, dtype, xp = temp
390
+
391
+ finfo = xp.finfo(dtype)
392
+ atol = finfo.smallest_normal if atol is None else atol
393
+ rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `hessian`
394
+
395
+ x, f = xs[0], fs[0]
396
+ df = xp.full_like(f, xp.nan)
397
+
398
+ # Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but
399
+ # it's simpler to do it here than to generalize `_elementwise_algo_init` further.
400
+ # `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know
401
+ # that `hdir` can be broadcasted to the final shape. Same with `h0`.
402
+ hdir = xp.broadcast_to(hdir, shape)
403
+ hdir = xp.reshape(hdir, (-1,))
404
+ hdir = xp.astype(xp.sign(hdir), dtype)
405
+ h0 = xp.broadcast_to(h0, shape)
406
+ h0 = xp.reshape(h0, (-1,))
407
+ h0 = xp.astype(h0, dtype)
408
+ h0 = xpx.at(h0)[h0 <= 0].set(xp.nan)
409
+
410
+ status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32) # in progress
411
+ nit, nfev = 0, 1 # one function evaluations performed above
412
+ # Boolean indices of left, central, right, and (all) one-sided steps
413
+ il = hdir < 0
414
+ ic = hdir == 0
415
+ ir = hdir > 0
416
+ io = il | ir
417
+
418
+ # Most of these attributes are reasonably obvious, but:
419
+ # - `fs` holds all the function values of all active `x`. The zeroth
420
+ # axis corresponds with active points `x`, the first axis corresponds
421
+ # with the different steps (in the order described in
422
+ # `_derivative_weights`).
423
+ # - `terms` (which could probably use a better name) is half the `order`,
424
+ # which is always even.
425
+ work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
426
+ df_last=xp.nan, error_last=xp.nan, fac=fac,
427
+ atol=atol, rtol=rtol, nit=nit, nfev=nfev,
428
+ status=status, dtype=dtype, terms=(order+1)//2,
429
+ hdir=hdir, il=il, ic=ic, ir=ir, io=io,
430
+ # Store the weights in an object so they can't get compressed
431
+ # Using RichResult to allow dot notation, but a dict would work
432
+ diff_state=_RichResult(central=[], right=[], fac=None))
433
+
434
+ # This is the correspondence between terms in the `work` object and the
435
+ # final result. In this case, the mapping is trivial. Note that `success`
436
+ # is prepended automatically.
437
+ res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
438
+ ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
439
+
440
+ def pre_func_eval(work):
441
+ """Determine the abscissae at which the function needs to be evaluated.
442
+
443
+ See `_derivative_weights` for a description of the stencil (pattern
444
+ of the abscissae).
445
+
446
+ In the first iteration, there is only one stored function value in
447
+ `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
448
+ subsequent iterations, we evaluate at two new points. Note that
449
+ `work.x` is always flattened into a 1D array after broadcasting with
450
+ all `args`, so we add a new axis at the end and evaluate all point
451
+ in one call to the function.
452
+
453
+ For improvement:
454
+ - Consider measuring the step size actually taken, since ``(x + h) - x``
455
+ is not identically equal to `h` with floating point arithmetic.
456
+ - Adjust the step size automatically if `x` is too big to resolve the
457
+ step.
458
+ - We could probably save some work if there are no central difference
459
+ steps or no one-sided steps.
460
+ """
461
+ n = work.terms # half the order
462
+ h = work.h[:, xp.newaxis] # step size
463
+ c = work.fac # step reduction factor
464
+ d = c**0.5 # square root of step reduction factor (one-sided stencil)
465
+ # Note - no need to be careful about dtypes until we allocate `x_eval`
466
+
467
+ if work.nit == 0:
468
+ hc = h / c**xp.arange(n, dtype=work.dtype)
469
+ hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
470
+ else:
471
+ hc = xp.concat((-h, h), axis=-1) / c**(n-1)
472
+
473
+ if work.nit == 0:
474
+ hr = h / d**xp.arange(2*n, dtype=work.dtype)
475
+ else:
476
+ hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
477
+
478
+ n_new = 2*n if work.nit == 0 else 2 # number of new abscissae
479
+ x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
480
+ il, ic, ir = work.il, work.ic, work.ir
481
+ x_eval = xpx.at(x_eval)[ir].set(work.x[ir][:, xp.newaxis] + hr[ir])
482
+ x_eval = xpx.at(x_eval)[ic].set(work.x[ic][:, xp.newaxis] + hc[ic])
483
+ x_eval = xpx.at(x_eval)[il].set(work.x[il][:, xp.newaxis] - hr[il])
484
+ return x_eval
485
+
486
+ def post_func_eval(x, f, work):
487
+ """ Estimate the derivative and error from the function evaluations
488
+
489
+ As in `pre_func_eval`: in the first iteration, there is only one stored
490
+ function value in `work.fs`, `f(x)`, so we need to add the `order` new
491
+ points. In subsequent iterations, we add two new points. The tricky
492
+ part is getting the order to match that of the weights, which is
493
+ described in `_derivative_weights`.
494
+
495
+ For improvement:
496
+ - Change the order of the weights (and steps in `pre_func_eval`) to
497
+ simplify `work_fc` concatenation and eliminate `fc` concatenation.
498
+ - It would be simple to do one-step Richardson extrapolation with `df`
499
+ and `df_last` to increase the order of the estimate and/or improve
500
+ the error estimate.
501
+ - Process the function evaluations in a more numerically favorable
502
+ way. For instance, combining the pairs of central difference evals
503
+ into a second-order approximation and using Richardson extrapolation
504
+ to produce a higher order approximation seemed to retain accuracy up
505
+ to very high order.
506
+ - Alternatively, we could use `polyfit` like Jacobi. An advantage of
507
+ fitting polynomial to more points than necessary is improved noise
508
+ tolerance.
509
+ """
510
+ n = work.terms
511
+ n_new = n if work.nit == 0 else 1
512
+ il, ic, io = work.il, work.ic, work.io
513
+
514
+ # Central difference
515
+ # `work_fc` is *all* the points at which the function has been evaluated
516
+ # `fc` is the points we're using *this iteration* to produce the estimate
517
+ work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
518
+ work_fc = xp.concat(work_fc, axis=-1)
519
+ if work.nit == 0:
520
+ fc = work_fc
521
+ else:
522
+ fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
523
+ fc = xp.concat(fc, axis=-1)
524
+
525
+ # One-sided difference
526
+ work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
527
+ if work.nit == 0:
528
+ fo = work_fo
529
+ else:
530
+ fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
531
+
532
+ work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
533
+ work.fs = xpx.at(work.fs)[ic].set(work_fc)
534
+ work.fs = xpx.at(work.fs)[io].set(work_fo)
535
+
536
+ wc, wo = _derivative_weights(work, n, xp)
537
+ work.df_last = xp.asarray(work.df, copy=True)
538
+ work.df = xpx.at(work.df)[ic].set(fc @ wc / work.h[ic])
539
+ work.df = xpx.at(work.df)[io].set(fo @ wo / work.h[io])
540
+ work.df = xpx.at(work.df)[il].multiply(-1)
541
+
542
+ work.h /= work.fac
543
+ work.error_last = work.error
544
+ # Simple error estimate - the difference in derivative estimates between
545
+ # this iteration and the last. This is typically conservative because if
546
+ # convergence has begin, the true error is much closer to the difference
547
+ # between the current estimate and the *next* error estimate. However,
548
+ # we could use Richarson extrapolation to produce an error estimate that
549
+ # is one order higher, and take the difference between that and
550
+ # `work.df` (which would just be constant factor that depends on `fac`.)
551
+ work.error = xp.abs(work.df - work.df_last)
552
+
553
+ def check_termination(work):
554
+ """Terminate due to convergence, non-finite values, or error increase"""
555
+ stop = xp.astype(xp.zeros_like(work.df), xp.bool)
556
+
557
+ i = work.error < work.atol + work.rtol*abs(work.df)
558
+ work.status = xpx.at(work.status)[i].set(eim._ECONVERGED)
559
+ stop = xpx.at(stop)[i].set(True)
560
+
561
+ if work.nit > 0:
562
+ i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
563
+ work.df = xpx.at(work.df)[i].set(xp.nan)
564
+ work.status = xpx.at(work.status)[i].set(eim._EVALUEERR)
565
+ stop = xpx.at(stop)[i].set(True)
566
+
567
+ # With infinite precision, there is a step size below which
568
+ # all smaller step sizes will reduce the error. But in floating point
569
+ # arithmetic, catastrophic cancellation will begin to cause the error
570
+ # to increase again. This heuristic tries to avoid step sizes that are
571
+ # too small. There may be more theoretically sound approaches for
572
+ # detecting a step size that minimizes the total error, but this
573
+ # heuristic seems simple and effective.
574
+ i = (work.error > work.error_last*10) & ~stop
575
+ work.status = xpx.at(work.status)[i].set(_EERRORINCREASE)
576
+ stop = xpx.at(stop)[i].set(True)
577
+
578
+ return stop
579
+
580
+ def post_termination_check(work):
581
+ return
582
+
583
+ def customize_result(res, shape):
584
+ return shape
585
+
586
+ return eim._loop(work, callback, shape, maxiter, func, args, dtype,
587
+ pre_func_eval, post_func_eval, check_termination,
588
+ post_termination_check, customize_result, res_work_pairs,
589
+ xp, preserve_shape)
590
+
591
+
592
+ def _derivative_weights(work, n, xp):
593
+ # This produces the weights of the finite difference formula for a given
594
+ # stencil. In experiments, use of a second-order central difference formula
595
+ # with Richardson extrapolation was more accurate numerically, but it was
596
+ # more complicated, and it would have become even more complicated when
597
+ # adding support for one-sided differences. However, now that all the
598
+ # function evaluation values are stored, they can be processed in whatever
599
+ # way is desired to produce the derivative estimate. We leave alternative
600
+ # approaches to future work. To be more self-contained, here is the theory
601
+ # for deriving the weights below.
602
+ #
603
+ # Recall that the Taylor expansion of a univariate, scalar-values function
604
+ # about a point `x` may be expressed as:
605
+ # f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3)
606
+ # Suppose we evaluate f(x), f(x+h), and f(x-h). We have:
607
+ # f(x) = f(x)
608
+ # f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3)
609
+ # f(x - h) = f(x) - f'(x)*h + f''(x)/2!*h**2 + O(h**3)
610
+ # We can solve for weights `wi` such that:
611
+ # w1*f(x) = w1*(f(x))
612
+ # + w2*f(x + h) = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
613
+ # + w3*f(x - h) = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
614
+ # = 0 + f'(x)*h + 0 + O(h**3)
615
+ # Then
616
+ # f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
617
+ # is a finite difference derivative approximation with error O(h**2),
618
+ # and so it is said to be a "second-order" approximation. Under certain
619
+ # conditions (e.g. well-behaved function, `h` sufficiently small), the
620
+ # error in the approximation will decrease with h**2; that is, if `h` is
621
+ # reduced by a factor of 2, the error is reduced by a factor of 4.
622
+ #
623
+ # By default, we use eighth-order formulae. Our central-difference formula
624
+ # uses abscissae:
625
+ # x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
626
+ # where `c` is the step factor. (Typically, the step factor is greater than
627
+ # one, so the outermost points - as written above - are actually closest to
628
+ # `x`.) This "stencil" is chosen so that each iteration, the step can be
629
+ # reduced by the factor `c`, and most of the function evaluations can be
630
+ # reused with the new step size. For example, in the next iteration, we
631
+ # will have:
632
+ # x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
633
+ # We do not reuse `x-h` and `x+h` for the new derivative estimate.
634
+ # While this would increase the order of the formula and thus the
635
+ # theoretical convergence rate, it is also less stable numerically.
636
+ # (As noted above, there are other ways of processing the values that are
637
+ # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
638
+ # to simplify future development of this sort of improvement.)
639
+ #
640
+ # The (right) one-sided formula is produced similarly using abscissae
641
+ # x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
642
+ # where `d` is the square root of `c`. (The left one-sided formula simply
643
+ # uses -h.) When the step size is reduced by factor `c = d**2`, we have
644
+ # abscissae:
645
+ # x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
646
+ # `d` is chosen as the square root of `c` so that the rate of the step-size
647
+ # reduction is the same per iteration as in the central difference case.
648
+ # Note that because the central difference formulas are inherently of even
649
+ # order, for simplicity, we use only even-order formulas for one-sided
650
+ # differences, too.
651
+
652
+ # It's possible for the user to specify `fac` in, say, double precision but
653
+ # `x` and `args` in single precision. `fac` gets converted to single
654
+ # precision, but we should always use double precision for the intermediate
655
+ # calculations here to avoid additional error in the weights.
656
+ fac = float(work.fac)
657
+
658
+ # Note that if the user switches back to floating point precision with
659
+ # `x` and `args`, then `fac` will not necessarily equal the (lower
660
+ # precision) cached `_derivative_weights.fac`, and the weights will
661
+ # need to be recalculated. This could be fixed, but it's late, and of
662
+ # low consequence.
663
+
664
+ diff_state = work.diff_state
665
+ if fac != diff_state.fac:
666
+ diff_state.central = []
667
+ diff_state.right = []
668
+ diff_state.fac = fac
669
+
670
+ if len(diff_state.central) != 2*n + 1:
671
+ # Central difference weights. Consider refactoring this; it could
672
+ # probably be more compact.
673
+ # Note: Using NumPy here is OK; we convert to xp-type at the end
674
+ i = np.arange(-n, n + 1)
675
+ p = np.abs(i) - 1. # center point has power `p` -1, but sign `s` is 0
676
+ s = np.sign(i)
677
+
678
+ h = s / fac ** p
679
+ A = np.vander(h, increasing=True).T
680
+ b = np.zeros(2*n + 1)
681
+ b[1] = 1
682
+ weights = np.linalg.solve(A, b)
683
+
684
+ # Enforce identities to improve accuracy
685
+ weights[n] = 0
686
+ for i in range(n):
687
+ weights[-i-1] = -weights[i]
688
+
689
+ # Cache the weights. We only need to calculate them once unless
690
+ # the step factor changes.
691
+ diff_state.central = weights
692
+
693
+ # One-sided difference weights. The left one-sided weights (with
694
+ # negative steps) are simply the negative of the right one-sided
695
+ # weights, so no need to compute them separately.
696
+ i = np.arange(2*n + 1)
697
+ p = i - 1.
698
+ s = np.sign(i)
699
+
700
+ h = s / np.sqrt(fac) ** p
701
+ A = np.vander(h, increasing=True).T
702
+ b = np.zeros(2 * n + 1)
703
+ b[1] = 1
704
+ weights = np.linalg.solve(A, b)
705
+
706
+ diff_state.right = weights
707
+
708
+ return (xp.asarray(diff_state.central, dtype=work.dtype),
709
+ xp.asarray(diff_state.right, dtype=work.dtype))
710
+
711
+
712
+ def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
713
+ step_factor=2.0, step_direction=0):
714
+ r"""Evaluate the Jacobian of a function numerically.
715
+
716
+ Parameters
717
+ ----------
718
+ f : callable
719
+ The function whose Jacobian is desired. The signature must be::
720
+
721
+ f(xi: ndarray) -> ndarray
722
+
723
+ where each element of ``xi`` is a finite real. If the function to be
724
+ differentiated accepts additional arguments, wrap it (e.g. using
725
+ `functools.partial` or ``lambda``) and pass the wrapped callable
726
+ into `jacobian`. `f` must not mutate the array ``xi``. See Notes
727
+ regarding vectorization and the dimensionality of the input and output.
728
+ x : float array_like
729
+ Points at which to evaluate the Jacobian. Must have at least one dimension.
730
+ See Notes regarding the dimensionality and vectorization.
731
+ tolerances : dictionary of floats, optional
732
+ Absolute and relative tolerances. Valid keys of the dictionary are:
733
+
734
+ - ``atol`` - absolute tolerance on the derivative
735
+ - ``rtol`` - relative tolerance on the derivative
736
+
737
+ Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
738
+ `atol` is the smallest normal number of the appropriate dtype, and
739
+ the default `rtol` is the square root of the precision of the
740
+ appropriate dtype.
741
+ maxiter : int, default: 10
742
+ The maximum number of iterations of the algorithm to perform. See
743
+ Notes.
744
+ order : int, default: 8
745
+ The (positive integer) order of the finite difference formula to be
746
+ used. Odd integers will be rounded up to the next even integer.
747
+ initial_step : float array_like, default: 0.5
748
+ The (absolute) initial step size for the finite difference derivative
749
+ approximation. Must be broadcastable with `x` and `step_direction`.
750
+ step_factor : float, default: 2.0
751
+ The factor by which the step size is *reduced* in each iteration; i.e.
752
+ the step size in iteration 1 is ``initial_step/step_factor``. If
753
+ ``step_factor < 1``, subsequent steps will be greater than the initial
754
+ step; this may be useful if steps smaller than some threshold are
755
+ undesirable (e.g. due to subtractive cancellation error).
756
+ step_direction : integer array_like
757
+ An array representing the direction of the finite difference steps (e.g.
758
+ for use when `x` lies near to the boundary of the domain of the function.)
759
+ Must be broadcastable with `x` and `initial_step`.
760
+ Where 0 (default), central differences are used; where negative (e.g.
761
+ -1), steps are non-positive; and where positive (e.g. 1), all steps are
762
+ non-negative.
763
+
764
+ Returns
765
+ -------
766
+ res : _RichResult
767
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
768
+ following attributes. The descriptions are written as though the values will
769
+ be scalars; however, if `f` returns an array, the outputs will be
770
+ arrays of the same shape.
771
+
772
+ success : bool array
773
+ ``True`` where the algorithm terminated successfully (status ``0``);
774
+ ``False`` otherwise.
775
+ status : int array
776
+ An integer representing the exit status of the algorithm.
777
+
778
+ - ``0`` : The algorithm converged to the specified tolerances.
779
+ - ``-1`` : The error estimate increased, so iteration was terminated.
780
+ - ``-2`` : The maximum number of iterations was reached.
781
+ - ``-3`` : A non-finite value was encountered.
782
+
783
+ df : float array
784
+ The Jacobian of `f` at `x`, if the algorithm terminated
785
+ successfully.
786
+ error : float array
787
+ An estimate of the error: the magnitude of the difference between
788
+ the current estimate of the Jacobian and the estimate in the
789
+ previous iteration.
790
+ nit : int array
791
+ The number of iterations of the algorithm that were performed.
792
+ nfev : int array
793
+ The number of points at which `f` was evaluated.
794
+
795
+ Each element of an attribute is associated with the corresponding
796
+ element of `df`. For instance, element ``i`` of `nfev` is the
797
+ number of points at which `f` was evaluated for the sake of
798
+ computing element ``i`` of `df`.
799
+
800
+ See Also
801
+ --------
802
+ derivative, hessian
803
+
804
+ Notes
805
+ -----
806
+ Suppose we wish to evaluate the Jacobian of a function
807
+ :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
808
+ ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
809
+ respectively, and let ``...`` represent an arbitrary tuple of integers.
810
+ If we wish to evaluate the Jacobian at a single point, then:
811
+
812
+ - argument `x` must be an array of shape ``(m,)``
813
+ - argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
814
+ The first axis represents the :math:`m` inputs of :math:`f`; the remainder
815
+ are for evaluating the function at multiple points in a single call.
816
+ - argument `f` must return an array of shape ``(n, ...)``. The first
817
+ axis represents the :math:`n` outputs of :math:`f`; the remainder
818
+ are for the result of evaluating the function at multiple points.
819
+ - attribute ``df`` of the result object will be an array of shape ``(n, m)``,
820
+ the Jacobian.
821
+
822
+ This function is also vectorized in the sense that the Jacobian can be
823
+ evaluated at ``k`` points in a single call. In this case, `x` would be an
824
+ array of shape ``(m, k)``, `f` would accept an array of shape
825
+ ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
826
+ attribute of the result would have shape ``(n, m, k)``.
827
+
828
+ Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
829
+ only accept an array of shape ``(m,)``. A simple solution to satisfy the required
830
+ interface is to wrap ``f_not_vectorized`` as follows::
831
+
832
+ def f(x):
833
+ return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)
834
+
835
+ Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
836
+ only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
837
+ consider::
838
+
839
+ def f(x):
840
+ m, batch = x.shape[0], x.shape[1:] # x.shape is (m, ...)
841
+ x = np.reshape(x, (m, -1)) # `-1` is short for q = prod(batch)
842
+ res = f_vec_q(x) # pass shape (m, q) to function
843
+ n = res.shape[0]
844
+ return np.reshape(res, (n,) + batch) # return shape (n, ...)
845
+
846
+ Then pass the wrapped callable ``f`` as the first argument of `jacobian`.
847
+
848
+ References
849
+ ----------
850
+ .. [1] Jacobian matrix and determinant, *Wikipedia*,
851
+ https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
852
+
853
+ Examples
854
+ --------
855
+ The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
856
+ the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
857
+ array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
858
+ to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
859
+ at ``[0.5, 0.5, 0.5]``.
860
+
861
+ >>> import numpy as np
862
+ >>> from scipy.differentiate import jacobian
863
+ >>> from scipy.optimize import rosen, rosen_der
864
+ >>> m = 3
865
+ >>> x = np.full(m, 0.5)
866
+ >>> res = jacobian(rosen, x)
867
+ >>> ref = rosen_der(x) # reference value of the gradient
868
+ >>> res.df, ref
869
+ (array([-51., -1., 50.]), array([-51., -1., 50.]))
870
+
871
+ As an example of a function with multiple outputs, consider Example 4
872
+ from [1]_.
873
+
874
+ >>> def f(x):
875
+ ... x1, x2, x3 = x
876
+ ... return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]
877
+
878
+ The true Jacobian is given by:
879
+
880
+ >>> def df(x):
881
+ ... x1, x2, x3 = x
882
+ ... one = np.ones_like(x1)
883
+ ... return [[one, 0*one, 0*one],
884
+ ... [0*one, 0*one, 5*one],
885
+ ... [0*one, 8*x2, -2*one],
886
+ ... [x3*np.cos(x1), 0*one, np.sin(x1)]]
887
+
888
+ Evaluate the Jacobian at an arbitrary point.
889
+
890
+ >>> rng = np.random.default_rng(389252938452)
891
+ >>> x = rng.random(size=3)
892
+ >>> res = jacobian(f, x)
893
+ >>> ref = df(x)
894
+ >>> res.df.shape == (4, 3)
895
+ True
896
+ >>> np.allclose(res.df, ref)
897
+ True
898
+
899
+ Evaluate the Jacobian at 10 arbitrary points in a single call.
900
+
901
+ >>> x = rng.random(size=(3, 10))
902
+ >>> res = jacobian(f, x)
903
+ >>> ref = df(x)
904
+ >>> res.df.shape == (4, 3, 10)
905
+ True
906
+ >>> np.allclose(res.df, ref)
907
+ True
908
+
909
+ """
910
+ xp = array_namespace(x)
911
+ x0 = xp_promote(x, force_floating=True, xp=xp)
912
+
913
+ if x0.ndim < 1:
914
+ message = "Argument `x` must be at least 1-D."
915
+ raise ValueError(message)
916
+
917
+ m = x0.shape[0]
918
+ i = xp.arange(m)
919
+
920
+ def wrapped(x):
921
+ p = () if x.ndim == x0.ndim else (x.shape[-1],) # number of abscissae
922
+
923
+ new_shape = (m, m) + x0.shape[1:] + p
924
+ xph = xp.expand_dims(x0, axis=1)
925
+ if x.ndim != x0.ndim:
926
+ xph = xp.expand_dims(xph, axis=-1)
927
+ xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
928
+ xph = xpx.at(xph)[i, i].set(x)
929
+ return f(xph)
930
+
931
+ res = derivative(wrapped, x, tolerances=tolerances,
932
+ maxiter=maxiter, order=order, initial_step=initial_step,
933
+ step_factor=step_factor, preserve_shape=True,
934
+ step_direction=step_direction)
935
+
936
+ del res.x # the user knows `x`, and the way it gets broadcasted is meaningless here
937
+ return res
938
+
939
+
940
+ def hessian(f, x, *, tolerances=None, maxiter=10,
941
+ order=8, initial_step=0.5, step_factor=2.0):
942
+ r"""Evaluate the Hessian of a function numerically.
943
+
944
+ Parameters
945
+ ----------
946
+ f : callable
947
+ The function whose Hessian is desired. The signature must be::
948
+
949
+ f(xi: ndarray) -> ndarray
950
+
951
+ where each element of ``xi`` is a finite real. If the function to be
952
+ differentiated accepts additional arguments, wrap it (e.g. using
953
+ `functools.partial` or ``lambda``) and pass the wrapped callable
954
+ into `hessian`. `f` must not mutate the array ``xi``. See Notes
955
+ regarding vectorization and the dimensionality of the input and output.
956
+ x : float array_like
957
+ Points at which to evaluate the Hessian. Must have at least one dimension.
958
+ See Notes regarding the dimensionality and vectorization.
959
+ tolerances : dictionary of floats, optional
960
+ Absolute and relative tolerances. Valid keys of the dictionary are:
961
+
962
+ - ``atol`` - absolute tolerance on the derivative
963
+ - ``rtol`` - relative tolerance on the derivative
964
+
965
+ Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
966
+ `atol` is the smallest normal number of the appropriate dtype, and
967
+ the default `rtol` is the square root of the precision of the
968
+ appropriate dtype.
969
+ order : int, default: 8
970
+ The (positive integer) order of the finite difference formula to be
971
+ used. Odd integers will be rounded up to the next even integer.
972
+ initial_step : float, default: 0.5
973
+ The (absolute) initial step size for the finite difference derivative
974
+ approximation.
975
+ step_factor : float, default: 2.0
976
+ The factor by which the step size is *reduced* in each iteration; i.e.
977
+ the step size in iteration 1 is ``initial_step/step_factor``. If
978
+ ``step_factor < 1``, subsequent steps will be greater than the initial
979
+ step; this may be useful if steps smaller than some threshold are
980
+ undesirable (e.g. due to subtractive cancellation error).
981
+ maxiter : int, default: 10
982
+ The maximum number of iterations of the algorithm to perform. See
983
+ Notes.
984
+
985
+ Returns
986
+ -------
987
+ res : _RichResult
988
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
989
+ following attributes. The descriptions are written as though the values will
990
+ be scalars; however, if `f` returns an array, the outputs will be
991
+ arrays of the same shape.
992
+
993
+ success : bool array
994
+ ``True`` where the algorithm terminated successfully (status ``0``);
995
+ ``False`` otherwise.
996
+ status : int array
997
+ An integer representing the exit status of the algorithm.
998
+
999
+ - ``0`` : The algorithm converged to the specified tolerances.
1000
+ - ``-1`` : The error estimate increased, so iteration was terminated.
1001
+ - ``-2`` : The maximum number of iterations was reached.
1002
+ - ``-3`` : A non-finite value was encountered.
1003
+
1004
+ ddf : float array
1005
+ The Hessian of `f` at `x`, if the algorithm terminated
1006
+ successfully.
1007
+ error : float array
1008
+ An estimate of the error: the magnitude of the difference between
1009
+ the current estimate of the Hessian and the estimate in the
1010
+ previous iteration.
1011
+ nfev : int array
1012
+ The number of points at which `f` was evaluated.
1013
+
1014
+ Each element of an attribute is associated with the corresponding
1015
+ element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
1016
+ number of points at which `f` was evaluated for the sake of
1017
+ computing element ``[i, j]`` of `ddf`.
1018
+
1019
+ See Also
1020
+ --------
1021
+ derivative, jacobian
1022
+
1023
+ Notes
1024
+ -----
1025
+ Suppose we wish to evaluate the Hessian of a function
1026
+ :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
1027
+ ``m`` the positive integer value of :math:`m`. If we wish to evaluate
1028
+ the Hessian at a single point, then:
1029
+
1030
+ - argument `x` must be an array of shape ``(m,)``
1031
+ - argument `f` must be vectorized to accept an array of shape
1032
+ ``(m, ...)``. The first axis represents the :math:`m` inputs of
1033
+ :math:`f`; the remaining axes indicated by ellipses are for evaluating
1034
+ the function at several abscissae in a single call.
1035
+ - argument `f` must return an array of shape ``(...)``.
1036
+ - attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
1037
+ the Hessian.
1038
+
1039
+ This function is also vectorized in the sense that the Hessian can be
1040
+ evaluated at ``k`` points in a single call. In this case, `x` would be an
1041
+ array of shape ``(m, k)``, `f` would accept an array of shape
1042
+ ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
1043
+ attribute of the result would have shape ``(m, m, k)``. Note that the
1044
+ axis associated with the ``k`` points is included within the axes
1045
+ denoted by ``(...)``.
1046
+
1047
+ Currently, `hessian` is implemented by nesting calls to `jacobian`.
1048
+ All options passed to `hessian` are used for both the inner and outer
1049
+ calls with one exception: the `rtol` used in the inner `jacobian` call
1050
+ is tightened by a factor of 100 with the expectation that the inner
1051
+ error can be ignored. A consequence is that `rtol` should not be set
1052
+ less than 100 times the precision of the dtype of `x`; a warning is
1053
+ emitted otherwise.
1054
+
1055
+ References
1056
+ ----------
1057
+ .. [1] Hessian matrix, *Wikipedia*,
1058
+ https://en.wikipedia.org/wiki/Hessian_matrix
1059
+
1060
+ Examples
1061
+ --------
1062
+ The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
1063
+ the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
1064
+ array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
1065
+ wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.
1066
+
1067
+ >>> import numpy as np
1068
+ >>> from scipy.differentiate import hessian
1069
+ >>> from scipy.optimize import rosen, rosen_hess
1070
+ >>> m = 3
1071
+ >>> x = np.full(m, 0.5)
1072
+ >>> res = hessian(rosen, x)
1073
+ >>> ref = rosen_hess(x) # reference value of the Hessian
1074
+ >>> np.allclose(res.ddf, ref)
1075
+ True
1076
+
1077
+ `hessian` is vectorized to evaluate the Hessian at multiple points
1078
+ in a single call.
1079
+
1080
+ >>> rng = np.random.default_rng(4589245925010)
1081
+ >>> x = rng.random((m, 10))
1082
+ >>> res = hessian(rosen, x)
1083
+ >>> ref = [rosen_hess(xi) for xi in x.T]
1084
+ >>> ref = np.moveaxis(ref, 0, -1)
1085
+ >>> np.allclose(res.ddf, ref)
1086
+ True
1087
+
1088
+ """
1089
+ # todo:
1090
+ # - add ability to vectorize over additional parameters (*args?)
1091
+ # - error estimate stack with inner jacobian (or use legit 2D stencil)
1092
+
1093
+ kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step,
1094
+ step_factor=step_factor)
1095
+ tolerances = {} if tolerances is None else tolerances
1096
+ atol = tolerances.get('atol', None)
1097
+ rtol = tolerances.get('rtol', None)
1098
+
1099
+ xp = array_namespace(x)
1100
+ x0 = xp_promote(x, force_floating=True, xp=xp)
1101
+
1102
+ finfo = xp.finfo(x0.dtype)
1103
+ rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `derivative`
1104
+
1105
+ # tighten the inner tolerance to make the inner error negligible
1106
+ rtol_min = finfo.eps * 100
1107
+ message = (f"The specified `{rtol=}`, but error estimates are likely to be "
1108
+ f"unreliable when `rtol < {rtol_min}`.")
1109
+ if 0 < rtol < rtol_min: # rtol <= 0 is an error
1110
+ warnings.warn(message, RuntimeWarning, stacklevel=2)
1111
+ rtol = rtol_min
1112
+
1113
+ def df(x):
1114
+ tolerances = dict(rtol=rtol/100, atol=atol)
1115
+ temp = jacobian(f, x, tolerances=tolerances, **kwargs)
1116
+ nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
1117
+ return temp.df
1118
+
1119
+ nfev = [] # track inner function evaluations
1120
+ res = jacobian(df, x, tolerances=tolerances, **kwargs) # jacobian of jacobian
1121
+
1122
+ nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
1123
+ res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64) # appease torch
1124
+ res.nfev = xp.take_along_axis(nfev, res_nit, axis=0)[0]
1125
+ res.ddf = res.df
1126
+ del res.df # this is renamed to ddf
1127
+ del res.nit # this is only the outer-jacobian nit
1128
+
1129
+ return res
tool_server/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ==============================================
3
+ Discrete Fourier transforms (:mod:`scipy.fft`)
4
+ ==============================================
5
+
6
+ .. currentmodule:: scipy.fft
7
+
8
+ Fast Fourier Transforms (FFTs)
9
+ ==============================
10
+
11
+ .. autosummary::
12
+ :toctree: generated/
13
+
14
+ fft - Fast (discrete) Fourier Transform (FFT)
15
+ ifft - Inverse FFT
16
+ fft2 - 2-D FFT
17
+ ifft2 - 2-D inverse FFT
18
+ fftn - N-D FFT
19
+ ifftn - N-D inverse FFT
20
+ rfft - FFT of strictly real-valued sequence
21
+ irfft - Inverse of rfft
22
+ rfft2 - 2-D FFT of real sequence
23
+ irfft2 - Inverse of rfft2
24
+ rfftn - N-D FFT of real sequence
25
+ irfftn - Inverse of rfftn
26
+ hfft - FFT of a Hermitian sequence (real spectrum)
27
+ ihfft - Inverse of hfft
28
+ hfft2 - 2-D FFT of a Hermitian sequence
29
+ ihfft2 - Inverse of hfft2
30
+ hfftn - N-D FFT of a Hermitian sequence
31
+ ihfftn - Inverse of hfftn
32
+
33
+ Discrete Sin and Cosine Transforms (DST and DCT)
34
+ ================================================
35
+
36
+ .. autosummary::
37
+ :toctree: generated/
38
+
39
+ dct - Discrete cosine transform
40
+ idct - Inverse discrete cosine transform
41
+ dctn - N-D Discrete cosine transform
42
+ idctn - N-D Inverse discrete cosine transform
43
+ dst - Discrete sine transform
44
+ idst - Inverse discrete sine transform
45
+ dstn - N-D Discrete sine transform
46
+ idstn - N-D Inverse discrete sine transform
47
+
48
+ Fast Hankel Transforms
49
+ ======================
50
+
51
+ .. autosummary::
52
+ :toctree: generated/
53
+
54
+ fht - Fast Hankel transform
55
+ ifht - Inverse of fht
56
+
57
+ Helper functions
58
+ ================
59
+
60
+ .. autosummary::
61
+ :toctree: generated/
62
+
63
+ fftshift - Shift the zero-frequency component to the center of the spectrum
64
+ ifftshift - The inverse of `fftshift`
65
+ fftfreq - Return the Discrete Fourier Transform sample frequencies
66
+ rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
67
+ fhtoffset - Compute an optimal offset for the Fast Hankel Transform
68
+ next_fast_len - Find the optimal length to zero-pad an FFT for speed
69
+ prev_fast_len - Find the maximum slice length that results in a fast FFT
70
+ set_workers - Context manager to set default number of workers
71
+ get_workers - Get the current default number of workers
72
+
73
+ Backend control
74
+ ===============
75
+
76
+ .. autosummary::
77
+ :toctree: generated/
78
+
79
+ set_backend - Context manager to set the backend within a fixed scope
80
+ skip_backend - Context manager to skip a backend within a fixed scope
81
+ set_global_backend - Sets the global fft backend
82
+ register_backend - Register a backend for permanent use
83
+
84
+ """
85
+
86
+ from ._basic import (
87
+ fft, ifft, fft2, ifft2, fftn, ifftn,
88
+ rfft, irfft, rfft2, irfft2, rfftn, irfftn,
89
+ hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn)
90
+ from ._realtransforms import dct, idct, dst, idst, dctn, idctn, dstn, idstn
91
+ from ._fftlog import fht, ifht, fhtoffset
92
+ from ._helper import (
93
+ next_fast_len, prev_fast_len, fftfreq,
94
+ rfftfreq, fftshift, ifftshift)
95
+ from ._backend import (set_backend, skip_backend, set_global_backend,
96
+ register_backend)
97
+ from ._pocketfft.helper import set_workers, get_workers
98
+
99
+ __all__ = [
100
+ 'fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn',
101
+ 'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn',
102
+ 'hfft', 'ihfft', 'hfft2', 'ihfft2', 'hfftn', 'ihfftn',
103
+ 'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift',
104
+ 'next_fast_len', 'prev_fast_len',
105
+ 'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn',
106
+ 'fht', 'ifht',
107
+ 'fhtoffset',
108
+ 'set_backend', 'skip_backend', 'set_global_backend', 'register_backend',
109
+ 'get_workers', 'set_workers']
110
+
111
+
112
+ from scipy._lib._testutils import PytestTester
113
+ test = PytestTester(__name__)
114
+ del PytestTester
tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import scipy._lib.uarray as ua
2
+ from . import _basic_backend
3
+ from . import _realtransforms_backend
4
+ from . import _fftlog_backend
5
+
6
+
7
+ class _ScipyBackend:
8
+ """The default backend for fft calculations
9
+
10
+ Notes
11
+ -----
12
+ We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
13
+ treats the domain as a hierarchy. This means the user can install a single
14
+ backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
15
+ """
16
+ __ua_domain__ = "numpy.scipy.fft"
17
+
18
+ @staticmethod
19
+ def __ua_function__(method, args, kwargs):
20
+
21
+ fn = getattr(_basic_backend, method.__name__, None)
22
+ if fn is None:
23
+ fn = getattr(_realtransforms_backend, method.__name__, None)
24
+ if fn is None:
25
+ fn = getattr(_fftlog_backend, method.__name__, None)
26
+ if fn is None:
27
+ return NotImplemented
28
+ return fn(*args, **kwargs)
29
+
30
+
31
+ _named_backends = {
32
+ 'scipy': _ScipyBackend,
33
+ }
34
+
35
+
36
+ def _backend_from_arg(backend):
37
+ """Maps strings to known backends and validates the backend"""
38
+
39
+ if isinstance(backend, str):
40
+ try:
41
+ backend = _named_backends[backend]
42
+ except KeyError as e:
43
+ raise ValueError(f'Unknown backend {backend}') from e
44
+
45
+ if backend.__ua_domain__ != 'numpy.scipy.fft':
46
+ raise ValueError('Backend does not implement "numpy.scipy.fft"')
47
+
48
+ return backend
49
+
50
+
51
+ def set_global_backend(backend, coerce=False, only=False, try_last=False):
52
+ """Sets the global fft backend
53
+
54
+ This utility method replaces the default backend for permanent use. It
55
+ will be tried in the list of backends automatically, unless the
56
+ ``only`` flag is set on a backend. This will be the first tried
57
+ backend outside the :obj:`set_backend` context manager.
58
+
59
+ Parameters
60
+ ----------
61
+ backend : {object, 'scipy'}
62
+ The backend to use.
63
+ Can either be a ``str`` containing the name of a known backend
64
+ {'scipy'} or an object that implements the uarray protocol.
65
+ coerce : bool
66
+ Whether to coerce input types when trying this backend.
67
+ only : bool
68
+ If ``True``, no more backends will be tried if this fails.
69
+ Implied by ``coerce=True``.
70
+ try_last : bool
71
+ If ``True``, the global backend is tried after registered backends.
72
+
73
+ Raises
74
+ ------
75
+ ValueError: If the backend does not implement ``numpy.scipy.fft``.
76
+
77
+ Notes
78
+ -----
79
+ This will overwrite the previously set global backend, which, by default, is
80
+ the SciPy implementation.
81
+
82
+ Examples
83
+ --------
84
+ We can set the global fft backend:
85
+
86
+ >>> from scipy.fft import fft, set_global_backend
87
+ >>> set_global_backend("scipy") # Sets global backend (default is "scipy").
88
+ >>> fft([1]) # Calls the global backend
89
+ array([1.+0.j])
90
+ """
91
+ backend = _backend_from_arg(backend)
92
+ ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
93
+
94
+
95
+ def register_backend(backend):
96
+ """
97
+ Register a backend for permanent use.
98
+
99
+ Registered backends have the lowest priority and will be tried after the
100
+ global backend.
101
+
102
+ Parameters
103
+ ----------
104
+ backend : {object, 'scipy'}
105
+ The backend to use.
106
+ Can either be a ``str`` containing the name of a known backend
107
+ {'scipy'} or an object that implements the uarray protocol.
108
+
109
+ Raises
110
+ ------
111
+ ValueError: If the backend does not implement ``numpy.scipy.fft``.
112
+
113
+ Examples
114
+ --------
115
+ We can register a new fft backend:
116
+
117
+ >>> from scipy.fft import fft, register_backend, set_global_backend
118
+ >>> class NoopBackend: # Define an invalid Backend
119
+ ... __ua_domain__ = "numpy.scipy.fft"
120
+ ... def __ua_function__(self, func, args, kwargs):
121
+ ... return NotImplemented
122
+ >>> set_global_backend(NoopBackend()) # Set the invalid backend as global
123
+ >>> register_backend("scipy") # Register a new backend
124
+ # The registered backend is called because
125
+ # the global backend returns `NotImplemented`
126
+ >>> fft([1])
127
+ array([1.+0.j])
128
+ >>> set_global_backend("scipy") # Restore global backend to default
129
+
130
+ """
131
+ backend = _backend_from_arg(backend)
132
+ ua.register_backend(backend)
133
+
134
+
135
+ def set_backend(backend, coerce=False, only=False):
136
+ """Context manager to set the backend within a fixed scope.
137
+
138
+ Upon entering the ``with`` statement, the given backend will be added to
139
+ the list of available backends with the highest priority. Upon exit, the
140
+ backend is reset to the state before entering the scope.
141
+
142
+ Parameters
143
+ ----------
144
+ backend : {object, 'scipy'}
145
+ The backend to use.
146
+ Can either be a ``str`` containing the name of a known backend
147
+ {'scipy'} or an object that implements the uarray protocol.
148
+ coerce : bool, optional
149
+ Whether to allow expensive conversions for the ``x`` parameter. e.g.,
150
+ copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
151
+ only : bool, optional
152
+ If only is ``True`` and this backend returns ``NotImplemented``, then a
153
+ BackendNotImplemented error will be raised immediately. Ignoring any
154
+ lower priority backends.
155
+
156
+ Examples
157
+ --------
158
+ >>> import scipy.fft as fft
159
+ >>> with fft.set_backend('scipy', only=True):
160
+ ... fft.fft([1]) # Always calls the scipy implementation
161
+ array([1.+0.j])
162
+ """
163
+ backend = _backend_from_arg(backend)
164
+ return ua.set_backend(backend, coerce=coerce, only=only)
165
+
166
+
167
+ def skip_backend(backend):
168
+ """Context manager to skip a backend within a fixed scope.
169
+
170
+ Within the context of a ``with`` statement, the given backend will not be
171
+ called. This covers backends registered both locally and globally. Upon
172
+ exit, the backend will again be considered.
173
+
174
+ Parameters
175
+ ----------
176
+ backend : {object, 'scipy'}
177
+ The backend to skip.
178
+ Can either be a ``str`` containing the name of a known backend
179
+ {'scipy'} or an object that implements the uarray protocol.
180
+
181
+ Examples
182
+ --------
183
+ >>> import scipy.fft as fft
184
+ >>> fft.fft([1]) # Calls default SciPy backend
185
+ array([1.+0.j])
186
+ >>> with fft.skip_backend('scipy'): # We explicitly skip the SciPy backend
187
+ ... fft.fft([1]) # leaving no implementation available
188
+ Traceback (most recent call last):
189
+ ...
190
+ BackendNotImplementedError: No selected backends had an implementation ...
191
+ """
192
+ backend = _backend_from_arg(backend)
193
+ return ua.skip_backend(backend)
194
+
195
+
196
+ set_global_backend('scipy', try_last=True)
tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py ADDED
@@ -0,0 +1,1650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scipy._lib.uarray import generate_multimethod, Dispatchable
2
+ import numpy as np
3
+
4
+
5
+ def _x_replacer(args, kwargs, dispatchables):
6
+ """
7
+ uarray argument replacer to replace the transform input array (``x``)
8
+ """
9
+ if len(args) > 0:
10
+ return (dispatchables[0],) + args[1:], kwargs
11
+ kw = kwargs.copy()
12
+ kw['x'] = dispatchables[0]
13
+ return args, kw
14
+
15
+
16
+ def _dispatch(func):
17
+ """
18
+ Function annotation that creates a uarray multimethod from the function
19
+ """
20
+ return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft")
21
+
22
+
23
+ @_dispatch
24
+ def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
25
+ plan=None):
26
+ """
27
+ Compute the 1-D discrete Fourier Transform.
28
+
29
+ This function computes the 1-D *n*-point discrete Fourier
30
+ Transform (DFT) with the efficient Fast Fourier Transform (FFT)
31
+ algorithm [1]_.
32
+
33
+ Parameters
34
+ ----------
35
+ x : array_like
36
+ Input array, can be complex.
37
+ n : int, optional
38
+ Length of the transformed axis of the output.
39
+ If `n` is smaller than the length of the input, the input is cropped.
40
+ If it is larger, the input is padded with zeros. If `n` is not given,
41
+ the length of the input along the axis specified by `axis` is used.
42
+ axis : int, optional
43
+ Axis over which to compute the FFT. If not given, the last axis is
44
+ used.
45
+ norm : {"backward", "ortho", "forward"}, optional
46
+ Normalization mode. Default is "backward", meaning no normalization on
47
+ the forward transforms and scaling by ``1/n`` on the `ifft`.
48
+ "forward" instead applies the ``1/n`` factor on the forward transform.
49
+ For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``.
50
+
51
+ .. versionadded:: 1.6.0
52
+ ``norm={"forward", "backward"}`` options were added
53
+
54
+ overwrite_x : bool, optional
55
+ If True, the contents of `x` can be destroyed; the default is False.
56
+ See the notes below for more details.
57
+ workers : int, optional
58
+ Maximum number of workers to use for parallel computation. If negative,
59
+ the value wraps around from ``os.cpu_count()``. See below for more
60
+ details.
61
+ plan : object, optional
62
+ This argument is reserved for passing in a precomputed plan provided
63
+ by downstream FFT vendors. It is currently not used in SciPy.
64
+
65
+ .. versionadded:: 1.5.0
66
+
67
+ Returns
68
+ -------
69
+ out : complex ndarray
70
+ The truncated or zero-padded input, transformed along the axis
71
+ indicated by `axis`, or the last one if `axis` is not specified.
72
+
73
+ Raises
74
+ ------
75
+ IndexError
76
+ if `axes` is larger than the last axis of `x`.
77
+
78
+ See Also
79
+ --------
80
+ ifft : The inverse of `fft`.
81
+ fft2 : The 2-D FFT.
82
+ fftn : The N-D FFT.
83
+ rfftn : The N-D FFT of real input.
84
+ fftfreq : Frequency bins for given FFT parameters.
85
+ next_fast_len : Size to pad input to for most efficient transforms
86
+
87
+ Notes
88
+ -----
89
+ FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform
90
+ (DFT) can be calculated efficiently, by using symmetries in the calculated
91
+ terms. The symmetry is highest when `n` is a power of 2, and the transform
92
+ is therefore most efficient for these sizes. For poorly factorizable sizes,
93
+ `scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than
94
+ O(`n` log `n`). Further performance improvements may be seen by zero-padding
95
+ the input using `next_fast_len`.
96
+
97
+ If ``x`` is a 1d array, then the `fft` is equivalent to ::
98
+
99
+ y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))
100
+
101
+ The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach
102
+ the Nyquist frequency and wrap around to the negative-frequency terms. So,
103
+ for an 8-point transform, the frequencies of the result are
104
+ [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the
105
+ zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3],
106
+ use `fftshift`.
107
+
108
+ Transforms can be done in single, double, or extended precision (long
109
+ double) floating point. Half precision inputs will be converted to single
110
+ precision and non-floating-point inputs will be converted to double
111
+ precision.
112
+
113
+ If the data type of ``x`` is real, a "real FFT" algorithm is automatically
114
+ used, which roughly halves the computation time. To increase efficiency
115
+ a little further, use `rfft`, which does the same calculation, but only
116
+ outputs half of the symmetrical spectrum. If the data are both real and
117
+ symmetrical, the `dct` can again double the efficiency, by generating
118
+ half of the spectrum from half of the signal.
119
+
120
+ When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may
121
+ be used by the implementation in any way. This may include reusing the
122
+ memory for the result, but this is in no way guaranteed. You should not
123
+ rely on the contents of ``x`` after the transform as this may change in
124
+ future without warning.
125
+
126
+ The ``workers`` argument specifies the maximum number of parallel jobs to
127
+ split the FFT computation into. This will execute independent 1-D
128
+ FFTs within ``x``. So, ``x`` must be at least 2-D and the
129
+ non-transformed axes must be large enough to split into chunks. If ``x`` is
130
+ too small, fewer jobs may be used than requested.
131
+
132
+ References
133
+ ----------
134
+ .. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
135
+ machine calculation of complex Fourier series," *Math. Comput.*
136
+ 19: 297-301.
137
+ .. [2] Bluestein, L., 1970, "A linear filtering approach to the
138
+ computation of discrete Fourier transform". *IEEE Transactions on
139
+ Audio and Electroacoustics.* 18 (4): 451-455.
140
+
141
+ Examples
142
+ --------
143
+ >>> import scipy.fft
144
+ >>> import numpy as np
145
+ >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
146
+ array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j,
147
+ 2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j,
148
+ -1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j,
149
+ 1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j])
150
+
151
+ In this example, real input has an FFT which is Hermitian, i.e., symmetric
152
+ in the real part and anti-symmetric in the imaginary part:
153
+
154
+ >>> from scipy.fft import fft, fftfreq, fftshift
155
+ >>> import matplotlib.pyplot as plt
156
+ >>> t = np.arange(256)
157
+ >>> sp = fftshift(fft(np.sin(t)))
158
+ >>> freq = fftshift(fftfreq(t.shape[-1]))
159
+ >>> plt.plot(freq, sp.real, freq, sp.imag)
160
+ [<matplotlib.lines.Line2D object at 0x...>,
161
+ <matplotlib.lines.Line2D object at 0x...>]
162
+ >>> plt.show()
163
+
164
+ """
165
+ return (Dispatchable(x, np.ndarray),)
166
+
167
+
168
+ @_dispatch
169
+ def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
170
+ plan=None):
171
+ """
172
+ Compute the 1-D inverse discrete Fourier Transform.
173
+
174
+ This function computes the inverse of the 1-D *n*-point
175
+ discrete Fourier transform computed by `fft`. In other words,
176
+ ``ifft(fft(x)) == x`` to within numerical accuracy.
177
+
178
+ The input should be ordered in the same way as is returned by `fft`,
179
+ i.e.,
180
+
181
+ * ``x[0]`` should contain the zero frequency term,
182
+ * ``x[1:n//2]`` should contain the positive-frequency terms,
183
+ * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
184
+ increasing order starting from the most negative frequency.
185
+
186
+ For an even number of input points, ``x[n//2]`` represents the sum of
187
+ the values at the positive and negative Nyquist frequencies, as the two
188
+ are aliased together. See `fft` for details.
189
+
190
+ Parameters
191
+ ----------
192
+ x : array_like
193
+ Input array, can be complex.
194
+ n : int, optional
195
+ Length of the transformed axis of the output.
196
+ If `n` is smaller than the length of the input, the input is cropped.
197
+ If it is larger, the input is padded with zeros. If `n` is not given,
198
+ the length of the input along the axis specified by `axis` is used.
199
+ See notes about padding issues.
200
+ axis : int, optional
201
+ Axis over which to compute the inverse DFT. If not given, the last
202
+ axis is used.
203
+ norm : {"backward", "ortho", "forward"}, optional
204
+ Normalization mode (see `fft`). Default is "backward".
205
+ overwrite_x : bool, optional
206
+ If True, the contents of `x` can be destroyed; the default is False.
207
+ See :func:`fft` for more details.
208
+ workers : int, optional
209
+ Maximum number of workers to use for parallel computation. If negative,
210
+ the value wraps around from ``os.cpu_count()``.
211
+ See :func:`~scipy.fft.fft` for more details.
212
+ plan : object, optional
213
+ This argument is reserved for passing in a precomputed plan provided
214
+ by downstream FFT vendors. It is currently not used in SciPy.
215
+
216
+ .. versionadded:: 1.5.0
217
+
218
+ Returns
219
+ -------
220
+ out : complex ndarray
221
+ The truncated or zero-padded input, transformed along the axis
222
+ indicated by `axis`, or the last one if `axis` is not specified.
223
+
224
+ Raises
225
+ ------
226
+ IndexError
227
+ If `axes` is larger than the last axis of `x`.
228
+
229
+ See Also
230
+ --------
231
+ fft : The 1-D (forward) FFT, of which `ifft` is the inverse.
232
+ ifft2 : The 2-D inverse FFT.
233
+ ifftn : The N-D inverse FFT.
234
+
235
+ Notes
236
+ -----
237
+ If the input parameter `n` is larger than the size of the input, the input
238
+ is padded by appending zeros at the end. Even though this is the common
239
+ approach, it might lead to surprising results. If a different padding is
240
+ desired, it must be performed before calling `ifft`.
241
+
242
+ If ``x`` is a 1-D array, then the `ifft` is equivalent to ::
243
+
244
+ y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)
245
+
246
+ As with `fft`, `ifft` has support for all floating point types and is
247
+ optimized for real input.
248
+
249
+ Examples
250
+ --------
251
+ >>> import scipy.fft
252
+ >>> import numpy as np
253
+ >>> scipy.fft.ifft([0, 4, 0, 0])
254
+ array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary
255
+
256
+ Create and plot a band-limited signal with random phases:
257
+
258
+ >>> import matplotlib.pyplot as plt
259
+ >>> rng = np.random.default_rng()
260
+ >>> t = np.arange(400)
261
+ >>> n = np.zeros((400,), dtype=complex)
262
+ >>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,)))
263
+ >>> s = scipy.fft.ifft(n)
264
+ >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
265
+ [<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]
266
+ >>> plt.legend(('real', 'imaginary'))
267
+ <matplotlib.legend.Legend object at ...>
268
+ >>> plt.show()
269
+
270
+ """
271
+ return (Dispatchable(x, np.ndarray),)
272
+
273
+
274
+ @_dispatch
275
+ def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
276
+ plan=None):
277
+ """
278
+ Compute the 1-D discrete Fourier Transform for real input.
279
+
280
+ This function computes the 1-D *n*-point discrete Fourier
281
+ Transform (DFT) of a real-valued array by means of an efficient algorithm
282
+ called the Fast Fourier Transform (FFT).
283
+
284
+ Parameters
285
+ ----------
286
+ x : array_like
287
+ Input array
288
+ n : int, optional
289
+ Number of points along transformation axis in the input to use.
290
+ If `n` is smaller than the length of the input, the input is cropped.
291
+ If it is larger, the input is padded with zeros. If `n` is not given,
292
+ the length of the input along the axis specified by `axis` is used.
293
+ axis : int, optional
294
+ Axis over which to compute the FFT. If not given, the last axis is
295
+ used.
296
+ norm : {"backward", "ortho", "forward"}, optional
297
+ Normalization mode (see `fft`). Default is "backward".
298
+ overwrite_x : bool, optional
299
+ If True, the contents of `x` can be destroyed; the default is False.
300
+ See :func:`fft` for more details.
301
+ workers : int, optional
302
+ Maximum number of workers to use for parallel computation. If negative,
303
+ the value wraps around from ``os.cpu_count()``.
304
+ See :func:`~scipy.fft.fft` for more details.
305
+ plan : object, optional
306
+ This argument is reserved for passing in a precomputed plan provided
307
+ by downstream FFT vendors. It is currently not used in SciPy.
308
+
309
+ .. versionadded:: 1.5.0
310
+
311
+ Returns
312
+ -------
313
+ out : complex ndarray
314
+ The truncated or zero-padded input, transformed along the axis
315
+ indicated by `axis`, or the last one if `axis` is not specified.
316
+ If `n` is even, the length of the transformed axis is ``(n/2)+1``.
317
+ If `n` is odd, the length is ``(n+1)/2``.
318
+
319
+ Raises
320
+ ------
321
+ IndexError
322
+ If `axis` is larger than the last axis of `a`.
323
+
324
+ See Also
325
+ --------
326
+ irfft : The inverse of `rfft`.
327
+ fft : The 1-D FFT of general (complex) input.
328
+ fftn : The N-D FFT.
329
+ rfft2 : The 2-D FFT of real input.
330
+ rfftn : The N-D FFT of real input.
331
+
332
+ Notes
333
+ -----
334
+ When the DFT is computed for purely real input, the output is
335
+ Hermitian-symmetric, i.e., the negative frequency terms are just the complex
336
+ conjugates of the corresponding positive-frequency terms, and the
337
+ negative-frequency terms are therefore redundant. This function does not
338
+ compute the negative frequency terms, and the length of the transformed
339
+ axis of the output is therefore ``n//2 + 1``.
340
+
341
+ When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains
342
+ the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
343
+
344
+ If `n` is even, ``A[-1]`` contains the term representing both positive
345
+ and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
346
+ real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
347
+ the largest positive frequency (fs/2*(n-1)/n), and is complex in the
348
+ general case.
349
+
350
+ If the input `a` contains an imaginary part, it is silently discarded.
351
+
352
+ Examples
353
+ --------
354
+ >>> import scipy.fft
355
+ >>> scipy.fft.fft([0, 1, 0, 0])
356
+ array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary
357
+ >>> scipy.fft.rfft([0, 1, 0, 0])
358
+ array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary
359
+
360
+ Notice how the final element of the `fft` output is the complex conjugate
361
+ of the second element, for real input. For `rfft`, this symmetry is
362
+ exploited to compute only the non-negative frequency terms.
363
+
364
+ """
365
+ return (Dispatchable(x, np.ndarray),)
366
+
367
+
368
+ @_dispatch
369
+ def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
370
+ plan=None):
371
+ """
372
+ Computes the inverse of `rfft`.
373
+
374
+ This function computes the inverse of the 1-D *n*-point
375
+ discrete Fourier Transform of real input computed by `rfft`.
376
+ In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical
377
+ accuracy. (See Notes below for why ``len(a)`` is necessary here.)
378
+
379
+ The input is expected to be in the form returned by `rfft`, i.e., the
380
+ real zero-frequency term followed by the complex positive frequency terms
381
+ in order of increasing frequency. Since the discrete Fourier Transform of
382
+ real input is Hermitian-symmetric, the negative frequency terms are taken
383
+ to be the complex conjugates of the corresponding positive frequency terms.
384
+
385
+ Parameters
386
+ ----------
387
+ x : array_like
388
+ The input array.
389
+ n : int, optional
390
+ Length of the transformed axis of the output.
391
+ For `n` output points, ``n//2+1`` input points are necessary. If the
392
+ input is longer than this, it is cropped. If it is shorter than this,
393
+ it is padded with zeros. If `n` is not given, it is taken to be
394
+ ``2*(m-1)``, where ``m`` is the length of the input along the axis
395
+ specified by `axis`.
396
+ axis : int, optional
397
+ Axis over which to compute the inverse FFT. If not given, the last
398
+ axis is used.
399
+ norm : {"backward", "ortho", "forward"}, optional
400
+ Normalization mode (see `fft`). Default is "backward".
401
+ overwrite_x : bool, optional
402
+ If True, the contents of `x` can be destroyed; the default is False.
403
+ See :func:`fft` for more details.
404
+ workers : int, optional
405
+ Maximum number of workers to use for parallel computation. If negative,
406
+ the value wraps around from ``os.cpu_count()``.
407
+ See :func:`~scipy.fft.fft` for more details.
408
+ plan : object, optional
409
+ This argument is reserved for passing in a precomputed plan provided
410
+ by downstream FFT vendors. It is currently not used in SciPy.
411
+
412
+ .. versionadded:: 1.5.0
413
+
414
+ Returns
415
+ -------
416
+ out : ndarray
417
+ The truncated or zero-padded input, transformed along the axis
418
+ indicated by `axis`, or the last one if `axis` is not specified.
419
+ The length of the transformed axis is `n`, or, if `n` is not given,
420
+ ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
421
+ input. To get an odd number of output points, `n` must be specified.
422
+
423
+ Raises
424
+ ------
425
+ IndexError
426
+ If `axis` is larger than the last axis of `x`.
427
+
428
+ See Also
429
+ --------
430
+ rfft : The 1-D FFT of real input, of which `irfft` is inverse.
431
+ fft : The 1-D FFT.
432
+ irfft2 : The inverse of the 2-D FFT of real input.
433
+ irfftn : The inverse of the N-D FFT of real input.
434
+
435
+ Notes
436
+ -----
437
+ Returns the real valued `n`-point inverse discrete Fourier transform
438
+ of `x`, where `x` contains the non-negative frequency terms of a
439
+ Hermitian-symmetric sequence. `n` is the length of the result, not the
440
+ input.
441
+
442
+ If you specify an `n` such that `a` must be zero-padded or truncated, the
443
+ extra/removed values will be added/removed at high frequencies. One can
444
+ thus resample a series to `m` points via Fourier interpolation by:
445
+ ``a_resamp = irfft(rfft(a), m)``.
446
+
447
+ The default value of `n` assumes an even output length. By the Hermitian
448
+ symmetry, the last imaginary component must be 0 and so is ignored. To
449
+ avoid losing information, the correct length of the real input *must* be
450
+ given.
451
+
452
+ Examples
453
+ --------
454
+ >>> import scipy.fft
455
+ >>> scipy.fft.ifft([1, -1j, -1, 1j])
456
+ array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary
457
+ >>> scipy.fft.irfft([1, -1j, -1])
458
+ array([0., 1., 0., 0.])
459
+
460
+ Notice how the last term in the input to the ordinary `ifft` is the
461
+ complex conjugate of the second term, and the output has zero imaginary
462
+ part everywhere. When calling `irfft`, the negative frequencies are not
463
+ specified, and the output array is purely real.
464
+
465
+ """
466
+ return (Dispatchable(x, np.ndarray),)
467
+
468
+
469
+ @_dispatch
470
+ def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
471
+ plan=None):
472
+ """
473
+ Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
474
+ spectrum.
475
+
476
+ Parameters
477
+ ----------
478
+ x : array_like
479
+ The input array.
480
+ n : int, optional
481
+ Length of the transformed axis of the output. For `n` output
482
+ points, ``n//2 + 1`` input points are necessary. If the input is
483
+ longer than this, it is cropped. If it is shorter than this, it is
484
+ padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``,
485
+ where ``m`` is the length of the input along the axis specified by
486
+ `axis`.
487
+ axis : int, optional
488
+ Axis over which to compute the FFT. If not given, the last
489
+ axis is used.
490
+ norm : {"backward", "ortho", "forward"}, optional
491
+ Normalization mode (see `fft`). Default is "backward".
492
+ overwrite_x : bool, optional
493
+ If True, the contents of `x` can be destroyed; the default is False.
494
+ See `fft` for more details.
495
+ workers : int, optional
496
+ Maximum number of workers to use for parallel computation. If negative,
497
+ the value wraps around from ``os.cpu_count()``.
498
+ See :func:`~scipy.fft.fft` for more details.
499
+ plan : object, optional
500
+ This argument is reserved for passing in a precomputed plan provided
501
+ by downstream FFT vendors. It is currently not used in SciPy.
502
+
503
+ .. versionadded:: 1.5.0
504
+
505
+ Returns
506
+ -------
507
+ out : ndarray
508
+ The truncated or zero-padded input, transformed along the axis
509
+ indicated by `axis`, or the last one if `axis` is not specified.
510
+ The length of the transformed axis is `n`, or, if `n` is not given,
511
+ ``2*m - 2``, where ``m`` is the length of the transformed axis of
512
+ the input. To get an odd number of output points, `n` must be
513
+ specified, for instance, as ``2*m - 1`` in the typical case,
514
+
515
+ Raises
516
+ ------
517
+ IndexError
518
+ If `axis` is larger than the last axis of `a`.
519
+
520
+ See Also
521
+ --------
522
+ rfft : Compute the 1-D FFT for real input.
523
+ ihfft : The inverse of `hfft`.
524
+ hfftn : Compute the N-D FFT of a Hermitian signal.
525
+
526
+ Notes
527
+ -----
528
+ `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
529
+ opposite case: here the signal has Hermitian symmetry in the time
530
+ domain and is real in the frequency domain. So, here, it's `hfft`, for
531
+ which you must supply the length of the result if it is to be odd.
532
+ * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
533
+ * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
534
+
535
+ Examples
536
+ --------
537
+ >>> from scipy.fft import fft, hfft
538
+ >>> import numpy as np
539
+ >>> a = 2 * np.pi * np.arange(10) / 10
540
+ >>> signal = np.cos(a) + 3j * np.sin(3 * a)
541
+ >>> fft(signal).round(10)
542
+ array([ -0.+0.j, 5.+0.j, -0.+0.j, 15.-0.j, 0.+0.j, 0.+0.j,
543
+ -0.+0.j, -15.-0.j, 0.+0.j, 5.+0.j])
544
+ >>> hfft(signal[:6]).round(10) # Input first half of signal
545
+ array([ 0., 5., 0., 15., -0., 0., 0., -15., -0., 5.])
546
+ >>> hfft(signal, 10) # Input entire signal and truncate
547
+ array([ 0., 5., 0., 15., -0., 0., 0., -15., -0., 5.])
548
+ """
549
+ return (Dispatchable(x, np.ndarray),)
550
+
551
+
552
+ @_dispatch
553
+ def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
554
+ plan=None):
555
+ """
556
+ Compute the inverse FFT of a signal that has Hermitian symmetry.
557
+
558
+ Parameters
559
+ ----------
560
+ x : array_like
561
+ Input array.
562
+ n : int, optional
563
+ Length of the inverse FFT, the number of points along
564
+ transformation axis in the input to use. If `n` is smaller than
565
+ the length of the input, the input is cropped. If it is larger,
566
+ the input is padded with zeros. If `n` is not given, the length of
567
+ the input along the axis specified by `axis` is used.
568
+ axis : int, optional
569
+ Axis over which to compute the inverse FFT. If not given, the last
570
+ axis is used.
571
+ norm : {"backward", "ortho", "forward"}, optional
572
+ Normalization mode (see `fft`). Default is "backward".
573
+ overwrite_x : bool, optional
574
+ If True, the contents of `x` can be destroyed; the default is False.
575
+ See `fft` for more details.
576
+ workers : int, optional
577
+ Maximum number of workers to use for parallel computation. If negative,
578
+ the value wraps around from ``os.cpu_count()``.
579
+ See :func:`~scipy.fft.fft` for more details.
580
+ plan : object, optional
581
+ This argument is reserved for passing in a precomputed plan provided
582
+ by downstream FFT vendors. It is currently not used in SciPy.
583
+
584
+ .. versionadded:: 1.5.0
585
+
586
+ Returns
587
+ -------
588
+ out : complex ndarray
589
+ The truncated or zero-padded input, transformed along the axis
590
+ indicated by `axis`, or the last one if `axis` is not specified.
591
+ The length of the transformed axis is ``n//2 + 1``.
592
+
593
+ See Also
594
+ --------
595
+ hfft, irfft
596
+
597
+ Notes
598
+ -----
599
+ `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
600
+ opposite case: here, the signal has Hermitian symmetry in the time
601
+ domain and is real in the frequency domain. So, here, it's `hfft`, for
602
+ which you must supply the length of the result if it is to be odd:
603
+ * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
604
+ * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
605
+
606
+ Examples
607
+ --------
608
+ >>> from scipy.fft import ifft, ihfft
609
+ >>> import numpy as np
610
+ >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
611
+ >>> ifft(spectrum)
612
+ array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary
613
+ >>> ihfft(spectrum)
614
+ array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary
615
+ """
616
+ return (Dispatchable(x, np.ndarray),)
617
+
618
+
619
+ @_dispatch
620
+ def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
621
+ plan=None):
622
+ """
623
+ Compute the N-D discrete Fourier Transform.
624
+
625
+ This function computes the N-D discrete Fourier Transform over
626
+ any number of axes in an M-D array by means of the Fast Fourier
627
+ Transform (FFT).
628
+
629
+ Parameters
630
+ ----------
631
+ x : array_like
632
+ Input array, can be complex.
633
+ s : sequence of ints, optional
634
+ Shape (length of each transformed axis) of the output
635
+ (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
636
+ This corresponds to ``n`` for ``fft(x, n)``.
637
+ Along any axis, if the given shape is smaller than that of the input,
638
+ the input is cropped. If it is larger, the input is padded with zeros.
639
+ if `s` is not given, the shape of the input along the axes specified
640
+ by `axes` is used.
641
+ axes : sequence of ints, optional
642
+ Axes over which to compute the FFT. If not given, the last ``len(s)``
643
+ axes are used, or all axes if `s` is also not specified.
644
+ norm : {"backward", "ortho", "forward"}, optional
645
+ Normalization mode (see `fft`). Default is "backward".
646
+ overwrite_x : bool, optional
647
+ If True, the contents of `x` can be destroyed; the default is False.
648
+ See :func:`fft` for more details.
649
+ workers : int, optional
650
+ Maximum number of workers to use for parallel computation. If negative,
651
+ the value wraps around from ``os.cpu_count()``.
652
+ See :func:`~scipy.fft.fft` for more details.
653
+ plan : object, optional
654
+ This argument is reserved for passing in a precomputed plan provided
655
+ by downstream FFT vendors. It is currently not used in SciPy.
656
+
657
+ .. versionadded:: 1.5.0
658
+
659
+ Returns
660
+ -------
661
+ out : complex ndarray
662
+ The truncated or zero-padded input, transformed along the axes
663
+ indicated by `axes`, or by a combination of `s` and `x`,
664
+ as explained in the parameters section above.
665
+
666
+ Raises
667
+ ------
668
+ ValueError
669
+ If `s` and `axes` have different length.
670
+ IndexError
671
+ If an element of `axes` is larger than the number of axes of `x`.
672
+
673
+ See Also
674
+ --------
675
+ ifftn : The inverse of `fftn`, the inverse N-D FFT.
676
+ fft : The 1-D FFT, with definitions and conventions used.
677
+ rfftn : The N-D FFT of real input.
678
+ fft2 : The 2-D FFT.
679
+ fftshift : Shifts zero-frequency terms to centre of array.
680
+
681
+ Notes
682
+ -----
683
+ The output, analogously to `fft`, contains the term for zero frequency in
684
+ the low-order corner of all axes, the positive frequency terms in the
685
+ first half of all axes, the term for the Nyquist frequency in the middle
686
+ of all axes and the negative frequency terms in the second half of all
687
+ axes, in order of decreasingly negative frequency.
688
+
689
+ Examples
690
+ --------
691
+ >>> import scipy.fft
692
+ >>> import numpy as np
693
+ >>> x = np.mgrid[:3, :3, :3][0]
694
+ >>> scipy.fft.fftn(x, axes=(1, 2))
695
+ array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary
696
+ [ 0.+0.j, 0.+0.j, 0.+0.j],
697
+ [ 0.+0.j, 0.+0.j, 0.+0.j]],
698
+ [[ 9.+0.j, 0.+0.j, 0.+0.j],
699
+ [ 0.+0.j, 0.+0.j, 0.+0.j],
700
+ [ 0.+0.j, 0.+0.j, 0.+0.j]],
701
+ [[18.+0.j, 0.+0.j, 0.+0.j],
702
+ [ 0.+0.j, 0.+0.j, 0.+0.j],
703
+ [ 0.+0.j, 0.+0.j, 0.+0.j]]])
704
+ >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1))
705
+ array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary
706
+ [ 0.+0.j, 0.+0.j, 0.+0.j]],
707
+ [[-2.+0.j, -2.+0.j, -2.+0.j],
708
+ [ 0.+0.j, 0.+0.j, 0.+0.j]]])
709
+
710
+ >>> import matplotlib.pyplot as plt
711
+ >>> rng = np.random.default_rng()
712
+ >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
713
+ ... 2 * np.pi * np.arange(200) / 34)
714
+ >>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape)
715
+ >>> FS = scipy.fft.fftn(S)
716
+ >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2))
717
+ <matplotlib.image.AxesImage object at 0x...>
718
+ >>> plt.show()
719
+
720
+ """
721
+ return (Dispatchable(x, np.ndarray),)
722
+
723
+
724
+ @_dispatch
725
+ def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
726
+ plan=None):
727
+ """
728
+ Compute the N-D inverse discrete Fourier Transform.
729
+
730
+ This function computes the inverse of the N-D discrete
731
+ Fourier Transform over any number of axes in an M-D array by
732
+ means of the Fast Fourier Transform (FFT). In other words,
733
+ ``ifftn(fftn(x)) == x`` to within numerical accuracy.
734
+
735
+ The input, analogously to `ifft`, should be ordered in the same way as is
736
+ returned by `fftn`, i.e., it should have the term for zero frequency
737
+ in all axes in the low-order corner, the positive frequency terms in the
738
+ first half of all axes, the term for the Nyquist frequency in the middle
739
+ of all axes and the negative frequency terms in the second half of all
740
+ axes, in order of decreasingly negative frequency.
741
+
742
+ Parameters
743
+ ----------
744
+ x : array_like
745
+ Input array, can be complex.
746
+ s : sequence of ints, optional
747
+ Shape (length of each transformed axis) of the output
748
+ (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
749
+ This corresponds to ``n`` for ``ifft(x, n)``.
750
+ Along any axis, if the given shape is smaller than that of the input,
751
+ the input is cropped. If it is larger, the input is padded with zeros.
752
+ if `s` is not given, the shape of the input along the axes specified
753
+ by `axes` is used. See notes for issue on `ifft` zero padding.
754
+ axes : sequence of ints, optional
755
+ Axes over which to compute the IFFT. If not given, the last ``len(s)``
756
+ axes are used, or all axes if `s` is also not specified.
757
+ norm : {"backward", "ortho", "forward"}, optional
758
+ Normalization mode (see `fft`). Default is "backward".
759
+ overwrite_x : bool, optional
760
+ If True, the contents of `x` can be destroyed; the default is False.
761
+ See :func:`fft` for more details.
762
+ workers : int, optional
763
+ Maximum number of workers to use for parallel computation. If negative,
764
+ the value wraps around from ``os.cpu_count()``.
765
+ See :func:`~scipy.fft.fft` for more details.
766
+ plan : object, optional
767
+ This argument is reserved for passing in a precomputed plan provided
768
+ by downstream FFT vendors. It is currently not used in SciPy.
769
+
770
+ .. versionadded:: 1.5.0
771
+
772
+ Returns
773
+ -------
774
+ out : complex ndarray
775
+ The truncated or zero-padded input, transformed along the axes
776
+ indicated by `axes`, or by a combination of `s` or `x`,
777
+ as explained in the parameters section above.
778
+
779
+ Raises
780
+ ------
781
+ ValueError
782
+ If `s` and `axes` have different length.
783
+ IndexError
784
+ If an element of `axes` is larger than the number of axes of `x`.
785
+
786
+ See Also
787
+ --------
788
+ fftn : The forward N-D FFT, of which `ifftn` is the inverse.
789
+ ifft : The 1-D inverse FFT.
790
+ ifft2 : The 2-D inverse FFT.
791
+ ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
792
+ of array.
793
+
794
+ Notes
795
+ -----
796
+ Zero-padding, analogously with `ifft`, is performed by appending zeros to
797
+ the input along the specified dimension. Although this is the common
798
+ approach, it might lead to surprising results. If another form of zero
799
+ padding is desired, it must be performed before `ifftn` is called.
800
+
801
+ Examples
802
+ --------
803
+ >>> import scipy.fft
804
+ >>> import numpy as np
805
+ >>> x = np.eye(4)
806
+ >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,))
807
+ array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
808
+ [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
809
+ [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
810
+ [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
811
+
812
+
813
+ Create and plot an image with band-limited frequency content:
814
+
815
+ >>> import matplotlib.pyplot as plt
816
+ >>> rng = np.random.default_rng()
817
+ >>> n = np.zeros((200,200), dtype=complex)
818
+ >>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20)))
819
+ >>> im = scipy.fft.ifftn(n).real
820
+ >>> plt.imshow(im)
821
+ <matplotlib.image.AxesImage object at 0x...>
822
+ >>> plt.show()
823
+
824
+ """
825
+ return (Dispatchable(x, np.ndarray),)
826
+
827
+
828
+ @_dispatch
829
+ def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
830
+ plan=None):
831
+ """
832
+ Compute the 2-D discrete Fourier Transform
833
+
834
+ This function computes the N-D discrete Fourier Transform
835
+ over any axes in an M-D array by means of the
836
+ Fast Fourier Transform (FFT). By default, the transform is computed over
837
+ the last two axes of the input array, i.e., a 2-dimensional FFT.
838
+
839
+ Parameters
840
+ ----------
841
+ x : array_like
842
+ Input array, can be complex
843
+ s : sequence of ints, optional
844
+ Shape (length of each transformed axis) of the output
845
+ (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
846
+ This corresponds to ``n`` for ``fft(x, n)``.
847
+ Along each axis, if the given shape is smaller than that of the input,
848
+ the input is cropped. If it is larger, the input is padded with zeros.
849
+ if `s` is not given, the shape of the input along the axes specified
850
+ by `axes` is used.
851
+ axes : sequence of ints, optional
852
+ Axes over which to compute the FFT. If not given, the last two axes are
853
+ used.
854
+ norm : {"backward", "ortho", "forward"}, optional
855
+ Normalization mode (see `fft`). Default is "backward".
856
+ overwrite_x : bool, optional
857
+ If True, the contents of `x` can be destroyed; the default is False.
858
+ See :func:`fft` for more details.
859
+ workers : int, optional
860
+ Maximum number of workers to use for parallel computation. If negative,
861
+ the value wraps around from ``os.cpu_count()``.
862
+ See :func:`~scipy.fft.fft` for more details.
863
+ plan : object, optional
864
+ This argument is reserved for passing in a precomputed plan provided
865
+ by downstream FFT vendors. It is currently not used in SciPy.
866
+
867
+ .. versionadded:: 1.5.0
868
+
869
+ Returns
870
+ -------
871
+ out : complex ndarray
872
+ The truncated or zero-padded input, transformed along the axes
873
+ indicated by `axes`, or the last two axes if `axes` is not given.
874
+
875
+ Raises
876
+ ------
877
+ ValueError
878
+ If `s` and `axes` have different length, or `axes` not given and
879
+ ``len(s) != 2``.
880
+ IndexError
881
+ If an element of `axes` is larger than the number of axes of `x`.
882
+
883
+ See Also
884
+ --------
885
+ ifft2 : The inverse 2-D FFT.
886
+ fft : The 1-D FFT.
887
+ fftn : The N-D FFT.
888
+ fftshift : Shifts zero-frequency terms to the center of the array.
889
+ For 2-D input, swaps first and third quadrants, and second
890
+ and fourth quadrants.
891
+
892
+ Notes
893
+ -----
894
+ `fft2` is just `fftn` with a different default for `axes`.
895
+
896
+ The output, analogously to `fft`, contains the term for zero frequency in
897
+ the low-order corner of the transformed axes, the positive frequency terms
898
+ in the first half of these axes, the term for the Nyquist frequency in the
899
+ middle of the axes and the negative frequency terms in the second half of
900
+ the axes, in order of decreasingly negative frequency.
901
+
902
+ See `fftn` for details and a plotting example, and `fft` for
903
+ definitions and conventions used.
904
+
905
+
906
+ Examples
907
+ --------
908
+ >>> import scipy.fft
909
+ >>> import numpy as np
910
+ >>> x = np.mgrid[:5, :5][0]
911
+ >>> scipy.fft.fft2(x)
912
+ array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary
913
+ 0. +0.j , 0. +0.j ],
914
+ [-12.5+17.20477401j, 0. +0.j , 0. +0.j ,
915
+ 0. +0.j , 0. +0.j ],
916
+ [-12.5 +4.0614962j , 0. +0.j , 0. +0.j ,
917
+ 0. +0.j , 0. +0.j ],
918
+ [-12.5 -4.0614962j , 0. +0.j , 0. +0.j ,
919
+ 0. +0.j , 0. +0.j ],
920
+ [-12.5-17.20477401j, 0. +0.j , 0. +0.j ,
921
+ 0. +0.j , 0. +0.j ]])
922
+
923
+ """
924
+ return (Dispatchable(x, np.ndarray),)
925
+
926
+
927
+ @_dispatch
928
+ def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
929
+ plan=None):
930
+ """
931
+ Compute the 2-D inverse discrete Fourier Transform.
932
+
933
+ This function computes the inverse of the 2-D discrete Fourier
934
+ Transform over any number of axes in an M-D array by means of
935
+ the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
936
+ to within numerical accuracy. By default, the inverse transform is
937
+ computed over the last two axes of the input array.
938
+
939
+ The input, analogously to `ifft`, should be ordered in the same way as is
940
+ returned by `fft2`, i.e., it should have the term for zero frequency
941
+ in the low-order corner of the two axes, the positive frequency terms in
942
+ the first half of these axes, the term for the Nyquist frequency in the
943
+ middle of the axes and the negative frequency terms in the second half of
944
+ both axes, in order of decreasingly negative frequency.
945
+
946
+ Parameters
947
+ ----------
948
+ x : array_like
949
+ Input array, can be complex.
950
+ s : sequence of ints, optional
951
+ Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
952
+ ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
953
+ Along each axis, if the given shape is smaller than that of the input,
954
+ the input is cropped. If it is larger, the input is padded with zeros.
955
+ if `s` is not given, the shape of the input along the axes specified
956
+ by `axes` is used. See notes for issue on `ifft` zero padding.
957
+ axes : sequence of ints, optional
958
+ Axes over which to compute the FFT. If not given, the last two
959
+ axes are used.
960
+ norm : {"backward", "ortho", "forward"}, optional
961
+ Normalization mode (see `fft`). Default is "backward".
962
+ overwrite_x : bool, optional
963
+ If True, the contents of `x` can be destroyed; the default is False.
964
+ See :func:`fft` for more details.
965
+ workers : int, optional
966
+ Maximum number of workers to use for parallel computation. If negative,
967
+ the value wraps around from ``os.cpu_count()``.
968
+ See :func:`~scipy.fft.fft` for more details.
969
+ plan : object, optional
970
+ This argument is reserved for passing in a precomputed plan provided
971
+ by downstream FFT vendors. It is currently not used in SciPy.
972
+
973
+ .. versionadded:: 1.5.0
974
+
975
+ Returns
976
+ -------
977
+ out : complex ndarray
978
+ The truncated or zero-padded input, transformed along the axes
979
+ indicated by `axes`, or the last two axes if `axes` is not given.
980
+
981
+ Raises
982
+ ------
983
+ ValueError
984
+ If `s` and `axes` have different length, or `axes` not given and
985
+ ``len(s) != 2``.
986
+ IndexError
987
+ If an element of `axes` is larger than the number of axes of `x`.
988
+
989
+ See Also
990
+ --------
991
+ fft2 : The forward 2-D FFT, of which `ifft2` is the inverse.
992
+ ifftn : The inverse of the N-D FFT.
993
+ fft : The 1-D FFT.
994
+ ifft : The 1-D inverse FFT.
995
+
996
+ Notes
997
+ -----
998
+ `ifft2` is just `ifftn` with a different default for `axes`.
999
+
1000
+ See `ifftn` for details and a plotting example, and `fft` for
1001
+ definition and conventions used.
1002
+
1003
+ Zero-padding, analogously with `ifft`, is performed by appending zeros to
1004
+ the input along the specified dimension. Although this is the common
1005
+ approach, it might lead to surprising results. If another form of zero
1006
+ padding is desired, it must be performed before `ifft2` is called.
1007
+
1008
+ Examples
1009
+ --------
1010
+ >>> import scipy.fft
1011
+ >>> import numpy as np
1012
+ >>> x = 4 * np.eye(4)
1013
+ >>> scipy.fft.ifft2(x)
1014
+ array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
1015
+ [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],
1016
+ [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
1017
+ [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])
1018
+
1019
+ """
1020
+ return (Dispatchable(x, np.ndarray),)
1021
+
1022
+
1023
+ @_dispatch
1024
+ def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
1025
+ plan=None):
1026
+ """
1027
+ Compute the N-D discrete Fourier Transform for real input.
1028
+
1029
+ This function computes the N-D discrete Fourier Transform over
1030
+ any number of axes in an M-D real array by means of the Fast
1031
+ Fourier Transform (FFT). By default, all axes are transformed, with the
1032
+ real transform performed over the last axis, while the remaining
1033
+ transforms are complex.
1034
+
1035
+ Parameters
1036
+ ----------
1037
+ x : array_like
1038
+ Input array, taken to be real.
1039
+ s : sequence of ints, optional
1040
+ Shape (length along each transformed axis) to use from the input.
1041
+ (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
1042
+ The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
1043
+ for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
1044
+ Along any axis, if the given shape is smaller than that of the input,
1045
+ the input is cropped. If it is larger, the input is padded with zeros.
1046
+ if `s` is not given, the shape of the input along the axes specified
1047
+ by `axes` is used.
1048
+ axes : sequence of ints, optional
1049
+ Axes over which to compute the FFT. If not given, the last ``len(s)``
1050
+ axes are used, or all axes if `s` is also not specified.
1051
+ norm : {"backward", "ortho", "forward"}, optional
1052
+ Normalization mode (see `fft`). Default is "backward".
1053
+ overwrite_x : bool, optional
1054
+ If True, the contents of `x` can be destroyed; the default is False.
1055
+ See :func:`fft` for more details.
1056
+ workers : int, optional
1057
+ Maximum number of workers to use for parallel computation. If negative,
1058
+ the value wraps around from ``os.cpu_count()``.
1059
+ See :func:`~scipy.fft.fft` for more details.
1060
+ plan : object, optional
1061
+ This argument is reserved for passing in a precomputed plan provided
1062
+ by downstream FFT vendors. It is currently not used in SciPy.
1063
+
1064
+ .. versionadded:: 1.5.0
1065
+
1066
+ Returns
1067
+ -------
1068
+ out : complex ndarray
1069
+ The truncated or zero-padded input, transformed along the axes
1070
+ indicated by `axes`, or by a combination of `s` and `x`,
1071
+ as explained in the parameters section above.
1072
+ The length of the last axis transformed will be ``s[-1]//2+1``,
1073
+ while the remaining transformed axes will have lengths according to
1074
+ `s`, or unchanged from the input.
1075
+
1076
+ Raises
1077
+ ------
1078
+ ValueError
1079
+ If `s` and `axes` have different length.
1080
+ IndexError
1081
+ If an element of `axes` is larger than the number of axes of `x`.
1082
+
1083
+ See Also
1084
+ --------
1085
+ irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT
1086
+ of real input.
1087
+ fft : The 1-D FFT, with definitions and conventions used.
1088
+ rfft : The 1-D FFT of real input.
1089
+ fftn : The N-D FFT.
1090
+ rfft2 : The 2-D FFT of real input.
1091
+
1092
+ Notes
1093
+ -----
1094
+ The transform for real input is performed over the last transformation
1095
+ axis, as by `rfft`, then the transform over the remaining axes is
1096
+ performed as by `fftn`. The order of the output is as for `rfft` for the
1097
+ final transformation axis, and as for `fftn` for the remaining
1098
+ transformation axes.
1099
+
1100
+ See `fft` for details, definitions and conventions used.
1101
+
1102
+ Examples
1103
+ --------
1104
+ >>> import scipy.fft
1105
+ >>> import numpy as np
1106
+ >>> x = np.ones((2, 2, 2))
1107
+ >>> scipy.fft.rfftn(x)
1108
+ array([[[8.+0.j, 0.+0.j], # may vary
1109
+ [0.+0.j, 0.+0.j]],
1110
+ [[0.+0.j, 0.+0.j],
1111
+ [0.+0.j, 0.+0.j]]])
1112
+
1113
+ >>> scipy.fft.rfftn(x, axes=(2, 0))
1114
+ array([[[4.+0.j, 0.+0.j], # may vary
1115
+ [4.+0.j, 0.+0.j]],
1116
+ [[0.+0.j, 0.+0.j],
1117
+ [0.+0.j, 0.+0.j]]])
1118
+
1119
+ """
1120
+ return (Dispatchable(x, np.ndarray),)
1121
+
1122
+
1123
+ @_dispatch
1124
+ def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
1125
+ plan=None):
1126
+ """
1127
+ Compute the 2-D FFT of a real array.
1128
+
1129
+ Parameters
1130
+ ----------
1131
+ x : array
1132
+ Input array, taken to be real.
1133
+ s : sequence of ints, optional
1134
+ Shape of the FFT.
1135
+ axes : sequence of ints, optional
1136
+ Axes over which to compute the FFT.
1137
+ norm : {"backward", "ortho", "forward"}, optional
1138
+ Normalization mode (see `fft`). Default is "backward".
1139
+ overwrite_x : bool, optional
1140
+ If True, the contents of `x` can be destroyed; the default is False.
1141
+ See :func:`fft` for more details.
1142
+ workers : int, optional
1143
+ Maximum number of workers to use for parallel computation. If negative,
1144
+ the value wraps around from ``os.cpu_count()``.
1145
+ See :func:`~scipy.fft.fft` for more details.
1146
+ plan : object, optional
1147
+ This argument is reserved for passing in a precomputed plan provided
1148
+ by downstream FFT vendors. It is currently not used in SciPy.
1149
+
1150
+ .. versionadded:: 1.5.0
1151
+
1152
+ Returns
1153
+ -------
1154
+ out : ndarray
1155
+ The result of the real 2-D FFT.
1156
+
1157
+ See Also
1158
+ --------
1159
+ irfft2 : The inverse of the 2-D FFT of real input.
1160
+ rfft : The 1-D FFT of real input.
1161
+ rfftn : Compute the N-D discrete Fourier Transform for real
1162
+ input.
1163
+
1164
+ Notes
1165
+ -----
1166
+ This is really just `rfftn` with different default behavior.
1167
+ For more details see `rfftn`.
1168
+
1169
+ Examples
1170
+ --------
1171
+ >>> import scipy.fft
1172
+ >>> import numpy as np
1173
+ >>> x = np.broadcast_to([1, 0, -1, 0], (4, 4))
1174
+ >>> scipy.fft.rfft2(x)
1175
+ array([[0.+0.j, 8.+0.j, 0.+0.j],
1176
+ [0.+0.j, 0.+0.j, 0.+0.j],
1177
+ [0.+0.j, 0.+0.j, 0.+0.j],
1178
+ [0.+0.j, 0.+0.j, 0.+0.j]])
1179
+
1180
+ """
1181
+ return (Dispatchable(x, np.ndarray),)
1182
+
1183
+
1184
+ @_dispatch
1185
+ def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
1186
+ plan=None):
1187
+ """
1188
+ Computes the inverse of `rfftn`
1189
+
1190
+ This function computes the inverse of the N-D discrete
1191
+ Fourier Transform for real input over any number of axes in an
1192
+ M-D array by means of the Fast Fourier Transform (FFT). In
1193
+ other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
1194
+ accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
1195
+ and for the same reason.)
1196
+
1197
+ The input should be ordered in the same way as is returned by `rfftn`,
1198
+ i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
1199
+ along all the other axes.
1200
+
1201
+ Parameters
1202
+ ----------
1203
+ x : array_like
1204
+ Input array.
1205
+ s : sequence of ints, optional
1206
+ Shape (length of each transformed axis) of the output
1207
+ (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
1208
+ number of input points used along this axis, except for the last axis,
1209
+ where ``s[-1]//2+1`` points of the input are used.
1210
+ Along any axis, if the shape indicated by `s` is smaller than that of
1211
+ the input, the input is cropped. If it is larger, the input is padded
1212
+ with zeros. If `s` is not given, the shape of the input along the axes
1213
+ specified by axes is used. Except for the last axis which is taken to be
1214
+ ``2*(m-1)``, where ``m`` is the length of the input along that axis.
1215
+ axes : sequence of ints, optional
1216
+ Axes over which to compute the inverse FFT. If not given, the last
1217
+ `len(s)` axes are used, or all axes if `s` is also not specified.
1218
+ norm : {"backward", "ortho", "forward"}, optional
1219
+ Normalization mode (see `fft`). Default is "backward".
1220
+ overwrite_x : bool, optional
1221
+ If True, the contents of `x` can be destroyed; the default is False.
1222
+ See :func:`fft` for more details.
1223
+ workers : int, optional
1224
+ Maximum number of workers to use for parallel computation. If negative,
1225
+ the value wraps around from ``os.cpu_count()``.
1226
+ See :func:`~scipy.fft.fft` for more details.
1227
+ plan : object, optional
1228
+ This argument is reserved for passing in a precomputed plan provided
1229
+ by downstream FFT vendors. It is currently not used in SciPy.
1230
+
1231
+ .. versionadded:: 1.5.0
1232
+
1233
+ Returns
1234
+ -------
1235
+ out : ndarray
1236
+ The truncated or zero-padded input, transformed along the axes
1237
+ indicated by `axes`, or by a combination of `s` or `x`,
1238
+ as explained in the parameters section above.
1239
+ The length of each transformed axis is as given by the corresponding
1240
+ element of `s`, or the length of the input in every axis except for the
1241
+ last one if `s` is not given. In the final transformed axis the length
1242
+ of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the
1243
+ length of the final transformed axis of the input. To get an odd
1244
+ number of output points in the final axis, `s` must be specified.
1245
+
1246
+ Raises
1247
+ ------
1248
+ ValueError
1249
+ If `s` and `axes` have different length.
1250
+ IndexError
1251
+ If an element of `axes` is larger than the number of axes of `x`.
1252
+
1253
+ See Also
1254
+ --------
1255
+ rfftn : The forward N-D FFT of real input,
1256
+ of which `ifftn` is the inverse.
1257
+ fft : The 1-D FFT, with definitions and conventions used.
1258
+ irfft : The inverse of the 1-D FFT of real input.
1259
+ irfft2 : The inverse of the 2-D FFT of real input.
1260
+
1261
+ Notes
1262
+ -----
1263
+ See `fft` for definitions and conventions used.
1264
+
1265
+ See `rfft` for definitions and conventions used for real input.
1266
+
1267
+ The default value of `s` assumes an even output length in the final
1268
+ transformation axis. When performing the final complex to real
1269
+ transformation, the Hermitian symmetry requires that the last imaginary
1270
+ component along that axis must be 0 and so it is ignored. To avoid losing
1271
+ information, the correct length of the real input *must* be given.
1272
+
1273
+ Examples
1274
+ --------
1275
+ >>> import scipy.fft
1276
+ >>> import numpy as np
1277
+ >>> x = np.zeros((3, 2, 2))
1278
+ >>> x[0, 0, 0] = 3 * 2 * 2
1279
+ >>> scipy.fft.irfftn(x)
1280
+ array([[[1., 1.],
1281
+ [1., 1.]],
1282
+ [[1., 1.],
1283
+ [1., 1.]],
1284
+ [[1., 1.],
1285
+ [1., 1.]]])
1286
+
1287
+ """
1288
+ return (Dispatchable(x, np.ndarray),)
1289
+
1290
+
1291
+ @_dispatch
1292
+ def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
1293
+ plan=None):
1294
+ """
1295
+ Computes the inverse of `rfft2`
1296
+
1297
+ Parameters
1298
+ ----------
1299
+ x : array_like
1300
+ The input array
1301
+ s : sequence of ints, optional
1302
+ Shape of the real output to the inverse FFT.
1303
+ axes : sequence of ints, optional
1304
+ The axes over which to compute the inverse fft.
1305
+ Default is the last two axes.
1306
+ norm : {"backward", "ortho", "forward"}, optional
1307
+ Normalization mode (see `fft`). Default is "backward".
1308
+ overwrite_x : bool, optional
1309
+ If True, the contents of `x` can be destroyed; the default is False.
1310
+ See :func:`fft` for more details.
1311
+ workers : int, optional
1312
+ Maximum number of workers to use for parallel computation. If negative,
1313
+ the value wraps around from ``os.cpu_count()``.
1314
+ See :func:`~scipy.fft.fft` for more details.
1315
+ plan : object, optional
1316
+ This argument is reserved for passing in a precomputed plan provided
1317
+ by downstream FFT vendors. It is currently not used in SciPy.
1318
+
1319
+ .. versionadded:: 1.5.0
1320
+
1321
+ Returns
1322
+ -------
1323
+ out : ndarray
1324
+ The result of the inverse real 2-D FFT.
1325
+
1326
+ See Also
1327
+ --------
1328
+ rfft2 : The 2-D FFT of real input.
1329
+ irfft : The inverse of the 1-D FFT of real input.
1330
+ irfftn : The inverse of the N-D FFT of real input.
1331
+
1332
+ Notes
1333
+ -----
1334
+ This is really `irfftn` with different defaults.
1335
+ For more details see `irfftn`.
1336
+
1337
+ """
1338
+ return (Dispatchable(x, np.ndarray),)
1339
+
1340
+
1341
+ @_dispatch
1342
+ def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
1343
+ plan=None):
1344
+ """
1345
+ Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
1346
+ signal with a real spectrum.
1347
+
1348
+ This function computes the N-D discrete Fourier Transform for a
1349
+ Hermitian symmetric complex input over any number of axes in an
1350
+ M-D array by means of the Fast Fourier Transform (FFT). In other
1351
+ words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s``
1352
+ here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary
1353
+ for the same reason ``x.shape`` would be necessary for `irfft`.)
1354
+
1355
+ Parameters
1356
+ ----------
1357
+ x : array_like
1358
+ Input array.
1359
+ s : sequence of ints, optional
1360
+ Shape (length of each transformed axis) of the output
1361
+ (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
1362
+ number of input points used along this axis, except for the last axis,
1363
+ where ``s[-1]//2+1`` points of the input are used.
1364
+ Along any axis, if the shape indicated by `s` is smaller than that of
1365
+ the input, the input is cropped. If it is larger, the input is padded
1366
+ with zeros. If `s` is not given, the shape of the input along the axes
1367
+ specified by axes is used. Except for the last axis which is taken to be
1368
+ ``2*(m-1)`` where ``m`` is the length of the input along that axis.
1369
+ axes : sequence of ints, optional
1370
+ Axes over which to compute the inverse FFT. If not given, the last
1371
+ `len(s)` axes are used, or all axes if `s` is also not specified.
1372
+ norm : {"backward", "ortho", "forward"}, optional
1373
+ Normalization mode (see `fft`). Default is "backward".
1374
+ overwrite_x : bool, optional
1375
+ If True, the contents of `x` can be destroyed; the default is False.
1376
+ See :func:`fft` for more details.
1377
+ workers : int, optional
1378
+ Maximum number of workers to use for parallel computation. If negative,
1379
+ the value wraps around from ``os.cpu_count()``.
1380
+ See :func:`~scipy.fft.fft` for more details.
1381
+ plan : object, optional
1382
+ This argument is reserved for passing in a precomputed plan provided
1383
+ by downstream FFT vendors. It is currently not used in SciPy.
1384
+
1385
+ .. versionadded:: 1.5.0
1386
+
1387
+ Returns
1388
+ -------
1389
+ out : ndarray
1390
+ The truncated or zero-padded input, transformed along the axes
1391
+ indicated by `axes`, or by a combination of `s` or `x`,
1392
+ as explained in the parameters section above.
1393
+ The length of each transformed axis is as given by the corresponding
1394
+ element of `s`, or the length of the input in every axis except for the
1395
+ last one if `s` is not given. In the final transformed axis the length
1396
+ of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
1397
+ length of the final transformed axis of the input. To get an odd
1398
+ number of output points in the final axis, `s` must be specified.
1399
+
1400
+ Raises
1401
+ ------
1402
+ ValueError
1403
+ If `s` and `axes` have different length.
1404
+ IndexError
1405
+ If an element of `axes` is larger than the number of axes of `x`.
1406
+
1407
+ See Also
1408
+ --------
1409
+ ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`.
1410
+ fft : The 1-D FFT, with definitions and conventions used.
1411
+ rfft : Forward FFT of real input.
1412
+
1413
+ Notes
1414
+ -----
1415
+ For a 1-D signal ``x`` to have a real spectrum, it must satisfy
1416
+ the Hermitian property::
1417
+
1418
+ x[i] == np.conj(x[-i]) for all i
1419
+
1420
+ This generalizes into higher dimensions by reflecting over each axis in
1421
+ turn::
1422
+
1423
+ x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ...
1424
+
1425
+ This should not be confused with a Hermitian matrix, for which the
1426
+ transpose is its own conjugate::
1427
+
1428
+ x[i, j] == np.conj(x[j, i]) for all i, j
1429
+
1430
+
1431
+ The default value of `s` assumes an even output length in the final
1432
+ transformation axis. When performing the final complex to real
1433
+ transformation, the Hermitian symmetry requires that the last imaginary
1434
+ component along that axis must be 0 and so it is ignored. To avoid losing
1435
+ information, the correct length of the real input *must* be given.
1436
+
1437
+ Examples
1438
+ --------
1439
+ >>> import scipy.fft
1440
+ >>> import numpy as np
1441
+ >>> x = np.ones((3, 2, 2))
1442
+ >>> scipy.fft.hfftn(x)
1443
+ array([[[12., 0.],
1444
+ [ 0., 0.]],
1445
+ [[ 0., 0.],
1446
+ [ 0., 0.]],
1447
+ [[ 0., 0.],
1448
+ [ 0., 0.]]])
1449
+
1450
+ """
1451
+ return (Dispatchable(x, np.ndarray),)
1452
+
1453
+
1454
+ @_dispatch
1455
+ def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
1456
+ plan=None):
1457
+ """
1458
+ Compute the 2-D FFT of a Hermitian complex array.
1459
+
1460
+ Parameters
1461
+ ----------
1462
+ x : array
1463
+ Input array, taken to be Hermitian complex.
1464
+ s : sequence of ints, optional
1465
+ Shape of the real output.
1466
+ axes : sequence of ints, optional
1467
+ Axes over which to compute the FFT.
1468
+ norm : {"backward", "ortho", "forward"}, optional
1469
+ Normalization mode (see `fft`). Default is "backward".
1470
+ overwrite_x : bool, optional
1471
+ If True, the contents of `x` can be destroyed; the default is False.
1472
+ See `fft` for more details.
1473
+ workers : int, optional
1474
+ Maximum number of workers to use for parallel computation. If negative,
1475
+ the value wraps around from ``os.cpu_count()``.
1476
+ See :func:`~scipy.fft.fft` for more details.
1477
+ plan : object, optional
1478
+ This argument is reserved for passing in a precomputed plan provided
1479
+ by downstream FFT vendors. It is currently not used in SciPy.
1480
+
1481
+ .. versionadded:: 1.5.0
1482
+
1483
+ Returns
1484
+ -------
1485
+ out : ndarray
1486
+ The real result of the 2-D Hermitian complex real FFT.
1487
+
1488
+ See Also
1489
+ --------
1490
+ hfftn : Compute the N-D discrete Fourier Transform for Hermitian
1491
+ complex input.
1492
+
1493
+ Notes
1494
+ -----
1495
+ This is really just `hfftn` with different default behavior.
1496
+ For more details see `hfftn`.
1497
+
1498
+ Examples
1499
+ --------
1500
+ >>> import scipy.fft
1501
+ >>> import numpy as np
1502
+ >>> x = np.array([[1+0j, 2+0j], [2+0j, 1+0j]]) # Hermitian-symmetric input
1503
+ >>> scipy.fft.hfft2(x, s=(2, 2))
1504
+ array([[ 6., 0.],
1505
+ [ 0., -2.]])
1506
+
1507
+ """
1508
+ return (Dispatchable(x, np.ndarray),)
1509
+
1510
+
1511
+ @_dispatch
1512
+ def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
1513
+ plan=None):
1514
+ """
1515
+ Compute the N-D inverse discrete Fourier Transform for a real
1516
+ spectrum.
1517
+
1518
+ This function computes the N-D inverse discrete Fourier Transform
1519
+ over any number of axes in an M-D real array by means of the Fast
1520
+ Fourier Transform (FFT). By default, all axes are transformed, with the
1521
+ real transform performed over the last axis, while the remaining transforms
1522
+ are complex.
1523
+
1524
+ Parameters
1525
+ ----------
1526
+ x : array_like
1527
+ Input array, taken to be real.
1528
+ s : sequence of ints, optional
1529
+ Shape (length along each transformed axis) to use from the input.
1530
+ (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
1531
+ Along any axis, if the given shape is smaller than that of the input,
1532
+ the input is cropped. If it is larger, the input is padded with zeros.
1533
+ if `s` is not given, the shape of the input along the axes specified
1534
+ by `axes` is used.
1535
+ axes : sequence of ints, optional
1536
+ Axes over which to compute the FFT. If not given, the last ``len(s)``
1537
+ axes are used, or all axes if `s` is also not specified.
1538
+ norm : {"backward", "ortho", "forward"}, optional
1539
+ Normalization mode (see `fft`). Default is "backward".
1540
+ overwrite_x : bool, optional
1541
+ If True, the contents of `x` can be destroyed; the default is False.
1542
+ See :func:`fft` for more details.
1543
+ workers : int, optional
1544
+ Maximum number of workers to use for parallel computation. If negative,
1545
+ the value wraps around from ``os.cpu_count()``.
1546
+ See :func:`~scipy.fft.fft` for more details.
1547
+ plan : object, optional
1548
+ This argument is reserved for passing in a precomputed plan provided
1549
+ by downstream FFT vendors. It is currently not used in SciPy.
1550
+
1551
+ .. versionadded:: 1.5.0
1552
+
1553
+ Returns
1554
+ -------
1555
+ out : complex ndarray
1556
+ The truncated or zero-padded input, transformed along the axes
1557
+ indicated by `axes`, or by a combination of `s` and `x`,
1558
+ as explained in the parameters section above.
1559
+ The length of the last axis transformed will be ``s[-1]//2+1``,
1560
+ while the remaining transformed axes will have lengths according to
1561
+ `s`, or unchanged from the input.
1562
+
1563
+ Raises
1564
+ ------
1565
+ ValueError
1566
+ If `s` and `axes` have different length.
1567
+ IndexError
1568
+ If an element of `axes` is larger than the number of axes of `x`.
1569
+
1570
+ See Also
1571
+ --------
1572
+ hfftn : The forward N-D FFT of Hermitian input.
1573
+ hfft : The 1-D FFT of Hermitian input.
1574
+ fft : The 1-D FFT, with definitions and conventions used.
1575
+ fftn : The N-D FFT.
1576
+ hfft2 : The 2-D FFT of Hermitian input.
1577
+
1578
+ Notes
1579
+ -----
1580
+ The transform for real input is performed over the last transformation
1581
+ axis, as by `ihfft`, then the transform over the remaining axes is
1582
+ performed as by `ifftn`. The order of the output is the positive part of
1583
+ the Hermitian output signal, in the same format as `rfft`.
1584
+
1585
+ Examples
1586
+ --------
1587
+ >>> import scipy.fft
1588
+ >>> import numpy as np
1589
+ >>> x = np.ones((2, 2, 2))
1590
+ >>> scipy.fft.ihfftn(x)
1591
+ array([[[1.+0.j, 0.+0.j], # may vary
1592
+ [0.+0.j, 0.+0.j]],
1593
+ [[0.+0.j, 0.+0.j],
1594
+ [0.+0.j, 0.+0.j]]])
1595
+ >>> scipy.fft.ihfftn(x, axes=(2, 0))
1596
+ array([[[1.+0.j, 0.+0.j], # may vary
1597
+ [1.+0.j, 0.+0.j]],
1598
+ [[0.+0.j, 0.+0.j],
1599
+ [0.+0.j, 0.+0.j]]])
1600
+
1601
+ """
1602
+ return (Dispatchable(x, np.ndarray),)
1603
+
1604
+
1605
+ @_dispatch
1606
+ def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
1607
+ plan=None):
1608
+ """
1609
+ Compute the 2-D inverse FFT of a real spectrum.
1610
+
1611
+ Parameters
1612
+ ----------
1613
+ x : array_like
1614
+ The input array
1615
+ s : sequence of ints, optional
1616
+ Shape of the real input to the inverse FFT.
1617
+ axes : sequence of ints, optional
1618
+ The axes over which to compute the inverse fft.
1619
+ Default is the last two axes.
1620
+ norm : {"backward", "ortho", "forward"}, optional
1621
+ Normalization mode (see `fft`). Default is "backward".
1622
+ overwrite_x : bool, optional
1623
+ If True, the contents of `x` can be destroyed; the default is False.
1624
+ See :func:`fft` for more details.
1625
+ workers : int, optional
1626
+ Maximum number of workers to use for parallel computation. If negative,
1627
+ the value wraps around from ``os.cpu_count()``.
1628
+ See :func:`~scipy.fft.fft` for more details.
1629
+ plan : object, optional
1630
+ This argument is reserved for passing in a precomputed plan provided
1631
+ by downstream FFT vendors. It is currently not used in SciPy.
1632
+
1633
+ .. versionadded:: 1.5.0
1634
+
1635
+ Returns
1636
+ -------
1637
+ out : ndarray
1638
+ The result of the inverse real 2-D FFT.
1639
+
1640
+ See Also
1641
+ --------
1642
+ ihfftn : Compute the inverse of the N-D FFT of Hermitian input.
1643
+
1644
+ Notes
1645
+ -----
1646
+ This is really `ihfftn` with different defaults.
1647
+ For more details see `ihfftn`.
1648
+
1649
+ """
1650
+ return (Dispatchable(x, np.ndarray),)
tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scipy._lib._array_api import (
2
+ array_namespace, is_numpy, xp_unsupported_param_msg, is_complex, xp_float_to_complex
3
+ )
4
+ from . import _pocketfft
5
+ import numpy as np
6
+
7
+
8
+ def _validate_fft_args(workers, plan, norm):
9
+ if workers is not None:
10
+ raise ValueError(xp_unsupported_param_msg("workers"))
11
+ if plan is not None:
12
+ raise ValueError(xp_unsupported_param_msg("plan"))
13
+ if norm is None:
14
+ norm = 'backward'
15
+ return norm
16
+
17
+
18
+ # these functions expect complex input in the fft standard extension
19
+ complex_funcs = {'fft', 'ifft', 'fftn', 'ifftn', 'hfft', 'irfft', 'irfftn'}
20
+
21
+ # pocketfft is used whenever SCIPY_ARRAY_API is not set,
22
+ # or x is a NumPy array or array-like.
23
+ # When SCIPY_ARRAY_API is set, we try to use xp.fft for CuPy arrays,
24
+ # PyTorch arrays and other array API standard supporting objects.
25
+ # If xp.fft does not exist, we attempt to convert to np and back to use pocketfft.
26
+
27
+ def _execute_1D(func_str, pocketfft_func, x, n, axis, norm, overwrite_x, workers, plan):
28
+ xp = array_namespace(x)
29
+
30
+ if is_numpy(xp):
31
+ x = np.asarray(x)
32
+ return pocketfft_func(x, n=n, axis=axis, norm=norm,
33
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
34
+
35
+ norm = _validate_fft_args(workers, plan, norm)
36
+ if hasattr(xp, 'fft'):
37
+ xp_func = getattr(xp.fft, func_str)
38
+ if func_str in complex_funcs:
39
+ try:
40
+ res = xp_func(x, n=n, axis=axis, norm=norm)
41
+ except: # backends may require complex input # noqa: E722
42
+ x = xp_float_to_complex(x, xp)
43
+ res = xp_func(x, n=n, axis=axis, norm=norm)
44
+ return res
45
+ return xp_func(x, n=n, axis=axis, norm=norm)
46
+
47
+ x = np.asarray(x)
48
+ y = pocketfft_func(x, n=n, axis=axis, norm=norm)
49
+ return xp.asarray(y)
50
+
51
+
52
+ def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan):
53
+ xp = array_namespace(x)
54
+
55
+ if is_numpy(xp):
56
+ x = np.asarray(x)
57
+ return pocketfft_func(x, s=s, axes=axes, norm=norm,
58
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
59
+
60
+ norm = _validate_fft_args(workers, plan, norm)
61
+ if hasattr(xp, 'fft'):
62
+ xp_func = getattr(xp.fft, func_str)
63
+ if func_str in complex_funcs:
64
+ try:
65
+ res = xp_func(x, s=s, axes=axes, norm=norm)
66
+ except: # backends may require complex input # noqa: E722
67
+ x = xp_float_to_complex(x, xp)
68
+ res = xp_func(x, s=s, axes=axes, norm=norm)
69
+ return res
70
+ return xp_func(x, s=s, axes=axes, norm=norm)
71
+
72
+ x = np.asarray(x)
73
+ y = pocketfft_func(x, s=s, axes=axes, norm=norm)
74
+ return xp.asarray(y)
75
+
76
+
77
+ def fft(x, n=None, axis=-1, norm=None,
78
+ overwrite_x=False, workers=None, *, plan=None):
79
+ return _execute_1D('fft', _pocketfft.fft, x, n=n, axis=axis, norm=norm,
80
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
81
+
82
+
83
+ def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
84
+ plan=None):
85
+ return _execute_1D('ifft', _pocketfft.ifft, x, n=n, axis=axis, norm=norm,
86
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
87
+
88
+
89
+ def rfft(x, n=None, axis=-1, norm=None,
90
+ overwrite_x=False, workers=None, *, plan=None):
91
+ return _execute_1D('rfft', _pocketfft.rfft, x, n=n, axis=axis, norm=norm,
92
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
93
+
94
+
95
+ def irfft(x, n=None, axis=-1, norm=None,
96
+ overwrite_x=False, workers=None, *, plan=None):
97
+ return _execute_1D('irfft', _pocketfft.irfft, x, n=n, axis=axis, norm=norm,
98
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
99
+
100
+
101
+ def hfft(x, n=None, axis=-1, norm=None,
102
+ overwrite_x=False, workers=None, *, plan=None):
103
+ return _execute_1D('hfft', _pocketfft.hfft, x, n=n, axis=axis, norm=norm,
104
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
105
+
106
+
107
+ def ihfft(x, n=None, axis=-1, norm=None,
108
+ overwrite_x=False, workers=None, *, plan=None):
109
+ return _execute_1D('ihfft', _pocketfft.ihfft, x, n=n, axis=axis, norm=norm,
110
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
111
+
112
+
113
+ def fftn(x, s=None, axes=None, norm=None,
114
+ overwrite_x=False, workers=None, *, plan=None):
115
+ return _execute_nD('fftn', _pocketfft.fftn, x, s=s, axes=axes, norm=norm,
116
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
117
+
118
+
119
+
120
+ def ifftn(x, s=None, axes=None, norm=None,
121
+ overwrite_x=False, workers=None, *, plan=None):
122
+ return _execute_nD('ifftn', _pocketfft.ifftn, x, s=s, axes=axes, norm=norm,
123
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
124
+
125
+
126
+ def fft2(x, s=None, axes=(-2, -1), norm=None,
127
+ overwrite_x=False, workers=None, *, plan=None):
128
+ return fftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
129
+
130
+
131
+ def ifft2(x, s=None, axes=(-2, -1), norm=None,
132
+ overwrite_x=False, workers=None, *, plan=None):
133
+ return ifftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
134
+
135
+
136
+ def rfftn(x, s=None, axes=None, norm=None,
137
+ overwrite_x=False, workers=None, *, plan=None):
138
+ return _execute_nD('rfftn', _pocketfft.rfftn, x, s=s, axes=axes, norm=norm,
139
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
140
+
141
+
142
+ def rfft2(x, s=None, axes=(-2, -1), norm=None,
143
+ overwrite_x=False, workers=None, *, plan=None):
144
+ return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
145
+
146
+
147
+ def irfftn(x, s=None, axes=None, norm=None,
148
+ overwrite_x=False, workers=None, *, plan=None):
149
+ return _execute_nD('irfftn', _pocketfft.irfftn, x, s=s, axes=axes, norm=norm,
150
+ overwrite_x=overwrite_x, workers=workers, plan=plan)
151
+
152
+
153
+ def irfft2(x, s=None, axes=(-2, -1), norm=None,
154
+ overwrite_x=False, workers=None, *, plan=None):
155
+ return irfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
156
+
157
+
158
+ def _swap_direction(norm):
159
+ if norm in (None, 'backward'):
160
+ norm = 'forward'
161
+ elif norm == 'forward':
162
+ norm = 'backward'
163
+ elif norm != 'ortho':
164
+ raise ValueError(f'Invalid norm value {norm}; should be "backward", '
165
+ '"ortho", or "forward".')
166
+ return norm
167
+
168
+
169
+ def hfftn(x, s=None, axes=None, norm=None,
170
+ overwrite_x=False, workers=None, *, plan=None):
171
+ xp = array_namespace(x)
172
+ if is_numpy(xp):
173
+ x = np.asarray(x)
174
+ return _pocketfft.hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
175
+ if is_complex(x, xp):
176
+ x = xp.conj(x)
177
+ return irfftn(x, s, axes, _swap_direction(norm),
178
+ overwrite_x, workers, plan=plan)
179
+
180
+
181
+ def hfft2(x, s=None, axes=(-2, -1), norm=None,
182
+ overwrite_x=False, workers=None, *, plan=None):
183
+ return hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
184
+
185
+
186
+ def ihfftn(x, s=None, axes=None, norm=None,
187
+ overwrite_x=False, workers=None, *, plan=None):
188
+ xp = array_namespace(x)
189
+ if is_numpy(xp):
190
+ x = np.asarray(x)
191
+ return _pocketfft.ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
192
+ return xp.conj(rfftn(x, s, axes, _swap_direction(norm),
193
+ overwrite_x, workers, plan=plan))
194
+
195
+ def ihfft2(x, s=None, axes=(-2, -1), norm=None,
196
+ overwrite_x=False, workers=None, *, plan=None):
197
+ return ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ class NumPyBackend:
4
+ """Backend that uses numpy.fft"""
5
+ __ua_domain__ = "numpy.scipy.fft"
6
+
7
+ @staticmethod
8
+ def __ua_function__(method, args, kwargs):
9
+ kwargs.pop("overwrite_x", None)
10
+
11
+ fn = getattr(np.fft, method.__name__, None)
12
+ return (NotImplemented if fn is None
13
+ else fn(*args, **kwargs))
14
+
15
+
16
+ class EchoBackend:
17
+ """Backend that just prints the __ua_function__ arguments"""
18
+ __ua_domain__ = "numpy.scipy.fft"
19
+
20
+ @staticmethod
21
+ def __ua_function__(method, args, kwargs):
22
+ print(method, args, kwargs, sep='\n')