Datasets:
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/__config__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/_distributor_init.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/version.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__init__.py +14 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py +606 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py +103 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py +225 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py +251 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py +254 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py +761 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py +357 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py +145 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py +105 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py +487 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py +369 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py +58 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py +86 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py +116 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py +1179 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py +1 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py +555 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py +183 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py +156 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py +23 -0
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/__config__.cpython-310.pyc
ADDED
|
Binary file (3.66 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (3.71 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/_distributor_init.cpython-310.pyc
ADDED
|
Binary file (854 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/__pycache__/version.cpython-310.pyc
ADDED
|
Binary file (508 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/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
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (581 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc
ADDED
|
Binary file (6.96 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc
ADDED
|
Binary file (7.06 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc
ADDED
|
Binary file (20.3 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc
ADDED
|
Binary file (4.09 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc
ADDED
|
Binary file (2.34 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc
ADDED
|
Binary file (39.4 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc
ADDED
|
Binary file (11.5 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc
ADDED
|
Binary file (8.68 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc
ADDED
|
Binary file (841 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 os
|
| 10 |
+
|
| 11 |
+
from types import ModuleType
|
| 12 |
+
from typing import Any, Literal, TypeAlias
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import numpy.typing as npt
|
| 16 |
+
|
| 17 |
+
from scipy._lib import array_api_compat
|
| 18 |
+
from scipy._lib.array_api_compat import (
|
| 19 |
+
is_array_api_obj,
|
| 20 |
+
size as xp_size,
|
| 21 |
+
numpy as np_compat,
|
| 22 |
+
device as xp_device,
|
| 23 |
+
is_numpy_namespace as is_numpy,
|
| 24 |
+
is_cupy_namespace as is_cupy,
|
| 25 |
+
is_torch_namespace as is_torch,
|
| 26 |
+
is_jax_namespace as is_jax,
|
| 27 |
+
is_array_api_strict_namespace as is_array_api_strict
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
'_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal',
|
| 32 |
+
'get_xp_devices',
|
| 33 |
+
'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch',
|
| 34 |
+
'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for',
|
| 35 |
+
'xp_assert_close', 'xp_assert_equal', 'xp_assert_less',
|
| 36 |
+
'xp_copy', 'xp_copysign', 'xp_device',
|
| 37 |
+
'xp_moveaxis_to_end', 'xp_ravel', 'xp_real', 'xp_sign', 'xp_size',
|
| 38 |
+
'xp_take_along_axis', 'xp_unsupported_param_msg', 'xp_vector_norm',
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# To enable array API and strict array-like input validation
|
| 43 |
+
SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False)
|
| 44 |
+
# To control the default device - for use in the test suite only
|
| 45 |
+
SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu")
|
| 46 |
+
|
| 47 |
+
_GLOBAL_CONFIG = {
|
| 48 |
+
"SCIPY_ARRAY_API": SCIPY_ARRAY_API,
|
| 49 |
+
"SCIPY_DEVICE": SCIPY_DEVICE,
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589)
|
| 54 |
+
ArrayLike: TypeAlias = Array | npt.ArrayLike
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _compliance_scipy(arrays):
|
| 58 |
+
"""Raise exceptions on known-bad subclasses.
|
| 59 |
+
|
| 60 |
+
The following subclasses are not supported and raise and error:
|
| 61 |
+
- `numpy.ma.MaskedArray`
|
| 62 |
+
- `numpy.matrix`
|
| 63 |
+
- NumPy arrays which do not have a boolean or numerical dtype
|
| 64 |
+
- Any array-like which is neither array API compatible nor coercible by NumPy
|
| 65 |
+
- Any array-like which is coerced by NumPy to an unsupported dtype
|
| 66 |
+
"""
|
| 67 |
+
for i in range(len(arrays)):
|
| 68 |
+
array = arrays[i]
|
| 69 |
+
|
| 70 |
+
from scipy.sparse import issparse
|
| 71 |
+
# this comes from `_util._asarray_validated`
|
| 72 |
+
if issparse(array):
|
| 73 |
+
msg = ('Sparse arrays/matrices are not supported by this function. '
|
| 74 |
+
'Perhaps one of the `scipy.sparse.linalg` functions '
|
| 75 |
+
'would work instead.')
|
| 76 |
+
raise ValueError(msg)
|
| 77 |
+
|
| 78 |
+
if isinstance(array, np.ma.MaskedArray):
|
| 79 |
+
raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.")
|
| 80 |
+
elif isinstance(array, np.matrix):
|
| 81 |
+
raise TypeError("Inputs of type `numpy.matrix` are not supported.")
|
| 82 |
+
if isinstance(array, np.ndarray | np.generic):
|
| 83 |
+
dtype = array.dtype
|
| 84 |
+
if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)):
|
| 85 |
+
raise TypeError(f"An argument has dtype `{dtype!r}`; "
|
| 86 |
+
f"only boolean and numerical dtypes are supported.")
|
| 87 |
+
elif not is_array_api_obj(array):
|
| 88 |
+
try:
|
| 89 |
+
array = np.asanyarray(array)
|
| 90 |
+
except TypeError:
|
| 91 |
+
raise TypeError("An argument is neither array API compatible nor "
|
| 92 |
+
"coercible by NumPy.")
|
| 93 |
+
dtype = array.dtype
|
| 94 |
+
if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)):
|
| 95 |
+
message = (
|
| 96 |
+
f"An argument was coerced to an unsupported dtype `{dtype!r}`; "
|
| 97 |
+
f"only boolean and numerical dtypes are supported."
|
| 98 |
+
)
|
| 99 |
+
raise TypeError(message)
|
| 100 |
+
arrays[i] = array
|
| 101 |
+
return arrays
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _check_finite(array: Array, xp: ModuleType) -> None:
|
| 105 |
+
"""Check for NaNs or Infs."""
|
| 106 |
+
msg = "array must not contain infs or NaNs"
|
| 107 |
+
try:
|
| 108 |
+
if not xp.all(xp.isfinite(array)):
|
| 109 |
+
raise ValueError(msg)
|
| 110 |
+
except TypeError:
|
| 111 |
+
raise ValueError(msg)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def array_namespace(*arrays: Array) -> ModuleType:
|
| 115 |
+
"""Get the array API compatible namespace for the arrays xs.
|
| 116 |
+
|
| 117 |
+
Parameters
|
| 118 |
+
----------
|
| 119 |
+
*arrays : sequence of array_like
|
| 120 |
+
Arrays used to infer the common namespace.
|
| 121 |
+
|
| 122 |
+
Returns
|
| 123 |
+
-------
|
| 124 |
+
namespace : module
|
| 125 |
+
Common namespace.
|
| 126 |
+
|
| 127 |
+
Notes
|
| 128 |
+
-----
|
| 129 |
+
Thin wrapper around `array_api_compat.array_namespace`.
|
| 130 |
+
|
| 131 |
+
1. Check for the global switch: SCIPY_ARRAY_API. This can also be accessed
|
| 132 |
+
dynamically through ``_GLOBAL_CONFIG['SCIPY_ARRAY_API']``.
|
| 133 |
+
2. `_compliance_scipy` raise exceptions on known-bad subclasses. See
|
| 134 |
+
its definition for more details.
|
| 135 |
+
|
| 136 |
+
When the global switch is False, it defaults to the `numpy` namespace.
|
| 137 |
+
In that case, there is no compliance check. This is a convenience to
|
| 138 |
+
ease the adoption. Otherwise, arrays must comply with the new rules.
|
| 139 |
+
"""
|
| 140 |
+
if not _GLOBAL_CONFIG["SCIPY_ARRAY_API"]:
|
| 141 |
+
# here we could wrap the namespace if needed
|
| 142 |
+
return np_compat
|
| 143 |
+
|
| 144 |
+
_arrays = [array for array in arrays if array is not None]
|
| 145 |
+
|
| 146 |
+
_arrays = _compliance_scipy(_arrays)
|
| 147 |
+
|
| 148 |
+
return array_api_compat.array_namespace(*_arrays)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _asarray(
|
| 152 |
+
array: ArrayLike,
|
| 153 |
+
dtype: Any = None,
|
| 154 |
+
order: Literal['K', 'A', 'C', 'F'] | None = None,
|
| 155 |
+
copy: bool | None = None,
|
| 156 |
+
*,
|
| 157 |
+
xp: ModuleType | None = None,
|
| 158 |
+
check_finite: bool = False,
|
| 159 |
+
subok: bool = False,
|
| 160 |
+
) -> Array:
|
| 161 |
+
"""SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and
|
| 162 |
+
`subok`.
|
| 163 |
+
|
| 164 |
+
Memory layout parameter `order` is not exposed in the Array API standard.
|
| 165 |
+
`order` is only enforced if the input array implementation
|
| 166 |
+
is NumPy based, otherwise `order` is just silently ignored.
|
| 167 |
+
|
| 168 |
+
`check_finite` is also not a keyword in the array API standard; included
|
| 169 |
+
here for convenience rather than that having to be a separate function
|
| 170 |
+
call inside SciPy functions.
|
| 171 |
+
|
| 172 |
+
`subok` is included to allow this function to preserve the behaviour of
|
| 173 |
+
`np.asanyarray` for NumPy based inputs.
|
| 174 |
+
"""
|
| 175 |
+
if xp is None:
|
| 176 |
+
xp = array_namespace(array)
|
| 177 |
+
if is_numpy(xp):
|
| 178 |
+
# Use NumPy API to support order
|
| 179 |
+
if copy is True:
|
| 180 |
+
array = np.array(array, order=order, dtype=dtype, subok=subok)
|
| 181 |
+
elif subok:
|
| 182 |
+
array = np.asanyarray(array, order=order, dtype=dtype)
|
| 183 |
+
else:
|
| 184 |
+
array = np.asarray(array, order=order, dtype=dtype)
|
| 185 |
+
else:
|
| 186 |
+
try:
|
| 187 |
+
array = xp.asarray(array, dtype=dtype, copy=copy)
|
| 188 |
+
except TypeError:
|
| 189 |
+
coerced_xp = array_namespace(xp.asarray(3))
|
| 190 |
+
array = coerced_xp.asarray(array, dtype=dtype, copy=copy)
|
| 191 |
+
|
| 192 |
+
if check_finite:
|
| 193 |
+
_check_finite(array, xp)
|
| 194 |
+
|
| 195 |
+
return array
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array:
|
| 199 |
+
"""
|
| 200 |
+
Copies an array.
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
----------
|
| 204 |
+
x : array
|
| 205 |
+
|
| 206 |
+
xp : array_namespace
|
| 207 |
+
|
| 208 |
+
Returns
|
| 209 |
+
-------
|
| 210 |
+
copy : array
|
| 211 |
+
Copied array
|
| 212 |
+
|
| 213 |
+
Notes
|
| 214 |
+
-----
|
| 215 |
+
This copy function does not offer all the semantics of `np.copy`, i.e. the
|
| 216 |
+
`subok` and `order` keywords are not used.
|
| 217 |
+
"""
|
| 218 |
+
# Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg,
|
| 219 |
+
# so this uses our other helper `_asarray`.
|
| 220 |
+
if xp is None:
|
| 221 |
+
xp = array_namespace(x)
|
| 222 |
+
|
| 223 |
+
return _asarray(x, copy=True, xp=xp)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _strict_check(actual, desired, xp, *,
|
| 227 |
+
check_namespace=True, check_dtype=True, check_shape=True,
|
| 228 |
+
check_0d=True):
|
| 229 |
+
__tracebackhide__ = True # Hide traceback for py.test
|
| 230 |
+
if check_namespace:
|
| 231 |
+
_assert_matching_namespace(actual, desired)
|
| 232 |
+
|
| 233 |
+
# only NumPy distinguishes between scalars and arrays; we do if check_0d=True.
|
| 234 |
+
# do this first so we can then cast to array (and thus use the array API) below.
|
| 235 |
+
if is_numpy(xp) and check_0d:
|
| 236 |
+
_msg = ("Array-ness does not match:\n Actual: "
|
| 237 |
+
f"{type(actual)}\n Desired: {type(desired)}")
|
| 238 |
+
assert ((xp.isscalar(actual) and xp.isscalar(desired))
|
| 239 |
+
or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg
|
| 240 |
+
|
| 241 |
+
actual = xp.asarray(actual)
|
| 242 |
+
desired = xp.asarray(desired)
|
| 243 |
+
|
| 244 |
+
if check_dtype:
|
| 245 |
+
_msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}"
|
| 246 |
+
assert actual.dtype == desired.dtype, _msg
|
| 247 |
+
|
| 248 |
+
if check_shape:
|
| 249 |
+
_msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}"
|
| 250 |
+
assert actual.shape == desired.shape, _msg
|
| 251 |
+
|
| 252 |
+
desired = xp.broadcast_to(desired, actual.shape)
|
| 253 |
+
return actual, desired
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def _assert_matching_namespace(actual, desired):
|
| 257 |
+
__tracebackhide__ = True # Hide traceback for py.test
|
| 258 |
+
actual = actual if isinstance(actual, tuple) else (actual,)
|
| 259 |
+
desired_space = array_namespace(desired)
|
| 260 |
+
for arr in actual:
|
| 261 |
+
arr_space = array_namespace(arr)
|
| 262 |
+
_msg = (f"Namespaces do not match.\n"
|
| 263 |
+
f"Actual: {arr_space.__name__}\n"
|
| 264 |
+
f"Desired: {desired_space.__name__}")
|
| 265 |
+
assert arr_space == desired_space, _msg
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True,
|
| 269 |
+
check_shape=True, check_0d=True, err_msg='', xp=None):
|
| 270 |
+
__tracebackhide__ = True # Hide traceback for py.test
|
| 271 |
+
if xp is None:
|
| 272 |
+
xp = array_namespace(actual)
|
| 273 |
+
|
| 274 |
+
actual, desired = _strict_check(
|
| 275 |
+
actual, desired, xp, check_namespace=check_namespace,
|
| 276 |
+
check_dtype=check_dtype, check_shape=check_shape,
|
| 277 |
+
check_0d=check_0d
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if is_cupy(xp):
|
| 281 |
+
return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg)
|
| 282 |
+
elif is_torch(xp):
|
| 283 |
+
# PyTorch recommends using `rtol=0, atol=0` like this
|
| 284 |
+
# to test for exact equality
|
| 285 |
+
err_msg = None if err_msg == '' else err_msg
|
| 286 |
+
return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True,
|
| 287 |
+
check_dtype=False, msg=err_msg)
|
| 288 |
+
# JAX uses `np.testing`
|
| 289 |
+
return np.testing.assert_array_equal(actual, desired, err_msg=err_msg)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True,
|
| 293 |
+
check_dtype=True, check_shape=True, check_0d=True,
|
| 294 |
+
err_msg='', xp=None):
|
| 295 |
+
__tracebackhide__ = True # Hide traceback for py.test
|
| 296 |
+
if xp is None:
|
| 297 |
+
xp = array_namespace(actual)
|
| 298 |
+
|
| 299 |
+
actual, desired = _strict_check(
|
| 300 |
+
actual, desired, xp,
|
| 301 |
+
check_namespace=check_namespace, check_dtype=check_dtype,
|
| 302 |
+
check_shape=check_shape, check_0d=check_0d
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating'))
|
| 306 |
+
if rtol is None and floating:
|
| 307 |
+
# multiplier of 4 is used as for `np.float64` this puts the default `rtol`
|
| 308 |
+
# roughly half way between sqrt(eps) and the default for
|
| 309 |
+
# `numpy.testing.assert_allclose`, 1e-7
|
| 310 |
+
rtol = xp.finfo(actual.dtype).eps**0.5 * 4
|
| 311 |
+
elif rtol is None:
|
| 312 |
+
rtol = 1e-7
|
| 313 |
+
|
| 314 |
+
if is_cupy(xp):
|
| 315 |
+
return xp.testing.assert_allclose(actual, desired, rtol=rtol,
|
| 316 |
+
atol=atol, err_msg=err_msg)
|
| 317 |
+
elif is_torch(xp):
|
| 318 |
+
err_msg = None if err_msg == '' else err_msg
|
| 319 |
+
return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol,
|
| 320 |
+
equal_nan=True, check_dtype=False, msg=err_msg)
|
| 321 |
+
# JAX uses `np.testing`
|
| 322 |
+
return np.testing.assert_allclose(actual, desired, rtol=rtol,
|
| 323 |
+
atol=atol, err_msg=err_msg)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True,
|
| 327 |
+
check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None):
|
| 328 |
+
__tracebackhide__ = True # Hide traceback for py.test
|
| 329 |
+
if xp is None:
|
| 330 |
+
xp = array_namespace(actual)
|
| 331 |
+
|
| 332 |
+
actual, desired = _strict_check(
|
| 333 |
+
actual, desired, xp, check_namespace=check_namespace,
|
| 334 |
+
check_dtype=check_dtype, check_shape=check_shape,
|
| 335 |
+
check_0d=check_0d
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
if is_cupy(xp):
|
| 339 |
+
return xp.testing.assert_array_less(actual, desired,
|
| 340 |
+
err_msg=err_msg, verbose=verbose)
|
| 341 |
+
elif is_torch(xp):
|
| 342 |
+
if actual.device.type != 'cpu':
|
| 343 |
+
actual = actual.cpu()
|
| 344 |
+
if desired.device.type != 'cpu':
|
| 345 |
+
desired = desired.cpu()
|
| 346 |
+
# JAX uses `np.testing`
|
| 347 |
+
return np.testing.assert_array_less(actual, desired,
|
| 348 |
+
err_msg=err_msg, verbose=verbose)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
|
| 352 |
+
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
|
| 353 |
+
"""
|
| 354 |
+
rtol, atol = 0, 1.5*10**(-decimal)
|
| 355 |
+
return xp_assert_close(actual, desired,
|
| 356 |
+
atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
|
| 357 |
+
*args, **kwds)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
|
| 361 |
+
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
|
| 362 |
+
"""
|
| 363 |
+
rtol, atol = 0, 1.5*10**(-decimal)
|
| 364 |
+
return xp_assert_close(actual, desired,
|
| 365 |
+
atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
|
| 366 |
+
*args, **kwds)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def xp_unsupported_param_msg(param: Any) -> str:
|
| 370 |
+
return f'Providing {param!r} is only supported for numpy arrays.'
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def is_complex(x: Array, xp: ModuleType) -> bool:
|
| 374 |
+
return xp.isdtype(x.dtype, 'complex floating')
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def get_xp_devices(xp: ModuleType) -> list[str] | list[None]:
|
| 378 |
+
"""Returns a list of available devices for the given namespace."""
|
| 379 |
+
devices: list[str] = []
|
| 380 |
+
if is_torch(xp):
|
| 381 |
+
devices += ['cpu']
|
| 382 |
+
import torch # type: ignore[import]
|
| 383 |
+
num_cuda = torch.cuda.device_count()
|
| 384 |
+
for i in range(0, num_cuda):
|
| 385 |
+
devices += [f'cuda:{i}']
|
| 386 |
+
if torch.backends.mps.is_available():
|
| 387 |
+
devices += ['mps']
|
| 388 |
+
return devices
|
| 389 |
+
elif is_cupy(xp):
|
| 390 |
+
import cupy # type: ignore[import]
|
| 391 |
+
num_cuda = cupy.cuda.runtime.getDeviceCount()
|
| 392 |
+
for i in range(0, num_cuda):
|
| 393 |
+
devices += [f'cuda:{i}']
|
| 394 |
+
return devices
|
| 395 |
+
elif is_jax(xp):
|
| 396 |
+
import jax # type: ignore[import]
|
| 397 |
+
num_cpu = jax.device_count(backend='cpu')
|
| 398 |
+
for i in range(0, num_cpu):
|
| 399 |
+
devices += [f'cpu:{i}']
|
| 400 |
+
num_gpu = jax.device_count(backend='gpu')
|
| 401 |
+
for i in range(0, num_gpu):
|
| 402 |
+
devices += [f'gpu:{i}']
|
| 403 |
+
num_tpu = jax.device_count(backend='tpu')
|
| 404 |
+
for i in range(0, num_tpu):
|
| 405 |
+
devices += [f'tpu:{i}']
|
| 406 |
+
return devices
|
| 407 |
+
|
| 408 |
+
# given namespace is not known to have a list of available devices;
|
| 409 |
+
# return `[None]` so that one can use this in tests for `device=None`.
|
| 410 |
+
return [None]
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def scipy_namespace_for(xp: ModuleType) -> ModuleType | None:
|
| 414 |
+
"""Return the `scipy`-like namespace of a non-NumPy backend
|
| 415 |
+
|
| 416 |
+
That is, return the namespace corresponding with backend `xp` that contains
|
| 417 |
+
`scipy` sub-namespaces like `linalg` and `special`. If no such namespace
|
| 418 |
+
exists, return ``None``. Useful for dispatching.
|
| 419 |
+
"""
|
| 420 |
+
|
| 421 |
+
if is_cupy(xp):
|
| 422 |
+
import cupyx # type: ignore[import-not-found,import-untyped]
|
| 423 |
+
return cupyx.scipy
|
| 424 |
+
|
| 425 |
+
if is_jax(xp):
|
| 426 |
+
import jax # type: ignore[import-not-found]
|
| 427 |
+
return jax.scipy
|
| 428 |
+
|
| 429 |
+
if is_torch(xp):
|
| 430 |
+
return xp
|
| 431 |
+
|
| 432 |
+
return None
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
# temporary substitute for xp.moveaxis, which is not yet in all backends
|
| 436 |
+
# or covered by array_api_compat.
|
| 437 |
+
def xp_moveaxis_to_end(
|
| 438 |
+
x: Array,
|
| 439 |
+
source: int,
|
| 440 |
+
/, *,
|
| 441 |
+
xp: ModuleType | None = None) -> Array:
|
| 442 |
+
xp = array_namespace(xp) if xp is None else xp
|
| 443 |
+
axes = list(range(x.ndim))
|
| 444 |
+
temp = axes.pop(source)
|
| 445 |
+
axes = axes + [temp]
|
| 446 |
+
return xp.permute_dims(x, axes)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
# temporary substitute for xp.copysign, which is not yet in all backends
|
| 450 |
+
# or covered by array_api_compat.
|
| 451 |
+
def xp_copysign(x1: Array, x2: Array, /, *, xp: ModuleType | None = None) -> Array:
|
| 452 |
+
# no attempt to account for special cases
|
| 453 |
+
xp = array_namespace(x1, x2) if xp is None else xp
|
| 454 |
+
abs_x1 = xp.abs(x1)
|
| 455 |
+
return xp.where(x2 >= 0, abs_x1, -abs_x1)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
# partial substitute for xp.sign, which does not cover the NaN special case
|
| 459 |
+
# that I need. (https://github.com/data-apis/array-api-compat/issues/136)
|
| 460 |
+
def xp_sign(x: Array, /, *, xp: ModuleType | None = None) -> Array:
|
| 461 |
+
xp = array_namespace(x) if xp is None else xp
|
| 462 |
+
if is_numpy(xp): # only NumPy implements the special cases correctly
|
| 463 |
+
return xp.sign(x)
|
| 464 |
+
sign = xp.zeros_like(x)
|
| 465 |
+
one = xp.asarray(1, dtype=x.dtype)
|
| 466 |
+
sign = xp.where(x > 0, one, sign)
|
| 467 |
+
sign = xp.where(x < 0, -one, sign)
|
| 468 |
+
sign = xp.where(xp.isnan(x), xp.nan*one, sign)
|
| 469 |
+
return sign
|
| 470 |
+
|
| 471 |
+
# maybe use `scipy.linalg` if/when array API support is added
|
| 472 |
+
def xp_vector_norm(x: Array, /, *,
|
| 473 |
+
axis: int | tuple[int] | None = None,
|
| 474 |
+
keepdims: bool = False,
|
| 475 |
+
ord: int | float = 2,
|
| 476 |
+
xp: ModuleType | None = None) -> Array:
|
| 477 |
+
xp = array_namespace(x) if xp is None else xp
|
| 478 |
+
|
| 479 |
+
if SCIPY_ARRAY_API:
|
| 480 |
+
# check for optional `linalg` extension
|
| 481 |
+
if hasattr(xp, 'linalg'):
|
| 482 |
+
return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord)
|
| 483 |
+
else:
|
| 484 |
+
if ord != 2:
|
| 485 |
+
raise ValueError(
|
| 486 |
+
"only the Euclidean norm (`ord=2`) is currently supported in "
|
| 487 |
+
"`xp_vector_norm` for backends not implementing the `linalg` "
|
| 488 |
+
"extension."
|
| 489 |
+
)
|
| 490 |
+
# return (x @ x)**0.5
|
| 491 |
+
# or to get the right behavior with nd, complex arrays
|
| 492 |
+
return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5
|
| 493 |
+
else:
|
| 494 |
+
# to maintain backwards compatibility
|
| 495 |
+
return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array:
|
| 499 |
+
# Equivalent of np.ravel written in terms of array API
|
| 500 |
+
# Even though it's one line, it comes up so often that it's worth having
|
| 501 |
+
# this function for readability
|
| 502 |
+
xp = array_namespace(x) if xp is None else xp
|
| 503 |
+
return xp.reshape(x, (-1,))
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def xp_real(x: Array, /, *, xp: ModuleType | None = None) -> Array:
|
| 507 |
+
# Convenience wrapper of xp.real that allows non-complex input;
|
| 508 |
+
# see data-apis/array-api#824
|
| 509 |
+
xp = array_namespace(x) if xp is None else xp
|
| 510 |
+
return xp.real(x) if xp.isdtype(x.dtype, 'complex floating') else x
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def xp_take_along_axis(arr: Array,
|
| 514 |
+
indices: Array, /, *,
|
| 515 |
+
axis: int = -1,
|
| 516 |
+
xp: ModuleType | None = None) -> Array:
|
| 517 |
+
# Dispatcher for np.take_along_axis for backends that support it;
|
| 518 |
+
# see data-apis/array-api/pull#816
|
| 519 |
+
xp = array_namespace(arr) if xp is None else xp
|
| 520 |
+
if is_torch(xp):
|
| 521 |
+
return xp.take_along_dim(arr, indices, dim=axis)
|
| 522 |
+
elif is_array_api_strict(xp):
|
| 523 |
+
raise NotImplementedError("Array API standard does not define take_along_axis")
|
| 524 |
+
else:
|
| 525 |
+
return xp.take_along_axis(arr, indices, axis)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
# utility to broadcast arrays and promote to common dtype
|
| 529 |
+
def xp_broadcast_promote(*args, ensure_writeable=False, force_floating=False, xp=None):
|
| 530 |
+
xp = array_namespace(*args) if xp is None else xp
|
| 531 |
+
|
| 532 |
+
args = [(_asarray(arg, subok=True) if arg is not None else arg) for arg in args]
|
| 533 |
+
args_not_none = [arg for arg in args if arg is not None]
|
| 534 |
+
|
| 535 |
+
# determine minimum dtype
|
| 536 |
+
default_float = xp.asarray(1.).dtype
|
| 537 |
+
dtypes = [arg.dtype for arg in args_not_none]
|
| 538 |
+
try: # follow library's prefered mixed promotion rules
|
| 539 |
+
dtype = xp.result_type(*dtypes)
|
| 540 |
+
if force_floating and xp.isdtype(dtype, 'integral'):
|
| 541 |
+
# If we were to add `default_float` before checking whether the result
|
| 542 |
+
# type is otherwise integral, we risk promotion from lower float.
|
| 543 |
+
dtype = xp.result_type(dtype, default_float)
|
| 544 |
+
except TypeError: # mixed type promotion isn't defined
|
| 545 |
+
float_dtypes = [dtype for dtype in dtypes
|
| 546 |
+
if not xp.isdtype(dtype, 'integral')]
|
| 547 |
+
if float_dtypes:
|
| 548 |
+
dtype = xp.result_type(*float_dtypes, default_float)
|
| 549 |
+
elif force_floating:
|
| 550 |
+
dtype = default_float
|
| 551 |
+
else:
|
| 552 |
+
dtype = xp.result_type(*dtypes)
|
| 553 |
+
|
| 554 |
+
# determine result shape
|
| 555 |
+
shapes = {arg.shape for arg in args_not_none}
|
| 556 |
+
try:
|
| 557 |
+
shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1
|
| 558 |
+
else args_not_none[0].shape)
|
| 559 |
+
except ValueError as e:
|
| 560 |
+
message = "Array shapes are incompatible for broadcasting."
|
| 561 |
+
raise ValueError(message) from e
|
| 562 |
+
|
| 563 |
+
out = []
|
| 564 |
+
for arg in args:
|
| 565 |
+
if arg is None:
|
| 566 |
+
out.append(arg)
|
| 567 |
+
continue
|
| 568 |
+
|
| 569 |
+
# broadcast only if needed
|
| 570 |
+
# Even if two arguments need broadcasting, this is faster than
|
| 571 |
+
# `broadcast_arrays`, especially since we've already determined `shape`
|
| 572 |
+
if arg.shape != shape:
|
| 573 |
+
kwargs = {'subok': True} if is_numpy(xp) else {}
|
| 574 |
+
arg = xp.broadcast_to(arg, shape, **kwargs)
|
| 575 |
+
|
| 576 |
+
# convert dtype/copy only if needed
|
| 577 |
+
if (arg.dtype != dtype) or ensure_writeable:
|
| 578 |
+
arg = xp.astype(arg, dtype, copy=True)
|
| 579 |
+
out.append(arg)
|
| 580 |
+
|
| 581 |
+
return out
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array:
|
| 585 |
+
xp = array_namespace(arr) if xp is None else xp
|
| 586 |
+
arr_dtype = arr.dtype
|
| 587 |
+
# The standard float dtypes are float32 and float64.
|
| 588 |
+
# Convert float32 to complex64,
|
| 589 |
+
# and float64 (and non-standard real dtypes) to complex128
|
| 590 |
+
if xp.isdtype(arr_dtype, xp.float32):
|
| 591 |
+
arr = xp.astype(arr, xp.complex64)
|
| 592 |
+
elif xp.isdtype(arr_dtype, 'real floating'):
|
| 593 |
+
arr = xp.astype(arr, xp.complex128)
|
| 594 |
+
|
| 595 |
+
return arr
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def xp_default_dtype(xp):
|
| 599 |
+
"""Query the namespace-dependent default floating-point dtype.
|
| 600 |
+
"""
|
| 601 |
+
if is_torch(xp):
|
| 602 |
+
# historically, we allow pytorch to keep its default of float32
|
| 603 |
+
return xp.get_default_dtype()
|
| 604 |
+
else:
|
| 605 |
+
# we default to float64
|
| 606 |
+
return xp.float64
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/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)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
}
|
| 198 |
+
for index, name in enumerate(field_names):
|
| 199 |
+
|
| 200 |
+
def _get(self, index=index):
|
| 201 |
+
return self[index]
|
| 202 |
+
class_namespace[name] = property(_get)
|
| 203 |
+
for name in extra_field_names:
|
| 204 |
+
|
| 205 |
+
def _get(self, name=name):
|
| 206 |
+
return self.__dict__[name]
|
| 207 |
+
class_namespace[name] = property(_get)
|
| 208 |
+
|
| 209 |
+
result = type(typename, (tuple,), class_namespace)
|
| 210 |
+
|
| 211 |
+
# For pickling to work, the __module__ variable needs to be set to the
|
| 212 |
+
# frame where the named tuple is created. Bypass this step in environments
|
| 213 |
+
# where sys._getframe is not defined (Jython for example) or sys._getframe
|
| 214 |
+
# is not defined for arguments greater than 0 (IronPython), or where the
|
| 215 |
+
# user has specified a particular module.
|
| 216 |
+
if module is None:
|
| 217 |
+
try:
|
| 218 |
+
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
|
| 219 |
+
except (AttributeError, ValueError):
|
| 220 |
+
pass
|
| 221 |
+
if module is not None:
|
| 222 |
+
result.__module__ = module
|
| 223 |
+
__new__.__module__ = module
|
| 224 |
+
|
| 225 |
+
return result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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 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
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py
ADDED
|
@@ -0,0 +1,761 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 19 |
+
|
| 20 |
+
_ESIGNERR = -1
|
| 21 |
+
_ECONVERR = -2
|
| 22 |
+
_EVALUEERR = -3
|
| 23 |
+
_ECALLBACK = -4
|
| 24 |
+
_EINPUTERR = -5
|
| 25 |
+
_ECONVERGED = 0
|
| 26 |
+
_EINPROGRESS = 1
|
| 27 |
+
|
| 28 |
+
def _initialize(func, xs, args, complex_ok=False, preserve_shape=None, xp=None):
|
| 29 |
+
"""Initialize abscissa, function, and args arrays for elementwise function
|
| 30 |
+
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
func : callable
|
| 34 |
+
An elementwise function with signature
|
| 35 |
+
|
| 36 |
+
func(x: ndarray, *args) -> ndarray
|
| 37 |
+
|
| 38 |
+
where each element of ``x`` is a finite real and ``args`` is a tuple,
|
| 39 |
+
which may contain an arbitrary number of arrays that are broadcastable
|
| 40 |
+
with ``x``.
|
| 41 |
+
xs : tuple of arrays
|
| 42 |
+
Finite real abscissa arrays. Must be broadcastable.
|
| 43 |
+
args : tuple, optional
|
| 44 |
+
Additional positional arguments to be passed to `func`.
|
| 45 |
+
preserve_shape : bool, default:False
|
| 46 |
+
When ``preserve_shape=False`` (default), `func` may be passed
|
| 47 |
+
arguments of any shape; `_scalar_optimization_loop` is permitted
|
| 48 |
+
to reshape and compress arguments at will. When
|
| 49 |
+
``preserve_shape=False``, arguments passed to `func` must have shape
|
| 50 |
+
`shape` or ``shape + (n,)``, where ``n`` is any integer.
|
| 51 |
+
xp : namespace
|
| 52 |
+
Namespace of array arguments in `xs`.
|
| 53 |
+
|
| 54 |
+
Returns
|
| 55 |
+
-------
|
| 56 |
+
xs, fs, args : tuple of arrays
|
| 57 |
+
Broadcasted, writeable, 1D abscissa and function value arrays (or
|
| 58 |
+
NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are
|
| 59 |
+
`xfat`; the dtype of the `args` are unchanged.
|
| 60 |
+
shape : tuple of ints
|
| 61 |
+
Original shape of broadcasted arrays.
|
| 62 |
+
xfat : NumPy dtype
|
| 63 |
+
Result dtype of abscissae, function values, and args determined using
|
| 64 |
+
`np.result_type`, except integer types are promoted to `np.float64`.
|
| 65 |
+
|
| 66 |
+
Raises
|
| 67 |
+
------
|
| 68 |
+
ValueError
|
| 69 |
+
If the result dtype is not that of a real scalar
|
| 70 |
+
|
| 71 |
+
Notes
|
| 72 |
+
-----
|
| 73 |
+
Useful for initializing the input of SciPy functions that accept
|
| 74 |
+
an elementwise callable, abscissae, and arguments; e.g.
|
| 75 |
+
`scipy.optimize._chandrupatla`.
|
| 76 |
+
"""
|
| 77 |
+
nx = len(xs)
|
| 78 |
+
xp = array_namespace(*xs) if xp is None else xp
|
| 79 |
+
|
| 80 |
+
# Try to preserve `dtype`, but we need to ensure that the arguments are at
|
| 81 |
+
# least floats before passing them into the function; integers can overflow
|
| 82 |
+
# and cause failure.
|
| 83 |
+
# There might be benefit to combining the `xs` into a single array and
|
| 84 |
+
# calling `func` once on the combined array. For now, keep them separate.
|
| 85 |
+
xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename
|
| 86 |
+
xat = xp.result_type(*[xa.dtype for xa in xas])
|
| 87 |
+
xat = xp.asarray(1.).dtype if xp.isdtype(xat, "integral") else xat
|
| 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[:] = _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 |
+
# Need to find a better way than these try/excepts
|
| 294 |
+
# Somehow need to keep compressible numerical args separate
|
| 295 |
+
if key == 'args':
|
| 296 |
+
continue
|
| 297 |
+
try:
|
| 298 |
+
work[key] = val[proceed]
|
| 299 |
+
except (IndexError, TypeError, KeyError): # not a compressible array
|
| 300 |
+
work[key] = val
|
| 301 |
+
work.args = [arg[proceed] for arg in work.args]
|
| 302 |
+
|
| 303 |
+
return active
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp):
|
| 307 |
+
# Update `active` indices of the arrays in result object `res` with the
|
| 308 |
+
# contents of the scalars and arrays in `update_dict`. When provided,
|
| 309 |
+
# `mask` is a boolean array applied both to the arrays in `update_dict`
|
| 310 |
+
# that are to be used and to the arrays in `res` that are to be updated.
|
| 311 |
+
update_dict = {key1: work[key2] for key1, key2 in res_work_pairs}
|
| 312 |
+
update_dict['success'] = work.status == 0
|
| 313 |
+
|
| 314 |
+
if mask is not None:
|
| 315 |
+
if preserve_shape:
|
| 316 |
+
active_mask = xp.zeros_like(mask)
|
| 317 |
+
active_mask[active] = 1
|
| 318 |
+
active_mask = active_mask & mask
|
| 319 |
+
for key, val in update_dict.items():
|
| 320 |
+
try:
|
| 321 |
+
res[key][active_mask] = val[active_mask]
|
| 322 |
+
except (IndexError, TypeError, KeyError):
|
| 323 |
+
res[key][active_mask] = val
|
| 324 |
+
else:
|
| 325 |
+
active_mask = active[mask]
|
| 326 |
+
for key, val in update_dict.items():
|
| 327 |
+
try:
|
| 328 |
+
res[key][active_mask] = val[mask]
|
| 329 |
+
except (IndexError, TypeError, KeyError):
|
| 330 |
+
res[key][active_mask] = val
|
| 331 |
+
else:
|
| 332 |
+
for key, val in update_dict.items():
|
| 333 |
+
if preserve_shape:
|
| 334 |
+
try:
|
| 335 |
+
val = val[active]
|
| 336 |
+
except (IndexError, TypeError, KeyError):
|
| 337 |
+
pass
|
| 338 |
+
res[key][active] = val
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _prepare_result(work, res, res_work_pairs, active, shape, customize_result,
|
| 342 |
+
preserve_shape, xp):
|
| 343 |
+
# Prepare the result object `res` by creating a copy, copying the latest
|
| 344 |
+
# data from work, running the provided result customization function,
|
| 345 |
+
# and reshaping the data to the original shapes.
|
| 346 |
+
res = res.copy()
|
| 347 |
+
_update_active(work, res, res_work_pairs, active, None, preserve_shape, xp)
|
| 348 |
+
|
| 349 |
+
shape = customize_result(res, shape)
|
| 350 |
+
|
| 351 |
+
for key, val in res.items():
|
| 352 |
+
# this looks like it won't work for xp != np if val is not numeric
|
| 353 |
+
temp = xp.reshape(val, shape)
|
| 354 |
+
res[key] = temp[()] if temp.ndim == 0 else temp
|
| 355 |
+
|
| 356 |
+
res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs]
|
| 357 |
+
return _RichResult(**res)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy import arange, newaxis, hstack, prod, array
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _central_diff_weights(Np, ndiv=1):
|
| 5 |
+
"""
|
| 6 |
+
Return weights for an Np-point central derivative.
|
| 7 |
+
|
| 8 |
+
Assumes equally-spaced function points.
|
| 9 |
+
|
| 10 |
+
If weights are in the vector w, then
|
| 11 |
+
derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx)
|
| 12 |
+
|
| 13 |
+
Parameters
|
| 14 |
+
----------
|
| 15 |
+
Np : int
|
| 16 |
+
Number of points for the central derivative.
|
| 17 |
+
ndiv : int, optional
|
| 18 |
+
Number of divisions. Default is 1.
|
| 19 |
+
|
| 20 |
+
Returns
|
| 21 |
+
-------
|
| 22 |
+
w : ndarray
|
| 23 |
+
Weights for an Np-point central derivative. Its size is `Np`.
|
| 24 |
+
|
| 25 |
+
Notes
|
| 26 |
+
-----
|
| 27 |
+
Can be inaccurate for a large number of points.
|
| 28 |
+
|
| 29 |
+
Examples
|
| 30 |
+
--------
|
| 31 |
+
We can calculate a derivative value of a function.
|
| 32 |
+
|
| 33 |
+
>>> def f(x):
|
| 34 |
+
... return 2 * x**2 + 3
|
| 35 |
+
>>> x = 3.0 # derivative point
|
| 36 |
+
>>> h = 0.1 # differential step
|
| 37 |
+
>>> Np = 3 # point number for central derivative
|
| 38 |
+
>>> weights = _central_diff_weights(Np) # weights for first derivative
|
| 39 |
+
>>> vals = [f(x + (i - Np/2) * h) for i in range(Np)]
|
| 40 |
+
>>> sum(w * v for (w, v) in zip(weights, vals))/h
|
| 41 |
+
11.79999999999998
|
| 42 |
+
|
| 43 |
+
This value is close to the analytical solution:
|
| 44 |
+
f'(x) = 4x, so f'(3) = 12
|
| 45 |
+
|
| 46 |
+
References
|
| 47 |
+
----------
|
| 48 |
+
.. [1] https://en.wikipedia.org/wiki/Finite_difference
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
if Np < ndiv + 1:
|
| 52 |
+
raise ValueError(
|
| 53 |
+
"Number of points must be at least the derivative order + 1."
|
| 54 |
+
)
|
| 55 |
+
if Np % 2 == 0:
|
| 56 |
+
raise ValueError("The number of points must be odd.")
|
| 57 |
+
from scipy import linalg
|
| 58 |
+
|
| 59 |
+
ho = Np >> 1
|
| 60 |
+
x = arange(-ho, ho + 1.0)
|
| 61 |
+
x = x[:, newaxis]
|
| 62 |
+
X = x**0.0
|
| 63 |
+
for k in range(1, Np):
|
| 64 |
+
X = hstack([X, x**k])
|
| 65 |
+
w = prod(arange(1, ndiv + 1), axis=0) * linalg.inv(X)[ndiv]
|
| 66 |
+
return w
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _derivative(func, x0, dx=1.0, n=1, args=(), order=3):
|
| 70 |
+
"""
|
| 71 |
+
Find the nth derivative of a function at a point.
|
| 72 |
+
|
| 73 |
+
Given a function, use a central difference formula with spacing `dx` to
|
| 74 |
+
compute the nth derivative at `x0`.
|
| 75 |
+
|
| 76 |
+
Parameters
|
| 77 |
+
----------
|
| 78 |
+
func : function
|
| 79 |
+
Input function.
|
| 80 |
+
x0 : float
|
| 81 |
+
The point at which the nth derivative is found.
|
| 82 |
+
dx : float, optional
|
| 83 |
+
Spacing.
|
| 84 |
+
n : int, optional
|
| 85 |
+
Order of the derivative. Default is 1.
|
| 86 |
+
args : tuple, optional
|
| 87 |
+
Arguments
|
| 88 |
+
order : int, optional
|
| 89 |
+
Number of points to use, must be odd.
|
| 90 |
+
|
| 91 |
+
Notes
|
| 92 |
+
-----
|
| 93 |
+
Decreasing the step size too small can result in round-off error.
|
| 94 |
+
|
| 95 |
+
Examples
|
| 96 |
+
--------
|
| 97 |
+
>>> def f(x):
|
| 98 |
+
... return x**3 + x**2
|
| 99 |
+
>>> _derivative(f, 1.0, dx=1e-6)
|
| 100 |
+
4.9999999999217337
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
if order < n + 1:
|
| 104 |
+
raise ValueError(
|
| 105 |
+
"'order' (the number of points used to compute the derivative), "
|
| 106 |
+
"must be at least the derivative order 'n' + 1."
|
| 107 |
+
)
|
| 108 |
+
if order % 2 == 0:
|
| 109 |
+
raise ValueError(
|
| 110 |
+
"'order' (the number of points used to compute the derivative) "
|
| 111 |
+
"must be odd."
|
| 112 |
+
)
|
| 113 |
+
# pre-computed for n=1 and 2 and low-order for speed.
|
| 114 |
+
if n == 1:
|
| 115 |
+
if order == 3:
|
| 116 |
+
weights = array([-1, 0, 1]) / 2.0
|
| 117 |
+
elif order == 5:
|
| 118 |
+
weights = array([1, -8, 0, 8, -1]) / 12.0
|
| 119 |
+
elif order == 7:
|
| 120 |
+
weights = array([-1, 9, -45, 0, 45, -9, 1]) / 60.0
|
| 121 |
+
elif order == 9:
|
| 122 |
+
weights = array([3, -32, 168, -672, 0, 672, -168, 32, -3]) / 840.0
|
| 123 |
+
else:
|
| 124 |
+
weights = _central_diff_weights(order, 1)
|
| 125 |
+
elif n == 2:
|
| 126 |
+
if order == 3:
|
| 127 |
+
weights = array([1, -2.0, 1])
|
| 128 |
+
elif order == 5:
|
| 129 |
+
weights = array([-1, 16, -30, 16, -1]) / 12.0
|
| 130 |
+
elif order == 7:
|
| 131 |
+
weights = array([2, -27, 270, -490, 270, -27, 2]) / 180.0
|
| 132 |
+
elif order == 9:
|
| 133 |
+
weights = (
|
| 134 |
+
array([-9, 128, -1008, 8064, -14350, 8064, -1008, 128, -9])
|
| 135 |
+
/ 5040.0
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
weights = _central_diff_weights(order, 2)
|
| 139 |
+
else:
|
| 140 |
+
weights = _central_diff_weights(order, n)
|
| 141 |
+
val = 0.0
|
| 142 |
+
ho = order >> 1
|
| 143 |
+
for k in range(order):
|
| 144 |
+
val += weights[k] * func(x0 + (k - ho) * dx, *args)
|
| 145 |
+
return val / prod((dx,) * n, axis=0)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (16.4 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/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")
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (23.2 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (49.5 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
| 99 |
+
pytest_args += list(extra_argv)
|
| 100 |
+
|
| 101 |
+
if verbose and int(verbose) > 1:
|
| 102 |
+
pytest_args += ["-" + "v"*(int(verbose)-1)]
|
| 103 |
+
|
| 104 |
+
if coverage:
|
| 105 |
+
pytest_args += ["--cov=" + module_path]
|
| 106 |
+
|
| 107 |
+
if label == "fast":
|
| 108 |
+
pytest_args += ["-m", "not slow"]
|
| 109 |
+
elif label != "full":
|
| 110 |
+
pytest_args += ["-m", label]
|
| 111 |
+
|
| 112 |
+
if tests is None:
|
| 113 |
+
tests = [self.module_name]
|
| 114 |
+
|
| 115 |
+
if parallel is not None and parallel > 1:
|
| 116 |
+
if _pytest_has_xdist():
|
| 117 |
+
pytest_args += ['-n', str(parallel)]
|
| 118 |
+
else:
|
| 119 |
+
import warnings
|
| 120 |
+
warnings.warn('Could not run tests in parallel because '
|
| 121 |
+
'pytest-xdist plugin is not available.',
|
| 122 |
+
stacklevel=2)
|
| 123 |
+
|
| 124 |
+
pytest_args += ['--pyargs'] + list(tests)
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
code = pytest.main(pytest_args)
|
| 128 |
+
except SystemExit as exc:
|
| 129 |
+
code = exc.code
|
| 130 |
+
|
| 131 |
+
return (code == 0)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class _TestPythranFunc:
|
| 135 |
+
'''
|
| 136 |
+
These are situations that can be tested in our pythran tests:
|
| 137 |
+
- A function with multiple array arguments and then
|
| 138 |
+
other positional and keyword arguments.
|
| 139 |
+
- A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
|
| 140 |
+
Note: list/tuple input is not yet tested!
|
| 141 |
+
|
| 142 |
+
`self.arguments`: A dictionary which key is the index of the argument,
|
| 143 |
+
value is tuple(array value, all supported dtypes)
|
| 144 |
+
`self.partialfunc`: A function used to freeze some non-array argument
|
| 145 |
+
that of no interests in the original function
|
| 146 |
+
'''
|
| 147 |
+
ALL_INTEGER = [np.int8, np.int16, np.int32, np.int64, np.intc, np.intp]
|
| 148 |
+
ALL_FLOAT = [np.float32, np.float64]
|
| 149 |
+
ALL_COMPLEX = [np.complex64, np.complex128]
|
| 150 |
+
|
| 151 |
+
def setup_method(self):
|
| 152 |
+
self.arguments = {}
|
| 153 |
+
self.partialfunc = None
|
| 154 |
+
self.expected = None
|
| 155 |
+
|
| 156 |
+
def get_optional_args(self, func):
|
| 157 |
+
# get optional arguments with its default value,
|
| 158 |
+
# used for testing keywords
|
| 159 |
+
signature = inspect.signature(func)
|
| 160 |
+
optional_args = {}
|
| 161 |
+
for k, v in signature.parameters.items():
|
| 162 |
+
if v.default is not inspect.Parameter.empty:
|
| 163 |
+
optional_args[k] = v.default
|
| 164 |
+
return optional_args
|
| 165 |
+
|
| 166 |
+
def get_max_dtype_list_length(self):
|
| 167 |
+
# get the max supported dtypes list length in all arguments
|
| 168 |
+
max_len = 0
|
| 169 |
+
for arg_idx in self.arguments:
|
| 170 |
+
cur_len = len(self.arguments[arg_idx][1])
|
| 171 |
+
if cur_len > max_len:
|
| 172 |
+
max_len = cur_len
|
| 173 |
+
return max_len
|
| 174 |
+
|
| 175 |
+
def get_dtype(self, dtype_list, dtype_idx):
|
| 176 |
+
# get the dtype from dtype_list via index
|
| 177 |
+
# if the index is out of range, then return the last dtype
|
| 178 |
+
if dtype_idx > len(dtype_list)-1:
|
| 179 |
+
return dtype_list[-1]
|
| 180 |
+
else:
|
| 181 |
+
return dtype_list[dtype_idx]
|
| 182 |
+
|
| 183 |
+
def test_all_dtypes(self):
|
| 184 |
+
for type_idx in range(self.get_max_dtype_list_length()):
|
| 185 |
+
args_array = []
|
| 186 |
+
for arg_idx in self.arguments:
|
| 187 |
+
new_dtype = self.get_dtype(self.arguments[arg_idx][1],
|
| 188 |
+
type_idx)
|
| 189 |
+
args_array.append(self.arguments[arg_idx][0].astype(new_dtype))
|
| 190 |
+
self.pythranfunc(*args_array)
|
| 191 |
+
|
| 192 |
+
def test_views(self):
|
| 193 |
+
args_array = []
|
| 194 |
+
for arg_idx in self.arguments:
|
| 195 |
+
args_array.append(self.arguments[arg_idx][0][::-1][::-1])
|
| 196 |
+
self.pythranfunc(*args_array)
|
| 197 |
+
|
| 198 |
+
def test_strided(self):
|
| 199 |
+
args_array = []
|
| 200 |
+
for arg_idx in self.arguments:
|
| 201 |
+
args_array.append(np.repeat(self.arguments[arg_idx][0],
|
| 202 |
+
2, axis=0)[::2])
|
| 203 |
+
self.pythranfunc(*args_array)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _pytest_has_xdist():
|
| 207 |
+
"""
|
| 208 |
+
Check if the pytest-xdist plugin is installed, providing parallel tests
|
| 209 |
+
"""
|
| 210 |
+
# Check xdist exists without importing, otherwise pytests emits warnings
|
| 211 |
+
from importlib.util import find_spec
|
| 212 |
+
return find_spec('xdist') is not None
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def check_free_memory(free_mb):
|
| 216 |
+
"""
|
| 217 |
+
Check *free_mb* of memory is available, otherwise do pytest.skip
|
| 218 |
+
"""
|
| 219 |
+
import pytest
|
| 220 |
+
|
| 221 |
+
try:
|
| 222 |
+
mem_free = _parse_size(os.environ['SCIPY_AVAILABLE_MEM'])
|
| 223 |
+
msg = '{} MB memory required, but environment SCIPY_AVAILABLE_MEM={}'.format(
|
| 224 |
+
free_mb, os.environ['SCIPY_AVAILABLE_MEM'])
|
| 225 |
+
except KeyError:
|
| 226 |
+
mem_free = _get_mem_available()
|
| 227 |
+
if mem_free is None:
|
| 228 |
+
pytest.skip("Could not determine available memory; set SCIPY_AVAILABLE_MEM "
|
| 229 |
+
"variable to free memory in MB to run the test.")
|
| 230 |
+
msg = f'{free_mb} MB memory required, but {mem_free/1e6} MB available'
|
| 231 |
+
|
| 232 |
+
if mem_free < free_mb * 1e6:
|
| 233 |
+
pytest.skip(msg)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _parse_size(size_str):
|
| 237 |
+
suffixes = {'': 1e6,
|
| 238 |
+
'b': 1.0,
|
| 239 |
+
'k': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12,
|
| 240 |
+
'kb': 1e3, 'Mb': 1e6, 'Gb': 1e9, 'Tb': 1e12,
|
| 241 |
+
'kib': 1024.0, 'Mib': 1024.0**2, 'Gib': 1024.0**3, 'Tib': 1024.0**4}
|
| 242 |
+
m = re.match(r'^\s*(\d+)\s*({})\s*$'.format('|'.join(suffixes.keys())),
|
| 243 |
+
size_str,
|
| 244 |
+
re.I)
|
| 245 |
+
if not m or m.group(2) not in suffixes:
|
| 246 |
+
raise ValueError("Invalid size string")
|
| 247 |
+
|
| 248 |
+
return float(m.group(1)) * suffixes[m.group(2)]
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _get_mem_available():
|
| 252 |
+
"""
|
| 253 |
+
Get information about memory available, not counting swap.
|
| 254 |
+
"""
|
| 255 |
+
try:
|
| 256 |
+
import psutil
|
| 257 |
+
return psutil.virtual_memory().available
|
| 258 |
+
except (ImportError, AttributeError):
|
| 259 |
+
pass
|
| 260 |
+
|
| 261 |
+
if sys.platform.startswith('linux'):
|
| 262 |
+
info = {}
|
| 263 |
+
with open('/proc/meminfo') as f:
|
| 264 |
+
for line in f:
|
| 265 |
+
p = line.split()
|
| 266 |
+
info[p[0].strip(':').lower()] = float(p[1]) * 1e3
|
| 267 |
+
|
| 268 |
+
if 'memavailable' in info:
|
| 269 |
+
# Linux >= 3.14
|
| 270 |
+
return info['memavailable']
|
| 271 |
+
else:
|
| 272 |
+
return info['memfree'] + info['cached']
|
| 273 |
+
|
| 274 |
+
return None
|
| 275 |
+
|
| 276 |
+
def _test_cython_extension(tmp_path, srcdir):
|
| 277 |
+
"""
|
| 278 |
+
Helper function to test building and importing Cython modules that
|
| 279 |
+
make use of the Cython APIs for BLAS, LAPACK, optimize, and special.
|
| 280 |
+
"""
|
| 281 |
+
import pytest
|
| 282 |
+
try:
|
| 283 |
+
subprocess.check_call(["meson", "--version"])
|
| 284 |
+
except FileNotFoundError:
|
| 285 |
+
pytest.skip("No usable 'meson' found")
|
| 286 |
+
|
| 287 |
+
# Make safe for being called by multiple threads within one test
|
| 288 |
+
tmp_path = tmp_path / str(threading.get_ident())
|
| 289 |
+
|
| 290 |
+
# build the examples in a temporary directory
|
| 291 |
+
mod_name = os.path.split(srcdir)[1]
|
| 292 |
+
shutil.copytree(srcdir, tmp_path / mod_name)
|
| 293 |
+
build_dir = tmp_path / mod_name / 'tests' / '_cython_examples'
|
| 294 |
+
target_dir = build_dir / 'build'
|
| 295 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 296 |
+
|
| 297 |
+
# Ensure we use the correct Python interpreter even when `meson` is
|
| 298 |
+
# installed in a different Python environment (see numpy#24956)
|
| 299 |
+
native_file = str(build_dir / 'interpreter-native-file.ini')
|
| 300 |
+
with open(native_file, 'w') as f:
|
| 301 |
+
f.write("[binaries]\n")
|
| 302 |
+
f.write(f"python = '{sys.executable}'")
|
| 303 |
+
|
| 304 |
+
if sys.platform == "win32":
|
| 305 |
+
subprocess.check_call(["meson", "setup",
|
| 306 |
+
"--buildtype=release",
|
| 307 |
+
"--native-file", native_file,
|
| 308 |
+
"--vsenv", str(build_dir)],
|
| 309 |
+
cwd=target_dir,
|
| 310 |
+
)
|
| 311 |
+
else:
|
| 312 |
+
subprocess.check_call(["meson", "setup",
|
| 313 |
+
"--native-file", native_file, str(build_dir)],
|
| 314 |
+
cwd=target_dir
|
| 315 |
+
)
|
| 316 |
+
subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
|
| 317 |
+
|
| 318 |
+
# import without adding the directory to sys.path
|
| 319 |
+
suffix = sysconfig.get_config_var('EXT_SUFFIX')
|
| 320 |
+
|
| 321 |
+
def load(modname):
|
| 322 |
+
so = (target_dir / modname).with_suffix(suffix)
|
| 323 |
+
spec = spec_from_file_location(modname, so)
|
| 324 |
+
mod = module_from_spec(spec)
|
| 325 |
+
spec.loader.exec_module(mod)
|
| 326 |
+
return mod
|
| 327 |
+
|
| 328 |
+
# test that the module can be imported
|
| 329 |
+
return load("extending"), load("extending_cpp")
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _run_concurrent_barrier(n_workers, fn, *args, **kwargs):
|
| 333 |
+
"""
|
| 334 |
+
Run a given function concurrently across a given number of threads.
|
| 335 |
+
|
| 336 |
+
This is equivalent to using a ThreadPoolExecutor, but using the threading
|
| 337 |
+
primitives instead. This function ensures that the closure passed by
|
| 338 |
+
parameter gets called concurrently by setting up a barrier before it gets
|
| 339 |
+
called before any of the threads.
|
| 340 |
+
|
| 341 |
+
Arguments
|
| 342 |
+
---------
|
| 343 |
+
n_workers: int
|
| 344 |
+
Number of concurrent threads to spawn.
|
| 345 |
+
fn: callable
|
| 346 |
+
Function closure to execute concurrently. Its first argument will
|
| 347 |
+
be the thread id.
|
| 348 |
+
*args: tuple
|
| 349 |
+
Variable number of positional arguments to pass to the function.
|
| 350 |
+
**kwargs: dict
|
| 351 |
+
Keyword arguments to pass to the function.
|
| 352 |
+
"""
|
| 353 |
+
barrier = threading.Barrier(n_workers)
|
| 354 |
+
|
| 355 |
+
def closure(i, *args, **kwargs):
|
| 356 |
+
barrier.wait()
|
| 357 |
+
fn(i, *args, **kwargs)
|
| 358 |
+
|
| 359 |
+
workers = []
|
| 360 |
+
for i in range(0, n_workers):
|
| 361 |
+
workers.append(threading.Thread(
|
| 362 |
+
target=closure,
|
| 363 |
+
args=(i,) + args, kwargs=kwargs))
|
| 364 |
+
|
| 365 |
+
for worker in workers:
|
| 366 |
+
worker.start()
|
| 367 |
+
|
| 368 |
+
for worker in workers:
|
| 369 |
+
worker.join()
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/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
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/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)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
.. note:
|
| 3 |
+
If you are looking for overrides for NumPy-specific methods, see the
|
| 4 |
+
documentation for :obj:`unumpy`. This page explains how to write
|
| 5 |
+
back-ends and multimethods.
|
| 6 |
+
|
| 7 |
+
``uarray`` is built around a back-end protocol, and overridable multimethods.
|
| 8 |
+
It is necessary to define multimethods for back-ends to be able to override them.
|
| 9 |
+
See the documentation of :obj:`generate_multimethod` on how to write multimethods.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
Let's start with the simplest:
|
| 14 |
+
|
| 15 |
+
``__ua_domain__`` defines the back-end *domain*. The domain consists of period-
|
| 16 |
+
separated string consisting of the modules you extend plus the submodule. For
|
| 17 |
+
example, if a submodule ``module2.submodule`` extends ``module1``
|
| 18 |
+
(i.e., it exposes dispatchables marked as types available in ``module1``),
|
| 19 |
+
then the domain string should be ``"module1.module2.submodule"``.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
For the purpose of this demonstration, we'll be creating an object and setting
|
| 23 |
+
its attributes directly. However, note that you can use a module or your own type
|
| 24 |
+
as a backend as well.
|
| 25 |
+
|
| 26 |
+
>>> class Backend: pass
|
| 27 |
+
>>> be = Backend()
|
| 28 |
+
>>> be.__ua_domain__ = "ua_examples"
|
| 29 |
+
|
| 30 |
+
It might be useful at this point to sidetrack to the documentation of
|
| 31 |
+
:obj:`generate_multimethod` to find out how to generate a multimethod
|
| 32 |
+
overridable by :obj:`uarray`. Needless to say, writing a backend and
|
| 33 |
+
creating multimethods are mostly orthogonal activities, and knowing
|
| 34 |
+
one doesn't necessarily require knowledge of the other, although it
|
| 35 |
+
is certainly helpful. We expect core API designers/specifiers to write the
|
| 36 |
+
multimethods, and implementors to override them. But, as is often the case,
|
| 37 |
+
similar people write both.
|
| 38 |
+
|
| 39 |
+
Without further ado, here's an example multimethod:
|
| 40 |
+
|
| 41 |
+
>>> import uarray as ua
|
| 42 |
+
>>> from uarray import Dispatchable
|
| 43 |
+
>>> def override_me(a, b):
|
| 44 |
+
... return Dispatchable(a, int),
|
| 45 |
+
>>> def override_replacer(args, kwargs, dispatchables):
|
| 46 |
+
... return (dispatchables[0], args[1]), {}
|
| 47 |
+
>>> overridden_me = ua.generate_multimethod(
|
| 48 |
+
... override_me, override_replacer, "ua_examples"
|
| 49 |
+
... )
|
| 50 |
+
|
| 51 |
+
Next comes the part about overriding the multimethod. This requires
|
| 52 |
+
the ``__ua_function__`` protocol, and the ``__ua_convert__``
|
| 53 |
+
protocol. The ``__ua_function__`` protocol has the signature
|
| 54 |
+
``(method, args, kwargs)`` where ``method`` is the passed
|
| 55 |
+
multimethod, ``args``/``kwargs`` specify the arguments and ``dispatchables``
|
| 56 |
+
is the list of converted dispatchables passed in.
|
| 57 |
+
|
| 58 |
+
>>> def __ua_function__(method, args, kwargs):
|
| 59 |
+
... return method.__name__, args, kwargs
|
| 60 |
+
>>> be.__ua_function__ = __ua_function__
|
| 61 |
+
|
| 62 |
+
The other protocol of interest is the ``__ua_convert__`` protocol. It has the
|
| 63 |
+
signature ``(dispatchables, coerce)``. When ``coerce`` is ``False``, conversion
|
| 64 |
+
between the formats should ideally be an ``O(1)`` operation, but it means that
|
| 65 |
+
no memory copying should be involved, only views of the existing data.
|
| 66 |
+
|
| 67 |
+
>>> def __ua_convert__(dispatchables, coerce):
|
| 68 |
+
... for d in dispatchables:
|
| 69 |
+
... if d.type is int:
|
| 70 |
+
... if coerce and d.coercible:
|
| 71 |
+
... yield str(d.value)
|
| 72 |
+
... else:
|
| 73 |
+
... yield d.value
|
| 74 |
+
>>> be.__ua_convert__ = __ua_convert__
|
| 75 |
+
|
| 76 |
+
Now that we have defined the backend, the next thing to do is to call the multimethod.
|
| 77 |
+
|
| 78 |
+
>>> with ua.set_backend(be):
|
| 79 |
+
... overridden_me(1, "2")
|
| 80 |
+
('override_me', (1, '2'), {})
|
| 81 |
+
|
| 82 |
+
Note that the marked type has no effect on the actual type of the passed object.
|
| 83 |
+
We can also coerce the type of the input.
|
| 84 |
+
|
| 85 |
+
>>> with ua.set_backend(be, coerce=True):
|
| 86 |
+
... overridden_me(1, "2")
|
| 87 |
+
... overridden_me(1.0, "2")
|
| 88 |
+
('override_me', ('1', '2'), {})
|
| 89 |
+
('override_me', ('1.0', '2'), {})
|
| 90 |
+
|
| 91 |
+
Another feature is that if you remove ``__ua_convert__``, the arguments are not
|
| 92 |
+
converted at all and it's up to the backend to handle that.
|
| 93 |
+
|
| 94 |
+
>>> del be.__ua_convert__
|
| 95 |
+
>>> with ua.set_backend(be):
|
| 96 |
+
... overridden_me(1, "2")
|
| 97 |
+
('override_me', (1, '2'), {})
|
| 98 |
+
|
| 99 |
+
You also have the option to return ``NotImplemented``, in which case processing moves on
|
| 100 |
+
to the next back-end, which in this case, doesn't exist. The same applies to
|
| 101 |
+
``__ua_convert__``.
|
| 102 |
+
|
| 103 |
+
>>> be.__ua_function__ = lambda *a, **kw: NotImplemented
|
| 104 |
+
>>> with ua.set_backend(be):
|
| 105 |
+
... overridden_me(1, "2")
|
| 106 |
+
Traceback (most recent call last):
|
| 107 |
+
...
|
| 108 |
+
uarray.BackendNotImplementedError: ...
|
| 109 |
+
|
| 110 |
+
The last possibility is if we don't have ``__ua_convert__``, in which case the job is
|
| 111 |
+
left up to ``__ua_function__``, but putting things back into arrays after conversion
|
| 112 |
+
will not be possible.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
from ._backend import *
|
| 116 |
+
__version__ = '0.8.8.dev0+aa94c5a4.scipy'
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py
ADDED
|
@@ -0,0 +1,1179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 typing import TypeAlias, TypeVar
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
from scipy._lib._array_api import array_namespace, is_numpy, xp_size
|
| 14 |
+
from scipy._lib._docscrape import FunctionDoc, Parameter
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
AxisError: type[Exception]
|
| 18 |
+
ComplexWarning: type[Warning]
|
| 19 |
+
VisibleDeprecationWarning: type[Warning]
|
| 20 |
+
|
| 21 |
+
if np.lib.NumpyVersion(np.__version__) >= '1.25.0':
|
| 22 |
+
from numpy.exceptions import (
|
| 23 |
+
AxisError, ComplexWarning, VisibleDeprecationWarning,
|
| 24 |
+
DTypePromotionError
|
| 25 |
+
)
|
| 26 |
+
else:
|
| 27 |
+
from numpy import ( # type: ignore[attr-defined, no-redef]
|
| 28 |
+
AxisError, ComplexWarning, VisibleDeprecationWarning # noqa: F401
|
| 29 |
+
)
|
| 30 |
+
DTypePromotionError = TypeError # type: ignore
|
| 31 |
+
|
| 32 |
+
np_long: type
|
| 33 |
+
np_ulong: type
|
| 34 |
+
|
| 35 |
+
if np.lib.NumpyVersion(np.__version__) >= "2.0.0.dev0":
|
| 36 |
+
try:
|
| 37 |
+
with warnings.catch_warnings():
|
| 38 |
+
warnings.filterwarnings(
|
| 39 |
+
"ignore",
|
| 40 |
+
r".*In the future `np\.long` will be defined as.*",
|
| 41 |
+
FutureWarning,
|
| 42 |
+
)
|
| 43 |
+
np_long = np.long # type: ignore[attr-defined]
|
| 44 |
+
np_ulong = np.ulong # type: ignore[attr-defined]
|
| 45 |
+
except AttributeError:
|
| 46 |
+
np_long = np.int_
|
| 47 |
+
np_ulong = np.uint
|
| 48 |
+
else:
|
| 49 |
+
np_long = np.int_
|
| 50 |
+
np_ulong = np.uint
|
| 51 |
+
|
| 52 |
+
IntNumber = int | np.integer
|
| 53 |
+
DecimalNumber = float | np.floating | np.integer
|
| 54 |
+
|
| 55 |
+
copy_if_needed: bool | None
|
| 56 |
+
|
| 57 |
+
if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
|
| 58 |
+
copy_if_needed = None
|
| 59 |
+
elif np.lib.NumpyVersion(np.__version__) < "1.28.0":
|
| 60 |
+
copy_if_needed = False
|
| 61 |
+
else:
|
| 62 |
+
# 2.0.0 dev versions, handle cases where copy may or may not exist
|
| 63 |
+
try:
|
| 64 |
+
np.array([1]).__array__(copy=None) # type: ignore[call-overload]
|
| 65 |
+
copy_if_needed = None
|
| 66 |
+
except TypeError:
|
| 67 |
+
copy_if_needed = False
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
_RNG: TypeAlias = np.random.Generator | np.random.RandomState
|
| 71 |
+
SeedType: TypeAlias = IntNumber | _RNG | None
|
| 72 |
+
|
| 73 |
+
GeneratorType = TypeVar("GeneratorType", bound=_RNG)
|
| 74 |
+
|
| 75 |
+
# Since Generator was introduced in numpy 1.17, the following condition is needed for
|
| 76 |
+
# backward compatibility
|
| 77 |
+
try:
|
| 78 |
+
from numpy.random import Generator as Generator
|
| 79 |
+
except ImportError:
|
| 80 |
+
class Generator: # type: ignore[no-redef]
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
|
| 85 |
+
"""Return elements chosen from two possibilities depending on a condition
|
| 86 |
+
|
| 87 |
+
Equivalent to ``f(*arrays) if cond else fillvalue`` performed elementwise.
|
| 88 |
+
|
| 89 |
+
Parameters
|
| 90 |
+
----------
|
| 91 |
+
cond : array
|
| 92 |
+
The condition (expressed as a boolean array).
|
| 93 |
+
arrays : tuple of array
|
| 94 |
+
Arguments to `f` (and `f2`). Must be broadcastable with `cond`.
|
| 95 |
+
f : callable
|
| 96 |
+
Where `cond` is True, output will be ``f(arr1[cond], arr2[cond], ...)``
|
| 97 |
+
fillvalue : object
|
| 98 |
+
If provided, value with which to fill output array where `cond` is
|
| 99 |
+
not True.
|
| 100 |
+
f2 : callable
|
| 101 |
+
If provided, output will be ``f2(arr1[cond], arr2[cond], ...)`` where
|
| 102 |
+
`cond` is not True.
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
out : array
|
| 107 |
+
An array with elements from the output of `f` where `cond` is True
|
| 108 |
+
and `fillvalue` (or elements from the output of `f2`) elsewhere. The
|
| 109 |
+
returned array has data type determined by Type Promotion Rules
|
| 110 |
+
with the output of `f` and `fillvalue` (or the output of `f2`).
|
| 111 |
+
|
| 112 |
+
Notes
|
| 113 |
+
-----
|
| 114 |
+
``xp.where(cond, x, fillvalue)`` requires explicitly forming `x` even where
|
| 115 |
+
`cond` is False. This function evaluates ``f(arr1[cond], arr2[cond], ...)``
|
| 116 |
+
onle where `cond` ``is True.
|
| 117 |
+
|
| 118 |
+
Examples
|
| 119 |
+
--------
|
| 120 |
+
>>> import numpy as np
|
| 121 |
+
>>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
|
| 122 |
+
>>> def f(a, b):
|
| 123 |
+
... return a*b
|
| 124 |
+
>>> _lazywhere(a > 2, (a, b), f, np.nan)
|
| 125 |
+
array([ nan, nan, 21., 32.])
|
| 126 |
+
|
| 127 |
+
"""
|
| 128 |
+
xp = array_namespace(cond, *arrays)
|
| 129 |
+
|
| 130 |
+
if (f2 is fillvalue is None) or (f2 is not None and fillvalue is not None):
|
| 131 |
+
raise ValueError("Exactly one of `fillvalue` or `f2` must be given.")
|
| 132 |
+
|
| 133 |
+
args = xp.broadcast_arrays(cond, *arrays)
|
| 134 |
+
bool_dtype = xp.asarray([True]).dtype # numpy 1.xx doesn't have `bool`
|
| 135 |
+
cond, arrays = xp.astype(args[0], bool_dtype, copy=False), args[1:]
|
| 136 |
+
|
| 137 |
+
temp1 = xp.asarray(f(*(arr[cond] for arr in arrays)))
|
| 138 |
+
|
| 139 |
+
if f2 is None:
|
| 140 |
+
# If `fillvalue` is a Python scalar and we convert to `xp.asarray`, it gets the
|
| 141 |
+
# default `int` or `float` type of `xp`, so `result_type` could be wrong.
|
| 142 |
+
# `result_type` should/will handle mixed array/Python scalars;
|
| 143 |
+
# remove this special logic when it does.
|
| 144 |
+
if type(fillvalue) in {bool, int, float, complex}:
|
| 145 |
+
with np.errstate(invalid='ignore'):
|
| 146 |
+
dtype = (temp1 * fillvalue).dtype
|
| 147 |
+
else:
|
| 148 |
+
dtype = xp.result_type(temp1.dtype, fillvalue)
|
| 149 |
+
out = xp.full(cond.shape, dtype=dtype,
|
| 150 |
+
fill_value=xp.asarray(fillvalue, dtype=dtype))
|
| 151 |
+
else:
|
| 152 |
+
ncond = ~cond
|
| 153 |
+
temp2 = xp.asarray(f2(*(arr[ncond] for arr in arrays)))
|
| 154 |
+
dtype = xp.result_type(temp1, temp2)
|
| 155 |
+
out = xp.empty(cond.shape, dtype=dtype)
|
| 156 |
+
out[ncond] = temp2
|
| 157 |
+
|
| 158 |
+
out[cond] = temp1
|
| 159 |
+
|
| 160 |
+
return out
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _lazyselect(condlist, choicelist, arrays, default=0):
|
| 164 |
+
"""
|
| 165 |
+
Mimic `np.select(condlist, choicelist)`.
|
| 166 |
+
|
| 167 |
+
Notice, it assumes that all `arrays` are of the same shape or can be
|
| 168 |
+
broadcasted together.
|
| 169 |
+
|
| 170 |
+
All functions in `choicelist` must accept array arguments in the order
|
| 171 |
+
given in `arrays` and must return an array of the same shape as broadcasted
|
| 172 |
+
`arrays`.
|
| 173 |
+
|
| 174 |
+
Examples
|
| 175 |
+
--------
|
| 176 |
+
>>> import numpy as np
|
| 177 |
+
>>> x = np.arange(6)
|
| 178 |
+
>>> np.select([x <3, x > 3], [x**2, x**3], default=0)
|
| 179 |
+
array([ 0, 1, 4, 0, 64, 125])
|
| 180 |
+
|
| 181 |
+
>>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
|
| 182 |
+
array([ 0., 1., 4., 0., 64., 125.])
|
| 183 |
+
|
| 184 |
+
>>> a = -np.ones_like(x)
|
| 185 |
+
>>> _lazyselect([x < 3, x > 3],
|
| 186 |
+
... [lambda x, a: x**2, lambda x, a: a * x**3],
|
| 187 |
+
... (x, a), default=np.nan)
|
| 188 |
+
array([ 0., 1., 4., nan, -64., -125.])
|
| 189 |
+
|
| 190 |
+
"""
|
| 191 |
+
arrays = np.broadcast_arrays(*arrays)
|
| 192 |
+
tcode = np.mintypecode([a.dtype.char for a in arrays])
|
| 193 |
+
out = np.full(np.shape(arrays[0]), fill_value=default, dtype=tcode)
|
| 194 |
+
for func, cond in zip(choicelist, condlist):
|
| 195 |
+
if np.all(cond is False):
|
| 196 |
+
continue
|
| 197 |
+
cond, _ = np.broadcast_arrays(cond, arrays[0])
|
| 198 |
+
temp = tuple(np.extract(cond, arr) for arr in arrays)
|
| 199 |
+
np.place(out, cond, func(*temp))
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _aligned_zeros(shape, dtype=float, order="C", align=None):
|
| 204 |
+
"""Allocate a new ndarray with aligned memory.
|
| 205 |
+
|
| 206 |
+
Primary use case for this currently is working around a f2py issue
|
| 207 |
+
in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
|
| 208 |
+
not necessarily create arrays aligned up to it.
|
| 209 |
+
|
| 210 |
+
"""
|
| 211 |
+
dtype = np.dtype(dtype)
|
| 212 |
+
if align is None:
|
| 213 |
+
align = dtype.alignment
|
| 214 |
+
if not hasattr(shape, '__len__'):
|
| 215 |
+
shape = (shape,)
|
| 216 |
+
size = functools.reduce(operator.mul, shape) * dtype.itemsize
|
| 217 |
+
buf = np.empty(size + align + 1, np.uint8)
|
| 218 |
+
offset = buf.__array_interface__['data'][0] % align
|
| 219 |
+
if offset != 0:
|
| 220 |
+
offset = align - offset
|
| 221 |
+
# Note: slices producing 0-size arrays do not necessarily change
|
| 222 |
+
# data pointer --- so we use and allocate size+1
|
| 223 |
+
buf = buf[offset:offset+size+1][:-1]
|
| 224 |
+
data = np.ndarray(shape, dtype, buf, order=order)
|
| 225 |
+
data.fill(0)
|
| 226 |
+
return data
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _prune_array(array):
|
| 230 |
+
"""Return an array equivalent to the input array. If the input
|
| 231 |
+
array is a view of a much larger array, copy its contents to a
|
| 232 |
+
newly allocated array. Otherwise, return the input unchanged.
|
| 233 |
+
"""
|
| 234 |
+
if array.base is not None and array.size < array.base.size // 2:
|
| 235 |
+
return array.copy()
|
| 236 |
+
return array
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def float_factorial(n: int) -> float:
|
| 240 |
+
"""Compute the factorial and return as a float
|
| 241 |
+
|
| 242 |
+
Returns infinity when result is too large for a double
|
| 243 |
+
"""
|
| 244 |
+
return float(math.factorial(n)) if n < 171 else np.inf
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
_rng_desc = (
|
| 248 |
+
r"""If `rng` is passed by keyword, types other than `numpy.random.Generator` are
|
| 249 |
+
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
|
| 250 |
+
If `rng` is already a ``Generator`` instance, then the provided instance is
|
| 251 |
+
used. Specify `rng` for repeatable function behavior.
|
| 252 |
+
|
| 253 |
+
If this argument is passed by position or `{old_name}` is passed by keyword,
|
| 254 |
+
legacy behavior for the argument `{old_name}` applies:
|
| 255 |
+
|
| 256 |
+
- If `{old_name}` is None (or `numpy.random`), the `numpy.random.RandomState`
|
| 257 |
+
singleton is used.
|
| 258 |
+
- If `{old_name}` is an int, a new ``RandomState`` instance is used,
|
| 259 |
+
seeded with `{old_name}`.
|
| 260 |
+
- If `{old_name}` is already a ``Generator`` or ``RandomState`` instance then
|
| 261 |
+
that instance is used.
|
| 262 |
+
|
| 263 |
+
.. versionchanged:: 1.15.0
|
| 264 |
+
As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
|
| 265 |
+
transition from use of `numpy.random.RandomState` to
|
| 266 |
+
`numpy.random.Generator`, this keyword was changed from `{old_name}` to `rng`.
|
| 267 |
+
For an interim period, both keywords will continue to work, although only one
|
| 268 |
+
may be specified at a time. After the interim period, function calls using the
|
| 269 |
+
`{old_name}` keyword will emit warnings. The behavior of both `{old_name}` and
|
| 270 |
+
`rng` are outlined above, but only the `rng` keyword should be used in new code.
|
| 271 |
+
"""
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
# SPEC 7
|
| 276 |
+
def _transition_to_rng(old_name, *, position_num=None, end_version=None,
|
| 277 |
+
replace_doc=True):
|
| 278 |
+
"""Example decorator to transition from old PRNG usage to new `rng` behavior
|
| 279 |
+
|
| 280 |
+
Suppose the decorator is applied to a function that used to accept parameter
|
| 281 |
+
`old_name='random_state'` either by keyword or as a positional argument at
|
| 282 |
+
`position_num=1`. At the time of application, the name of the argument in the
|
| 283 |
+
function signature is manually changed to the new name, `rng`. If positional
|
| 284 |
+
use was allowed before, this is not changed.*
|
| 285 |
+
|
| 286 |
+
- If the function is called with both `random_state` and `rng`, the decorator
|
| 287 |
+
raises an error.
|
| 288 |
+
- If `random_state` is provided as a keyword argument, the decorator passes
|
| 289 |
+
`random_state` to the function's `rng` argument as a keyword. If `end_version`
|
| 290 |
+
is specified, the decorator will emit a `DeprecationWarning` about the
|
| 291 |
+
deprecation of keyword `random_state`.
|
| 292 |
+
- If `random_state` is provided as a positional argument, the decorator passes
|
| 293 |
+
`random_state` to the function's `rng` argument by position. If `end_version`
|
| 294 |
+
is specified, the decorator will emit a `FutureWarning` about the changing
|
| 295 |
+
interpretation of the argument.
|
| 296 |
+
- If `rng` is provided as a keyword argument, the decorator validates `rng` using
|
| 297 |
+
`numpy.random.default_rng` before passing it to the function.
|
| 298 |
+
- If `end_version` is specified and neither `random_state` nor `rng` is provided
|
| 299 |
+
by the user, the decorator checks whether `np.random.seed` has been used to set
|
| 300 |
+
the global seed. If so, it emits a `FutureWarning`, noting that usage of
|
| 301 |
+
`numpy.random.seed` will eventually have no effect. Either way, the decorator
|
| 302 |
+
calls the function without explicitly passing the `rng` argument.
|
| 303 |
+
|
| 304 |
+
If `end_version` is specified, a user must pass `rng` as a keyword to avoid
|
| 305 |
+
warnings.
|
| 306 |
+
|
| 307 |
+
After the deprecation period, the decorator can be removed, and the function
|
| 308 |
+
can simply validate the `rng` argument by calling `np.random.default_rng(rng)`.
|
| 309 |
+
|
| 310 |
+
* A `FutureWarning` is emitted when the PRNG argument is used by
|
| 311 |
+
position. It indicates that the "Hinsen principle" (same
|
| 312 |
+
code yielding different results in two versions of the software)
|
| 313 |
+
will be violated, unless positional use is deprecated. Specifically:
|
| 314 |
+
|
| 315 |
+
- If `None` is passed by position and `np.random.seed` has been used,
|
| 316 |
+
the function will change from being seeded to being unseeded.
|
| 317 |
+
- If an integer is passed by position, the random stream will change.
|
| 318 |
+
- If `np.random` or an instance of `RandomState` is passed by position,
|
| 319 |
+
an error will be raised.
|
| 320 |
+
|
| 321 |
+
We suggest that projects consider deprecating positional use of
|
| 322 |
+
`random_state`/`rng` (i.e., change their function signatures to
|
| 323 |
+
``def my_func(..., *, rng=None)``); that might not make sense
|
| 324 |
+
for all projects, so this SPEC does not make that
|
| 325 |
+
recommendation, neither does this decorator enforce it.
|
| 326 |
+
|
| 327 |
+
Parameters
|
| 328 |
+
----------
|
| 329 |
+
old_name : str
|
| 330 |
+
The old name of the PRNG argument (e.g. `seed` or `random_state`).
|
| 331 |
+
position_num : int, optional
|
| 332 |
+
The (0-indexed) position of the old PRNG argument (if accepted by position).
|
| 333 |
+
Maintainers are welcome to eliminate this argument and use, for example,
|
| 334 |
+
`inspect`, if preferred.
|
| 335 |
+
end_version : str, optional
|
| 336 |
+
The full version number of the library when the behavior described in
|
| 337 |
+
`DeprecationWarning`s and `FutureWarning`s will take effect. If left
|
| 338 |
+
unspecified, no warnings will be emitted by the decorator.
|
| 339 |
+
replace_doc : bool, default: True
|
| 340 |
+
Whether the decorator should replace the documentation for parameter `rng` with
|
| 341 |
+
`_rng_desc` (defined above), which documents both new `rng` keyword behavior
|
| 342 |
+
and typical legacy `random_state`/`seed` behavior. If True, manually replace
|
| 343 |
+
the first paragraph of the function's old `random_state`/`seed` documentation
|
| 344 |
+
with the desired *final* `rng` documentation; this way, no changes to
|
| 345 |
+
documentation are needed when the decorator is removed. Documentation of `rng`
|
| 346 |
+
after the first blank line is preserved. Use False if the function's old
|
| 347 |
+
`random_state`/`seed` behavior does not match that described by `_rng_desc`.
|
| 348 |
+
|
| 349 |
+
"""
|
| 350 |
+
NEW_NAME = "rng"
|
| 351 |
+
|
| 352 |
+
cmn_msg = (
|
| 353 |
+
"To silence this warning and ensure consistent behavior in SciPy "
|
| 354 |
+
f"{end_version}, control the RNG using argument `{NEW_NAME}`. Arguments passed "
|
| 355 |
+
f"to keyword `{NEW_NAME}` will be validated by `np.random.default_rng`, so the "
|
| 356 |
+
"behavior corresponding with a given value may change compared to use of "
|
| 357 |
+
f"`{old_name}`. For example, "
|
| 358 |
+
"1) `None` will result in unpredictable random numbers, "
|
| 359 |
+
"2) an integer will result in a different stream of random numbers, (with the "
|
| 360 |
+
"same distribution), and "
|
| 361 |
+
"3) `np.random` or `RandomState` instances will result in an error. "
|
| 362 |
+
"See the documentation of `default_rng` for more information."
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
def decorator(fun):
|
| 366 |
+
@functools.wraps(fun)
|
| 367 |
+
def wrapper(*args, **kwargs):
|
| 368 |
+
# Determine how PRNG was passed
|
| 369 |
+
as_old_kwarg = old_name in kwargs
|
| 370 |
+
as_new_kwarg = NEW_NAME in kwargs
|
| 371 |
+
as_pos_arg = position_num is not None and len(args) >= position_num + 1
|
| 372 |
+
emit_warning = end_version is not None
|
| 373 |
+
|
| 374 |
+
# Can only specify PRNG one of the three ways
|
| 375 |
+
if int(as_old_kwarg) + int(as_new_kwarg) + int(as_pos_arg) > 1:
|
| 376 |
+
message = (
|
| 377 |
+
f"{fun.__name__}() got multiple values for "
|
| 378 |
+
f"argument now known as `{NEW_NAME}`. Specify one of "
|
| 379 |
+
f"`{NEW_NAME}` or `{old_name}`."
|
| 380 |
+
)
|
| 381 |
+
raise TypeError(message)
|
| 382 |
+
|
| 383 |
+
# Check whether global random state has been set
|
| 384 |
+
global_seed_set = np.random.mtrand._rand._bit_generator._seed_seq is None
|
| 385 |
+
|
| 386 |
+
if as_old_kwarg: # warn about deprecated use of old kwarg
|
| 387 |
+
kwargs[NEW_NAME] = kwargs.pop(old_name)
|
| 388 |
+
if emit_warning:
|
| 389 |
+
message = (
|
| 390 |
+
f"Use of keyword argument `{old_name}` is "
|
| 391 |
+
f"deprecated and replaced by `{NEW_NAME}`. "
|
| 392 |
+
f"Support for `{old_name}` will be removed "
|
| 393 |
+
f"in SciPy {end_version}. "
|
| 394 |
+
) + cmn_msg
|
| 395 |
+
warnings.warn(message, DeprecationWarning, stacklevel=2)
|
| 396 |
+
|
| 397 |
+
elif as_pos_arg:
|
| 398 |
+
# Warn about changing meaning of positional arg
|
| 399 |
+
|
| 400 |
+
# Note that this decorator does not deprecate positional use of the
|
| 401 |
+
# argument; it only warns that the behavior will change in the future.
|
| 402 |
+
# Simultaneously transitioning to keyword-only use is another option.
|
| 403 |
+
|
| 404 |
+
arg = args[position_num]
|
| 405 |
+
# If the argument is None and the global seed wasn't set, or if the
|
| 406 |
+
# argument is one of a few new classes, the user will not notice change
|
| 407 |
+
# in behavior.
|
| 408 |
+
ok_classes = (
|
| 409 |
+
np.random.Generator,
|
| 410 |
+
np.random.SeedSequence,
|
| 411 |
+
np.random.BitGenerator,
|
| 412 |
+
)
|
| 413 |
+
if (arg is None and not global_seed_set) or isinstance(arg, ok_classes):
|
| 414 |
+
pass
|
| 415 |
+
elif emit_warning:
|
| 416 |
+
message = (
|
| 417 |
+
f"Positional use of `{NEW_NAME}` (formerly known as "
|
| 418 |
+
f"`{old_name}`) is still allowed, but the behavior is "
|
| 419 |
+
"changing: the argument will be normalized using "
|
| 420 |
+
f"`np.random.default_rng` beginning in SciPy {end_version}, "
|
| 421 |
+
"and the resulting `Generator` will be used to generate "
|
| 422 |
+
"random numbers."
|
| 423 |
+
) + cmn_msg
|
| 424 |
+
warnings.warn(message, FutureWarning, stacklevel=2)
|
| 425 |
+
|
| 426 |
+
elif as_new_kwarg: # no warnings; this is the preferred use
|
| 427 |
+
# After the removal of the decorator, normalization with
|
| 428 |
+
# np.random.default_rng will be done inside the decorated function
|
| 429 |
+
kwargs[NEW_NAME] = np.random.default_rng(kwargs[NEW_NAME])
|
| 430 |
+
|
| 431 |
+
elif global_seed_set and emit_warning:
|
| 432 |
+
# Emit FutureWarning if `np.random.seed` was used and no PRNG was passed
|
| 433 |
+
message = (
|
| 434 |
+
"The NumPy global RNG was seeded by calling "
|
| 435 |
+
f"`np.random.seed`. Beginning in {end_version}, this "
|
| 436 |
+
"function will no longer use the global RNG."
|
| 437 |
+
) + cmn_msg
|
| 438 |
+
warnings.warn(message, FutureWarning, stacklevel=2)
|
| 439 |
+
|
| 440 |
+
return fun(*args, **kwargs)
|
| 441 |
+
|
| 442 |
+
if replace_doc:
|
| 443 |
+
doc = FunctionDoc(wrapper)
|
| 444 |
+
parameter_names = [param.name for param in doc['Parameters']]
|
| 445 |
+
if 'rng' in parameter_names:
|
| 446 |
+
_type = "{None, int, `numpy.random.Generator`}, optional"
|
| 447 |
+
_desc = _rng_desc.replace("{old_name}", old_name)
|
| 448 |
+
old_doc = doc['Parameters'][parameter_names.index('rng')].desc
|
| 449 |
+
old_doc_keep = old_doc[old_doc.index("") + 1:] if "" in old_doc else []
|
| 450 |
+
new_doc = [_desc] + old_doc_keep
|
| 451 |
+
_rng_parameter_doc = Parameter('rng', _type, new_doc)
|
| 452 |
+
doc['Parameters'][parameter_names.index('rng')] = _rng_parameter_doc
|
| 453 |
+
doc = str(doc).split("\n", 1)[1] # remove signature
|
| 454 |
+
wrapper.__doc__ = str(doc)
|
| 455 |
+
return wrapper
|
| 456 |
+
|
| 457 |
+
return decorator
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# copy-pasted from scikit-learn utils/validation.py
|
| 461 |
+
def check_random_state(seed):
|
| 462 |
+
"""Turn `seed` into a `np.random.RandomState` instance.
|
| 463 |
+
|
| 464 |
+
Parameters
|
| 465 |
+
----------
|
| 466 |
+
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
|
| 467 |
+
If `seed` is None (or `np.random`), the `numpy.random.RandomState`
|
| 468 |
+
singleton is used.
|
| 469 |
+
If `seed` is an int, a new ``RandomState`` instance is used,
|
| 470 |
+
seeded with `seed`.
|
| 471 |
+
If `seed` is already a ``Generator`` or ``RandomState`` instance then
|
| 472 |
+
that instance is used.
|
| 473 |
+
|
| 474 |
+
Returns
|
| 475 |
+
-------
|
| 476 |
+
seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
|
| 477 |
+
Random number generator.
|
| 478 |
+
|
| 479 |
+
"""
|
| 480 |
+
if seed is None or seed is np.random:
|
| 481 |
+
return np.random.mtrand._rand
|
| 482 |
+
if isinstance(seed, numbers.Integral | np.integer):
|
| 483 |
+
return np.random.RandomState(seed)
|
| 484 |
+
if isinstance(seed, np.random.RandomState | np.random.Generator):
|
| 485 |
+
return seed
|
| 486 |
+
|
| 487 |
+
raise ValueError(f"'{seed}' cannot be used to seed a numpy.random.RandomState"
|
| 488 |
+
" instance")
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _asarray_validated(a, check_finite=True,
|
| 492 |
+
sparse_ok=False, objects_ok=False, mask_ok=False,
|
| 493 |
+
as_inexact=False):
|
| 494 |
+
"""
|
| 495 |
+
Helper function for SciPy argument validation.
|
| 496 |
+
|
| 497 |
+
Many SciPy linear algebra functions do support arbitrary array-like
|
| 498 |
+
input arguments. Examples of commonly unsupported inputs include
|
| 499 |
+
matrices containing inf/nan, sparse matrix representations, and
|
| 500 |
+
matrices with complicated elements.
|
| 501 |
+
|
| 502 |
+
Parameters
|
| 503 |
+
----------
|
| 504 |
+
a : array_like
|
| 505 |
+
The array-like input.
|
| 506 |
+
check_finite : bool, optional
|
| 507 |
+
Whether to check that the input matrices contain only finite numbers.
|
| 508 |
+
Disabling may give a performance gain, but may result in problems
|
| 509 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 510 |
+
Default: True
|
| 511 |
+
sparse_ok : bool, optional
|
| 512 |
+
True if scipy sparse matrices are allowed.
|
| 513 |
+
objects_ok : bool, optional
|
| 514 |
+
True if arrays with dype('O') are allowed.
|
| 515 |
+
mask_ok : bool, optional
|
| 516 |
+
True if masked arrays are allowed.
|
| 517 |
+
as_inexact : bool, optional
|
| 518 |
+
True to convert the input array to a np.inexact dtype.
|
| 519 |
+
|
| 520 |
+
Returns
|
| 521 |
+
-------
|
| 522 |
+
ret : ndarray
|
| 523 |
+
The converted validated array.
|
| 524 |
+
|
| 525 |
+
"""
|
| 526 |
+
if not sparse_ok:
|
| 527 |
+
import scipy.sparse
|
| 528 |
+
if scipy.sparse.issparse(a):
|
| 529 |
+
msg = ('Sparse arrays/matrices are not supported by this function. '
|
| 530 |
+
'Perhaps one of the `scipy.sparse.linalg` functions '
|
| 531 |
+
'would work instead.')
|
| 532 |
+
raise ValueError(msg)
|
| 533 |
+
if not mask_ok:
|
| 534 |
+
if np.ma.isMaskedArray(a):
|
| 535 |
+
raise ValueError('masked arrays are not supported')
|
| 536 |
+
toarray = np.asarray_chkfinite if check_finite else np.asarray
|
| 537 |
+
a = toarray(a)
|
| 538 |
+
if not objects_ok:
|
| 539 |
+
if a.dtype is np.dtype('O'):
|
| 540 |
+
raise ValueError('object arrays are not supported')
|
| 541 |
+
if as_inexact:
|
| 542 |
+
if not np.issubdtype(a.dtype, np.inexact):
|
| 543 |
+
a = toarray(a, dtype=np.float64)
|
| 544 |
+
return a
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def _validate_int(k, name, minimum=None):
|
| 548 |
+
"""
|
| 549 |
+
Validate a scalar integer.
|
| 550 |
+
|
| 551 |
+
This function can be used to validate an argument to a function
|
| 552 |
+
that expects the value to be an integer. It uses `operator.index`
|
| 553 |
+
to validate the value (so, for example, k=2.0 results in a
|
| 554 |
+
TypeError).
|
| 555 |
+
|
| 556 |
+
Parameters
|
| 557 |
+
----------
|
| 558 |
+
k : int
|
| 559 |
+
The value to be validated.
|
| 560 |
+
name : str
|
| 561 |
+
The name of the parameter.
|
| 562 |
+
minimum : int, optional
|
| 563 |
+
An optional lower bound.
|
| 564 |
+
"""
|
| 565 |
+
try:
|
| 566 |
+
k = operator.index(k)
|
| 567 |
+
except TypeError:
|
| 568 |
+
raise TypeError(f'{name} must be an integer.') from None
|
| 569 |
+
if minimum is not None and k < minimum:
|
| 570 |
+
raise ValueError(f'{name} must be an integer not less '
|
| 571 |
+
f'than {minimum}') from None
|
| 572 |
+
return k
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
# Add a replacement for inspect.getfullargspec()/
|
| 576 |
+
# The version below is borrowed from Django,
|
| 577 |
+
# https://github.com/django/django/pull/4846.
|
| 578 |
+
|
| 579 |
+
# Note an inconsistency between inspect.getfullargspec(func) and
|
| 580 |
+
# inspect.signature(func). If `func` is a bound method, the latter does *not*
|
| 581 |
+
# list `self` as a first argument, while the former *does*.
|
| 582 |
+
# Hence, cook up a common ground replacement: `getfullargspec_no_self` which
|
| 583 |
+
# mimics `inspect.getfullargspec` but does not list `self`.
|
| 584 |
+
#
|
| 585 |
+
# This way, the caller code does not need to know whether it uses a legacy
|
| 586 |
+
# .getfullargspec or a bright and shiny .signature.
|
| 587 |
+
|
| 588 |
+
FullArgSpec = namedtuple('FullArgSpec',
|
| 589 |
+
['args', 'varargs', 'varkw', 'defaults',
|
| 590 |
+
'kwonlyargs', 'kwonlydefaults', 'annotations'])
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def getfullargspec_no_self(func):
|
| 594 |
+
"""inspect.getfullargspec replacement using inspect.signature.
|
| 595 |
+
|
| 596 |
+
If func is a bound method, do not list the 'self' parameter.
|
| 597 |
+
|
| 598 |
+
Parameters
|
| 599 |
+
----------
|
| 600 |
+
func : callable
|
| 601 |
+
A callable to inspect
|
| 602 |
+
|
| 603 |
+
Returns
|
| 604 |
+
-------
|
| 605 |
+
fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
|
| 606 |
+
kwonlydefaults, annotations)
|
| 607 |
+
|
| 608 |
+
NOTE: if the first argument of `func` is self, it is *not*, I repeat
|
| 609 |
+
*not*, included in fullargspec.args.
|
| 610 |
+
This is done for consistency between inspect.getargspec() under
|
| 611 |
+
Python 2.x, and inspect.signature() under Python 3.x.
|
| 612 |
+
|
| 613 |
+
"""
|
| 614 |
+
sig = inspect.signature(func)
|
| 615 |
+
args = [
|
| 616 |
+
p.name for p in sig.parameters.values()
|
| 617 |
+
if p.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 618 |
+
inspect.Parameter.POSITIONAL_ONLY]
|
| 619 |
+
]
|
| 620 |
+
varargs = [
|
| 621 |
+
p.name for p in sig.parameters.values()
|
| 622 |
+
if p.kind == inspect.Parameter.VAR_POSITIONAL
|
| 623 |
+
]
|
| 624 |
+
varargs = varargs[0] if varargs else None
|
| 625 |
+
varkw = [
|
| 626 |
+
p.name for p in sig.parameters.values()
|
| 627 |
+
if p.kind == inspect.Parameter.VAR_KEYWORD
|
| 628 |
+
]
|
| 629 |
+
varkw = varkw[0] if varkw else None
|
| 630 |
+
defaults = tuple(
|
| 631 |
+
p.default for p in sig.parameters.values()
|
| 632 |
+
if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and
|
| 633 |
+
p.default is not p.empty)
|
| 634 |
+
) or None
|
| 635 |
+
kwonlyargs = [
|
| 636 |
+
p.name for p in sig.parameters.values()
|
| 637 |
+
if p.kind == inspect.Parameter.KEYWORD_ONLY
|
| 638 |
+
]
|
| 639 |
+
kwdefaults = {p.name: p.default for p in sig.parameters.values()
|
| 640 |
+
if p.kind == inspect.Parameter.KEYWORD_ONLY and
|
| 641 |
+
p.default is not p.empty}
|
| 642 |
+
annotations = {p.name: p.annotation for p in sig.parameters.values()
|
| 643 |
+
if p.annotation is not p.empty}
|
| 644 |
+
return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
|
| 645 |
+
kwdefaults or None, annotations)
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
class _FunctionWrapper:
|
| 649 |
+
"""
|
| 650 |
+
Object to wrap user's function, allowing picklability
|
| 651 |
+
"""
|
| 652 |
+
def __init__(self, f, args):
|
| 653 |
+
self.f = f
|
| 654 |
+
self.args = [] if args is None else args
|
| 655 |
+
|
| 656 |
+
def __call__(self, x):
|
| 657 |
+
return self.f(x, *self.args)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
class MapWrapper:
|
| 661 |
+
"""
|
| 662 |
+
Parallelisation wrapper for working with map-like callables, such as
|
| 663 |
+
`multiprocessing.Pool.map`.
|
| 664 |
+
|
| 665 |
+
Parameters
|
| 666 |
+
----------
|
| 667 |
+
pool : int or map-like callable
|
| 668 |
+
If `pool` is an integer, then it specifies the number of threads to
|
| 669 |
+
use for parallelization. If ``int(pool) == 1``, then no parallel
|
| 670 |
+
processing is used and the map builtin is used.
|
| 671 |
+
If ``pool == -1``, then the pool will utilize all available CPUs.
|
| 672 |
+
If `pool` is a map-like callable that follows the same
|
| 673 |
+
calling sequence as the built-in map function, then this callable is
|
| 674 |
+
used for parallelization.
|
| 675 |
+
"""
|
| 676 |
+
def __init__(self, pool=1):
|
| 677 |
+
self.pool = None
|
| 678 |
+
self._mapfunc = map
|
| 679 |
+
self._own_pool = False
|
| 680 |
+
|
| 681 |
+
if callable(pool):
|
| 682 |
+
self.pool = pool
|
| 683 |
+
self._mapfunc = self.pool
|
| 684 |
+
else:
|
| 685 |
+
from multiprocessing import Pool
|
| 686 |
+
# user supplies a number
|
| 687 |
+
if int(pool) == -1:
|
| 688 |
+
# use as many processors as possible
|
| 689 |
+
self.pool = Pool()
|
| 690 |
+
self._mapfunc = self.pool.map
|
| 691 |
+
self._own_pool = True
|
| 692 |
+
elif int(pool) == 1:
|
| 693 |
+
pass
|
| 694 |
+
elif int(pool) > 1:
|
| 695 |
+
# use the number of processors requested
|
| 696 |
+
self.pool = Pool(processes=int(pool))
|
| 697 |
+
self._mapfunc = self.pool.map
|
| 698 |
+
self._own_pool = True
|
| 699 |
+
else:
|
| 700 |
+
raise RuntimeError("Number of workers specified must be -1,"
|
| 701 |
+
" an int >= 1, or an object with a 'map' "
|
| 702 |
+
"method")
|
| 703 |
+
|
| 704 |
+
def __enter__(self):
|
| 705 |
+
return self
|
| 706 |
+
|
| 707 |
+
def terminate(self):
|
| 708 |
+
if self._own_pool:
|
| 709 |
+
self.pool.terminate()
|
| 710 |
+
|
| 711 |
+
def join(self):
|
| 712 |
+
if self._own_pool:
|
| 713 |
+
self.pool.join()
|
| 714 |
+
|
| 715 |
+
def close(self):
|
| 716 |
+
if self._own_pool:
|
| 717 |
+
self.pool.close()
|
| 718 |
+
|
| 719 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 720 |
+
if self._own_pool:
|
| 721 |
+
self.pool.close()
|
| 722 |
+
self.pool.terminate()
|
| 723 |
+
|
| 724 |
+
def __call__(self, func, iterable):
|
| 725 |
+
# only accept one iterable because that's all Pool.map accepts
|
| 726 |
+
try:
|
| 727 |
+
return self._mapfunc(func, iterable)
|
| 728 |
+
except TypeError as e:
|
| 729 |
+
# wrong number of arguments
|
| 730 |
+
raise TypeError("The map-like callable must be of the"
|
| 731 |
+
" form f(func, iterable)") from e
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def rng_integers(gen, low, high=None, size=None, dtype='int64',
|
| 735 |
+
endpoint=False):
|
| 736 |
+
"""
|
| 737 |
+
Return random integers from low (inclusive) to high (exclusive), or if
|
| 738 |
+
endpoint=True, low (inclusive) to high (inclusive). Replaces
|
| 739 |
+
`RandomState.randint` (with endpoint=False) and
|
| 740 |
+
`RandomState.random_integers` (with endpoint=True).
|
| 741 |
+
|
| 742 |
+
Return random integers from the "discrete uniform" distribution of the
|
| 743 |
+
specified dtype. If high is None (the default), then results are from
|
| 744 |
+
0 to low.
|
| 745 |
+
|
| 746 |
+
Parameters
|
| 747 |
+
----------
|
| 748 |
+
gen : {None, np.random.RandomState, np.random.Generator}
|
| 749 |
+
Random number generator. If None, then the np.random.RandomState
|
| 750 |
+
singleton is used.
|
| 751 |
+
low : int or array-like of ints
|
| 752 |
+
Lowest (signed) integers to be drawn from the distribution (unless
|
| 753 |
+
high=None, in which case this parameter is 0 and this value is used
|
| 754 |
+
for high).
|
| 755 |
+
high : int or array-like of ints
|
| 756 |
+
If provided, one above the largest (signed) integer to be drawn from
|
| 757 |
+
the distribution (see above for behavior if high=None). If array-like,
|
| 758 |
+
must contain integer values.
|
| 759 |
+
size : array-like of ints, optional
|
| 760 |
+
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
|
| 761 |
+
samples are drawn. Default is None, in which case a single value is
|
| 762 |
+
returned.
|
| 763 |
+
dtype : {str, dtype}, optional
|
| 764 |
+
Desired dtype of the result. All dtypes are determined by their name,
|
| 765 |
+
i.e., 'int64', 'int', etc, so byteorder is not available and a specific
|
| 766 |
+
precision may have different C types depending on the platform.
|
| 767 |
+
The default value is 'int64'.
|
| 768 |
+
endpoint : bool, optional
|
| 769 |
+
If True, sample from the interval [low, high] instead of the default
|
| 770 |
+
[low, high) Defaults to False.
|
| 771 |
+
|
| 772 |
+
Returns
|
| 773 |
+
-------
|
| 774 |
+
out: int or ndarray of ints
|
| 775 |
+
size-shaped array of random integers from the appropriate distribution,
|
| 776 |
+
or a single such random int if size not provided.
|
| 777 |
+
"""
|
| 778 |
+
if isinstance(gen, Generator):
|
| 779 |
+
return gen.integers(low, high=high, size=size, dtype=dtype,
|
| 780 |
+
endpoint=endpoint)
|
| 781 |
+
else:
|
| 782 |
+
if gen is None:
|
| 783 |
+
# default is RandomState singleton used by np.random.
|
| 784 |
+
gen = np.random.mtrand._rand
|
| 785 |
+
if endpoint:
|
| 786 |
+
# inclusive of endpoint
|
| 787 |
+
# remember that low and high can be arrays, so don't modify in
|
| 788 |
+
# place
|
| 789 |
+
if high is None:
|
| 790 |
+
return gen.randint(low + 1, size=size, dtype=dtype)
|
| 791 |
+
if high is not None:
|
| 792 |
+
return gen.randint(low, high=high + 1, size=size, dtype=dtype)
|
| 793 |
+
|
| 794 |
+
# exclusive
|
| 795 |
+
return gen.randint(low, high=high, size=size, dtype=dtype)
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
@contextmanager
|
| 799 |
+
def _fixed_default_rng(seed=1638083107694713882823079058616272161):
|
| 800 |
+
"""Context with a fixed np.random.default_rng seed."""
|
| 801 |
+
orig_fun = np.random.default_rng
|
| 802 |
+
np.random.default_rng = lambda seed=seed: orig_fun(seed)
|
| 803 |
+
try:
|
| 804 |
+
yield
|
| 805 |
+
finally:
|
| 806 |
+
np.random.default_rng = orig_fun
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _rng_html_rewrite(func):
|
| 810 |
+
"""Rewrite the HTML rendering of ``np.random.default_rng``.
|
| 811 |
+
|
| 812 |
+
This is intended to decorate
|
| 813 |
+
``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.
|
| 814 |
+
|
| 815 |
+
Examples are only run by Sphinx when there are plot involved. Even so,
|
| 816 |
+
it does not change the result values getting printed.
|
| 817 |
+
"""
|
| 818 |
+
# hexadecimal or number seed, case-insensitive
|
| 819 |
+
pattern = re.compile(r'np.random.default_rng\((0x[0-9A-F]+|\d+)\)', re.I)
|
| 820 |
+
|
| 821 |
+
def _wrapped(*args, **kwargs):
|
| 822 |
+
res = func(*args, **kwargs)
|
| 823 |
+
lines = [
|
| 824 |
+
re.sub(pattern, 'np.random.default_rng()', line)
|
| 825 |
+
for line in res
|
| 826 |
+
]
|
| 827 |
+
return lines
|
| 828 |
+
|
| 829 |
+
return _wrapped
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
def _argmin(a, keepdims=False, axis=None):
|
| 833 |
+
"""
|
| 834 |
+
argmin with a `keepdims` parameter.
|
| 835 |
+
|
| 836 |
+
See https://github.com/numpy/numpy/issues/8710
|
| 837 |
+
|
| 838 |
+
If axis is not None, a.shape[axis] must be greater than 0.
|
| 839 |
+
"""
|
| 840 |
+
res = np.argmin(a, axis=axis)
|
| 841 |
+
if keepdims and axis is not None:
|
| 842 |
+
res = np.expand_dims(res, axis=axis)
|
| 843 |
+
return res
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def _first_nonnan(a, axis):
|
| 847 |
+
"""
|
| 848 |
+
Return the first non-nan value along the given axis.
|
| 849 |
+
|
| 850 |
+
If a slice is all nan, nan is returned for that slice.
|
| 851 |
+
|
| 852 |
+
The shape of the return value corresponds to ``keepdims=True``.
|
| 853 |
+
|
| 854 |
+
Examples
|
| 855 |
+
--------
|
| 856 |
+
>>> import numpy as np
|
| 857 |
+
>>> nan = np.nan
|
| 858 |
+
>>> a = np.array([[ 3., 3., nan, 3.],
|
| 859 |
+
[ 1., nan, 2., 4.],
|
| 860 |
+
[nan, nan, 9., -1.],
|
| 861 |
+
[nan, 5., 4., 3.],
|
| 862 |
+
[ 2., 2., 2., 2.],
|
| 863 |
+
[nan, nan, nan, nan]])
|
| 864 |
+
>>> _first_nonnan(a, axis=0)
|
| 865 |
+
array([[3., 3., 2., 3.]])
|
| 866 |
+
>>> _first_nonnan(a, axis=1)
|
| 867 |
+
array([[ 3.],
|
| 868 |
+
[ 1.],
|
| 869 |
+
[ 9.],
|
| 870 |
+
[ 5.],
|
| 871 |
+
[ 2.],
|
| 872 |
+
[nan]])
|
| 873 |
+
"""
|
| 874 |
+
k = _argmin(np.isnan(a), axis=axis, keepdims=True)
|
| 875 |
+
return np.take_along_axis(a, k, axis=axis)
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def _nan_allsame(a, axis, keepdims=False):
|
| 879 |
+
"""
|
| 880 |
+
Determine if the values along an axis are all the same.
|
| 881 |
+
|
| 882 |
+
nan values are ignored.
|
| 883 |
+
|
| 884 |
+
`a` must be a numpy array.
|
| 885 |
+
|
| 886 |
+
`axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.
|
| 887 |
+
|
| 888 |
+
For an axis of length 0, the result is True. That is, we adopt the
|
| 889 |
+
convention that ``allsame([])`` is True. (There are no values in the
|
| 890 |
+
input that are different.)
|
| 891 |
+
|
| 892 |
+
`True` is returned for slices that are all nan--not because all the
|
| 893 |
+
values are the same, but because this is equivalent to ``allsame([])``.
|
| 894 |
+
|
| 895 |
+
Examples
|
| 896 |
+
--------
|
| 897 |
+
>>> from numpy import nan, array
|
| 898 |
+
>>> a = array([[ 3., 3., nan, 3.],
|
| 899 |
+
... [ 1., nan, 2., 4.],
|
| 900 |
+
... [nan, nan, 9., -1.],
|
| 901 |
+
... [nan, 5., 4., 3.],
|
| 902 |
+
... [ 2., 2., 2., 2.],
|
| 903 |
+
... [nan, nan, nan, nan]])
|
| 904 |
+
>>> _nan_allsame(a, axis=1, keepdims=True)
|
| 905 |
+
array([[ True],
|
| 906 |
+
[False],
|
| 907 |
+
[False],
|
| 908 |
+
[False],
|
| 909 |
+
[ True],
|
| 910 |
+
[ True]])
|
| 911 |
+
"""
|
| 912 |
+
if axis is None:
|
| 913 |
+
if a.size == 0:
|
| 914 |
+
return True
|
| 915 |
+
a = a.ravel()
|
| 916 |
+
axis = 0
|
| 917 |
+
else:
|
| 918 |
+
shp = a.shape
|
| 919 |
+
if shp[axis] == 0:
|
| 920 |
+
shp = shp[:axis] + (1,)*keepdims + shp[axis + 1:]
|
| 921 |
+
return np.full(shp, fill_value=True, dtype=bool)
|
| 922 |
+
a0 = _first_nonnan(a, axis=axis)
|
| 923 |
+
return ((a0 == a) | np.isnan(a)).all(axis=axis, keepdims=keepdims)
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
def _contains_nan(a, nan_policy='propagate', policies=None, *,
|
| 927 |
+
xp_omit_okay=False, xp=None):
|
| 928 |
+
# Regarding `xp_omit_okay`: Temporarily, while `_axis_nan_policy` does not
|
| 929 |
+
# handle non-NumPy arrays, most functions that call `_contains_nan` want
|
| 930 |
+
# it to raise an error if `nan_policy='omit'` and `xp` is not `np`.
|
| 931 |
+
# Some functions support `nan_policy='omit'` natively, so setting this to
|
| 932 |
+
# `True` prevents the error from being raised.
|
| 933 |
+
if xp is None:
|
| 934 |
+
xp = array_namespace(a)
|
| 935 |
+
not_numpy = not is_numpy(xp)
|
| 936 |
+
|
| 937 |
+
if policies is None:
|
| 938 |
+
policies = {'propagate', 'raise', 'omit'}
|
| 939 |
+
if nan_policy not in policies:
|
| 940 |
+
raise ValueError(f"nan_policy must be one of {set(policies)}.")
|
| 941 |
+
|
| 942 |
+
if xp_size(a) == 0:
|
| 943 |
+
contains_nan = False
|
| 944 |
+
elif xp.isdtype(a.dtype, "real floating"):
|
| 945 |
+
# Faster and less memory-intensive than xp.any(xp.isnan(a)), and unlike other
|
| 946 |
+
# reductions, `max`/`min` won't return NaN unless there is a NaN in the data.
|
| 947 |
+
contains_nan = xp.isnan(xp.max(a))
|
| 948 |
+
elif xp.isdtype(a.dtype, "complex floating"):
|
| 949 |
+
# Typically `real` and `imag` produce views; otherwise, `xp.any(xp.isnan(a))`
|
| 950 |
+
# would be more efficient.
|
| 951 |
+
contains_nan = xp.isnan(xp.max(xp.real(a))) | xp.isnan(xp.max(xp.imag(a)))
|
| 952 |
+
elif is_numpy(xp) and np.issubdtype(a.dtype, object):
|
| 953 |
+
contains_nan = False
|
| 954 |
+
for el in a.ravel():
|
| 955 |
+
# isnan doesn't work on non-numeric elements
|
| 956 |
+
if np.issubdtype(type(el), np.number) and np.isnan(el):
|
| 957 |
+
contains_nan = True
|
| 958 |
+
break
|
| 959 |
+
else:
|
| 960 |
+
# Only `object` and `inexact` arrays can have NaNs
|
| 961 |
+
contains_nan = False
|
| 962 |
+
|
| 963 |
+
if contains_nan and nan_policy == 'raise':
|
| 964 |
+
raise ValueError("The input contains nan values")
|
| 965 |
+
|
| 966 |
+
if not xp_omit_okay and not_numpy and contains_nan and nan_policy=='omit':
|
| 967 |
+
message = "`nan_policy='omit' is incompatible with non-NumPy arrays."
|
| 968 |
+
raise ValueError(message)
|
| 969 |
+
|
| 970 |
+
return contains_nan, nan_policy
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def _rename_parameter(old_name, new_name, dep_version=None):
|
| 974 |
+
"""
|
| 975 |
+
Generate decorator for backward-compatible keyword renaming.
|
| 976 |
+
|
| 977 |
+
Apply the decorator generated by `_rename_parameter` to functions with a
|
| 978 |
+
recently renamed parameter to maintain backward-compatibility.
|
| 979 |
+
|
| 980 |
+
After decoration, the function behaves as follows:
|
| 981 |
+
If only the new parameter is passed into the function, behave as usual.
|
| 982 |
+
If only the old parameter is passed into the function (as a keyword), raise
|
| 983 |
+
a DeprecationWarning if `dep_version` is provided, and behave as usual
|
| 984 |
+
otherwise.
|
| 985 |
+
If both old and new parameters are passed into the function, raise a
|
| 986 |
+
DeprecationWarning if `dep_version` is provided, and raise the appropriate
|
| 987 |
+
TypeError (function got multiple values for argument).
|
| 988 |
+
|
| 989 |
+
Parameters
|
| 990 |
+
----------
|
| 991 |
+
old_name : str
|
| 992 |
+
Old name of parameter
|
| 993 |
+
new_name : str
|
| 994 |
+
New name of parameter
|
| 995 |
+
dep_version : str, optional
|
| 996 |
+
Version of SciPy in which old parameter was deprecated in the format
|
| 997 |
+
'X.Y.Z'. If supplied, the deprecation message will indicate that
|
| 998 |
+
support for the old parameter will be removed in version 'X.Y+2.Z'
|
| 999 |
+
|
| 1000 |
+
Notes
|
| 1001 |
+
-----
|
| 1002 |
+
Untested with functions that accept *args. Probably won't work as written.
|
| 1003 |
+
|
| 1004 |
+
"""
|
| 1005 |
+
def decorator(fun):
|
| 1006 |
+
@functools.wraps(fun)
|
| 1007 |
+
def wrapper(*args, **kwargs):
|
| 1008 |
+
if old_name in kwargs:
|
| 1009 |
+
if dep_version:
|
| 1010 |
+
end_version = dep_version.split('.')
|
| 1011 |
+
end_version[1] = str(int(end_version[1]) + 2)
|
| 1012 |
+
end_version = '.'.join(end_version)
|
| 1013 |
+
message = (f"Use of keyword argument `{old_name}` is "
|
| 1014 |
+
f"deprecated and replaced by `{new_name}`. "
|
| 1015 |
+
f"Support for `{old_name}` will be removed "
|
| 1016 |
+
f"in SciPy {end_version}.")
|
| 1017 |
+
warnings.warn(message, DeprecationWarning, stacklevel=2)
|
| 1018 |
+
if new_name in kwargs:
|
| 1019 |
+
message = (f"{fun.__name__}() got multiple values for "
|
| 1020 |
+
f"argument now known as `{new_name}`")
|
| 1021 |
+
raise TypeError(message)
|
| 1022 |
+
kwargs[new_name] = kwargs.pop(old_name)
|
| 1023 |
+
return fun(*args, **kwargs)
|
| 1024 |
+
return wrapper
|
| 1025 |
+
return decorator
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
def _rng_spawn(rng, n_children):
|
| 1029 |
+
# spawns independent RNGs from a parent RNG
|
| 1030 |
+
bg = rng._bit_generator
|
| 1031 |
+
ss = bg._seed_seq
|
| 1032 |
+
child_rngs = [np.random.Generator(type(bg)(child_ss))
|
| 1033 |
+
for child_ss in ss.spawn(n_children)]
|
| 1034 |
+
return child_rngs
|
| 1035 |
+
|
| 1036 |
+
|
| 1037 |
+
def _get_nan(*data, xp=None):
|
| 1038 |
+
xp = array_namespace(*data) if xp is None else xp
|
| 1039 |
+
# Get NaN of appropriate dtype for data
|
| 1040 |
+
data = [xp.asarray(item) for item in data]
|
| 1041 |
+
try:
|
| 1042 |
+
min_float = getattr(xp, 'float16', xp.float32)
|
| 1043 |
+
dtype = xp.result_type(*data, min_float) # must be at least a float
|
| 1044 |
+
except DTypePromotionError:
|
| 1045 |
+
# fallback to float64
|
| 1046 |
+
dtype = xp.float64
|
| 1047 |
+
return xp.asarray(xp.nan, dtype=dtype)[()]
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
def normalize_axis_index(axis, ndim):
|
| 1051 |
+
# Check if `axis` is in the correct range and normalize it
|
| 1052 |
+
if axis < -ndim or axis >= ndim:
|
| 1053 |
+
msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
|
| 1054 |
+
raise AxisError(msg)
|
| 1055 |
+
|
| 1056 |
+
if axis < 0:
|
| 1057 |
+
axis = axis + ndim
|
| 1058 |
+
return axis
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
def _call_callback_maybe_halt(callback, res):
|
| 1062 |
+
"""Call wrapped callback; return True if algorithm should stop.
|
| 1063 |
+
|
| 1064 |
+
Parameters
|
| 1065 |
+
----------
|
| 1066 |
+
callback : callable or None
|
| 1067 |
+
A user-provided callback wrapped with `_wrap_callback`
|
| 1068 |
+
res : OptimizeResult
|
| 1069 |
+
Information about the current iterate
|
| 1070 |
+
|
| 1071 |
+
Returns
|
| 1072 |
+
-------
|
| 1073 |
+
halt : bool
|
| 1074 |
+
True if minimization should stop
|
| 1075 |
+
|
| 1076 |
+
"""
|
| 1077 |
+
if callback is None:
|
| 1078 |
+
return False
|
| 1079 |
+
try:
|
| 1080 |
+
callback(res)
|
| 1081 |
+
return False
|
| 1082 |
+
except StopIteration:
|
| 1083 |
+
callback.stop_iteration = True
|
| 1084 |
+
return True
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
class _RichResult(dict):
|
| 1088 |
+
""" Container for multiple outputs with pretty-printing """
|
| 1089 |
+
def __getattr__(self, name):
|
| 1090 |
+
try:
|
| 1091 |
+
return self[name]
|
| 1092 |
+
except KeyError as e:
|
| 1093 |
+
raise AttributeError(name) from e
|
| 1094 |
+
|
| 1095 |
+
__setattr__ = dict.__setitem__ # type: ignore[assignment]
|
| 1096 |
+
__delattr__ = dict.__delitem__ # type: ignore[assignment]
|
| 1097 |
+
|
| 1098 |
+
def __repr__(self):
|
| 1099 |
+
order_keys = ['message', 'success', 'status', 'fun', 'funl', 'x', 'xl',
|
| 1100 |
+
'col_ind', 'nit', 'lower', 'upper', 'eqlin', 'ineqlin',
|
| 1101 |
+
'converged', 'flag', 'function_calls', 'iterations',
|
| 1102 |
+
'root']
|
| 1103 |
+
order_keys = getattr(self, '_order_keys', order_keys)
|
| 1104 |
+
# 'slack', 'con' are redundant with residuals
|
| 1105 |
+
# 'crossover_nit' is probably not interesting to most users
|
| 1106 |
+
omit_keys = {'slack', 'con', 'crossover_nit', '_order_keys'}
|
| 1107 |
+
|
| 1108 |
+
def key(item):
|
| 1109 |
+
try:
|
| 1110 |
+
return order_keys.index(item[0].lower())
|
| 1111 |
+
except ValueError: # item not in list
|
| 1112 |
+
return np.inf
|
| 1113 |
+
|
| 1114 |
+
def omit_redundant(items):
|
| 1115 |
+
for item in items:
|
| 1116 |
+
if item[0] in omit_keys:
|
| 1117 |
+
continue
|
| 1118 |
+
yield item
|
| 1119 |
+
|
| 1120 |
+
def item_sorter(d):
|
| 1121 |
+
return sorted(omit_redundant(d.items()), key=key)
|
| 1122 |
+
|
| 1123 |
+
if self.keys():
|
| 1124 |
+
return _dict_formatter(self, sorter=item_sorter)
|
| 1125 |
+
else:
|
| 1126 |
+
return self.__class__.__name__ + "()"
|
| 1127 |
+
|
| 1128 |
+
def __dir__(self):
|
| 1129 |
+
return list(self.keys())
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
def _indenter(s, n=0):
|
| 1133 |
+
"""
|
| 1134 |
+
Ensures that lines after the first are indented by the specified amount
|
| 1135 |
+
"""
|
| 1136 |
+
split = s.split("\n")
|
| 1137 |
+
indent = " "*n
|
| 1138 |
+
return ("\n" + indent).join(split)
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
def _float_formatter_10(x):
|
| 1142 |
+
"""
|
| 1143 |
+
Returns a string representation of a float with exactly ten characters
|
| 1144 |
+
"""
|
| 1145 |
+
if np.isposinf(x):
|
| 1146 |
+
return " inf"
|
| 1147 |
+
elif np.isneginf(x):
|
| 1148 |
+
return " -inf"
|
| 1149 |
+
elif np.isnan(x):
|
| 1150 |
+
return " nan"
|
| 1151 |
+
return np.format_float_scientific(x, precision=3, pad_left=2, unique=False)
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
def _dict_formatter(d, n=0, mplus=1, sorter=None):
|
| 1155 |
+
"""
|
| 1156 |
+
Pretty printer for dictionaries
|
| 1157 |
+
|
| 1158 |
+
`n` keeps track of the starting indentation;
|
| 1159 |
+
lines are indented by this much after a line break.
|
| 1160 |
+
`mplus` is additional left padding applied to keys
|
| 1161 |
+
"""
|
| 1162 |
+
if isinstance(d, dict):
|
| 1163 |
+
m = max(map(len, list(d.keys()))) + mplus # width to print keys
|
| 1164 |
+
s = '\n'.join([k.rjust(m) + ': ' + # right justified, width m
|
| 1165 |
+
_indenter(_dict_formatter(v, m+n+2, 0, sorter), m+2)
|
| 1166 |
+
for k, v in sorter(d)]) # +2 for ': '
|
| 1167 |
+
else:
|
| 1168 |
+
# By default, NumPy arrays print with linewidth=76. `n` is
|
| 1169 |
+
# the indent at which a line begins printing, so it is subtracted
|
| 1170 |
+
# from the default to avoid exceeding 76 characters total.
|
| 1171 |
+
# `edgeitems` is the number of elements to include before and after
|
| 1172 |
+
# ellipses when arrays are not shown in full.
|
| 1173 |
+
# `threshold` is the maximum number of elements for which an
|
| 1174 |
+
# array is shown in full.
|
| 1175 |
+
# These values tend to work well for use with OptimizeResult.
|
| 1176 |
+
with np.printoptions(linewidth=76-n, edgeitems=2, threshold=12,
|
| 1177 |
+
formatter={'float_kind': _float_formatter_10}):
|
| 1178 |
+
s = str(d)
|
| 1179 |
+
return s
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.21 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc
ADDED
|
Binary file (1.56 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from ._helpers import * # noqa: F403
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (273 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc
ADDED
|
Binary file (12.4 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc
ADDED
|
Binary file (3.33 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc
ADDED
|
Binary file (19.5 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc
ADDED
|
Binary file (5.89 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
These are functions that are just aliases of existing functions in NumPy.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from typing import TYPE_CHECKING
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from typing import Optional, Sequence, Tuple, Union
|
| 10 |
+
from ._typing import ndarray, Device, Dtype
|
| 11 |
+
|
| 12 |
+
from typing import NamedTuple
|
| 13 |
+
import inspect
|
| 14 |
+
|
| 15 |
+
from ._helpers import array_namespace, _check_device, device, is_torch_array, is_cupy_namespace
|
| 16 |
+
|
| 17 |
+
# These functions are modified from the NumPy versions.
|
| 18 |
+
|
| 19 |
+
# Creation functions add the device keyword (which does nothing for NumPy)
|
| 20 |
+
|
| 21 |
+
def arange(
|
| 22 |
+
start: Union[int, float],
|
| 23 |
+
/,
|
| 24 |
+
stop: Optional[Union[int, float]] = None,
|
| 25 |
+
step: Union[int, float] = 1,
|
| 26 |
+
*,
|
| 27 |
+
xp,
|
| 28 |
+
dtype: Optional[Dtype] = None,
|
| 29 |
+
device: Optional[Device] = None,
|
| 30 |
+
**kwargs
|
| 31 |
+
) -> ndarray:
|
| 32 |
+
_check_device(xp, device)
|
| 33 |
+
return xp.arange(start, stop=stop, step=step, dtype=dtype, **kwargs)
|
| 34 |
+
|
| 35 |
+
def empty(
|
| 36 |
+
shape: Union[int, Tuple[int, ...]],
|
| 37 |
+
xp,
|
| 38 |
+
*,
|
| 39 |
+
dtype: Optional[Dtype] = None,
|
| 40 |
+
device: Optional[Device] = None,
|
| 41 |
+
**kwargs
|
| 42 |
+
) -> ndarray:
|
| 43 |
+
_check_device(xp, device)
|
| 44 |
+
return xp.empty(shape, dtype=dtype, **kwargs)
|
| 45 |
+
|
| 46 |
+
def empty_like(
|
| 47 |
+
x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
|
| 48 |
+
**kwargs
|
| 49 |
+
) -> ndarray:
|
| 50 |
+
_check_device(xp, device)
|
| 51 |
+
return xp.empty_like(x, dtype=dtype, **kwargs)
|
| 52 |
+
|
| 53 |
+
def eye(
|
| 54 |
+
n_rows: int,
|
| 55 |
+
n_cols: Optional[int] = None,
|
| 56 |
+
/,
|
| 57 |
+
*,
|
| 58 |
+
xp,
|
| 59 |
+
k: int = 0,
|
| 60 |
+
dtype: Optional[Dtype] = None,
|
| 61 |
+
device: Optional[Device] = None,
|
| 62 |
+
**kwargs,
|
| 63 |
+
) -> ndarray:
|
| 64 |
+
_check_device(xp, device)
|
| 65 |
+
return xp.eye(n_rows, M=n_cols, k=k, dtype=dtype, **kwargs)
|
| 66 |
+
|
| 67 |
+
def full(
|
| 68 |
+
shape: Union[int, Tuple[int, ...]],
|
| 69 |
+
fill_value: Union[int, float],
|
| 70 |
+
xp,
|
| 71 |
+
*,
|
| 72 |
+
dtype: Optional[Dtype] = None,
|
| 73 |
+
device: Optional[Device] = None,
|
| 74 |
+
**kwargs,
|
| 75 |
+
) -> ndarray:
|
| 76 |
+
_check_device(xp, device)
|
| 77 |
+
return xp.full(shape, fill_value, dtype=dtype, **kwargs)
|
| 78 |
+
|
| 79 |
+
def full_like(
|
| 80 |
+
x: ndarray,
|
| 81 |
+
/,
|
| 82 |
+
fill_value: Union[int, float],
|
| 83 |
+
*,
|
| 84 |
+
xp,
|
| 85 |
+
dtype: Optional[Dtype] = None,
|
| 86 |
+
device: Optional[Device] = None,
|
| 87 |
+
**kwargs,
|
| 88 |
+
) -> ndarray:
|
| 89 |
+
_check_device(xp, device)
|
| 90 |
+
return xp.full_like(x, fill_value, dtype=dtype, **kwargs)
|
| 91 |
+
|
| 92 |
+
def linspace(
|
| 93 |
+
start: Union[int, float],
|
| 94 |
+
stop: Union[int, float],
|
| 95 |
+
/,
|
| 96 |
+
num: int,
|
| 97 |
+
*,
|
| 98 |
+
xp,
|
| 99 |
+
dtype: Optional[Dtype] = None,
|
| 100 |
+
device: Optional[Device] = None,
|
| 101 |
+
endpoint: bool = True,
|
| 102 |
+
**kwargs,
|
| 103 |
+
) -> ndarray:
|
| 104 |
+
_check_device(xp, device)
|
| 105 |
+
return xp.linspace(start, stop, num, dtype=dtype, endpoint=endpoint, **kwargs)
|
| 106 |
+
|
| 107 |
+
def ones(
|
| 108 |
+
shape: Union[int, Tuple[int, ...]],
|
| 109 |
+
xp,
|
| 110 |
+
*,
|
| 111 |
+
dtype: Optional[Dtype] = None,
|
| 112 |
+
device: Optional[Device] = None,
|
| 113 |
+
**kwargs,
|
| 114 |
+
) -> ndarray:
|
| 115 |
+
_check_device(xp, device)
|
| 116 |
+
return xp.ones(shape, dtype=dtype, **kwargs)
|
| 117 |
+
|
| 118 |
+
def ones_like(
|
| 119 |
+
x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
|
| 120 |
+
**kwargs,
|
| 121 |
+
) -> ndarray:
|
| 122 |
+
_check_device(xp, device)
|
| 123 |
+
return xp.ones_like(x, dtype=dtype, **kwargs)
|
| 124 |
+
|
| 125 |
+
def zeros(
|
| 126 |
+
shape: Union[int, Tuple[int, ...]],
|
| 127 |
+
xp,
|
| 128 |
+
*,
|
| 129 |
+
dtype: Optional[Dtype] = None,
|
| 130 |
+
device: Optional[Device] = None,
|
| 131 |
+
**kwargs,
|
| 132 |
+
) -> ndarray:
|
| 133 |
+
_check_device(xp, device)
|
| 134 |
+
return xp.zeros(shape, dtype=dtype, **kwargs)
|
| 135 |
+
|
| 136 |
+
def zeros_like(
|
| 137 |
+
x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
|
| 138 |
+
**kwargs,
|
| 139 |
+
) -> ndarray:
|
| 140 |
+
_check_device(xp, device)
|
| 141 |
+
return xp.zeros_like(x, dtype=dtype, **kwargs)
|
| 142 |
+
|
| 143 |
+
# np.unique() is split into four functions in the array API:
|
| 144 |
+
# unique_all, unique_counts, unique_inverse, and unique_values (this is done
|
| 145 |
+
# to remove polymorphic return types).
|
| 146 |
+
|
| 147 |
+
# The functions here return namedtuples (np.unique() returns a normal
|
| 148 |
+
# tuple).
|
| 149 |
+
|
| 150 |
+
# Note that these named tuples aren't actually part of the standard namespace,
|
| 151 |
+
# but I don't see any issue with exporting the names here regardless.
|
| 152 |
+
class UniqueAllResult(NamedTuple):
|
| 153 |
+
values: ndarray
|
| 154 |
+
indices: ndarray
|
| 155 |
+
inverse_indices: ndarray
|
| 156 |
+
counts: ndarray
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class UniqueCountsResult(NamedTuple):
|
| 160 |
+
values: ndarray
|
| 161 |
+
counts: ndarray
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class UniqueInverseResult(NamedTuple):
|
| 165 |
+
values: ndarray
|
| 166 |
+
inverse_indices: ndarray
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _unique_kwargs(xp):
|
| 170 |
+
# Older versions of NumPy and CuPy do not have equal_nan. Rather than
|
| 171 |
+
# trying to parse version numbers, just check if equal_nan is in the
|
| 172 |
+
# signature.
|
| 173 |
+
s = inspect.signature(xp.unique)
|
| 174 |
+
if 'equal_nan' in s.parameters:
|
| 175 |
+
return {'equal_nan': False}
|
| 176 |
+
return {}
|
| 177 |
+
|
| 178 |
+
def unique_all(x: ndarray, /, xp) -> UniqueAllResult:
|
| 179 |
+
kwargs = _unique_kwargs(xp)
|
| 180 |
+
values, indices, inverse_indices, counts = xp.unique(
|
| 181 |
+
x,
|
| 182 |
+
return_counts=True,
|
| 183 |
+
return_index=True,
|
| 184 |
+
return_inverse=True,
|
| 185 |
+
**kwargs,
|
| 186 |
+
)
|
| 187 |
+
# np.unique() flattens inverse indices, but they need to share x's shape
|
| 188 |
+
# See https://github.com/numpy/numpy/issues/20638
|
| 189 |
+
inverse_indices = inverse_indices.reshape(x.shape)
|
| 190 |
+
return UniqueAllResult(
|
| 191 |
+
values,
|
| 192 |
+
indices,
|
| 193 |
+
inverse_indices,
|
| 194 |
+
counts,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def unique_counts(x: ndarray, /, xp) -> UniqueCountsResult:
|
| 199 |
+
kwargs = _unique_kwargs(xp)
|
| 200 |
+
res = xp.unique(
|
| 201 |
+
x,
|
| 202 |
+
return_counts=True,
|
| 203 |
+
return_index=False,
|
| 204 |
+
return_inverse=False,
|
| 205 |
+
**kwargs
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
return UniqueCountsResult(*res)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def unique_inverse(x: ndarray, /, xp) -> UniqueInverseResult:
|
| 212 |
+
kwargs = _unique_kwargs(xp)
|
| 213 |
+
values, inverse_indices = xp.unique(
|
| 214 |
+
x,
|
| 215 |
+
return_counts=False,
|
| 216 |
+
return_index=False,
|
| 217 |
+
return_inverse=True,
|
| 218 |
+
**kwargs,
|
| 219 |
+
)
|
| 220 |
+
# xp.unique() flattens inverse indices, but they need to share x's shape
|
| 221 |
+
# See https://github.com/numpy/numpy/issues/20638
|
| 222 |
+
inverse_indices = inverse_indices.reshape(x.shape)
|
| 223 |
+
return UniqueInverseResult(values, inverse_indices)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def unique_values(x: ndarray, /, xp) -> ndarray:
|
| 227 |
+
kwargs = _unique_kwargs(xp)
|
| 228 |
+
return xp.unique(
|
| 229 |
+
x,
|
| 230 |
+
return_counts=False,
|
| 231 |
+
return_index=False,
|
| 232 |
+
return_inverse=False,
|
| 233 |
+
**kwargs,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def astype(x: ndarray, dtype: Dtype, /, *, copy: bool = True) -> ndarray:
|
| 237 |
+
if not copy and dtype == x.dtype:
|
| 238 |
+
return x
|
| 239 |
+
return x.astype(dtype=dtype, copy=copy)
|
| 240 |
+
|
| 241 |
+
# These functions have different keyword argument names
|
| 242 |
+
|
| 243 |
+
def std(
|
| 244 |
+
x: ndarray,
|
| 245 |
+
/,
|
| 246 |
+
xp,
|
| 247 |
+
*,
|
| 248 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
| 249 |
+
correction: Union[int, float] = 0.0, # correction instead of ddof
|
| 250 |
+
keepdims: bool = False,
|
| 251 |
+
**kwargs,
|
| 252 |
+
) -> ndarray:
|
| 253 |
+
return xp.std(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
|
| 254 |
+
|
| 255 |
+
def var(
|
| 256 |
+
x: ndarray,
|
| 257 |
+
/,
|
| 258 |
+
xp,
|
| 259 |
+
*,
|
| 260 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
| 261 |
+
correction: Union[int, float] = 0.0, # correction instead of ddof
|
| 262 |
+
keepdims: bool = False,
|
| 263 |
+
**kwargs,
|
| 264 |
+
) -> ndarray:
|
| 265 |
+
return xp.var(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
|
| 266 |
+
|
| 267 |
+
# cumulative_sum is renamed from cumsum, and adds the include_initial keyword
|
| 268 |
+
# argument
|
| 269 |
+
|
| 270 |
+
def cumulative_sum(
|
| 271 |
+
x: ndarray,
|
| 272 |
+
/,
|
| 273 |
+
xp,
|
| 274 |
+
*,
|
| 275 |
+
axis: Optional[int] = None,
|
| 276 |
+
dtype: Optional[Dtype] = None,
|
| 277 |
+
include_initial: bool = False,
|
| 278 |
+
**kwargs
|
| 279 |
+
) -> ndarray:
|
| 280 |
+
wrapped_xp = array_namespace(x)
|
| 281 |
+
|
| 282 |
+
# TODO: The standard is not clear about what should happen when x.ndim == 0.
|
| 283 |
+
if axis is None:
|
| 284 |
+
if x.ndim > 1:
|
| 285 |
+
raise ValueError("axis must be specified in cumulative_sum for more than one dimension")
|
| 286 |
+
axis = 0
|
| 287 |
+
|
| 288 |
+
res = xp.cumsum(x, axis=axis, dtype=dtype, **kwargs)
|
| 289 |
+
|
| 290 |
+
# np.cumsum does not support include_initial
|
| 291 |
+
if include_initial:
|
| 292 |
+
initial_shape = list(x.shape)
|
| 293 |
+
initial_shape[axis] = 1
|
| 294 |
+
res = xp.concatenate(
|
| 295 |
+
[wrapped_xp.zeros(shape=initial_shape, dtype=res.dtype, device=device(res)), res],
|
| 296 |
+
axis=axis,
|
| 297 |
+
)
|
| 298 |
+
return res
|
| 299 |
+
|
| 300 |
+
# The min and max argument names in clip are different and not optional in numpy, and type
|
| 301 |
+
# promotion behavior is different.
|
| 302 |
+
def clip(
|
| 303 |
+
x: ndarray,
|
| 304 |
+
/,
|
| 305 |
+
min: Optional[Union[int, float, ndarray]] = None,
|
| 306 |
+
max: Optional[Union[int, float, ndarray]] = None,
|
| 307 |
+
*,
|
| 308 |
+
xp,
|
| 309 |
+
# TODO: np.clip has other ufunc kwargs
|
| 310 |
+
out: Optional[ndarray] = None,
|
| 311 |
+
) -> ndarray:
|
| 312 |
+
def _isscalar(a):
|
| 313 |
+
return isinstance(a, (int, float, type(None)))
|
| 314 |
+
min_shape = () if _isscalar(min) else min.shape
|
| 315 |
+
max_shape = () if _isscalar(max) else max.shape
|
| 316 |
+
|
| 317 |
+
wrapped_xp = array_namespace(x)
|
| 318 |
+
|
| 319 |
+
result_shape = xp.broadcast_shapes(x.shape, min_shape, max_shape)
|
| 320 |
+
|
| 321 |
+
# np.clip does type promotion but the array API clip requires that the
|
| 322 |
+
# output have the same dtype as x. We do this instead of just downcasting
|
| 323 |
+
# the result of xp.clip() to handle some corner cases better (e.g.,
|
| 324 |
+
# avoiding uint64 -> float64 promotion).
|
| 325 |
+
|
| 326 |
+
# Note: cases where min or max overflow (integer) or round (float) in the
|
| 327 |
+
# wrong direction when downcasting to x.dtype are unspecified. This code
|
| 328 |
+
# just does whatever NumPy does when it downcasts in the assignment, but
|
| 329 |
+
# other behavior could be preferred, especially for integers. For example,
|
| 330 |
+
# this code produces:
|
| 331 |
+
|
| 332 |
+
# >>> clip(asarray(0, dtype=int8), asarray(128, dtype=int16), None)
|
| 333 |
+
# -128
|
| 334 |
+
|
| 335 |
+
# but an answer of 0 might be preferred. See
|
| 336 |
+
# https://github.com/numpy/numpy/issues/24976 for more discussion on this issue.
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# At least handle the case of Python integers correctly (see
|
| 340 |
+
# https://github.com/numpy/numpy/pull/26892).
|
| 341 |
+
if type(min) is int and min <= wrapped_xp.iinfo(x.dtype).min:
|
| 342 |
+
min = None
|
| 343 |
+
if type(max) is int and max >= wrapped_xp.iinfo(x.dtype).max:
|
| 344 |
+
max = None
|
| 345 |
+
|
| 346 |
+
if out is None:
|
| 347 |
+
out = wrapped_xp.asarray(xp.broadcast_to(x, result_shape),
|
| 348 |
+
copy=True, device=device(x))
|
| 349 |
+
if min is not None:
|
| 350 |
+
if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(min):
|
| 351 |
+
# Avoid loss of precision due to torch defaulting to float32
|
| 352 |
+
min = wrapped_xp.asarray(min, dtype=xp.float64)
|
| 353 |
+
a = xp.broadcast_to(wrapped_xp.asarray(min, device=device(x)), result_shape)
|
| 354 |
+
ia = (out < a) | xp.isnan(a)
|
| 355 |
+
# torch requires an explicit cast here
|
| 356 |
+
out[ia] = wrapped_xp.astype(a[ia], out.dtype)
|
| 357 |
+
if max is not None:
|
| 358 |
+
if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(max):
|
| 359 |
+
max = wrapped_xp.asarray(max, dtype=xp.float64)
|
| 360 |
+
b = xp.broadcast_to(wrapped_xp.asarray(max, device=device(x)), result_shape)
|
| 361 |
+
ib = (out > b) | xp.isnan(b)
|
| 362 |
+
out[ib] = wrapped_xp.astype(b[ib], out.dtype)
|
| 363 |
+
# Return a scalar for 0-D
|
| 364 |
+
return out[()]
|
| 365 |
+
|
| 366 |
+
# Unlike transpose(), the axes argument to permute_dims() is required.
|
| 367 |
+
def permute_dims(x: ndarray, /, axes: Tuple[int, ...], xp) -> ndarray:
|
| 368 |
+
return xp.transpose(x, axes)
|
| 369 |
+
|
| 370 |
+
# np.reshape calls the keyword argument 'newshape' instead of 'shape'
|
| 371 |
+
def reshape(x: ndarray,
|
| 372 |
+
/,
|
| 373 |
+
shape: Tuple[int, ...],
|
| 374 |
+
xp, copy: Optional[bool] = None,
|
| 375 |
+
**kwargs) -> ndarray:
|
| 376 |
+
if copy is True:
|
| 377 |
+
x = x.copy()
|
| 378 |
+
elif copy is False:
|
| 379 |
+
y = x.view()
|
| 380 |
+
y.shape = shape
|
| 381 |
+
return y
|
| 382 |
+
return xp.reshape(x, shape, **kwargs)
|
| 383 |
+
|
| 384 |
+
# The descending keyword is new in sort and argsort, and 'kind' replaced with
|
| 385 |
+
# 'stable'
|
| 386 |
+
def argsort(
|
| 387 |
+
x: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
|
| 388 |
+
**kwargs,
|
| 389 |
+
) -> ndarray:
|
| 390 |
+
# Note: this keyword argument is different, and the default is different.
|
| 391 |
+
# We set it in kwargs like this because numpy.sort uses kind='quicksort'
|
| 392 |
+
# as the default whereas cupy.sort uses kind=None.
|
| 393 |
+
if stable:
|
| 394 |
+
kwargs['kind'] = "stable"
|
| 395 |
+
if not descending:
|
| 396 |
+
res = xp.argsort(x, axis=axis, **kwargs)
|
| 397 |
+
else:
|
| 398 |
+
# As NumPy has no native descending sort, we imitate it here. Note that
|
| 399 |
+
# simply flipping the results of xp.argsort(x, ...) would not
|
| 400 |
+
# respect the relative order like it would in native descending sorts.
|
| 401 |
+
res = xp.flip(
|
| 402 |
+
xp.argsort(xp.flip(x, axis=axis), axis=axis, **kwargs),
|
| 403 |
+
axis=axis,
|
| 404 |
+
)
|
| 405 |
+
# Rely on flip()/argsort() to validate axis
|
| 406 |
+
normalised_axis = axis if axis >= 0 else x.ndim + axis
|
| 407 |
+
max_i = x.shape[normalised_axis] - 1
|
| 408 |
+
res = max_i - res
|
| 409 |
+
return res
|
| 410 |
+
|
| 411 |
+
def sort(
|
| 412 |
+
x: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
|
| 413 |
+
**kwargs,
|
| 414 |
+
) -> ndarray:
|
| 415 |
+
# Note: this keyword argument is different, and the default is different.
|
| 416 |
+
# We set it in kwargs like this because numpy.sort uses kind='quicksort'
|
| 417 |
+
# as the default whereas cupy.sort uses kind=None.
|
| 418 |
+
if stable:
|
| 419 |
+
kwargs['kind'] = "stable"
|
| 420 |
+
res = xp.sort(x, axis=axis, **kwargs)
|
| 421 |
+
if descending:
|
| 422 |
+
res = xp.flip(res, axis=axis)
|
| 423 |
+
return res
|
| 424 |
+
|
| 425 |
+
# nonzero should error for zero-dimensional arrays
|
| 426 |
+
def nonzero(x: ndarray, /, xp, **kwargs) -> Tuple[ndarray, ...]:
|
| 427 |
+
if x.ndim == 0:
|
| 428 |
+
raise ValueError("nonzero() does not support zero-dimensional arrays")
|
| 429 |
+
return xp.nonzero(x, **kwargs)
|
| 430 |
+
|
| 431 |
+
# ceil, floor, and trunc return integers for integer inputs
|
| 432 |
+
|
| 433 |
+
def ceil(x: ndarray, /, xp, **kwargs) -> ndarray:
|
| 434 |
+
if xp.issubdtype(x.dtype, xp.integer):
|
| 435 |
+
return x
|
| 436 |
+
return xp.ceil(x, **kwargs)
|
| 437 |
+
|
| 438 |
+
def floor(x: ndarray, /, xp, **kwargs) -> ndarray:
|
| 439 |
+
if xp.issubdtype(x.dtype, xp.integer):
|
| 440 |
+
return x
|
| 441 |
+
return xp.floor(x, **kwargs)
|
| 442 |
+
|
| 443 |
+
def trunc(x: ndarray, /, xp, **kwargs) -> ndarray:
|
| 444 |
+
if xp.issubdtype(x.dtype, xp.integer):
|
| 445 |
+
return x
|
| 446 |
+
return xp.trunc(x, **kwargs)
|
| 447 |
+
|
| 448 |
+
# linear algebra functions
|
| 449 |
+
|
| 450 |
+
def matmul(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
|
| 451 |
+
return xp.matmul(x1, x2, **kwargs)
|
| 452 |
+
|
| 453 |
+
# Unlike transpose, matrix_transpose only transposes the last two axes.
|
| 454 |
+
def matrix_transpose(x: ndarray, /, xp) -> ndarray:
|
| 455 |
+
if x.ndim < 2:
|
| 456 |
+
raise ValueError("x must be at least 2-dimensional for matrix_transpose")
|
| 457 |
+
return xp.swapaxes(x, -1, -2)
|
| 458 |
+
|
| 459 |
+
def tensordot(x1: ndarray,
|
| 460 |
+
x2: ndarray,
|
| 461 |
+
/,
|
| 462 |
+
xp,
|
| 463 |
+
*,
|
| 464 |
+
axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2,
|
| 465 |
+
**kwargs,
|
| 466 |
+
) -> ndarray:
|
| 467 |
+
return xp.tensordot(x1, x2, axes=axes, **kwargs)
|
| 468 |
+
|
| 469 |
+
def vecdot(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1) -> ndarray:
|
| 470 |
+
if x1.shape[axis] != x2.shape[axis]:
|
| 471 |
+
raise ValueError("x1 and x2 must have the same size along the given axis")
|
| 472 |
+
|
| 473 |
+
if hasattr(xp, 'broadcast_tensors'):
|
| 474 |
+
_broadcast = xp.broadcast_tensors
|
| 475 |
+
else:
|
| 476 |
+
_broadcast = xp.broadcast_arrays
|
| 477 |
+
|
| 478 |
+
x1_ = xp.moveaxis(x1, axis, -1)
|
| 479 |
+
x2_ = xp.moveaxis(x2, axis, -1)
|
| 480 |
+
x1_, x2_ = _broadcast(x1_, x2_)
|
| 481 |
+
|
| 482 |
+
res = x1_[..., None, :] @ x2_[..., None]
|
| 483 |
+
return res[..., 0, 0]
|
| 484 |
+
|
| 485 |
+
# isdtype is a new function in the 2022.12 array API specification.
|
| 486 |
+
|
| 487 |
+
def isdtype(
|
| 488 |
+
dtype: Dtype, kind: Union[Dtype, str, Tuple[Union[Dtype, str], ...]], xp,
|
| 489 |
+
*, _tuple=True, # Disallow nested tuples
|
| 490 |
+
) -> bool:
|
| 491 |
+
"""
|
| 492 |
+
Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
|
| 493 |
+
|
| 494 |
+
Note that outside of this function, this compat library does not yet fully
|
| 495 |
+
support complex numbers.
|
| 496 |
+
|
| 497 |
+
See
|
| 498 |
+
https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
|
| 499 |
+
for more details
|
| 500 |
+
"""
|
| 501 |
+
if isinstance(kind, tuple) and _tuple:
|
| 502 |
+
return any(isdtype(dtype, k, xp, _tuple=False) for k in kind)
|
| 503 |
+
elif isinstance(kind, str):
|
| 504 |
+
if kind == 'bool':
|
| 505 |
+
return dtype == xp.bool_
|
| 506 |
+
elif kind == 'signed integer':
|
| 507 |
+
return xp.issubdtype(dtype, xp.signedinteger)
|
| 508 |
+
elif kind == 'unsigned integer':
|
| 509 |
+
return xp.issubdtype(dtype, xp.unsignedinteger)
|
| 510 |
+
elif kind == 'integral':
|
| 511 |
+
return xp.issubdtype(dtype, xp.integer)
|
| 512 |
+
elif kind == 'real floating':
|
| 513 |
+
return xp.issubdtype(dtype, xp.floating)
|
| 514 |
+
elif kind == 'complex floating':
|
| 515 |
+
return xp.issubdtype(dtype, xp.complexfloating)
|
| 516 |
+
elif kind == 'numeric':
|
| 517 |
+
return xp.issubdtype(dtype, xp.number)
|
| 518 |
+
else:
|
| 519 |
+
raise ValueError(f"Unrecognized data type kind: {kind!r}")
|
| 520 |
+
else:
|
| 521 |
+
# This will allow things that aren't required by the spec, like
|
| 522 |
+
# isdtype(np.float64, float) or isdtype(np.int64, 'l'). Should we be
|
| 523 |
+
# more strict here to match the type annotation? Note that the
|
| 524 |
+
# array_api_strict implementation will be very strict.
|
| 525 |
+
return dtype == kind
|
| 526 |
+
|
| 527 |
+
# unstack is a new function in the 2023.12 array API standard
|
| 528 |
+
def unstack(x: ndarray, /, xp, *, axis: int = 0) -> Tuple[ndarray, ...]:
|
| 529 |
+
if x.ndim == 0:
|
| 530 |
+
raise ValueError("Input array must be at least 1-d.")
|
| 531 |
+
return tuple(xp.moveaxis(x, axis, 0))
|
| 532 |
+
|
| 533 |
+
# numpy 1.26 does not use the standard definition for sign on complex numbers
|
| 534 |
+
|
| 535 |
+
def sign(x: ndarray, /, xp, **kwargs) -> ndarray:
|
| 536 |
+
if isdtype(x.dtype, 'complex floating', xp=xp):
|
| 537 |
+
out = (x/xp.abs(x, **kwargs))[...]
|
| 538 |
+
# sign(0) = 0 but the above formula would give nan
|
| 539 |
+
out[x == 0+0j] = 0+0j
|
| 540 |
+
else:
|
| 541 |
+
out = xp.sign(x, **kwargs)
|
| 542 |
+
# CuPy sign() does not propagate nans. See
|
| 543 |
+
# https://github.com/data-apis/array-api-compat/issues/136
|
| 544 |
+
if is_cupy_namespace(xp) and isdtype(x.dtype, 'real floating', xp=xp):
|
| 545 |
+
out[xp.isnan(x)] = xp.nan
|
| 546 |
+
return out[()]
|
| 547 |
+
|
| 548 |
+
__all__ = ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like',
|
| 549 |
+
'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like',
|
| 550 |
+
'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult',
|
| 551 |
+
'unique_all', 'unique_counts', 'unique_inverse', 'unique_values',
|
| 552 |
+
'astype', 'std', 'var', 'cumulative_sum', 'clip', 'permute_dims',
|
| 553 |
+
'reshape', 'argsort', 'sort', 'nonzero', 'ceil', 'floor', 'trunc',
|
| 554 |
+
'matmul', 'matrix_transpose', 'tensordot', 'vecdot', 'isdtype',
|
| 555 |
+
'unstack', 'sign']
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Union, Optional, Literal
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from ._typing import Device, ndarray
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
|
| 9 |
+
# Note: NumPy fft functions improperly upcast float32 and complex64 to
|
| 10 |
+
# complex128, which is why we require wrapping them all here.
|
| 11 |
+
|
| 12 |
+
def fft(
|
| 13 |
+
x: ndarray,
|
| 14 |
+
/,
|
| 15 |
+
xp,
|
| 16 |
+
*,
|
| 17 |
+
n: Optional[int] = None,
|
| 18 |
+
axis: int = -1,
|
| 19 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 20 |
+
) -> ndarray:
|
| 21 |
+
res = xp.fft.fft(x, n=n, axis=axis, norm=norm)
|
| 22 |
+
if x.dtype in [xp.float32, xp.complex64]:
|
| 23 |
+
return res.astype(xp.complex64)
|
| 24 |
+
return res
|
| 25 |
+
|
| 26 |
+
def ifft(
|
| 27 |
+
x: ndarray,
|
| 28 |
+
/,
|
| 29 |
+
xp,
|
| 30 |
+
*,
|
| 31 |
+
n: Optional[int] = None,
|
| 32 |
+
axis: int = -1,
|
| 33 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 34 |
+
) -> ndarray:
|
| 35 |
+
res = xp.fft.ifft(x, n=n, axis=axis, norm=norm)
|
| 36 |
+
if x.dtype in [xp.float32, xp.complex64]:
|
| 37 |
+
return res.astype(xp.complex64)
|
| 38 |
+
return res
|
| 39 |
+
|
| 40 |
+
def fftn(
|
| 41 |
+
x: ndarray,
|
| 42 |
+
/,
|
| 43 |
+
xp,
|
| 44 |
+
*,
|
| 45 |
+
s: Sequence[int] = None,
|
| 46 |
+
axes: Sequence[int] = None,
|
| 47 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 48 |
+
) -> ndarray:
|
| 49 |
+
res = xp.fft.fftn(x, s=s, axes=axes, norm=norm)
|
| 50 |
+
if x.dtype in [xp.float32, xp.complex64]:
|
| 51 |
+
return res.astype(xp.complex64)
|
| 52 |
+
return res
|
| 53 |
+
|
| 54 |
+
def ifftn(
|
| 55 |
+
x: ndarray,
|
| 56 |
+
/,
|
| 57 |
+
xp,
|
| 58 |
+
*,
|
| 59 |
+
s: Sequence[int] = None,
|
| 60 |
+
axes: Sequence[int] = None,
|
| 61 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 62 |
+
) -> ndarray:
|
| 63 |
+
res = xp.fft.ifftn(x, s=s, axes=axes, norm=norm)
|
| 64 |
+
if x.dtype in [xp.float32, xp.complex64]:
|
| 65 |
+
return res.astype(xp.complex64)
|
| 66 |
+
return res
|
| 67 |
+
|
| 68 |
+
def rfft(
|
| 69 |
+
x: ndarray,
|
| 70 |
+
/,
|
| 71 |
+
xp,
|
| 72 |
+
*,
|
| 73 |
+
n: Optional[int] = None,
|
| 74 |
+
axis: int = -1,
|
| 75 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 76 |
+
) -> ndarray:
|
| 77 |
+
res = xp.fft.rfft(x, n=n, axis=axis, norm=norm)
|
| 78 |
+
if x.dtype == xp.float32:
|
| 79 |
+
return res.astype(xp.complex64)
|
| 80 |
+
return res
|
| 81 |
+
|
| 82 |
+
def irfft(
|
| 83 |
+
x: ndarray,
|
| 84 |
+
/,
|
| 85 |
+
xp,
|
| 86 |
+
*,
|
| 87 |
+
n: Optional[int] = None,
|
| 88 |
+
axis: int = -1,
|
| 89 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 90 |
+
) -> ndarray:
|
| 91 |
+
res = xp.fft.irfft(x, n=n, axis=axis, norm=norm)
|
| 92 |
+
if x.dtype == xp.complex64:
|
| 93 |
+
return res.astype(xp.float32)
|
| 94 |
+
return res
|
| 95 |
+
|
| 96 |
+
def rfftn(
|
| 97 |
+
x: ndarray,
|
| 98 |
+
/,
|
| 99 |
+
xp,
|
| 100 |
+
*,
|
| 101 |
+
s: Sequence[int] = None,
|
| 102 |
+
axes: Sequence[int] = None,
|
| 103 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 104 |
+
) -> ndarray:
|
| 105 |
+
res = xp.fft.rfftn(x, s=s, axes=axes, norm=norm)
|
| 106 |
+
if x.dtype == xp.float32:
|
| 107 |
+
return res.astype(xp.complex64)
|
| 108 |
+
return res
|
| 109 |
+
|
| 110 |
+
def irfftn(
|
| 111 |
+
x: ndarray,
|
| 112 |
+
/,
|
| 113 |
+
xp,
|
| 114 |
+
*,
|
| 115 |
+
s: Sequence[int] = None,
|
| 116 |
+
axes: Sequence[int] = None,
|
| 117 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 118 |
+
) -> ndarray:
|
| 119 |
+
res = xp.fft.irfftn(x, s=s, axes=axes, norm=norm)
|
| 120 |
+
if x.dtype == xp.complex64:
|
| 121 |
+
return res.astype(xp.float32)
|
| 122 |
+
return res
|
| 123 |
+
|
| 124 |
+
def hfft(
|
| 125 |
+
x: ndarray,
|
| 126 |
+
/,
|
| 127 |
+
xp,
|
| 128 |
+
*,
|
| 129 |
+
n: Optional[int] = None,
|
| 130 |
+
axis: int = -1,
|
| 131 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 132 |
+
) -> ndarray:
|
| 133 |
+
res = xp.fft.hfft(x, n=n, axis=axis, norm=norm)
|
| 134 |
+
if x.dtype in [xp.float32, xp.complex64]:
|
| 135 |
+
return res.astype(xp.float32)
|
| 136 |
+
return res
|
| 137 |
+
|
| 138 |
+
def ihfft(
|
| 139 |
+
x: ndarray,
|
| 140 |
+
/,
|
| 141 |
+
xp,
|
| 142 |
+
*,
|
| 143 |
+
n: Optional[int] = None,
|
| 144 |
+
axis: int = -1,
|
| 145 |
+
norm: Literal["backward", "ortho", "forward"] = "backward",
|
| 146 |
+
) -> ndarray:
|
| 147 |
+
res = xp.fft.ihfft(x, n=n, axis=axis, norm=norm)
|
| 148 |
+
if x.dtype in [xp.float32, xp.complex64]:
|
| 149 |
+
return res.astype(xp.complex64)
|
| 150 |
+
return res
|
| 151 |
+
|
| 152 |
+
def fftfreq(n: int, /, xp, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
|
| 153 |
+
if device not in ["cpu", None]:
|
| 154 |
+
raise ValueError(f"Unsupported device {device!r}")
|
| 155 |
+
return xp.fft.fftfreq(n, d=d)
|
| 156 |
+
|
| 157 |
+
def rfftfreq(n: int, /, xp, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
|
| 158 |
+
if device not in ["cpu", None]:
|
| 159 |
+
raise ValueError(f"Unsupported device {device!r}")
|
| 160 |
+
return xp.fft.rfftfreq(n, d=d)
|
| 161 |
+
|
| 162 |
+
def fftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
|
| 163 |
+
return xp.fft.fftshift(x, axes=axes)
|
| 164 |
+
|
| 165 |
+
def ifftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
|
| 166 |
+
return xp.fft.ifftshift(x, axes=axes)
|
| 167 |
+
|
| 168 |
+
__all__ = [
|
| 169 |
+
"fft",
|
| 170 |
+
"ifft",
|
| 171 |
+
"fftn",
|
| 172 |
+
"ifftn",
|
| 173 |
+
"rfft",
|
| 174 |
+
"irfft",
|
| 175 |
+
"rfftn",
|
| 176 |
+
"irfftn",
|
| 177 |
+
"hfft",
|
| 178 |
+
"ihfft",
|
| 179 |
+
"fftfreq",
|
| 180 |
+
"rfftfreq",
|
| 181 |
+
"fftshift",
|
| 182 |
+
"ifftshift",
|
| 183 |
+
]
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, NamedTuple
|
| 4 |
+
if TYPE_CHECKING:
|
| 5 |
+
from typing import Literal, Optional, Tuple, Union
|
| 6 |
+
from ._typing import ndarray
|
| 7 |
+
|
| 8 |
+
import math
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
if np.__version__[0] == "2":
|
| 12 |
+
from numpy.lib.array_utils import normalize_axis_tuple
|
| 13 |
+
else:
|
| 14 |
+
from numpy.core.numeric import normalize_axis_tuple
|
| 15 |
+
|
| 16 |
+
from ._aliases import matmul, matrix_transpose, tensordot, vecdot, isdtype
|
| 17 |
+
from .._internal import get_xp
|
| 18 |
+
|
| 19 |
+
# These are in the main NumPy namespace but not in numpy.linalg
|
| 20 |
+
def cross(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1, **kwargs) -> ndarray:
|
| 21 |
+
return xp.cross(x1, x2, axis=axis, **kwargs)
|
| 22 |
+
|
| 23 |
+
def outer(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
|
| 24 |
+
return xp.outer(x1, x2, **kwargs)
|
| 25 |
+
|
| 26 |
+
class EighResult(NamedTuple):
|
| 27 |
+
eigenvalues: ndarray
|
| 28 |
+
eigenvectors: ndarray
|
| 29 |
+
|
| 30 |
+
class QRResult(NamedTuple):
|
| 31 |
+
Q: ndarray
|
| 32 |
+
R: ndarray
|
| 33 |
+
|
| 34 |
+
class SlogdetResult(NamedTuple):
|
| 35 |
+
sign: ndarray
|
| 36 |
+
logabsdet: ndarray
|
| 37 |
+
|
| 38 |
+
class SVDResult(NamedTuple):
|
| 39 |
+
U: ndarray
|
| 40 |
+
S: ndarray
|
| 41 |
+
Vh: ndarray
|
| 42 |
+
|
| 43 |
+
# These functions are the same as their NumPy counterparts except they return
|
| 44 |
+
# a namedtuple.
|
| 45 |
+
def eigh(x: ndarray, /, xp, **kwargs) -> EighResult:
|
| 46 |
+
return EighResult(*xp.linalg.eigh(x, **kwargs))
|
| 47 |
+
|
| 48 |
+
def qr(x: ndarray, /, xp, *, mode: Literal['reduced', 'complete'] = 'reduced',
|
| 49 |
+
**kwargs) -> QRResult:
|
| 50 |
+
return QRResult(*xp.linalg.qr(x, mode=mode, **kwargs))
|
| 51 |
+
|
| 52 |
+
def slogdet(x: ndarray, /, xp, **kwargs) -> SlogdetResult:
|
| 53 |
+
return SlogdetResult(*xp.linalg.slogdet(x, **kwargs))
|
| 54 |
+
|
| 55 |
+
def svd(x: ndarray, /, xp, *, full_matrices: bool = True, **kwargs) -> SVDResult:
|
| 56 |
+
return SVDResult(*xp.linalg.svd(x, full_matrices=full_matrices, **kwargs))
|
| 57 |
+
|
| 58 |
+
# These functions have additional keyword arguments
|
| 59 |
+
|
| 60 |
+
# The upper keyword argument is new from NumPy
|
| 61 |
+
def cholesky(x: ndarray, /, xp, *, upper: bool = False, **kwargs) -> ndarray:
|
| 62 |
+
L = xp.linalg.cholesky(x, **kwargs)
|
| 63 |
+
if upper:
|
| 64 |
+
U = get_xp(xp)(matrix_transpose)(L)
|
| 65 |
+
if get_xp(xp)(isdtype)(U.dtype, 'complex floating'):
|
| 66 |
+
U = xp.conj(U)
|
| 67 |
+
return U
|
| 68 |
+
return L
|
| 69 |
+
|
| 70 |
+
# The rtol keyword argument of matrix_rank() and pinv() is new from NumPy.
|
| 71 |
+
# Note that it has a different semantic meaning from tol and rcond.
|
| 72 |
+
def matrix_rank(x: ndarray,
|
| 73 |
+
/,
|
| 74 |
+
xp,
|
| 75 |
+
*,
|
| 76 |
+
rtol: Optional[Union[float, ndarray]] = None,
|
| 77 |
+
**kwargs) -> ndarray:
|
| 78 |
+
# this is different from xp.linalg.matrix_rank, which supports 1
|
| 79 |
+
# dimensional arrays.
|
| 80 |
+
if x.ndim < 2:
|
| 81 |
+
raise xp.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
|
| 82 |
+
S = get_xp(xp)(svdvals)(x, **kwargs)
|
| 83 |
+
if rtol is None:
|
| 84 |
+
tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * xp.finfo(S.dtype).eps
|
| 85 |
+
else:
|
| 86 |
+
# this is different from xp.linalg.matrix_rank, which does not
|
| 87 |
+
# multiply the tolerance by the largest singular value.
|
| 88 |
+
tol = S.max(axis=-1, keepdims=True)*xp.asarray(rtol)[..., xp.newaxis]
|
| 89 |
+
return xp.count_nonzero(S > tol, axis=-1)
|
| 90 |
+
|
| 91 |
+
def pinv(x: ndarray, /, xp, *, rtol: Optional[Union[float, ndarray]] = None, **kwargs) -> ndarray:
|
| 92 |
+
# this is different from xp.linalg.pinv, which does not multiply the
|
| 93 |
+
# default tolerance by max(M, N).
|
| 94 |
+
if rtol is None:
|
| 95 |
+
rtol = max(x.shape[-2:]) * xp.finfo(x.dtype).eps
|
| 96 |
+
return xp.linalg.pinv(x, rcond=rtol, **kwargs)
|
| 97 |
+
|
| 98 |
+
# These functions are new in the array API spec
|
| 99 |
+
|
| 100 |
+
def matrix_norm(x: ndarray, /, xp, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> ndarray:
|
| 101 |
+
return xp.linalg.norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord)
|
| 102 |
+
|
| 103 |
+
# svdvals is not in NumPy (but it is in SciPy). It is equivalent to
|
| 104 |
+
# xp.linalg.svd(compute_uv=False).
|
| 105 |
+
def svdvals(x: ndarray, /, xp) -> Union[ndarray, Tuple[ndarray, ...]]:
|
| 106 |
+
return xp.linalg.svd(x, compute_uv=False)
|
| 107 |
+
|
| 108 |
+
def vector_norm(x: ndarray, /, xp, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> ndarray:
|
| 109 |
+
# xp.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
|
| 110 |
+
# when axis=None and the input is 2-D, so to force a vector norm, we make
|
| 111 |
+
# it so the input is 1-D (for axis=None), or reshape so that norm is done
|
| 112 |
+
# on a single dimension.
|
| 113 |
+
if axis is None:
|
| 114 |
+
# Note: xp.linalg.norm() doesn't handle 0-D arrays
|
| 115 |
+
_x = x.ravel()
|
| 116 |
+
_axis = 0
|
| 117 |
+
elif isinstance(axis, tuple):
|
| 118 |
+
# Note: The axis argument supports any number of axes, whereas
|
| 119 |
+
# xp.linalg.norm() only supports a single axis for vector norm.
|
| 120 |
+
normalized_axis = normalize_axis_tuple(axis, x.ndim)
|
| 121 |
+
rest = tuple(i for i in range(x.ndim) if i not in normalized_axis)
|
| 122 |
+
newshape = axis + rest
|
| 123 |
+
_x = xp.transpose(x, newshape).reshape(
|
| 124 |
+
(math.prod([x.shape[i] for i in axis]), *[x.shape[i] for i in rest]))
|
| 125 |
+
_axis = 0
|
| 126 |
+
else:
|
| 127 |
+
_x = x
|
| 128 |
+
_axis = axis
|
| 129 |
+
|
| 130 |
+
res = xp.linalg.norm(_x, axis=_axis, ord=ord)
|
| 131 |
+
|
| 132 |
+
if keepdims:
|
| 133 |
+
# We can't reuse xp.linalg.norm(keepdims) because of the reshape hacks
|
| 134 |
+
# above to avoid matrix norm logic.
|
| 135 |
+
shape = list(x.shape)
|
| 136 |
+
_axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
|
| 137 |
+
for i in _axis:
|
| 138 |
+
shape[i] = 1
|
| 139 |
+
res = xp.reshape(res, tuple(shape))
|
| 140 |
+
|
| 141 |
+
return res
|
| 142 |
+
|
| 143 |
+
# xp.diagonal and xp.trace operate on the first two axes whereas these
|
| 144 |
+
# operates on the last two
|
| 145 |
+
|
| 146 |
+
def diagonal(x: ndarray, /, xp, *, offset: int = 0, **kwargs) -> ndarray:
|
| 147 |
+
return xp.diagonal(x, offset=offset, axis1=-2, axis2=-1, **kwargs)
|
| 148 |
+
|
| 149 |
+
def trace(x: ndarray, /, xp, *, offset: int = 0, dtype=None, **kwargs) -> ndarray:
|
| 150 |
+
return xp.asarray(xp.trace(x, offset=offset, dtype=dtype, axis1=-2, axis2=-1, **kwargs))
|
| 151 |
+
|
| 152 |
+
__all__ = ['cross', 'matmul', 'outer', 'tensordot', 'EighResult',
|
| 153 |
+
'QRResult', 'SlogdetResult', 'SVDResult', 'eigh', 'qr', 'slogdet',
|
| 154 |
+
'svd', 'cholesky', 'matrix_rank', 'pinv', 'matrix_norm',
|
| 155 |
+
'matrix_transpose', 'svdvals', 'vecdot', 'vector_norm', 'diagonal',
|
| 156 |
+
'trace']
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
__all__ = [
|
| 4 |
+
"NestedSequence",
|
| 5 |
+
"SupportsBufferProtocol",
|
| 6 |
+
]
|
| 7 |
+
|
| 8 |
+
from typing import (
|
| 9 |
+
Any,
|
| 10 |
+
TypeVar,
|
| 11 |
+
Protocol,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
_T_co = TypeVar("_T_co", covariant=True)
|
| 15 |
+
|
| 16 |
+
class NestedSequence(Protocol[_T_co]):
|
| 17 |
+
def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
|
| 18 |
+
def __len__(self, /) -> int: ...
|
| 19 |
+
|
| 20 |
+
SupportsBufferProtocol = Any
|
| 21 |
+
|
| 22 |
+
Array = Any
|
| 23 |
+
Device = Any
|