Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- python_embeded/Lib/site-packages/scipy/_lib/__init__.py +14 -0
- python_embeded/Lib/site-packages/scipy/_lib/_array_api.py +606 -0
- python_embeded/Lib/site-packages/scipy/_lib/_array_api_no_0d.py +103 -0
- python_embeded/Lib/site-packages/scipy/_lib/_bunch.py +225 -0
- python_embeded/Lib/site-packages/scipy/_lib/_ccallback.py +251 -0
- python_embeded/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/_lib/_disjoint_set.py +254 -0
- python_embeded/Lib/site-packages/scipy/_lib/_docscrape.py +761 -0
- python_embeded/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py +357 -0
- python_embeded/Lib/site-packages/scipy/_lib/_finite_differences.py +145 -0
- python_embeded/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/_lib/_gcutils.py +105 -0
- python_embeded/Lib/site-packages/scipy/_lib/_pep440.py +487 -0
- python_embeded/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/_lib/_testutils.py +369 -0
- python_embeded/Lib/site-packages/scipy/_lib/_threadsafety.py +58 -0
- python_embeded/Lib/site-packages/scipy/_lib/_tmpdirs.py +86 -0
- python_embeded/Lib/site-packages/scipy/_lib/_util.py +1179 -0
- python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/__init__.py +22 -0
- python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/_internal.py +46 -0
- python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/__init__.py +15 -0
- python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_funcs.py +484 -0
- python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_typing.py +8 -0
- python_embeded/Lib/site-packages/scipy/_lib/cobyqa/framework.py +1240 -0
- python_embeded/Lib/site-packages/scipy/_lib/cobyqa/main.py +1506 -0
- python_embeded/Lib/site-packages/scipy/_lib/cobyqa/models.py +1529 -0
- python_embeded/Lib/site-packages/scipy/_lib/cobyqa/problem.py +1296 -0
- python_embeded/Lib/site-packages/scipy/_lib/cobyqa/settings.py +132 -0
- python_embeded/Lib/site-packages/scipy/_lib/decorator.py +399 -0
- python_embeded/Lib/site-packages/scipy/_lib/deprecation.py +274 -0
- python_embeded/Lib/site-packages/scipy/_lib/doccer.py +372 -0
- python_embeded/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/_lib/uarray.py +31 -0
- python_embeded/Lib/site-packages/scipy/cluster/__init__.py +31 -0
- python_embeded/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a +0 -0
- python_embeded/Lib/site-packages/scipy/cluster/hierarchy.py +0 -0
- python_embeded/Lib/site-packages/scipy/cluster/vq.py +828 -0
- python_embeded/Lib/site-packages/scipy/constants/__init__.py +358 -0
- python_embeded/Lib/site-packages/scipy/constants/_codata.py +0 -0
- python_embeded/Lib/site-packages/scipy/constants/_constants.py +366 -0
- python_embeded/Lib/site-packages/scipy/constants/codata.py +21 -0
- python_embeded/Lib/site-packages/scipy/constants/constants.py +53 -0
- python_embeded/Lib/site-packages/scipy/datasets/__init__.py +90 -0
- python_embeded/Lib/site-packages/scipy/datasets/_download_all.py +57 -0
- python_embeded/Lib/site-packages/scipy/datasets/_fetchers.py +219 -0
.gitattributes
CHANGED
|
@@ -305,3 +305,5 @@ python_embeded/Lib/site-packages/PIL/_imaging.cp312-win_amd64.pyd filter=lfs dif
|
|
| 305 |
python_embeded/Lib/site-packages/tests/data/scotland_pitie.png filter=lfs diff=lfs merge=lfs -text
|
| 306 |
python_embeded/Lib/site-packages/tests/data/scotland_house.png filter=lfs diff=lfs merge=lfs -text
|
| 307 |
python_embeded/Lib/site-packages/pythonwin/win32ui.pyd filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 305 |
python_embeded/Lib/site-packages/tests/data/scotland_pitie.png filter=lfs diff=lfs merge=lfs -text
|
| 306 |
python_embeded/Lib/site-packages/tests/data/scotland_house.png filter=lfs diff=lfs merge=lfs -text
|
| 307 |
python_embeded/Lib/site-packages/pythonwin/win32ui.pyd filter=lfs diff=lfs merge=lfs -text
|
| 308 |
+
python_embeded/Lib/site-packages/sklearn/.libs/msvcp140.dll filter=lfs diff=lfs merge=lfs -text
|
| 309 |
+
python_embeded/Lib/site-packages/sklearn/.libs/vcomp140.dll filter=lfs diff=lfs merge=lfs -text
|
python_embeded/Lib/site-packages/scipy/_lib/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module containing private utility functions
|
| 3 |
+
===========================================
|
| 4 |
+
|
| 5 |
+
The ``scipy._lib`` namespace is empty (for now). Tests for all
|
| 6 |
+
utilities in submodules of ``_lib`` can be run with::
|
| 7 |
+
|
| 8 |
+
from scipy import _lib
|
| 9 |
+
_lib.test()
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
from scipy._lib._testutils import PytestTester
|
| 13 |
+
test = PytestTester(__name__)
|
| 14 |
+
del PytestTester
|
python_embeded/Lib/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
|
python_embeded/Lib/site-packages/scipy/_lib/_array_api_no_0d.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Extra testing functions that forbid 0d-input, see #21044
|
| 3 |
+
|
| 4 |
+
While the xp_assert_* functions generally aim to follow the conventions of the
|
| 5 |
+
underlying `xp` library, NumPy in particular is inconsistent in its handling
|
| 6 |
+
of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897.
|
| 7 |
+
|
| 8 |
+
For example, this means that the following operations (as of v2.0.1) currently
|
| 9 |
+
return scalars, even though a 0d-array would often be more appropriate:
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
np.array(0) * 2 # scalar, not 0d array
|
| 13 |
+
- np.array(0) # scalar, not 0d-array
|
| 14 |
+
np.sin(np.array(0)) # scalar, not 0d array
|
| 15 |
+
np.mean([1, 2, 3]) # scalar, not 0d array
|
| 16 |
+
|
| 17 |
+
Libraries like CuPy tend to return a 0d-array in scenarios like those above,
|
| 18 |
+
and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality
|
| 19 |
+
of the inconsistencies present in NumPy, as well as 20+ years of code on top,
|
| 20 |
+
the `xp_assert_*` functions here enforce consistency in the only way that
|
| 21 |
+
doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type.
|
| 22 |
+
|
| 23 |
+
However, when scalars are not generally the expected NumPy return type,
|
| 24 |
+
it remains preferable to use the assert functions from
|
| 25 |
+
the `scipy._lib._array_api` module, which have less surprising behaviour.
|
| 26 |
+
"""
|
| 27 |
+
from scipy._lib._array_api import array_namespace, is_numpy
|
| 28 |
+
from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base,
|
| 29 |
+
xp_assert_equal as xp_assert_equal_base,
|
| 30 |
+
xp_assert_less as xp_assert_less_base)
|
| 31 |
+
|
| 32 |
+
__all__: list[str] = []
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _check_scalar(actual, desired, *, xp=None, **kwargs):
|
| 36 |
+
__tracebackhide__ = True # Hide traceback for py.test
|
| 37 |
+
|
| 38 |
+
if xp is None:
|
| 39 |
+
xp = array_namespace(actual)
|
| 40 |
+
|
| 41 |
+
# necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape
|
| 42 |
+
desired = xp.asarray(desired)
|
| 43 |
+
|
| 44 |
+
# Only NumPy distinguishes between scalars and arrays;
|
| 45 |
+
# shape check in xp_assert_* is sufficient except for shape == ()
|
| 46 |
+
if not (is_numpy(xp) and desired.shape == ()):
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
_msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow "
|
| 50 |
+
"the convention of many NumPy functions, returning a scalar when a "
|
| 51 |
+
"0d-array would be correct. The specialized `xp_assert_*` functions "
|
| 52 |
+
"in the `scipy._lib._array_api_no_0d` module err on the side of "
|
| 53 |
+
"caution and do not accept 0d-arrays by default. If the correct "
|
| 54 |
+
"result may legitimately be a 0d-array, pass `check_0d=True`, "
|
| 55 |
+
"or use the `xp_assert_*` functions from `scipy._lib._array_api`.")
|
| 56 |
+
assert xp.isscalar(actual), _msg
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs):
|
| 60 |
+
# in contrast to xp_assert_equal_base, this defaults to check_0d=False,
|
| 61 |
+
# but will do an extra check in that case, which forbids 0d-arrays for `actual`
|
| 62 |
+
__tracebackhide__ = True # Hide traceback for py.test
|
| 63 |
+
|
| 64 |
+
# array-ness (check_0d == True) is taken care of by the *_base functions
|
| 65 |
+
if not check_0d:
|
| 66 |
+
_check_scalar(actual, desired, **kwargs)
|
| 67 |
+
return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def xp_assert_close(actual, desired, *, check_0d=False, **kwargs):
|
| 71 |
+
# as for xp_assert_equal
|
| 72 |
+
__tracebackhide__ = True
|
| 73 |
+
|
| 74 |
+
if not check_0d:
|
| 75 |
+
_check_scalar(actual, desired, **kwargs)
|
| 76 |
+
return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def xp_assert_less(actual, desired, *, check_0d=False, **kwargs):
|
| 80 |
+
# as for xp_assert_equal
|
| 81 |
+
__tracebackhide__ = True
|
| 82 |
+
|
| 83 |
+
if not check_0d:
|
| 84 |
+
_check_scalar(actual, desired, **kwargs)
|
| 85 |
+
return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
|
| 89 |
+
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
|
| 90 |
+
"""
|
| 91 |
+
rtol, atol = 0, 1.5*10**(-decimal)
|
| 92 |
+
return xp_assert_close(actual, desired,
|
| 93 |
+
atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
|
| 94 |
+
*args, **kwds)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
|
| 98 |
+
"""Backwards compatible replacement. In new code, use xp_assert_close instead.
|
| 99 |
+
"""
|
| 100 |
+
rtol, atol = 0, 1.5*10**(-decimal)
|
| 101 |
+
return xp_assert_close(actual, desired,
|
| 102 |
+
atol=atol, rt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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
|
python_embeded/Lib/site-packages/scipy/_lib/_ccallback.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
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)
|
python_embeded/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.61 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/_lib/_disjoint_set.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Disjoint set data structure
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DisjointSet:
|
| 7 |
+
""" Disjoint set data structure for incremental connectivity queries.
|
| 8 |
+
|
| 9 |
+
.. versionadded:: 1.6.0
|
| 10 |
+
|
| 11 |
+
Attributes
|
| 12 |
+
----------
|
| 13 |
+
n_subsets : int
|
| 14 |
+
The number of subsets.
|
| 15 |
+
|
| 16 |
+
Methods
|
| 17 |
+
-------
|
| 18 |
+
add
|
| 19 |
+
merge
|
| 20 |
+
connected
|
| 21 |
+
subset
|
| 22 |
+
subset_size
|
| 23 |
+
subsets
|
| 24 |
+
__getitem__
|
| 25 |
+
|
| 26 |
+
Notes
|
| 27 |
+
-----
|
| 28 |
+
This class implements the disjoint set [1]_, also known as the *union-find*
|
| 29 |
+
or *merge-find* data structure. The *find* operation (implemented in
|
| 30 |
+
`__getitem__`) implements the *path halving* variant. The *merge* method
|
| 31 |
+
implements the *merge by size* variant.
|
| 32 |
+
|
| 33 |
+
References
|
| 34 |
+
----------
|
| 35 |
+
.. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure
|
| 36 |
+
|
| 37 |
+
Examples
|
| 38 |
+
--------
|
| 39 |
+
>>> from scipy.cluster.hierarchy import DisjointSet
|
| 40 |
+
|
| 41 |
+
Initialize a disjoint set:
|
| 42 |
+
|
| 43 |
+
>>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b'])
|
| 44 |
+
|
| 45 |
+
Merge some subsets:
|
| 46 |
+
|
| 47 |
+
>>> disjoint_set.merge(1, 2)
|
| 48 |
+
True
|
| 49 |
+
>>> disjoint_set.merge(3, 'a')
|
| 50 |
+
True
|
| 51 |
+
>>> disjoint_set.merge('a', 'b')
|
| 52 |
+
True
|
| 53 |
+
>>> disjoint_set.merge('b', 'b')
|
| 54 |
+
False
|
| 55 |
+
|
| 56 |
+
Find root elements:
|
| 57 |
+
|
| 58 |
+
>>> disjoint_set[2]
|
| 59 |
+
1
|
| 60 |
+
>>> disjoint_set['b']
|
| 61 |
+
3
|
| 62 |
+
|
| 63 |
+
Test connectivity:
|
| 64 |
+
|
| 65 |
+
>>> disjoint_set.connected(1, 2)
|
| 66 |
+
True
|
| 67 |
+
>>> disjoint_set.connected(1, 'b')
|
| 68 |
+
False
|
| 69 |
+
|
| 70 |
+
List elements in disjoint set:
|
| 71 |
+
|
| 72 |
+
>>> list(disjoint_set)
|
| 73 |
+
[1, 2, 3, 'a', 'b']
|
| 74 |
+
|
| 75 |
+
Get the subset containing 'a':
|
| 76 |
+
|
| 77 |
+
>>> disjoint_set.subset('a')
|
| 78 |
+
{'a', 3, 'b'}
|
| 79 |
+
|
| 80 |
+
Get the size of the subset containing 'a' (without actually instantiating
|
| 81 |
+
the subset):
|
| 82 |
+
|
| 83 |
+
>>> disjoint_set.subset_size('a')
|
| 84 |
+
3
|
| 85 |
+
|
| 86 |
+
Get all subsets in the disjoint set:
|
| 87 |
+
|
| 88 |
+
>>> disjoint_set.subsets()
|
| 89 |
+
[{1, 2}, {'a', 3, 'b'}]
|
| 90 |
+
"""
|
| 91 |
+
def __init__(self, elements=None):
|
| 92 |
+
self.n_subsets = 0
|
| 93 |
+
self._sizes = {}
|
| 94 |
+
self._parents = {}
|
| 95 |
+
# _nbrs is a circular linked list which links connected elements.
|
| 96 |
+
self._nbrs = {}
|
| 97 |
+
# _indices tracks the element insertion order in `__iter__`.
|
| 98 |
+
self._indices = {}
|
| 99 |
+
if elements is not None:
|
| 100 |
+
for x in elements:
|
| 101 |
+
self.add(x)
|
| 102 |
+
|
| 103 |
+
def __iter__(self):
|
| 104 |
+
"""Returns an iterator of the elements in the disjoint set.
|
| 105 |
+
|
| 106 |
+
Elements are ordered by insertion order.
|
| 107 |
+
"""
|
| 108 |
+
return iter(self._indices)
|
| 109 |
+
|
| 110 |
+
def __len__(self):
|
| 111 |
+
return len(self._indices)
|
| 112 |
+
|
| 113 |
+
def __contains__(self, x):
|
| 114 |
+
return x in self._indices
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, x):
|
| 117 |
+
"""Find the root element of `x`.
|
| 118 |
+
|
| 119 |
+
Parameters
|
| 120 |
+
----------
|
| 121 |
+
x : hashable object
|
| 122 |
+
Input element.
|
| 123 |
+
|
| 124 |
+
Returns
|
| 125 |
+
-------
|
| 126 |
+
root : hashable object
|
| 127 |
+
Root element of `x`.
|
| 128 |
+
"""
|
| 129 |
+
if x not in self._indices:
|
| 130 |
+
raise KeyError(x)
|
| 131 |
+
|
| 132 |
+
# find by "path halving"
|
| 133 |
+
parents = self._parents
|
| 134 |
+
while self._indices[x] != self._indices[parents[x]]:
|
| 135 |
+
parents[x] = parents[parents[x]]
|
| 136 |
+
x = parents[x]
|
| 137 |
+
return x
|
| 138 |
+
|
| 139 |
+
def add(self, x):
|
| 140 |
+
"""Add element `x` to disjoint set
|
| 141 |
+
"""
|
| 142 |
+
if x in self._indices:
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
self._sizes[x] = 1
|
| 146 |
+
self._parents[x] = x
|
| 147 |
+
self._nbrs[x] = x
|
| 148 |
+
self._indices[x] = len(self._indices)
|
| 149 |
+
self.n_subsets += 1
|
| 150 |
+
|
| 151 |
+
def merge(self, x, y):
|
| 152 |
+
"""Merge the subsets of `x` and `y`.
|
| 153 |
+
|
| 154 |
+
The smaller subset (the child) is merged into the larger subset (the
|
| 155 |
+
parent). If the subsets are of equal size, the root element which was
|
| 156 |
+
first inserted into the disjoint set is selected as the parent.
|
| 157 |
+
|
| 158 |
+
Parameters
|
| 159 |
+
----------
|
| 160 |
+
x, y : hashable object
|
| 161 |
+
Elements to merge.
|
| 162 |
+
|
| 163 |
+
Returns
|
| 164 |
+
-------
|
| 165 |
+
merged : bool
|
| 166 |
+
True if `x` and `y` were in disjoint sets, False otherwise.
|
| 167 |
+
"""
|
| 168 |
+
xr = self[x]
|
| 169 |
+
yr = self[y]
|
| 170 |
+
if self._indices[xr] == self._indices[yr]:
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
sizes = self._sizes
|
| 174 |
+
if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]):
|
| 175 |
+
xr, yr = yr, xr
|
| 176 |
+
self._parents[yr] = xr
|
| 177 |
+
self._sizes[xr] += self._sizes[yr]
|
| 178 |
+
self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr]
|
| 179 |
+
self.n_subsets -= 1
|
| 180 |
+
return True
|
| 181 |
+
|
| 182 |
+
def connected(self, x, y):
|
| 183 |
+
"""Test whether `x` and `y` are in the same subset.
|
| 184 |
+
|
| 185 |
+
Parameters
|
| 186 |
+
----------
|
| 187 |
+
x, y : hashable object
|
| 188 |
+
Elements to test.
|
| 189 |
+
|
| 190 |
+
Returns
|
| 191 |
+
-------
|
| 192 |
+
result : bool
|
| 193 |
+
True if `x` and `y` are in the same set, False otherwise.
|
| 194 |
+
"""
|
| 195 |
+
return self._indices[self[x]] == self._indices[self[y]]
|
| 196 |
+
|
| 197 |
+
def subset(self, x):
|
| 198 |
+
"""Get the subset containing `x`.
|
| 199 |
+
|
| 200 |
+
Parameters
|
| 201 |
+
----------
|
| 202 |
+
x : hashable object
|
| 203 |
+
Input element.
|
| 204 |
+
|
| 205 |
+
Returns
|
| 206 |
+
-------
|
| 207 |
+
result : set
|
| 208 |
+
Subset containing `x`.
|
| 209 |
+
"""
|
| 210 |
+
if x not in self._indices:
|
| 211 |
+
raise KeyError(x)
|
| 212 |
+
|
| 213 |
+
result = [x]
|
| 214 |
+
nxt = self._nbrs[x]
|
| 215 |
+
while self._indices[nxt] != self._indices[x]:
|
| 216 |
+
result.append(nxt)
|
| 217 |
+
nxt = self._nbrs[nxt]
|
| 218 |
+
return set(result)
|
| 219 |
+
|
| 220 |
+
def subset_size(self, x):
|
| 221 |
+
"""Get the size of the subset containing `x`.
|
| 222 |
+
|
| 223 |
+
Note that this method is faster than ``len(self.subset(x))`` because
|
| 224 |
+
the size is directly read off an internal field, without the need to
|
| 225 |
+
instantiate the full subset.
|
| 226 |
+
|
| 227 |
+
Parameters
|
| 228 |
+
----------
|
| 229 |
+
x : hashable object
|
| 230 |
+
Input element.
|
| 231 |
+
|
| 232 |
+
Returns
|
| 233 |
+
-------
|
| 234 |
+
result : int
|
| 235 |
+
Size of the subset containing `x`.
|
| 236 |
+
"""
|
| 237 |
+
return self._sizes[self[x]]
|
| 238 |
+
|
| 239 |
+
def subsets(self):
|
| 240 |
+
"""Get all the subsets in the disjoint set.
|
| 241 |
+
|
| 242 |
+
Returns
|
| 243 |
+
-------
|
| 244 |
+
result : list
|
| 245 |
+
Subsets in the disjoint set.
|
| 246 |
+
"""
|
| 247 |
+
result = []
|
| 248 |
+
visited = set()
|
| 249 |
+
for x in self:
|
| 250 |
+
if x not in visited:
|
| 251 |
+
xset = self.subset(x)
|
| 252 |
+
visited.update(xset)
|
| 253 |
+
result.append(xset)
|
| 254 |
+
return result
|
python_embeded/Lib/site-packages/scipy/_lib/_docscrape.py
ADDED
|
@@ -0,0 +1,761 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2
|
| 2 |
+
"""Extract reference documentation from the NumPy source tree."""
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
import inspect
|
| 6 |
+
import pydoc
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
import textwrap
|
| 10 |
+
from collections import namedtuple
|
| 11 |
+
from collections.abc import Callable, Mapping
|
| 12 |
+
from functools import cached_property
|
| 13 |
+
from warnings import warn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def strip_blank_lines(l):
|
| 17 |
+
"Remove leading and trailing blank lines from a list of lines"
|
| 18 |
+
while l and not l[0].strip():
|
| 19 |
+
del l[0]
|
| 20 |
+
while l and not l[-1].strip():
|
| 21 |
+
del l[-1]
|
| 22 |
+
return l
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Reader:
|
| 26 |
+
"""A line-based string reader."""
|
| 27 |
+
|
| 28 |
+
def __init__(self, data):
|
| 29 |
+
"""
|
| 30 |
+
Parameters
|
| 31 |
+
----------
|
| 32 |
+
data : str
|
| 33 |
+
String with lines separated by '\\n'.
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
if isinstance(data, list):
|
| 37 |
+
self._str = data
|
| 38 |
+
else:
|
| 39 |
+
self._str = data.split("\n") # store string as list of lines
|
| 40 |
+
|
| 41 |
+
self.reset()
|
| 42 |
+
|
| 43 |
+
def __getitem__(self, n):
|
| 44 |
+
return self._str[n]
|
| 45 |
+
|
| 46 |
+
def reset(self):
|
| 47 |
+
self._l = 0 # current line nr
|
| 48 |
+
|
| 49 |
+
def read(self):
|
| 50 |
+
if not self.eof():
|
| 51 |
+
out = self[self._l]
|
| 52 |
+
self._l += 1
|
| 53 |
+
return out
|
| 54 |
+
else:
|
| 55 |
+
return ""
|
| 56 |
+
|
| 57 |
+
def seek_next_non_empty_line(self):
|
| 58 |
+
for l in self[self._l :]:
|
| 59 |
+
if l.strip():
|
| 60 |
+
break
|
| 61 |
+
else:
|
| 62 |
+
self._l += 1
|
| 63 |
+
|
| 64 |
+
def eof(self):
|
| 65 |
+
return self._l >= len(self._str)
|
| 66 |
+
|
| 67 |
+
def read_to_condition(self, condition_func):
|
| 68 |
+
start = self._l
|
| 69 |
+
for line in self[start:]:
|
| 70 |
+
if condition_func(line):
|
| 71 |
+
return self[start : self._l]
|
| 72 |
+
self._l += 1
|
| 73 |
+
if self.eof():
|
| 74 |
+
return self[start : self._l + 1]
|
| 75 |
+
return []
|
| 76 |
+
|
| 77 |
+
def read_to_next_empty_line(self):
|
| 78 |
+
self.seek_next_non_empty_line()
|
| 79 |
+
|
| 80 |
+
def is_empty(line):
|
| 81 |
+
return not line.strip()
|
| 82 |
+
|
| 83 |
+
return self.read_to_condition(is_empty)
|
| 84 |
+
|
| 85 |
+
def read_to_next_unindented_line(self):
|
| 86 |
+
def is_unindented(line):
|
| 87 |
+
return line.strip() and (len(line.lstrip()) == len(line))
|
| 88 |
+
|
| 89 |
+
return self.read_to_condition(is_unindented)
|
| 90 |
+
|
| 91 |
+
def peek(self, n=0):
|
| 92 |
+
if self._l + n < len(self._str):
|
| 93 |
+
return self[self._l + n]
|
| 94 |
+
else:
|
| 95 |
+
return ""
|
| 96 |
+
|
| 97 |
+
def is_empty(self):
|
| 98 |
+
return not "".join(self._str).strip()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ParseError(Exception):
|
| 102 |
+
def __str__(self):
|
| 103 |
+
message = self.args[0]
|
| 104 |
+
if hasattr(self, "docstring"):
|
| 105 |
+
message = f"{message} in {self.docstring!r}"
|
| 106 |
+
return message
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
Parameter = namedtuple("Parameter", ["name", "type", "desc"])
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class NumpyDocString(Mapping):
|
| 113 |
+
"""Parses a numpydoc string to an abstract representation
|
| 114 |
+
|
| 115 |
+
Instances define a mapping from section title to structured data.
|
| 116 |
+
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
sections = {
|
| 120 |
+
"Signature": "",
|
| 121 |
+
"Summary": [""],
|
| 122 |
+
"Extended Summary": [],
|
| 123 |
+
"Parameters": [],
|
| 124 |
+
"Attributes": [],
|
| 125 |
+
"Methods": [],
|
| 126 |
+
"Returns": [],
|
| 127 |
+
"Yields": [],
|
| 128 |
+
"Receives": [],
|
| 129 |
+
"Other Parameters": [],
|
| 130 |
+
"Raises": [],
|
| 131 |
+
"Warns": [],
|
| 132 |
+
"Warnings": [],
|
| 133 |
+
"See Also": [],
|
| 134 |
+
"Notes": [],
|
| 135 |
+
"References": "",
|
| 136 |
+
"Examples": "",
|
| 137 |
+
"index": {},
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
def __init__(self, docstring, config=None):
|
| 141 |
+
orig_docstring = docstring
|
| 142 |
+
docstring = textwrap.dedent(docstring).split("\n")
|
| 143 |
+
|
| 144 |
+
self._doc = Reader(docstring)
|
| 145 |
+
self._parsed_data = copy.deepcopy(self.sections)
|
| 146 |
+
|
| 147 |
+
try:
|
| 148 |
+
self._parse()
|
| 149 |
+
except ParseError as e:
|
| 150 |
+
e.docstring = orig_docstring
|
| 151 |
+
raise
|
| 152 |
+
|
| 153 |
+
def __getitem__(self, key):
|
| 154 |
+
return self._parsed_data[key]
|
| 155 |
+
|
| 156 |
+
def __setitem__(self, key, val):
|
| 157 |
+
if key not in self._parsed_data:
|
| 158 |
+
self._error_location(f"Unknown section {key}", error=False)
|
| 159 |
+
else:
|
| 160 |
+
self._parsed_data[key] = val
|
| 161 |
+
|
| 162 |
+
def __iter__(self):
|
| 163 |
+
return iter(self._parsed_data)
|
| 164 |
+
|
| 165 |
+
def __len__(self):
|
| 166 |
+
return len(self._parsed_data)
|
| 167 |
+
|
| 168 |
+
def _is_at_section(self):
|
| 169 |
+
self._doc.seek_next_non_empty_line()
|
| 170 |
+
|
| 171 |
+
if self._doc.eof():
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
l1 = self._doc.peek().strip() # e.g. Parameters
|
| 175 |
+
|
| 176 |
+
if l1.startswith(".. index::"):
|
| 177 |
+
return True
|
| 178 |
+
|
| 179 |
+
l2 = self._doc.peek(1).strip() # ---------- or ==========
|
| 180 |
+
if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1):
|
| 181 |
+
snip = "\n".join(self._doc._str[:2]) + "..."
|
| 182 |
+
self._error_location(
|
| 183 |
+
f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}",
|
| 184 |
+
error=False,
|
| 185 |
+
)
|
| 186 |
+
return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1))
|
| 187 |
+
|
| 188 |
+
def _strip(self, doc):
|
| 189 |
+
i = 0
|
| 190 |
+
j = 0
|
| 191 |
+
for i, line in enumerate(doc):
|
| 192 |
+
if line.strip():
|
| 193 |
+
break
|
| 194 |
+
|
| 195 |
+
for j, line in enumerate(doc[::-1]):
|
| 196 |
+
if line.strip():
|
| 197 |
+
break
|
| 198 |
+
|
| 199 |
+
return doc[i : len(doc) - j]
|
| 200 |
+
|
| 201 |
+
def _read_to_next_section(self):
|
| 202 |
+
section = self._doc.read_to_next_empty_line()
|
| 203 |
+
|
| 204 |
+
while not self._is_at_section() and not self._doc.eof():
|
| 205 |
+
if not self._doc.peek(-1).strip(): # previous line was empty
|
| 206 |
+
section += [""]
|
| 207 |
+
|
| 208 |
+
section += self._doc.read_to_next_empty_line()
|
| 209 |
+
|
| 210 |
+
return section
|
| 211 |
+
|
| 212 |
+
def _read_sections(self):
|
| 213 |
+
while not self._doc.eof():
|
| 214 |
+
data = self._read_to_next_section()
|
| 215 |
+
name = data[0].strip()
|
| 216 |
+
|
| 217 |
+
if name.startswith(".."): # index section
|
| 218 |
+
yield name, data[1:]
|
| 219 |
+
elif len(data) < 2:
|
| 220 |
+
yield StopIteration
|
| 221 |
+
else:
|
| 222 |
+
yield name, self._strip(data[2:])
|
| 223 |
+
|
| 224 |
+
def _parse_param_list(self, content, single_element_is_type=False):
|
| 225 |
+
content = dedent_lines(content)
|
| 226 |
+
r = Reader(content)
|
| 227 |
+
params = []
|
| 228 |
+
while not r.eof():
|
| 229 |
+
header = r.read().strip()
|
| 230 |
+
if " : " in header:
|
| 231 |
+
arg_name, arg_type = header.split(" : ", maxsplit=1)
|
| 232 |
+
else:
|
| 233 |
+
# NOTE: param line with single element should never have a
|
| 234 |
+
# a " :" before the description line, so this should probably
|
| 235 |
+
# warn.
|
| 236 |
+
if header.endswith(" :"):
|
| 237 |
+
header = header[:-2]
|
| 238 |
+
if single_element_is_type:
|
| 239 |
+
arg_name, arg_type = "", header
|
| 240 |
+
else:
|
| 241 |
+
arg_name, arg_type = header, ""
|
| 242 |
+
|
| 243 |
+
desc = r.read_to_next_unindented_line()
|
| 244 |
+
desc = dedent_lines(desc)
|
| 245 |
+
desc = strip_blank_lines(desc)
|
| 246 |
+
|
| 247 |
+
params.append(Parameter(arg_name, arg_type, desc))
|
| 248 |
+
|
| 249 |
+
return params
|
| 250 |
+
|
| 251 |
+
# See also supports the following formats.
|
| 252 |
+
#
|
| 253 |
+
# <FUNCNAME>
|
| 254 |
+
# <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE*
|
| 255 |
+
# <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE*
|
| 256 |
+
# <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE*
|
| 257 |
+
|
| 258 |
+
# <FUNCNAME> is one of
|
| 259 |
+
# <PLAIN_FUNCNAME>
|
| 260 |
+
# COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK
|
| 261 |
+
# where
|
| 262 |
+
# <PLAIN_FUNCNAME> is a legal function name, and
|
| 263 |
+
# <ROLE> is any nonempty sequence of word characters.
|
| 264 |
+
# Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`
|
| 265 |
+
# <DESC> is a string describing the function.
|
| 266 |
+
|
| 267 |
+
_role = r":(?P<role>(py:)?\w+):"
|
| 268 |
+
_funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`"
|
| 269 |
+
_funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)"
|
| 270 |
+
_funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")"
|
| 271 |
+
_funcnamenext = _funcname.replace("role", "rolenext")
|
| 272 |
+
_funcnamenext = _funcnamenext.replace("name", "namenext")
|
| 273 |
+
_description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$"
|
| 274 |
+
_func_rgx = re.compile(r"^\s*" + _funcname + r"\s*")
|
| 275 |
+
_line_rgx = re.compile(
|
| 276 |
+
r"^\s*"
|
| 277 |
+
+ r"(?P<allfuncs>"
|
| 278 |
+
+ _funcname # group for all function names
|
| 279 |
+
+ r"(?P<morefuncs>([,]\s+"
|
| 280 |
+
+ _funcnamenext
|
| 281 |
+
+ r")*)"
|
| 282 |
+
+ r")"
|
| 283 |
+
+ r"(?P<trailing>[,\.])?" # end of "allfuncs"
|
| 284 |
+
+ _description # Some function lists have a trailing comma (or period) '\s*'
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
# Empty <DESC> elements are replaced with '..'
|
| 288 |
+
empty_description = ".."
|
| 289 |
+
|
| 290 |
+
def _parse_see_also(self, content):
|
| 291 |
+
"""
|
| 292 |
+
func_name : Descriptive text
|
| 293 |
+
continued text
|
| 294 |
+
another_func_name : Descriptive text
|
| 295 |
+
func_name1, func_name2, :meth:`func_name`, func_name3
|
| 296 |
+
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
content = dedent_lines(content)
|
| 300 |
+
|
| 301 |
+
items = []
|
| 302 |
+
|
| 303 |
+
def parse_item_name(text):
|
| 304 |
+
"""Match ':role:`name`' or 'name'."""
|
| 305 |
+
m = self._func_rgx.match(text)
|
| 306 |
+
if not m:
|
| 307 |
+
self._error_location(f"Error parsing See Also entry {line!r}")
|
| 308 |
+
role = m.group("role")
|
| 309 |
+
name = m.group("name") if role else m.group("name2")
|
| 310 |
+
return name, role, m.end()
|
| 311 |
+
|
| 312 |
+
rest = []
|
| 313 |
+
for line in content:
|
| 314 |
+
if not line.strip():
|
| 315 |
+
continue
|
| 316 |
+
|
| 317 |
+
line_match = self._line_rgx.match(line)
|
| 318 |
+
description = None
|
| 319 |
+
if line_match:
|
| 320 |
+
description = line_match.group("desc")
|
| 321 |
+
if line_match.group("trailing") and description:
|
| 322 |
+
self._error_location(
|
| 323 |
+
"Unexpected comma or period after function list at index %d of "
|
| 324 |
+
'line "%s"' % (line_match.end("trailing"), line),
|
| 325 |
+
error=False,
|
| 326 |
+
)
|
| 327 |
+
if not description and line.startswith(" "):
|
| 328 |
+
rest.append(line.strip())
|
| 329 |
+
elif line_match:
|
| 330 |
+
funcs = []
|
| 331 |
+
text = line_match.group("allfuncs")
|
| 332 |
+
while True:
|
| 333 |
+
if not text.strip():
|
| 334 |
+
break
|
| 335 |
+
name, role, match_end = parse_item_name(text)
|
| 336 |
+
funcs.append((name, role))
|
| 337 |
+
text = text[match_end:].strip()
|
| 338 |
+
if text and text[0] == ",":
|
| 339 |
+
text = text[1:].strip()
|
| 340 |
+
rest = list(filter(None, [description]))
|
| 341 |
+
items.append((funcs, rest))
|
| 342 |
+
else:
|
| 343 |
+
self._error_location(f"Error parsing See Also entry {line!r}")
|
| 344 |
+
return items
|
| 345 |
+
|
| 346 |
+
def _parse_index(self, section, content):
|
| 347 |
+
"""
|
| 348 |
+
.. index:: default
|
| 349 |
+
:refguide: something, else, and more
|
| 350 |
+
|
| 351 |
+
"""
|
| 352 |
+
|
| 353 |
+
def strip_each_in(lst):
|
| 354 |
+
return [s.strip() for s in lst]
|
| 355 |
+
|
| 356 |
+
out = {}
|
| 357 |
+
section = section.split("::")
|
| 358 |
+
if len(section) > 1:
|
| 359 |
+
out["default"] = strip_each_in(section[1].split(","))[0]
|
| 360 |
+
for line in content:
|
| 361 |
+
line = line.split(":")
|
| 362 |
+
if len(line) > 2:
|
| 363 |
+
out[line[1]] = strip_each_in(line[2].split(","))
|
| 364 |
+
return out
|
| 365 |
+
|
| 366 |
+
def _parse_summary(self):
|
| 367 |
+
"""Grab signature (if given) and summary"""
|
| 368 |
+
if self._is_at_section():
|
| 369 |
+
return
|
| 370 |
+
|
| 371 |
+
# If several signatures present, take the last one
|
| 372 |
+
while True:
|
| 373 |
+
summary = self._doc.read_to_next_empty_line()
|
| 374 |
+
summary_str = " ".join([s.strip() for s in summary]).strip()
|
| 375 |
+
compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$")
|
| 376 |
+
if compiled.match(summary_str):
|
| 377 |
+
self["Signature"] = summary_str
|
| 378 |
+
if not self._is_at_section():
|
| 379 |
+
continue
|
| 380 |
+
break
|
| 381 |
+
|
| 382 |
+
if summary is not None:
|
| 383 |
+
self["Summary"] = summary
|
| 384 |
+
|
| 385 |
+
if not self._is_at_section():
|
| 386 |
+
self["Extended Summary"] = self._read_to_next_section()
|
| 387 |
+
|
| 388 |
+
def _parse(self):
|
| 389 |
+
self._doc.reset()
|
| 390 |
+
self._parse_summary()
|
| 391 |
+
|
| 392 |
+
sections = list(self._read_sections())
|
| 393 |
+
section_names = {section for section, content in sections}
|
| 394 |
+
|
| 395 |
+
has_yields = "Yields" in section_names
|
| 396 |
+
# We could do more tests, but we are not. Arbitrarily.
|
| 397 |
+
if not has_yields and "Receives" in section_names:
|
| 398 |
+
msg = "Docstring contains a Receives section but not Yields."
|
| 399 |
+
raise ValueError(msg)
|
| 400 |
+
|
| 401 |
+
for section, content in sections:
|
| 402 |
+
if not section.startswith(".."):
|
| 403 |
+
section = (s.capitalize() for s in section.split(" "))
|
| 404 |
+
section = " ".join(section)
|
| 405 |
+
if self.get(section):
|
| 406 |
+
self._error_location(
|
| 407 |
+
"The section %s appears twice in %s"
|
| 408 |
+
% (section, "\n".join(self._doc._str))
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):
|
| 412 |
+
self[section] = self._parse_param_list(content)
|
| 413 |
+
elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"):
|
| 414 |
+
self[section] = self._parse_param_list(
|
| 415 |
+
content, single_element_is_type=True
|
| 416 |
+
)
|
| 417 |
+
elif section.startswith(".. index::"):
|
| 418 |
+
self["index"] = self._parse_index(section, content)
|
| 419 |
+
elif section == "See Also":
|
| 420 |
+
self["See Also"] = self._parse_see_also(content)
|
| 421 |
+
else:
|
| 422 |
+
self[section] = content
|
| 423 |
+
|
| 424 |
+
@property
|
| 425 |
+
def _obj(self):
|
| 426 |
+
if hasattr(self, "_cls"):
|
| 427 |
+
return self._cls
|
| 428 |
+
elif hasattr(self, "_f"):
|
| 429 |
+
return self._f
|
| 430 |
+
return None
|
| 431 |
+
|
| 432 |
+
def _error_location(self, msg, error=True):
|
| 433 |
+
if self._obj is not None:
|
| 434 |
+
# we know where the docs came from:
|
| 435 |
+
try:
|
| 436 |
+
filename = inspect.getsourcefile(self._obj)
|
| 437 |
+
except TypeError:
|
| 438 |
+
filename = None
|
| 439 |
+
# Make UserWarning more descriptive via object introspection.
|
| 440 |
+
# Skip if introspection fails
|
| 441 |
+
name = getattr(self._obj, "__name__", None)
|
| 442 |
+
if name is None:
|
| 443 |
+
name = getattr(getattr(self._obj, "__class__", None), "__name__", None)
|
| 444 |
+
if name is not None:
|
| 445 |
+
msg += f" in the docstring of {name}"
|
| 446 |
+
msg += f" in {filename}." if filename else ""
|
| 447 |
+
if error:
|
| 448 |
+
raise ValueError(msg)
|
| 449 |
+
else:
|
| 450 |
+
warn(msg, stacklevel=3)
|
| 451 |
+
|
| 452 |
+
# string conversion routines
|
| 453 |
+
|
| 454 |
+
def _str_header(self, name, symbol="-"):
|
| 455 |
+
return [name, len(name) * symbol]
|
| 456 |
+
|
| 457 |
+
def _str_indent(self, doc, indent=4):
|
| 458 |
+
return [" " * indent + line for line in doc]
|
| 459 |
+
|
| 460 |
+
def _str_signature(self):
|
| 461 |
+
if self["Signature"]:
|
| 462 |
+
return [self["Signature"].replace("*", r"\*")] + [""]
|
| 463 |
+
return [""]
|
| 464 |
+
|
| 465 |
+
def _str_summary(self):
|
| 466 |
+
if self["Summary"]:
|
| 467 |
+
return self["Summary"] + [""]
|
| 468 |
+
return []
|
| 469 |
+
|
| 470 |
+
def _str_extended_summary(self):
|
| 471 |
+
if self["Extended Summary"]:
|
| 472 |
+
return self["Extended Summary"] + [""]
|
| 473 |
+
return []
|
| 474 |
+
|
| 475 |
+
def _str_param_list(self, name):
|
| 476 |
+
out = []
|
| 477 |
+
if self[name]:
|
| 478 |
+
out += self._str_header(name)
|
| 479 |
+
for param in self[name]:
|
| 480 |
+
parts = []
|
| 481 |
+
if param.name:
|
| 482 |
+
parts.append(param.name)
|
| 483 |
+
if param.type:
|
| 484 |
+
parts.append(param.type)
|
| 485 |
+
out += [" : ".join(parts)]
|
| 486 |
+
if param.desc and "".join(param.desc).strip():
|
| 487 |
+
out += self._str_indent(param.desc)
|
| 488 |
+
out += [""]
|
| 489 |
+
return out
|
| 490 |
+
|
| 491 |
+
def _str_section(self, name):
|
| 492 |
+
out = []
|
| 493 |
+
if self[name]:
|
| 494 |
+
out += self._str_header(name)
|
| 495 |
+
out += self[name]
|
| 496 |
+
out += [""]
|
| 497 |
+
return out
|
| 498 |
+
|
| 499 |
+
def _str_see_also(self, func_role):
|
| 500 |
+
if not self["See Also"]:
|
| 501 |
+
return []
|
| 502 |
+
out = []
|
| 503 |
+
out += self._str_header("See Also")
|
| 504 |
+
out += [""]
|
| 505 |
+
last_had_desc = True
|
| 506 |
+
for funcs, desc in self["See Also"]:
|
| 507 |
+
assert isinstance(funcs, list)
|
| 508 |
+
links = []
|
| 509 |
+
for func, role in funcs:
|
| 510 |
+
if role:
|
| 511 |
+
link = f":{role}:`{func}`"
|
| 512 |
+
elif func_role:
|
| 513 |
+
link = f":{func_role}:`{func}`"
|
| 514 |
+
else:
|
| 515 |
+
link = f"`{func}`_"
|
| 516 |
+
links.append(link)
|
| 517 |
+
link = ", ".join(links)
|
| 518 |
+
out += [link]
|
| 519 |
+
if desc:
|
| 520 |
+
out += self._str_indent([" ".join(desc)])
|
| 521 |
+
last_had_desc = True
|
| 522 |
+
else:
|
| 523 |
+
last_had_desc = False
|
| 524 |
+
out += self._str_indent([self.empty_description])
|
| 525 |
+
|
| 526 |
+
if last_had_desc:
|
| 527 |
+
out += [""]
|
| 528 |
+
out += [""]
|
| 529 |
+
return out
|
| 530 |
+
|
| 531 |
+
def _str_index(self):
|
| 532 |
+
idx = self["index"]
|
| 533 |
+
out = []
|
| 534 |
+
output_index = False
|
| 535 |
+
default_index = idx.get("default", "")
|
| 536 |
+
if default_index:
|
| 537 |
+
output_index = True
|
| 538 |
+
out += [f".. index:: {default_index}"]
|
| 539 |
+
for section, references in idx.items():
|
| 540 |
+
if section == "default":
|
| 541 |
+
continue
|
| 542 |
+
output_index = True
|
| 543 |
+
out += [f" :{section}: {', '.join(references)}"]
|
| 544 |
+
if output_index:
|
| 545 |
+
return out
|
| 546 |
+
return ""
|
| 547 |
+
|
| 548 |
+
def __str__(self, func_role=""):
|
| 549 |
+
out = []
|
| 550 |
+
out += self._str_signature()
|
| 551 |
+
out += self._str_summary()
|
| 552 |
+
out += self._str_extended_summary()
|
| 553 |
+
out += self._str_param_list("Parameters")
|
| 554 |
+
for param_list in ("Attributes", "Methods"):
|
| 555 |
+
out += self._str_param_list(param_list)
|
| 556 |
+
for param_list in (
|
| 557 |
+
"Returns",
|
| 558 |
+
"Yields",
|
| 559 |
+
"Receives",
|
| 560 |
+
"Other Parameters",
|
| 561 |
+
"Raises",
|
| 562 |
+
"Warns",
|
| 563 |
+
):
|
| 564 |
+
out += self._str_param_list(param_list)
|
| 565 |
+
out += self._str_section("Warnings")
|
| 566 |
+
out += self._str_see_also(func_role)
|
| 567 |
+
for s in ("Notes", "References", "Examples"):
|
| 568 |
+
out += self._str_section(s)
|
| 569 |
+
out += self._str_index()
|
| 570 |
+
return "\n".join(out)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def dedent_lines(lines):
|
| 574 |
+
"""Deindent a list of lines maximally"""
|
| 575 |
+
return textwrap.dedent("\n".join(lines)).split("\n")
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class FunctionDoc(NumpyDocString):
|
| 579 |
+
def __init__(self, func, role="func", doc=None, config=None):
|
| 580 |
+
self._f = func
|
| 581 |
+
self._role = role # e.g. "func" or "meth"
|
| 582 |
+
|
| 583 |
+
if doc is None:
|
| 584 |
+
if func is None:
|
| 585 |
+
raise ValueError("No function or docstring given")
|
| 586 |
+
doc = inspect.getdoc(func) or ""
|
| 587 |
+
if config is None:
|
| 588 |
+
config = {}
|
| 589 |
+
NumpyDocString.__init__(self, doc, config)
|
| 590 |
+
|
| 591 |
+
def get_func(self):
|
| 592 |
+
func_name = getattr(self._f, "__name__", self.__class__.__name__)
|
| 593 |
+
if inspect.isclass(self._f):
|
| 594 |
+
func = getattr(self._f, "__call__", self._f.__init__)
|
| 595 |
+
else:
|
| 596 |
+
func = self._f
|
| 597 |
+
return func, func_name
|
| 598 |
+
|
| 599 |
+
def __str__(self):
|
| 600 |
+
out = ""
|
| 601 |
+
|
| 602 |
+
func, func_name = self.get_func()
|
| 603 |
+
|
| 604 |
+
roles = {"func": "function", "meth": "method"}
|
| 605 |
+
|
| 606 |
+
if self._role:
|
| 607 |
+
if self._role not in roles:
|
| 608 |
+
print(f"Warning: invalid role {self._role}")
|
| 609 |
+
out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
|
| 610 |
+
|
| 611 |
+
out += super().__str__(func_role=self._role)
|
| 612 |
+
return out
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class ObjDoc(NumpyDocString):
|
| 616 |
+
def __init__(self, obj, doc=None, config=None):
|
| 617 |
+
self._f = obj
|
| 618 |
+
if config is None:
|
| 619 |
+
config = {}
|
| 620 |
+
NumpyDocString.__init__(self, doc, config=config)
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class ClassDoc(NumpyDocString):
|
| 624 |
+
extra_public_methods = ["__call__"]
|
| 625 |
+
|
| 626 |
+
def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
|
| 627 |
+
if not inspect.isclass(cls) and cls is not None:
|
| 628 |
+
raise ValueError(f"Expected a class or None, but got {cls!r}")
|
| 629 |
+
self._cls = cls
|
| 630 |
+
|
| 631 |
+
if "sphinx" in sys.modules:
|
| 632 |
+
from sphinx.ext.autodoc import ALL
|
| 633 |
+
else:
|
| 634 |
+
ALL = object()
|
| 635 |
+
|
| 636 |
+
if config is None:
|
| 637 |
+
config = {}
|
| 638 |
+
self.show_inherited_members = config.get("show_inherited_class_members", True)
|
| 639 |
+
|
| 640 |
+
if modulename and not modulename.endswith("."):
|
| 641 |
+
modulename += "."
|
| 642 |
+
self._mod = modulename
|
| 643 |
+
|
| 644 |
+
if doc is None:
|
| 645 |
+
if cls is None:
|
| 646 |
+
raise ValueError("No class or documentation string given")
|
| 647 |
+
doc = pydoc.getdoc(cls)
|
| 648 |
+
|
| 649 |
+
NumpyDocString.__init__(self, doc)
|
| 650 |
+
|
| 651 |
+
_members = config.get("members", [])
|
| 652 |
+
if _members is ALL:
|
| 653 |
+
_members = None
|
| 654 |
+
_exclude = config.get("exclude-members", [])
|
| 655 |
+
|
| 656 |
+
if config.get("show_class_members", True) and _exclude is not ALL:
|
| 657 |
+
|
| 658 |
+
def splitlines_x(s):
|
| 659 |
+
if not s:
|
| 660 |
+
return []
|
| 661 |
+
else:
|
| 662 |
+
return s.splitlines()
|
| 663 |
+
|
| 664 |
+
for field, items in [
|
| 665 |
+
("Methods", self.methods),
|
| 666 |
+
("Attributes", self.properties),
|
| 667 |
+
]:
|
| 668 |
+
if not self[field]:
|
| 669 |
+
doc_list = []
|
| 670 |
+
for name in sorted(items):
|
| 671 |
+
if name in _exclude or (_members and name not in _members):
|
| 672 |
+
continue
|
| 673 |
+
try:
|
| 674 |
+
doc_item = pydoc.getdoc(getattr(self._cls, name))
|
| 675 |
+
doc_list.append(Parameter(name, "", splitlines_x(doc_item)))
|
| 676 |
+
except AttributeError:
|
| 677 |
+
pass # method doesn't exist
|
| 678 |
+
self[field] = doc_list
|
| 679 |
+
|
| 680 |
+
@property
|
| 681 |
+
def methods(self):
|
| 682 |
+
if self._cls is None:
|
| 683 |
+
return []
|
| 684 |
+
return [
|
| 685 |
+
name
|
| 686 |
+
for name, func in inspect.getmembers(self._cls)
|
| 687 |
+
if (
|
| 688 |
+
(not name.startswith("_") or name in self.extra_public_methods)
|
| 689 |
+
and isinstance(func, Callable)
|
| 690 |
+
and self._is_show_member(name)
|
| 691 |
+
)
|
| 692 |
+
]
|
| 693 |
+
|
| 694 |
+
@property
|
| 695 |
+
def properties(self):
|
| 696 |
+
if self._cls is None:
|
| 697 |
+
return []
|
| 698 |
+
return [
|
| 699 |
+
name
|
| 700 |
+
for name, func in inspect.getmembers(self._cls)
|
| 701 |
+
if (
|
| 702 |
+
not name.startswith("_")
|
| 703 |
+
and not self._should_skip_member(name, self._cls)
|
| 704 |
+
and (
|
| 705 |
+
func is None
|
| 706 |
+
or isinstance(func, (property, cached_property))
|
| 707 |
+
or inspect.isdatadescriptor(func)
|
| 708 |
+
)
|
| 709 |
+
and self._is_show_member(name)
|
| 710 |
+
)
|
| 711 |
+
]
|
| 712 |
+
|
| 713 |
+
@staticmethod
|
| 714 |
+
def _should_skip_member(name, klass):
|
| 715 |
+
return (
|
| 716 |
+
# Namedtuples should skip everything in their ._fields as the
|
| 717 |
+
# docstrings for each of the members is: "Alias for field number X"
|
| 718 |
+
issubclass(klass, tuple)
|
| 719 |
+
and hasattr(klass, "_asdict")
|
| 720 |
+
and hasattr(klass, "_fields")
|
| 721 |
+
and name in klass._fields
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
def _is_show_member(self, name):
|
| 725 |
+
return (
|
| 726 |
+
# show all class members
|
| 727 |
+
self.show_inherited_members
|
| 728 |
+
# or class member is not inherited
|
| 729 |
+
or name in self._cls.__dict__
|
| 730 |
+
)
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
def get_doc_object(
|
| 734 |
+
obj,
|
| 735 |
+
what=None,
|
| 736 |
+
doc=None,
|
| 737 |
+
config=None,
|
| 738 |
+
class_doc=ClassDoc,
|
| 739 |
+
func_doc=FunctionDoc,
|
| 740 |
+
obj_doc=ObjDoc,
|
| 741 |
+
):
|
| 742 |
+
if what is None:
|
| 743 |
+
if inspect.isclass(obj):
|
| 744 |
+
what = "class"
|
| 745 |
+
elif inspect.ismodule(obj):
|
| 746 |
+
what = "module"
|
| 747 |
+
elif isinstance(obj, Callable):
|
| 748 |
+
what = "function"
|
| 749 |
+
else:
|
| 750 |
+
what = "object"
|
| 751 |
+
if config is None:
|
| 752 |
+
config = {}
|
| 753 |
+
|
| 754 |
+
if what == "class":
|
| 755 |
+
return class_doc(obj, func_doc=func_doc, doc=doc, config=config)
|
| 756 |
+
elif what in ("function", "method"):
|
| 757 |
+
return func_doc(obj, doc=doc, config=config)
|
| 758 |
+
else:
|
| 759 |
+
if doc is None:
|
| 760 |
+
doc = pydoc.getdoc(obj)
|
| 761 |
+
return obj_doc(obj, doc, config=config)
|
python_embeded/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ative_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)
|
python_embeded/Lib/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)
|
python_embeded/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.56 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/_lib/_gcutils.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module for testing automatic garbage collection of objects
|
| 3 |
+
|
| 4 |
+
.. autosummary::
|
| 5 |
+
:toctree: generated/
|
| 6 |
+
|
| 7 |
+
set_gc_state - enable or disable garbage collection
|
| 8 |
+
gc_state - context manager for given state of garbage collector
|
| 9 |
+
assert_deallocated - context manager to check for circular references on object
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
import weakref
|
| 13 |
+
import gc
|
| 14 |
+
|
| 15 |
+
from contextlib import contextmanager
|
| 16 |
+
from platform import python_implementation
|
| 17 |
+
|
| 18 |
+
__all__ = ['set_gc_state', 'gc_state', 'assert_deallocated']
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
IS_PYPY = python_implementation() == 'PyPy'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ReferenceError(AssertionError):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def set_gc_state(state):
|
| 29 |
+
""" Set status of garbage collector """
|
| 30 |
+
if gc.isenabled() == state:
|
| 31 |
+
return
|
| 32 |
+
if state:
|
| 33 |
+
gc.enable()
|
| 34 |
+
else:
|
| 35 |
+
gc.disable()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@contextmanager
|
| 39 |
+
def gc_state(state):
|
| 40 |
+
""" Context manager to set state of garbage collector to `state`
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
state : bool
|
| 45 |
+
True for gc enabled, False for disabled
|
| 46 |
+
|
| 47 |
+
Examples
|
| 48 |
+
--------
|
| 49 |
+
>>> with gc_state(False):
|
| 50 |
+
... assert not gc.isenabled()
|
| 51 |
+
>>> with gc_state(True):
|
| 52 |
+
... assert gc.isenabled()
|
| 53 |
+
"""
|
| 54 |
+
orig_state = gc.isenabled()
|
| 55 |
+
set_gc_state(state)
|
| 56 |
+
yield
|
| 57 |
+
set_gc_state(orig_state)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@contextmanager
|
| 61 |
+
def assert_deallocated(func, *args, **kwargs):
|
| 62 |
+
"""Context manager to check that object is deallocated
|
| 63 |
+
|
| 64 |
+
This is useful for checking that an object can be freed directly by
|
| 65 |
+
reference counting, without requiring gc to break reference cycles.
|
| 66 |
+
GC is disabled inside the context manager.
|
| 67 |
+
|
| 68 |
+
This check is not available on PyPy.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
func : callable
|
| 73 |
+
Callable to create object to check
|
| 74 |
+
\\*args : sequence
|
| 75 |
+
positional arguments to `func` in order to create object to check
|
| 76 |
+
\\*\\*kwargs : dict
|
| 77 |
+
keyword arguments to `func` in order to create object to check
|
| 78 |
+
|
| 79 |
+
Examples
|
| 80 |
+
--------
|
| 81 |
+
>>> class C: pass
|
| 82 |
+
>>> with assert_deallocated(C) as c:
|
| 83 |
+
... # do something
|
| 84 |
+
... del c
|
| 85 |
+
|
| 86 |
+
>>> class C:
|
| 87 |
+
... def __init__(self):
|
| 88 |
+
... self._circular = self # Make circular reference
|
| 89 |
+
>>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL
|
| 90 |
+
... # do something
|
| 91 |
+
... del c
|
| 92 |
+
Traceback (most recent call last):
|
| 93 |
+
...
|
| 94 |
+
ReferenceError: Remaining reference(s) to object
|
| 95 |
+
"""
|
| 96 |
+
if IS_PYPY:
|
| 97 |
+
raise RuntimeError("assert_deallocated is unavailable on PyPy")
|
| 98 |
+
|
| 99 |
+
with gc_state(False):
|
| 100 |
+
obj = func(*args, **kwargs)
|
| 101 |
+
ref = weakref.ref(obj)
|
| 102 |
+
yield obj
|
| 103 |
+
del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 |
+
|
| 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
|
python_embeded/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.64 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.72 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.71 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/_lib/_testutils.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 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()
|
python_embeded/Lib/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
|
python_embeded/Lib/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)
|
python_embeded/Lib/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
|
python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NumPy Array API compatibility library
|
| 3 |
+
|
| 4 |
+
This is a small wrapper around NumPy and CuPy that is compatible with the
|
| 5 |
+
Array API standard https://data-apis.org/array-api/latest/. See also NEP 47
|
| 6 |
+
https://numpy.org/neps/nep-0047-array-api-standard.html.
|
| 7 |
+
|
| 8 |
+
Unlike array_api_strict, this is not a strict minimal implementation of the
|
| 9 |
+
Array API, but rather just an extension of the main NumPy namespace with
|
| 10 |
+
changes needed to be compliant with the Array API. See
|
| 11 |
+
https://numpy.org/doc/stable/reference/array_api.html for a full list of
|
| 12 |
+
changes. In particular, unlike array_api_strict, this package does not use a
|
| 13 |
+
separate Array object, but rather just uses numpy.ndarray directly.
|
| 14 |
+
|
| 15 |
+
Library authors using the Array API may wish to test against array_api_strict
|
| 16 |
+
to ensure they are not using functionality outside of the standard, but prefer
|
| 17 |
+
this implementation for the default when working with NumPy arrays.
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
__version__ = '1.9.1'
|
| 21 |
+
|
| 22 |
+
from .common import * # noqa: F401, F403
|
python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/_internal.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Internal helpers
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from functools import wraps
|
| 6 |
+
from inspect import signature
|
| 7 |
+
|
| 8 |
+
def get_xp(xp):
|
| 9 |
+
"""
|
| 10 |
+
Decorator to automatically replace xp with the corresponding array module.
|
| 11 |
+
|
| 12 |
+
Use like
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
@get_xp(np)
|
| 17 |
+
def func(x, /, xp, kwarg=None):
|
| 18 |
+
return xp.func(x, kwarg=kwarg)
|
| 19 |
+
|
| 20 |
+
Note that xp must be a keyword argument and come after all non-keyword
|
| 21 |
+
arguments.
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def inner(f):
|
| 26 |
+
@wraps(f)
|
| 27 |
+
def wrapped_f(*args, **kwargs):
|
| 28 |
+
return f(*args, xp=xp, **kwargs)
|
| 29 |
+
|
| 30 |
+
sig = signature(f)
|
| 31 |
+
new_sig = sig.replace(
|
| 32 |
+
parameters=[sig.parameters[i] for i in sig.parameters if i != "xp"]
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
if wrapped_f.__doc__ is None:
|
| 36 |
+
wrapped_f.__doc__ = f"""\
|
| 37 |
+
Array API compatibility wrapper for {f.__name__}.
|
| 38 |
+
|
| 39 |
+
See the corresponding documentation in NumPy/CuPy and/or the array API
|
| 40 |
+
specification for more details.
|
| 41 |
+
|
| 42 |
+
"""
|
| 43 |
+
wrapped_f.__signature__ = new_sig
|
| 44 |
+
return wrapped_f
|
| 45 |
+
|
| 46 |
+
return inner
|
python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from ._funcs import atleast_nd, cov, create_diagonal, expand_dims, kron, sinc
|
| 4 |
+
|
| 5 |
+
__version__ = "0.2.0"
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"__version__",
|
| 9 |
+
"atleast_nd",
|
| 10 |
+
"cov",
|
| 11 |
+
"create_diagonal",
|
| 12 |
+
"expand_dims",
|
| 13 |
+
"kron",
|
| 14 |
+
"sinc",
|
| 15 |
+
]
|
python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_funcs.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from ._typing import Array, ModuleType
|
| 8 |
+
|
| 9 |
+
__all__ = ["atleast_nd", "cov", "create_diagonal", "expand_dims", "kron", "sinc"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array:
|
| 13 |
+
"""
|
| 14 |
+
Recursively expand the dimension of an array to at least `ndim`.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
x : array
|
| 19 |
+
ndim : int
|
| 20 |
+
The minimum number of dimensions for the result.
|
| 21 |
+
xp : array_namespace
|
| 22 |
+
The standard-compatible namespace for `x`.
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
res : array
|
| 27 |
+
An array with ``res.ndim`` >= `ndim`.
|
| 28 |
+
If ``x.ndim`` >= `ndim`, `x` is returned.
|
| 29 |
+
If ``x.ndim`` < `ndim`, `x` is expanded by prepending new axes
|
| 30 |
+
until ``res.ndim`` equals `ndim`.
|
| 31 |
+
|
| 32 |
+
Examples
|
| 33 |
+
--------
|
| 34 |
+
>>> import array_api_strict as xp
|
| 35 |
+
>>> import array_api_extra as xpx
|
| 36 |
+
>>> x = xp.asarray([1])
|
| 37 |
+
>>> xpx.atleast_nd(x, ndim=3, xp=xp)
|
| 38 |
+
Array([[[1]]], dtype=array_api_strict.int64)
|
| 39 |
+
|
| 40 |
+
>>> x = xp.asarray([[[1, 2],
|
| 41 |
+
... [3, 4]]])
|
| 42 |
+
>>> xpx.atleast_nd(x, ndim=1, xp=xp) is x
|
| 43 |
+
True
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
if x.ndim < ndim:
|
| 47 |
+
x = xp.expand_dims(x, axis=0)
|
| 48 |
+
x = atleast_nd(x, ndim=ndim, xp=xp)
|
| 49 |
+
return x
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def cov(m: Array, /, *, xp: ModuleType) -> Array:
|
| 53 |
+
"""
|
| 54 |
+
Estimate a covariance matrix.
|
| 55 |
+
|
| 56 |
+
Covariance indicates the level to which two variables vary together.
|
| 57 |
+
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
|
| 58 |
+
then the covariance matrix element :math:`C_{ij}` is the covariance of
|
| 59 |
+
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
|
| 60 |
+
of :math:`x_i`.
|
| 61 |
+
|
| 62 |
+
This provides a subset of the functionality of ``numpy.cov``.
|
| 63 |
+
|
| 64 |
+
Parameters
|
| 65 |
+
----------
|
| 66 |
+
m : array
|
| 67 |
+
A 1-D or 2-D array containing multiple variables and observations.
|
| 68 |
+
Each row of `m` represents a variable, and each column a single
|
| 69 |
+
observation of all those variables.
|
| 70 |
+
xp : array_namespace
|
| 71 |
+
The standard-compatible namespace for `m`.
|
| 72 |
+
|
| 73 |
+
Returns
|
| 74 |
+
-------
|
| 75 |
+
res : array
|
| 76 |
+
The covariance matrix of the variables.
|
| 77 |
+
|
| 78 |
+
Examples
|
| 79 |
+
--------
|
| 80 |
+
>>> import array_api_strict as xp
|
| 81 |
+
>>> import array_api_extra as xpx
|
| 82 |
+
|
| 83 |
+
Consider two variables, :math:`x_0` and :math:`x_1`, which
|
| 84 |
+
correlate perfectly, but in opposite directions:
|
| 85 |
+
|
| 86 |
+
>>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T
|
| 87 |
+
>>> x
|
| 88 |
+
Array([[0, 1, 2],
|
| 89 |
+
[2, 1, 0]], dtype=array_api_strict.int64)
|
| 90 |
+
|
| 91 |
+
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
|
| 92 |
+
matrix shows this clearly:
|
| 93 |
+
|
| 94 |
+
>>> xpx.cov(x, xp=xp)
|
| 95 |
+
Array([[ 1., -1.],
|
| 96 |
+
[-1., 1.]], dtype=array_api_strict.float64)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
Note that element :math:`C_{0,1}`, which shows the correlation between
|
| 100 |
+
:math:`x_0` and :math:`x_1`, is negative.
|
| 101 |
+
|
| 102 |
+
Further, note how `x` and `y` are combined:
|
| 103 |
+
|
| 104 |
+
>>> x = xp.asarray([-2.1, -1, 4.3])
|
| 105 |
+
>>> y = xp.asarray([3, 1.1, 0.12])
|
| 106 |
+
>>> X = xp.stack((x, y), axis=0)
|
| 107 |
+
>>> xpx.cov(X, xp=xp)
|
| 108 |
+
Array([[11.71 , -4.286 ],
|
| 109 |
+
[-4.286 , 2.14413333]], dtype=array_api_strict.float64)
|
| 110 |
+
|
| 111 |
+
>>> xpx.cov(x, xp=xp)
|
| 112 |
+
Array(11.71, dtype=array_api_strict.float64)
|
| 113 |
+
|
| 114 |
+
>>> xpx.cov(y, xp=xp)
|
| 115 |
+
Array(2.14413333, dtype=array_api_strict.float64)
|
| 116 |
+
|
| 117 |
+
"""
|
| 118 |
+
m = xp.asarray(m, copy=True)
|
| 119 |
+
dtype = (
|
| 120 |
+
xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64)
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
m = atleast_nd(m, ndim=2, xp=xp)
|
| 124 |
+
m = xp.astype(m, dtype)
|
| 125 |
+
|
| 126 |
+
avg = _mean(m, axis=1, xp=xp)
|
| 127 |
+
fact = m.shape[1] - 1
|
| 128 |
+
|
| 129 |
+
if fact <= 0:
|
| 130 |
+
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2)
|
| 131 |
+
fact = 0.0
|
| 132 |
+
|
| 133 |
+
m -= avg[:, None]
|
| 134 |
+
m_transpose = m.T
|
| 135 |
+
if xp.isdtype(m_transpose.dtype, "complex floating"):
|
| 136 |
+
m_transpose = xp.conj(m_transpose)
|
| 137 |
+
c = m @ m_transpose
|
| 138 |
+
c /= fact
|
| 139 |
+
axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1)
|
| 140 |
+
return xp.squeeze(c, axis=axes)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def create_diagonal(x: Array, /, *, offset: int = 0, xp: ModuleType) -> Array:
|
| 144 |
+
"""
|
| 145 |
+
Construct a diagonal array.
|
| 146 |
+
|
| 147 |
+
Parameters
|
| 148 |
+
----------
|
| 149 |
+
x : array
|
| 150 |
+
A 1-D array
|
| 151 |
+
offset : int, optional
|
| 152 |
+
Offset from the leading diagonal (default is ``0``).
|
| 153 |
+
Use positive ints for diagonals above the leading diagonal,
|
| 154 |
+
and negative ints for diagonals below the leading diagonal.
|
| 155 |
+
xp : array_namespace
|
| 156 |
+
The standard-compatible namespace for `x`.
|
| 157 |
+
|
| 158 |
+
Returns
|
| 159 |
+
-------
|
| 160 |
+
res : array
|
| 161 |
+
A 2-D array with `x` on the diagonal (offset by `offset`).
|
| 162 |
+
|
| 163 |
+
Examples
|
| 164 |
+
--------
|
| 165 |
+
>>> import array_api_strict as xp
|
| 166 |
+
>>> import array_api_extra as xpx
|
| 167 |
+
>>> x = xp.asarray([2, 4, 8])
|
| 168 |
+
|
| 169 |
+
>>> xpx.create_diagonal(x, xp=xp)
|
| 170 |
+
Array([[2, 0, 0],
|
| 171 |
+
[0, 4, 0],
|
| 172 |
+
[0, 0, 8]], dtype=array_api_strict.int64)
|
| 173 |
+
|
| 174 |
+
>>> xpx.create_diagonal(x, offset=-2, xp=xp)
|
| 175 |
+
Array([[0, 0, 0, 0, 0],
|
| 176 |
+
[0, 0, 0, 0, 0],
|
| 177 |
+
[2, 0, 0, 0, 0],
|
| 178 |
+
[0, 4, 0, 0, 0],
|
| 179 |
+
[0, 0, 8, 0, 0]], dtype=array_api_strict.int64)
|
| 180 |
+
|
| 181 |
+
"""
|
| 182 |
+
if x.ndim != 1:
|
| 183 |
+
err_msg = "`x` must be 1-dimensional."
|
| 184 |
+
raise ValueError(err_msg)
|
| 185 |
+
n = x.shape[0] + abs(offset)
|
| 186 |
+
diag = xp.zeros(n**2, dtype=x.dtype)
|
| 187 |
+
i = offset if offset >= 0 else abs(offset) * n
|
| 188 |
+
diag[i : min(n * (n - offset), diag.shape[0]) : n + 1] = x
|
| 189 |
+
return xp.reshape(diag, (n, n))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _mean(
|
| 193 |
+
x: Array,
|
| 194 |
+
/,
|
| 195 |
+
*,
|
| 196 |
+
axis: int | tuple[int, ...] | None = None,
|
| 197 |
+
keepdims: bool = False,
|
| 198 |
+
xp: ModuleType,
|
| 199 |
+
) -> Array:
|
| 200 |
+
"""
|
| 201 |
+
Complex mean, https://github.com/data-apis/array-api/issues/846.
|
| 202 |
+
"""
|
| 203 |
+
if xp.isdtype(x.dtype, "complex floating"):
|
| 204 |
+
x_real = xp.real(x)
|
| 205 |
+
x_imag = xp.imag(x)
|
| 206 |
+
mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims)
|
| 207 |
+
mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims)
|
| 208 |
+
return mean_real + (mean_imag * xp.asarray(1j))
|
| 209 |
+
return xp.mean(x, axis=axis, keepdims=keepdims)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def expand_dims(
|
| 213 |
+
a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType
|
| 214 |
+
) -> Array:
|
| 215 |
+
"""
|
| 216 |
+
Expand the shape of an array.
|
| 217 |
+
|
| 218 |
+
Insert (a) new axis/axes that will appear at the position(s) specified by
|
| 219 |
+
`axis` in the expanded array shape.
|
| 220 |
+
|
| 221 |
+
This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*.
|
| 222 |
+
Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays.
|
| 223 |
+
|
| 224 |
+
Parameters
|
| 225 |
+
----------
|
| 226 |
+
a : array
|
| 227 |
+
axis : int or tuple of ints, optional
|
| 228 |
+
Position(s) in the expanded axes where the new axis (or axes) is/are placed.
|
| 229 |
+
If multiple positions are provided, they should be unique (note that a position
|
| 230 |
+
given by a positive index could also be referred to by a negative index -
|
| 231 |
+
that will also result in an error).
|
| 232 |
+
Default: ``(0,)``.
|
| 233 |
+
xp : array_namespace
|
| 234 |
+
The standard-compatible namespace for `a`.
|
| 235 |
+
|
| 236 |
+
Returns
|
| 237 |
+
-------
|
| 238 |
+
res : array
|
| 239 |
+
`a` with an expanded shape.
|
| 240 |
+
|
| 241 |
+
Examples
|
| 242 |
+
--------
|
| 243 |
+
>>> import array_api_strict as xp
|
| 244 |
+
>>> import array_api_extra as xpx
|
| 245 |
+
>>> x = xp.asarray([1, 2])
|
| 246 |
+
>>> x.shape
|
| 247 |
+
(2,)
|
| 248 |
+
|
| 249 |
+
The following is equivalent to ``x[xp.newaxis, :]`` or ``x[xp.newaxis]``:
|
| 250 |
+
|
| 251 |
+
>>> y = xpx.expand_dims(x, axis=0, xp=xp)
|
| 252 |
+
>>> y
|
| 253 |
+
Array([[1, 2]], dtype=array_api_strict.int64)
|
| 254 |
+
>>> y.shape
|
| 255 |
+
(1, 2)
|
| 256 |
+
|
| 257 |
+
The following is equivalent to ``x[:, xp.newaxis]``:
|
| 258 |
+
|
| 259 |
+
>>> y = xpx.expand_dims(x, axis=1, xp=xp)
|
| 260 |
+
>>> y
|
| 261 |
+
Array([[1],
|
| 262 |
+
[2]], dtype=array_api_strict.int64)
|
| 263 |
+
>>> y.shape
|
| 264 |
+
(2, 1)
|
| 265 |
+
|
| 266 |
+
``axis`` may also be a tuple:
|
| 267 |
+
|
| 268 |
+
>>> y = xpx.expand_dims(x, axis=(0, 1), xp=xp)
|
| 269 |
+
>>> y
|
| 270 |
+
Array([[[1, 2]]], dtype=array_api_strict.int64)
|
| 271 |
+
|
| 272 |
+
>>> y = xpx.expand_dims(x, axis=(2, 0), xp=xp)
|
| 273 |
+
>>> y
|
| 274 |
+
Array([[[1],
|
| 275 |
+
[2]]], dtype=array_api_strict.int64)
|
| 276 |
+
|
| 277 |
+
"""
|
| 278 |
+
if not isinstance(axis, tuple):
|
| 279 |
+
axis = (axis,)
|
| 280 |
+
ndim = a.ndim + len(axis)
|
| 281 |
+
if axis != () and (min(axis) < -ndim or max(axis) >= ndim):
|
| 282 |
+
err_msg = (
|
| 283 |
+
f"a provided axis position is out of bounds for array of dimension {a.ndim}"
|
| 284 |
+
)
|
| 285 |
+
raise IndexError(err_msg)
|
| 286 |
+
axis = tuple(dim % ndim for dim in axis)
|
| 287 |
+
if len(set(axis)) != len(axis):
|
| 288 |
+
err_msg = "Duplicate dimensions specified in `axis`."
|
| 289 |
+
raise ValueError(err_msg)
|
| 290 |
+
for i in sorted(axis):
|
| 291 |
+
a = xp.expand_dims(a, axis=i)
|
| 292 |
+
return a
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def kron(a: Array, b: Array, /, *, xp: ModuleType) -> Array:
|
| 296 |
+
"""
|
| 297 |
+
Kronecker product of two arrays.
|
| 298 |
+
|
| 299 |
+
Computes the Kronecker product, a composite array made of blocks of the
|
| 300 |
+
second array scaled by the first.
|
| 301 |
+
|
| 302 |
+
Equivalent to ``numpy.kron`` for NumPy arrays.
|
| 303 |
+
|
| 304 |
+
Parameters
|
| 305 |
+
----------
|
| 306 |
+
a, b : array
|
| 307 |
+
xp : array_namespace
|
| 308 |
+
The standard-compatible namespace for `a` and `b`.
|
| 309 |
+
|
| 310 |
+
Returns
|
| 311 |
+
-------
|
| 312 |
+
res : array
|
| 313 |
+
The Kronecker product of `a` and `b`.
|
| 314 |
+
|
| 315 |
+
Notes
|
| 316 |
+
-----
|
| 317 |
+
The function assumes that the number of dimensions of `a` and `b`
|
| 318 |
+
are the same, if necessary prepending the smallest with ones.
|
| 319 |
+
If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
|
| 320 |
+
the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
|
| 321 |
+
The elements are products of elements from `a` and `b`, organized
|
| 322 |
+
explicitly by::
|
| 323 |
+
|
| 324 |
+
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
|
| 325 |
+
|
| 326 |
+
where::
|
| 327 |
+
|
| 328 |
+
kt = it * st + jt, t = 0,...,N
|
| 329 |
+
|
| 330 |
+
In the common 2-D case (N=1), the block structure can be visualized::
|
| 331 |
+
|
| 332 |
+
[[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
|
| 333 |
+
[ ... ... ],
|
| 334 |
+
[ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
Examples
|
| 338 |
+
--------
|
| 339 |
+
>>> import array_api_strict as xp
|
| 340 |
+
>>> import array_api_extra as xpx
|
| 341 |
+
>>> xpx.kron(xp.asarray([1, 10, 100]), xp.asarray([5, 6, 7]), xp=xp)
|
| 342 |
+
Array([ 5, 6, 7, 50, 60, 70, 500,
|
| 343 |
+
600, 700], dtype=array_api_strict.int64)
|
| 344 |
+
|
| 345 |
+
>>> xpx.kron(xp.asarray([5, 6, 7]), xp.asarray([1, 10, 100]), xp=xp)
|
| 346 |
+
Array([ 5, 50, 500, 6, 60, 600, 7,
|
| 347 |
+
70, 700], dtype=array_api_strict.int64)
|
| 348 |
+
|
| 349 |
+
>>> xpx.kron(xp.eye(2), xp.ones((2, 2)), xp=xp)
|
| 350 |
+
Array([[1., 1., 0., 0.],
|
| 351 |
+
[1., 1., 0., 0.],
|
| 352 |
+
[0., 0., 1., 1.],
|
| 353 |
+
[0., 0., 1., 1.]], dtype=array_api_strict.float64)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
>>> a = xp.reshape(xp.arange(100), (2, 5, 2, 5))
|
| 357 |
+
>>> b = xp.reshape(xp.arange(24), (2, 3, 4))
|
| 358 |
+
>>> c = xpx.kron(a, b, xp=xp)
|
| 359 |
+
>>> c.shape
|
| 360 |
+
(2, 10, 6, 20)
|
| 361 |
+
>>> I = (1, 3, 0, 2)
|
| 362 |
+
>>> J = (0, 2, 1)
|
| 363 |
+
>>> J1 = (0,) + J # extend to ndim=4
|
| 364 |
+
>>> S1 = (1,) + b.shape
|
| 365 |
+
>>> K = tuple(xp.asarray(I) * xp.asarray(S1) + xp.asarray(J1))
|
| 366 |
+
>>> c[K] == a[I]*b[J]
|
| 367 |
+
Array(True, dtype=array_api_strict.bool)
|
| 368 |
+
|
| 369 |
+
"""
|
| 370 |
+
|
| 371 |
+
b = xp.asarray(b)
|
| 372 |
+
singletons = (1,) * (b.ndim - a.ndim)
|
| 373 |
+
a = xp.broadcast_to(xp.asarray(a), singletons + a.shape)
|
| 374 |
+
|
| 375 |
+
nd_b, nd_a = b.ndim, a.ndim
|
| 376 |
+
nd_max = max(nd_b, nd_a)
|
| 377 |
+
if nd_a == 0 or nd_b == 0:
|
| 378 |
+
return xp.multiply(a, b)
|
| 379 |
+
|
| 380 |
+
a_shape = a.shape
|
| 381 |
+
b_shape = b.shape
|
| 382 |
+
|
| 383 |
+
# Equalise the shapes by prepending smaller one with 1s
|
| 384 |
+
a_shape = (1,) * max(0, nd_b - nd_a) + a_shape
|
| 385 |
+
b_shape = (1,) * max(0, nd_a - nd_b) + b_shape
|
| 386 |
+
|
| 387 |
+
# Insert empty dimensions
|
| 388 |
+
a_arr = expand_dims(a, axis=tuple(range(nd_b - nd_a)), xp=xp)
|
| 389 |
+
b_arr = expand_dims(b, axis=tuple(range(nd_a - nd_b)), xp=xp)
|
| 390 |
+
|
| 391 |
+
# Compute the product
|
| 392 |
+
a_arr = expand_dims(a_arr, axis=tuple(range(1, nd_max * 2, 2)), xp=xp)
|
| 393 |
+
b_arr = expand_dims(b_arr, axis=tuple(range(0, nd_max * 2, 2)), xp=xp)
|
| 394 |
+
result = xp.multiply(a_arr, b_arr)
|
| 395 |
+
|
| 396 |
+
# Reshape back and return
|
| 397 |
+
a_shape = xp.asarray(a_shape)
|
| 398 |
+
b_shape = xp.asarray(b_shape)
|
| 399 |
+
return xp.reshape(result, tuple(xp.multiply(a_shape, b_shape)))
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def sinc(x: Array, /, *, xp: ModuleType) -> Array:
|
| 403 |
+
r"""
|
| 404 |
+
Return the normalized sinc function.
|
| 405 |
+
|
| 406 |
+
The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument
|
| 407 |
+
:math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not
|
| 408 |
+
only everywhere continuous but also infinitely differentiable.
|
| 409 |
+
|
| 410 |
+
.. note::
|
| 411 |
+
|
| 412 |
+
Note the normalization factor of ``pi`` used in the definition.
|
| 413 |
+
This is the most commonly used definition in signal processing.
|
| 414 |
+
Use ``sinc(x / xp.pi)`` to obtain the unnormalized sinc function
|
| 415 |
+
:math:`\sin(x)/x` that is more common in mathematics.
|
| 416 |
+
|
| 417 |
+
Parameters
|
| 418 |
+
----------
|
| 419 |
+
x : array
|
| 420 |
+
Array (possibly multi-dimensional) of values for which to calculate
|
| 421 |
+
``sinc(x)``. Must have a real floating point dtype.
|
| 422 |
+
xp : array_namespace
|
| 423 |
+
The standard-compatible namespace for `x`.
|
| 424 |
+
|
| 425 |
+
Returns
|
| 426 |
+
-------
|
| 427 |
+
res : array
|
| 428 |
+
``sinc(x)`` calculated elementwise, which has the same shape as the input.
|
| 429 |
+
|
| 430 |
+
Notes
|
| 431 |
+
-----
|
| 432 |
+
The name sinc is short for "sine cardinal" or "sinus cardinalis".
|
| 433 |
+
|
| 434 |
+
The sinc function is used in various signal processing applications,
|
| 435 |
+
including in anti-aliasing, in the construction of a Lanczos resampling
|
| 436 |
+
filter, and in interpolation.
|
| 437 |
+
|
| 438 |
+
For bandlimited interpolation of discrete-time signals, the ideal
|
| 439 |
+
interpolation kernel is proportional to the sinc function.
|
| 440 |
+
|
| 441 |
+
References
|
| 442 |
+
----------
|
| 443 |
+
.. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
|
| 444 |
+
Resource. https://mathworld.wolfram.com/SincFunction.html
|
| 445 |
+
.. [2] Wikipedia, "Sinc function",
|
| 446 |
+
https://en.wikipedia.org/wiki/Sinc_function
|
| 447 |
+
|
| 448 |
+
Examples
|
| 449 |
+
--------
|
| 450 |
+
>>> import array_api_strict as xp
|
| 451 |
+
>>> import array_api_extra as xpx
|
| 452 |
+
>>> x = xp.linspace(-4, 4, 41)
|
| 453 |
+
>>> xpx.sinc(x, xp=xp)
|
| 454 |
+
Array([-3.89817183e-17, -4.92362781e-02,
|
| 455 |
+
-8.40918587e-02, -8.90384387e-02,
|
| 456 |
+
-5.84680802e-02, 3.89817183e-17,
|
| 457 |
+
6.68206631e-02, 1.16434881e-01,
|
| 458 |
+
1.26137788e-01, 8.50444803e-02,
|
| 459 |
+
-3.89817183e-17, -1.03943254e-01,
|
| 460 |
+
-1.89206682e-01, -2.16236208e-01,
|
| 461 |
+
-1.55914881e-01, 3.89817183e-17,
|
| 462 |
+
2.33872321e-01, 5.04551152e-01,
|
| 463 |
+
7.56826729e-01, 9.35489284e-01,
|
| 464 |
+
1.00000000e+00, 9.35489284e-01,
|
| 465 |
+
7.56826729e-01, 5.04551152e-01,
|
| 466 |
+
2.33872321e-01, 3.89817183e-17,
|
| 467 |
+
-1.55914881e-01, -2.16236208e-01,
|
| 468 |
+
-1.89206682e-01, -1.03943254e-01,
|
| 469 |
+
-3.89817183e-17, 8.50444803e-02,
|
| 470 |
+
1.26137788e-01, 1.16434881e-01,
|
| 471 |
+
6.68206631e-02, 3.89817183e-17,
|
| 472 |
+
-5.84680802e-02, -8.90384387e-02,
|
| 473 |
+
-8.40918587e-02, -4.92362781e-02,
|
| 474 |
+
-3.89817183e-17], dtype=array_api_strict.float64)
|
| 475 |
+
|
| 476 |
+
"""
|
| 477 |
+
if not xp.isdtype(x.dtype, "real floating"):
|
| 478 |
+
err_msg = "`x` must have a real floating data type."
|
| 479 |
+
raise ValueError(err_msg)
|
| 480 |
+
# no scalars in `where` - array-api#807
|
| 481 |
+
y = xp.pi * xp.where(
|
| 482 |
+
x, x, xp.asarray(xp.finfo(x.dtype).smallest_normal, dtype=x.dtype)
|
| 483 |
+
)
|
| 484 |
+
return xp.sin(y) / y
|
python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_typing.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from types import ModuleType
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
Array = Any # To be changed to a Protocol later (see array-api#589)
|
| 7 |
+
|
| 8 |
+
__all__ = ["Array", "ModuleType"]
|
python_embeded/Lib/site-packages/scipy/_lib/cobyqa/framework.py
ADDED
|
@@ -0,0 +1,1240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ipy.optimize import lsq_linear
|
| 5 |
+
|
| 6 |
+
from .models import Models, Quadratic
|
| 7 |
+
from .settings import Options, Constants
|
| 8 |
+
from .subsolvers import (
|
| 9 |
+
cauchy_geometry,
|
| 10 |
+
spider_geometry,
|
| 11 |
+
normal_byrd_omojokun,
|
| 12 |
+
tangential_byrd_omojokun,
|
| 13 |
+
constrained_tangential_byrd_omojokun,
|
| 14 |
+
)
|
| 15 |
+
from .subsolvers.optim import qr_tangential_byrd_omojokun
|
| 16 |
+
from .utils import get_arrays_tol
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
TINY = np.finfo(float).tiny
|
| 20 |
+
EPS = np.finfo(float).eps
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TrustRegion:
|
| 24 |
+
"""
|
| 25 |
+
Trust-region framework.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(self, pb, options, constants):
|
| 29 |
+
"""
|
| 30 |
+
Initialize the trust-region framework.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
pb : `cobyqa.problem.Problem`
|
| 35 |
+
Problem to solve.
|
| 36 |
+
options : dict
|
| 37 |
+
Options of the solver.
|
| 38 |
+
constants : dict
|
| 39 |
+
Constants of the solver.
|
| 40 |
+
|
| 41 |
+
Raises
|
| 42 |
+
------
|
| 43 |
+
`cobyqa.utils.MaxEvalError`
|
| 44 |
+
If the maximum number of evaluations is reached.
|
| 45 |
+
`cobyqa.utils.TargetSuccess`
|
| 46 |
+
If a nearly feasible point has been found with an objective
|
| 47 |
+
function value below the target.
|
| 48 |
+
`cobyqa.utils.FeasibleSuccess`
|
| 49 |
+
If a feasible point has been found for a feasibility problem.
|
| 50 |
+
`numpy.linalg.LinAlgError`
|
| 51 |
+
If the initial interpolation system is ill-defined.
|
| 52 |
+
"""
|
| 53 |
+
# Set the initial penalty parameter.
|
| 54 |
+
self._penalty = 0.0
|
| 55 |
+
|
| 56 |
+
# Initialize the models.
|
| 57 |
+
self._pb = pb
|
| 58 |
+
self._models = Models(self._pb, options, self.penalty)
|
| 59 |
+
self._constants = constants
|
| 60 |
+
|
| 61 |
+
# Set the index of the best interpolation point.
|
| 62 |
+
self._best_index = 0
|
| 63 |
+
self.set_best_index()
|
| 64 |
+
|
| 65 |
+
# Set the initial Lagrange multipliers.
|
| 66 |
+
self._lm_linear_ub = np.zeros(self.m_linear_ub)
|
| 67 |
+
self._lm_linear_eq = np.zeros(self.m_linear_eq)
|
| 68 |
+
self._lm_nonlinear_ub = np.zeros(self.m_nonlinear_ub)
|
| 69 |
+
self._lm_nonlinear_eq = np.zeros(self.m_nonlinear_eq)
|
| 70 |
+
self.set_multipliers(self.x_best)
|
| 71 |
+
|
| 72 |
+
# Set the initial trust-region radius and the resolution.
|
| 73 |
+
self._resolution = options[Options.RHOBEG]
|
| 74 |
+
self._radius = self.resolution
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def n(self):
|
| 78 |
+
"""
|
| 79 |
+
Number of variables.
|
| 80 |
+
|
| 81 |
+
Returns
|
| 82 |
+
-------
|
| 83 |
+
int
|
| 84 |
+
Number of variables.
|
| 85 |
+
"""
|
| 86 |
+
return self._pb.n
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def m_linear_ub(self):
|
| 90 |
+
"""
|
| 91 |
+
Number of linear inequality constraints.
|
| 92 |
+
|
| 93 |
+
Returns
|
| 94 |
+
-------
|
| 95 |
+
int
|
| 96 |
+
Number of linear inequality constraints.
|
| 97 |
+
"""
|
| 98 |
+
return self._pb.m_linear_ub
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def m_linear_eq(self):
|
| 102 |
+
"""
|
| 103 |
+
Number of linear equality constraints.
|
| 104 |
+
|
| 105 |
+
Returns
|
| 106 |
+
-------
|
| 107 |
+
int
|
| 108 |
+
Number of linear equality constraints.
|
| 109 |
+
"""
|
| 110 |
+
return self._pb.m_linear_eq
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def m_nonlinear_ub(self):
|
| 114 |
+
"""
|
| 115 |
+
Number of nonlinear inequality constraints.
|
| 116 |
+
|
| 117 |
+
Returns
|
| 118 |
+
-------
|
| 119 |
+
int
|
| 120 |
+
Number of nonlinear inequality constraints.
|
| 121 |
+
"""
|
| 122 |
+
return self._pb.m_nonlinear_ub
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def m_nonlinear_eq(self):
|
| 126 |
+
"""
|
| 127 |
+
Number of nonlinear equality constraints.
|
| 128 |
+
|
| 129 |
+
Returns
|
| 130 |
+
-------
|
| 131 |
+
int
|
| 132 |
+
Number of nonlinear equality constraints.
|
| 133 |
+
"""
|
| 134 |
+
return self._pb.m_nonlinear_eq
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def radius(self):
|
| 138 |
+
"""
|
| 139 |
+
Trust-region radius.
|
| 140 |
+
|
| 141 |
+
Returns
|
| 142 |
+
-------
|
| 143 |
+
float
|
| 144 |
+
Trust-region radius.
|
| 145 |
+
"""
|
| 146 |
+
return self._radius
|
| 147 |
+
|
| 148 |
+
@radius.setter
|
| 149 |
+
def radius(self, radius):
|
| 150 |
+
"""
|
| 151 |
+
Set the trust-region radius.
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
----------
|
| 155 |
+
radius : float
|
| 156 |
+
New trust-region radius.
|
| 157 |
+
"""
|
| 158 |
+
self._radius = radius
|
| 159 |
+
if (
|
| 160 |
+
self.radius
|
| 161 |
+
<= self._constants[Constants.DECREASE_RADIUS_THRESHOLD]
|
| 162 |
+
* self.resolution
|
| 163 |
+
):
|
| 164 |
+
self._radius = self.resolution
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def resolution(self):
|
| 168 |
+
"""
|
| 169 |
+
Resolution of the trust-region framework.
|
| 170 |
+
|
| 171 |
+
The resolution is a lower bound on the trust-region radius.
|
| 172 |
+
|
| 173 |
+
Returns
|
| 174 |
+
-------
|
| 175 |
+
float
|
| 176 |
+
Resolution of the trust-region framework.
|
| 177 |
+
"""
|
| 178 |
+
return self._resolution
|
| 179 |
+
|
| 180 |
+
@resolution.setter
|
| 181 |
+
def resolution(self, resolution):
|
| 182 |
+
"""
|
| 183 |
+
Set the resolution of the trust-region framework.
|
| 184 |
+
|
| 185 |
+
Parameters
|
| 186 |
+
----------
|
| 187 |
+
resolution : float
|
| 188 |
+
New resolution of the trust-region framework.
|
| 189 |
+
"""
|
| 190 |
+
self._resolution = resolution
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def penalty(self):
|
| 194 |
+
"""
|
| 195 |
+
Penalty parameter.
|
| 196 |
+
|
| 197 |
+
Returns
|
| 198 |
+
-------
|
| 199 |
+
float
|
| 200 |
+
Penalty parameter.
|
| 201 |
+
"""
|
| 202 |
+
return self._penalty
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def models(self):
|
| 206 |
+
"""
|
| 207 |
+
Models of the objective function and constraints.
|
| 208 |
+
|
| 209 |
+
Returns
|
| 210 |
+
-------
|
| 211 |
+
`cobyqa.models.Models`
|
| 212 |
+
Models of the objective function and constraints.
|
| 213 |
+
"""
|
| 214 |
+
return self._models
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def best_index(self):
|
| 218 |
+
"""
|
| 219 |
+
Index of the best interpolation point.
|
| 220 |
+
|
| 221 |
+
Returns
|
| 222 |
+
-------
|
| 223 |
+
int
|
| 224 |
+
Index of the best interpolation point.
|
| 225 |
+
"""
|
| 226 |
+
return self._best_index
|
| 227 |
+
|
| 228 |
+
@property
|
| 229 |
+
def x_best(self):
|
| 230 |
+
"""
|
| 231 |
+
Best interpolation point.
|
| 232 |
+
|
| 233 |
+
Its value is interpreted as relative to the origin, not the base point.
|
| 234 |
+
|
| 235 |
+
Returns
|
| 236 |
+
-------
|
| 237 |
+
`numpy.ndarray`
|
| 238 |
+
Best interpolation point.
|
| 239 |
+
"""
|
| 240 |
+
return self.models.interpolation.point(self.best_index)
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def fun_best(self):
|
| 244 |
+
"""
|
| 245 |
+
Value of the objective function at `x_best`.
|
| 246 |
+
|
| 247 |
+
Returns
|
| 248 |
+
-------
|
| 249 |
+
float
|
| 250 |
+
Value of the objective function at `x_best`.
|
| 251 |
+
"""
|
| 252 |
+
return self.models.fun_val[self.best_index]
|
| 253 |
+
|
| 254 |
+
@property
|
| 255 |
+
def cub_best(self):
|
| 256 |
+
"""
|
| 257 |
+
Values of the nonlinear inequality constraints at `x_best`.
|
| 258 |
+
|
| 259 |
+
Returns
|
| 260 |
+
-------
|
| 261 |
+
`numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 262 |
+
Values of the nonlinear inequality constraints at `x_best`.
|
| 263 |
+
"""
|
| 264 |
+
return self.models.cub_val[self.best_index, :]
|
| 265 |
+
|
| 266 |
+
@property
|
| 267 |
+
def ceq_best(self):
|
| 268 |
+
"""
|
| 269 |
+
Values of the nonlinear equality constraints at `x_best`.
|
| 270 |
+
|
| 271 |
+
Returns
|
| 272 |
+
-------
|
| 273 |
+
`numpy.ndarray`, shape (m_nonlinear_eq,)
|
| 274 |
+
Values of the nonlinear equality constraints at `x_best`.
|
| 275 |
+
"""
|
| 276 |
+
return self.models.ceq_val[self.best_index, :]
|
| 277 |
+
|
| 278 |
+
def lag_model(self, x):
|
| 279 |
+
"""
|
| 280 |
+
Evaluate the Lagrangian model at a given point.
|
| 281 |
+
|
| 282 |
+
Parameters
|
| 283 |
+
----------
|
| 284 |
+
x : `numpy.ndarray`, shape (n,)
|
| 285 |
+
Point at which the Lagrangian model is evaluated.
|
| 286 |
+
|
| 287 |
+
Returns
|
| 288 |
+
-------
|
| 289 |
+
float
|
| 290 |
+
Value of the Lagrangian model at `x`.
|
| 291 |
+
"""
|
| 292 |
+
return (
|
| 293 |
+
self.models.fun(x)
|
| 294 |
+
+ self._lm_linear_ub
|
| 295 |
+
@ (self._pb.linear.a_ub @ x - self._pb.linear.b_ub)
|
| 296 |
+
+ self._lm_linear_eq
|
| 297 |
+
@ (self._pb.linear.a_eq @ x - self._pb.linear.b_eq)
|
| 298 |
+
+ self._lm_nonlinear_ub @ self.models.cub(x)
|
| 299 |
+
+ self._lm_nonlinear_eq @ self.models.ceq(x)
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
def lag_model_grad(self, x):
|
| 303 |
+
"""
|
| 304 |
+
Evaluate the gradient of the Lagrangian model at a given point.
|
| 305 |
+
|
| 306 |
+
Parameters
|
| 307 |
+
----------
|
| 308 |
+
x : `numpy.ndarray`, shape (n,)
|
| 309 |
+
Point at which the gradient of the Lagrangian model is evaluated.
|
| 310 |
+
|
| 311 |
+
Returns
|
| 312 |
+
-------
|
| 313 |
+
`numpy.ndarray`, shape (n,)
|
| 314 |
+
Gradient of the Lagrangian model at `x`.
|
| 315 |
+
"""
|
| 316 |
+
return (
|
| 317 |
+
self.models.fun_grad(x)
|
| 318 |
+
+ self._lm_linear_ub @ self._pb.linear.a_ub
|
| 319 |
+
+ self._lm_linear_eq @ self._pb.linear.a_eq
|
| 320 |
+
+ self._lm_nonlinear_ub @ self.models.cub_grad(x)
|
| 321 |
+
+ self._lm_nonlinear_eq @ self.models.ceq_grad(x)
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
def lag_model_hess(self):
|
| 325 |
+
"""
|
| 326 |
+
Evaluate the Hessian matrix of the Lagrangian model at a given point.
|
| 327 |
+
|
| 328 |
+
Returns
|
| 329 |
+
-------
|
| 330 |
+
`numpy.ndarray`, shape (n, n)
|
| 331 |
+
Hessian matrix of the Lagrangian model at `x`.
|
| 332 |
+
"""
|
| 333 |
+
hess = self.models.fun_hess()
|
| 334 |
+
if self.m_nonlinear_ub > 0:
|
| 335 |
+
hess += self._lm_nonlinear_ub @ self.models.cub_hess()
|
| 336 |
+
if self.m_nonlinear_eq > 0:
|
| 337 |
+
hess += self._lm_nonlinear_eq @ self.models.ceq_hess()
|
| 338 |
+
return hess
|
| 339 |
+
|
| 340 |
+
def lag_model_hess_prod(self, v):
|
| 341 |
+
"""
|
| 342 |
+
Evaluate the right product of the Hessian matrix of the Lagrangian
|
| 343 |
+
model with a given vector.
|
| 344 |
+
|
| 345 |
+
Parameters
|
| 346 |
+
----------
|
| 347 |
+
v : `numpy.ndarray`, shape (n,)
|
| 348 |
+
Vector with which the Hessian matrix of the Lagrangian model is
|
| 349 |
+
multiplied from the right.
|
| 350 |
+
|
| 351 |
+
Returns
|
| 352 |
+
-------
|
| 353 |
+
`numpy.ndarray`, shape (n,)
|
| 354 |
+
Right product of the Hessian matrix of the Lagrangian model with
|
| 355 |
+
`v`.
|
| 356 |
+
"""
|
| 357 |
+
return (
|
| 358 |
+
self.models.fun_hess_prod(v)
|
| 359 |
+
+ self._lm_nonlinear_ub @ self.models.cub_hess_prod(v)
|
| 360 |
+
+ self._lm_nonlinear_eq @ self.models.ceq_hess_prod(v)
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
def lag_model_curv(self, v):
|
| 364 |
+
"""
|
| 365 |
+
Evaluate the curvature of the Lagrangian model along a given direction.
|
| 366 |
+
|
| 367 |
+
Parameters
|
| 368 |
+
----------
|
| 369 |
+
v : `numpy.ndarray`, shape (n,)
|
| 370 |
+
Direction along which the curvature of the Lagrangian model is
|
| 371 |
+
evaluated.
|
| 372 |
+
|
| 373 |
+
Returns
|
| 374 |
+
-------
|
| 375 |
+
float
|
| 376 |
+
Curvature of the Lagrangian model along `v`.
|
| 377 |
+
"""
|
| 378 |
+
return (
|
| 379 |
+
self.models.fun_curv(v)
|
| 380 |
+
+ self._lm_nonlinear_ub @ self.models.cub_curv(v)
|
| 381 |
+
+ self._lm_nonlinear_eq @ self.models.ceq_curv(v)
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
def sqp_fun(self, step):
|
| 385 |
+
"""
|
| 386 |
+
Evaluate the objective function of the SQP subproblem.
|
| 387 |
+
|
| 388 |
+
Parameters
|
| 389 |
+
----------
|
| 390 |
+
step : `numpy.ndarray`, shape (n,)
|
| 391 |
+
Step along which the objective function of the SQP subproblem is
|
| 392 |
+
evaluated.
|
| 393 |
+
|
| 394 |
+
Returns
|
| 395 |
+
-------
|
| 396 |
+
float
|
| 397 |
+
Value of the objective function of the SQP subproblem along `step`.
|
| 398 |
+
"""
|
| 399 |
+
return step @ (
|
| 400 |
+
self.models.fun_grad(self.x_best)
|
| 401 |
+
+ 0.5 * self.lag_model_hess_prod(step)
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
def sqp_cub(self, step):
|
| 405 |
+
"""
|
| 406 |
+
Evaluate the linearization of the nonlinear inequality constraints.
|
| 407 |
+
|
| 408 |
+
Parameters
|
| 409 |
+
----------
|
| 410 |
+
step : `numpy.ndarray`, shape (n,)
|
| 411 |
+
Step along which the linearization of the nonlinear inequality
|
| 412 |
+
constraints is evaluated.
|
| 413 |
+
|
| 414 |
+
Returns
|
| 415 |
+
-------
|
| 416 |
+
`numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 417 |
+
Value of the linearization of the nonlinear inequality constraints
|
| 418 |
+
along `step`.
|
| 419 |
+
"""
|
| 420 |
+
return (
|
| 421 |
+
self.models.cub(self.x_best)
|
| 422 |
+
+ self.models.cub_grad(self.x_best) @ step
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
def sqp_ceq(self, step):
|
| 426 |
+
"""
|
| 427 |
+
Evaluate the linearization of the nonlinear equality constraints.
|
| 428 |
+
|
| 429 |
+
Parameters
|
| 430 |
+
----------
|
| 431 |
+
step : `numpy.ndarray`, shape (n,)
|
| 432 |
+
Step along which the linearization of the nonlinear equality
|
| 433 |
+
constraints is evaluated.
|
| 434 |
+
|
| 435 |
+
Returns
|
| 436 |
+
-------
|
| 437 |
+
`numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 438 |
+
Value of the linearization of the nonlinear equality constraints
|
| 439 |
+
along `step`.
|
| 440 |
+
"""
|
| 441 |
+
return (
|
| 442 |
+
self.models.ceq(self.x_best)
|
| 443 |
+
+ self.models.ceq_grad(self.x_best) @ step
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
def merit(self, x, fun_val=None, cub_val=None, ceq_val=None):
|
| 447 |
+
"""
|
| 448 |
+
Evaluate the merit function at a given point.
|
| 449 |
+
|
| 450 |
+
Parameters
|
| 451 |
+
----------
|
| 452 |
+
x : `numpy.ndarray`, shape (n,)
|
| 453 |
+
Point at which the merit function is evaluated.
|
| 454 |
+
fun_val : float, optional
|
| 455 |
+
Value of the objective function at `x`. If not provided, the
|
| 456 |
+
objective function is evaluated at `x`.
|
| 457 |
+
cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 458 |
+
Values of the nonlinear inequality constraints. If not provided,
|
| 459 |
+
the nonlinear inequality constraints are evaluated at `x`.
|
| 460 |
+
ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 461 |
+
Values of the nonlinear equality constraints. If not provided,
|
| 462 |
+
the nonlinear equality constraints are evaluated at `x`.
|
| 463 |
+
|
| 464 |
+
Returns
|
| 465 |
+
-------
|
| 466 |
+
float
|
| 467 |
+
Value of the merit function at `x`.
|
| 468 |
+
"""
|
| 469 |
+
if fun_val is None or cub_val is None or ceq_val is None:
|
| 470 |
+
fun_val, cub_val, ceq_val = self._pb(x, self.penalty)
|
| 471 |
+
m_val = fun_val
|
| 472 |
+
if self._penalty > 0.0:
|
| 473 |
+
c_val = self._pb.violation(x, cub_val=cub_val, ceq_val=ceq_val)
|
| 474 |
+
if np.count_nonzero(c_val):
|
| 475 |
+
m_val += self._penalty * np.linalg.norm(c_val)
|
| 476 |
+
return m_val
|
| 477 |
+
|
| 478 |
+
def get_constraint_linearizations(self, x):
|
| 479 |
+
"""
|
| 480 |
+
Get the linearizations of the constraints at a given point.
|
| 481 |
+
|
| 482 |
+
Parameters
|
| 483 |
+
----------
|
| 484 |
+
x : `numpy.ndarray`, shape (n,)
|
| 485 |
+
Point at which the linearizations of the constraints are evaluated.
|
| 486 |
+
|
| 487 |
+
Returns
|
| 488 |
+
-------
|
| 489 |
+
`numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub, n)
|
| 490 |
+
Left-hand side matrix of the linearized inequality constraints.
|
| 491 |
+
`numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub,)
|
| 492 |
+
Right-hand side vector of the linearized inequality constraints.
|
| 493 |
+
`numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq, n)
|
| 494 |
+
Left-hand side matrix of the linearized equality constraints.
|
| 495 |
+
`numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq,)
|
| 496 |
+
Right-hand side vector of the linearized equality constraints.
|
| 497 |
+
"""
|
| 498 |
+
aub = np.block(
|
| 499 |
+
[
|
| 500 |
+
[self._pb.linear.a_ub],
|
| 501 |
+
[self.models.cub_grad(x)],
|
| 502 |
+
]
|
| 503 |
+
)
|
| 504 |
+
bub = np.block(
|
| 505 |
+
[
|
| 506 |
+
self._pb.linear.b_ub - self._pb.linear.a_ub @ x,
|
| 507 |
+
-self.models.cub(x),
|
| 508 |
+
]
|
| 509 |
+
)
|
| 510 |
+
aeq = np.block(
|
| 511 |
+
[
|
| 512 |
+
[self._pb.linear.a_eq],
|
| 513 |
+
[self.models.ceq_grad(x)],
|
| 514 |
+
]
|
| 515 |
+
)
|
| 516 |
+
beq = np.block(
|
| 517 |
+
[
|
| 518 |
+
self._pb.linear.b_eq - self._pb.linear.a_eq @ x,
|
| 519 |
+
-self.models.ceq(x),
|
| 520 |
+
]
|
| 521 |
+
)
|
| 522 |
+
return aub, bub, aeq, beq
|
| 523 |
+
|
| 524 |
+
def get_trust_region_step(self, options):
|
| 525 |
+
"""
|
| 526 |
+
Get the trust-region step.
|
| 527 |
+
|
| 528 |
+
The trust-region step is computed by solving the derivative-free
|
| 529 |
+
trust-region SQP subproblem using a Byrd-Omojokun composite-step
|
| 530 |
+
approach. For more details, see Section 5.2.3 of [1]_.
|
| 531 |
+
|
| 532 |
+
Parameters
|
| 533 |
+
----------
|
| 534 |
+
options : dict
|
| 535 |
+
Options of the solver.
|
| 536 |
+
|
| 537 |
+
Returns
|
| 538 |
+
-------
|
| 539 |
+
`numpy.ndarray`, shape (n,)
|
| 540 |
+
Normal step.
|
| 541 |
+
`numpy.ndarray`, shape (n,)
|
| 542 |
+
Tangential step.
|
| 543 |
+
|
| 544 |
+
References
|
| 545 |
+
----------
|
| 546 |
+
.. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization
|
| 547 |
+
Methods and Software*. PhD thesis, Department of Applied
|
| 548 |
+
Mathematics, The Hong Kong Polytechnic University, Hong Kong, China,
|
| 549 |
+
2022. URL: https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 550 |
+
"""
|
| 551 |
+
# Evaluate the linearizations of the constraints.
|
| 552 |
+
aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
|
| 553 |
+
xl = self._pb.bounds.xl - self.x_best
|
| 554 |
+
xu = self._pb.bounds.xu - self.x_best
|
| 555 |
+
|
| 556 |
+
# Evaluate the normal step.
|
| 557 |
+
radius = self._constants[Constants.BYRD_OMOJOKUN_FACTOR] * self.radius
|
| 558 |
+
normal_step = normal_byrd_omojokun(
|
| 559 |
+
aub,
|
| 560 |
+
bub,
|
| 561 |
+
aeq,
|
| 562 |
+
beq,
|
| 563 |
+
xl,
|
| 564 |
+
xu,
|
| 565 |
+
radius,
|
| 566 |
+
options[Options.DEBUG],
|
| 567 |
+
**self._constants,
|
| 568 |
+
)
|
| 569 |
+
if options[Options.DEBUG]:
|
| 570 |
+
tol = get_arrays_tol(xl, xu)
|
| 571 |
+
if (np.any(normal_step + tol < xl)
|
| 572 |
+
or np.any(xu < normal_step - tol)):
|
| 573 |
+
warnings.warn(
|
| 574 |
+
"the normal step does not respect the bound constraint.",
|
| 575 |
+
RuntimeWarning,
|
| 576 |
+
2,
|
| 577 |
+
)
|
| 578 |
+
if np.linalg.norm(normal_step) > 1.1 * radius:
|
| 579 |
+
warnings.warn(
|
| 580 |
+
"the normal step does not respect the trust-region "
|
| 581 |
+
"constraint.",
|
| 582 |
+
RuntimeWarning,
|
| 583 |
+
2,
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
# Evaluate the tangential step.
|
| 587 |
+
radius = np.sqrt(self.radius**2.0 - normal_step @ normal_step)
|
| 588 |
+
xl -= normal_step
|
| 589 |
+
xu -= normal_step
|
| 590 |
+
bub = np.maximum(bub - aub @ normal_step, 0.0)
|
| 591 |
+
g_best = self.models.fun_grad(self.x_best) + self.lag_model_hess_prod(
|
| 592 |
+
normal_step
|
| 593 |
+
)
|
| 594 |
+
if self._pb.type in ["unconstrained", "bound-constrained"]:
|
| 595 |
+
tangential_step = tangential_byrd_omojokun(
|
| 596 |
+
g_best,
|
| 597 |
+
self.lag_model_hess_prod,
|
| 598 |
+
xl,
|
| 599 |
+
xu,
|
| 600 |
+
radius,
|
| 601 |
+
options[Options.DEBUG],
|
| 602 |
+
**self._constants,
|
| 603 |
+
)
|
| 604 |
+
else:
|
| 605 |
+
tangential_step = constrained_tangential_byrd_omojokun(
|
| 606 |
+
g_best,
|
| 607 |
+
self.lag_model_hess_prod,
|
| 608 |
+
xl,
|
| 609 |
+
xu,
|
| 610 |
+
aub,
|
| 611 |
+
bub,
|
| 612 |
+
aeq,
|
| 613 |
+
radius,
|
| 614 |
+
options["debug"],
|
| 615 |
+
**self._constants,
|
| 616 |
+
)
|
| 617 |
+
if options[Options.DEBUG]:
|
| 618 |
+
tol = get_arrays_tol(xl, xu)
|
| 619 |
+
if np.any(tangential_step + tol < xl) or np.any(
|
| 620 |
+
xu < tangential_step - tol
|
| 621 |
+
):
|
| 622 |
+
warnings.warn(
|
| 623 |
+
"The tangential step does not respect the bound "
|
| 624 |
+
"constraints.",
|
| 625 |
+
RuntimeWarning,
|
| 626 |
+
2,
|
| 627 |
+
)
|
| 628 |
+
if (
|
| 629 |
+
np.linalg.norm(normal_step + tangential_step)
|
| 630 |
+
> 1.1 * np.sqrt(2.0) * self.radius
|
| 631 |
+
):
|
| 632 |
+
warnings.warn(
|
| 633 |
+
"The trial step does not respect the trust-region "
|
| 634 |
+
"constraint.",
|
| 635 |
+
RuntimeWarning,
|
| 636 |
+
2,
|
| 637 |
+
)
|
| 638 |
+
return normal_step, tangential_step
|
| 639 |
+
|
| 640 |
+
def get_geometry_step(self, k_new, options):
|
| 641 |
+
"""
|
| 642 |
+
Get the geometry-improving step.
|
| 643 |
+
|
| 644 |
+
Three different geometry-improving steps are computed and the best one
|
| 645 |
+
is returned. For more details, see Section 5.2.7 of [1]_.
|
| 646 |
+
|
| 647 |
+
Parameters
|
| 648 |
+
----------
|
| 649 |
+
k_new : int
|
| 650 |
+
Index of the interpolation point to be modified.
|
| 651 |
+
options : dict
|
| 652 |
+
Options of the solver.
|
| 653 |
+
|
| 654 |
+
Returns
|
| 655 |
+
-------
|
| 656 |
+
`numpy.ndarray`, shape (n,)
|
| 657 |
+
Geometry-improving step.
|
| 658 |
+
|
| 659 |
+
Raises
|
| 660 |
+
------
|
| 661 |
+
`numpy.linalg.LinAlgError`
|
| 662 |
+
If the computation of a determinant fails.
|
| 663 |
+
|
| 664 |
+
References
|
| 665 |
+
----------
|
| 666 |
+
.. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization
|
| 667 |
+
Methods and Software*. PhD thesis, Department of Applied
|
| 668 |
+
Mathematics, The Hong Kong Polytechnic University, Hong Kong, China,
|
| 669 |
+
2022. URL: https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 670 |
+
"""
|
| 671 |
+
if options[Options.DEBUG]:
|
| 672 |
+
assert (
|
| 673 |
+
k_new != self.best_index
|
| 674 |
+
), "The index `k_new` must be different from the best index."
|
| 675 |
+
|
| 676 |
+
# Build the k_new-th Lagrange polynomial.
|
| 677 |
+
coord_vec = np.squeeze(np.eye(1, self.models.npt, k_new))
|
| 678 |
+
lag = Quadratic(
|
| 679 |
+
self.models.interpolation,
|
| 680 |
+
coord_vec,
|
| 681 |
+
options[Options.DEBUG],
|
| 682 |
+
)
|
| 683 |
+
g_lag = lag.grad(self.x_best, self.models.interpolation)
|
| 684 |
+
|
| 685 |
+
# Compute a simple constrained Cauchy step.
|
| 686 |
+
xl = self._pb.bounds.xl - self.x_best
|
| 687 |
+
xu = self._pb.bounds.xu - self.x_best
|
| 688 |
+
step = cauchy_geometry(
|
| 689 |
+
0.0,
|
| 690 |
+
g_lag,
|
| 691 |
+
lambda v: lag.curv(v, self.models.interpolation),
|
| 692 |
+
xl,
|
| 693 |
+
xu,
|
| 694 |
+
self.radius,
|
| 695 |
+
options[Options.DEBUG],
|
| 696 |
+
)
|
| 697 |
+
sigma = self.models.determinants(self.x_best + step, k_new)
|
| 698 |
+
|
| 699 |
+
# Compute the solution on the straight lines joining the interpolation
|
| 700 |
+
# points to the k-th one, and choose it if it provides a larger value
|
| 701 |
+
# of the determinant of the interpolation system in absolute value.
|
| 702 |
+
xpt = (
|
| 703 |
+
self.models.interpolation.xpt
|
| 704 |
+
- self.models.interpolation.xpt[:, self.best_index, np.newaxis]
|
| 705 |
+
)
|
| 706 |
+
xpt[:, [0, self.best_index]] = xpt[:, [self.best_index, 0]]
|
| 707 |
+
step_alt = spider_geometry(
|
| 708 |
+
0.0,
|
| 709 |
+
g_lag,
|
| 710 |
+
lambda v: lag.curv(v, self.models.interpolation),
|
| 711 |
+
xpt[:, 1:],
|
| 712 |
+
xl,
|
| 713 |
+
xu,
|
| 714 |
+
self.radius,
|
| 715 |
+
options[Options.DEBUG],
|
| 716 |
+
)
|
| 717 |
+
sigma_alt = self.models.determinants(self.x_best + step_alt, k_new)
|
| 718 |
+
if abs(sigma_alt) > abs(sigma):
|
| 719 |
+
step = step_alt
|
| 720 |
+
sigma = sigma_alt
|
| 721 |
+
|
| 722 |
+
# Compute a Cauchy step on the tangent space of the active constraints.
|
| 723 |
+
if self._pb.type in [
|
| 724 |
+
"linearly constrained",
|
| 725 |
+
"nonlinearly constrained",
|
| 726 |
+
]:
|
| 727 |
+
aub, bub, aeq, beq = (
|
| 728 |
+
self.get_constraint_linearizations(self.x_best))
|
| 729 |
+
tol_bd = get_arrays_tol(xl, xu)
|
| 730 |
+
tol_ub = get_arrays_tol(bub)
|
| 731 |
+
free_xl = xl <= -tol_bd
|
| 732 |
+
free_xu = xu >= tol_bd
|
| 733 |
+
free_ub = bub >= tol_ub
|
| 734 |
+
|
| 735 |
+
# Compute the Cauchy step.
|
| 736 |
+
n_act, q = qr_tangential_byrd_omojokun(
|
| 737 |
+
aub,
|
| 738 |
+
aeq,
|
| 739 |
+
free_xl,
|
| 740 |
+
free_xu,
|
| 741 |
+
free_ub,
|
| 742 |
+
)
|
| 743 |
+
g_lag_proj = q[:, n_act:] @ (q[:, n_act:].T @ g_lag)
|
| 744 |
+
norm_g_lag_proj = np.linalg.norm(g_lag_proj)
|
| 745 |
+
if 0 < n_act < self._pb.n and norm_g_lag_proj > TINY * self.radius:
|
| 746 |
+
step_alt = (self.radius / norm_g_lag_proj) * g_lag_proj
|
| 747 |
+
if lag.curv(step_alt, self.models.interpolation) < 0.0:
|
| 748 |
+
step_alt = -step_alt
|
| 749 |
+
|
| 750 |
+
# Evaluate the constraint violation at the Cauchy step.
|
| 751 |
+
cbd = np.block([xl - step_alt, step_alt - xu])
|
| 752 |
+
cub = aub @ step_alt - bub
|
| 753 |
+
ceq = aeq @ step_alt - beq
|
| 754 |
+
maxcv_val = max(
|
| 755 |
+
np.max(array, initial=0.0)
|
| 756 |
+
for array in [cbd, cub, np.abs(ceq)]
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
# Accept the new step if it is nearly feasible and do not
|
| 760 |
+
# drastically worsen the determinant of the interpolation
|
| 761 |
+
# system in absolute value.
|
| 762 |
+
tol = np.max(np.abs(step_alt[~free_xl]), initial=0.0)
|
| 763 |
+
tol = np.max(np.abs(step_alt[~free_xu]), initial=tol)
|
| 764 |
+
tol = np.max(np.abs(aub[~free_ub, :] @ step_alt), initial=tol)
|
| 765 |
+
tol = min(10.0 * tol, 1e-2 * np.linalg.norm(step_alt))
|
| 766 |
+
if maxcv_val <= tol:
|
| 767 |
+
sigma_alt = self.models.determinants(
|
| 768 |
+
self.x_best + step_alt, k_new
|
| 769 |
+
)
|
| 770 |
+
if abs(sigma_alt) >= 0.1 * abs(sigma):
|
| 771 |
+
step = np.clip(step_alt, xl, xu)
|
| 772 |
+
|
| 773 |
+
if options[Options.DEBUG]:
|
| 774 |
+
tol = get_arrays_tol(xl, xu)
|
| 775 |
+
if np.any(step + tol < xl) or np.any(xu < step - tol):
|
| 776 |
+
warnings.warn(
|
| 777 |
+
"The geometry step does not respect the bound "
|
| 778 |
+
"constraints.",
|
| 779 |
+
RuntimeWarning,
|
| 780 |
+
2,
|
| 781 |
+
)
|
| 782 |
+
if np.linalg.norm(step) > 1.1 * self.radius:
|
| 783 |
+
warnings.warn(
|
| 784 |
+
"The geometry step does not respect the "
|
| 785 |
+
"trust-region constraint.",
|
| 786 |
+
RuntimeWarning,
|
| 787 |
+
2,
|
| 788 |
+
)
|
| 789 |
+
return step
|
| 790 |
+
|
| 791 |
+
def get_second_order_correction_step(self, step, options):
|
| 792 |
+
"""
|
| 793 |
+
Get the second-order correction step.
|
| 794 |
+
|
| 795 |
+
Parameters
|
| 796 |
+
----------
|
| 797 |
+
step : `numpy.ndarray`, shape (n,)
|
| 798 |
+
Trust-region step.
|
| 799 |
+
options : dict
|
| 800 |
+
Options of the solver.
|
| 801 |
+
|
| 802 |
+
Returns
|
| 803 |
+
-------
|
| 804 |
+
`numpy.ndarray`, shape (n,)
|
| 805 |
+
Second-order correction step.
|
| 806 |
+
"""
|
| 807 |
+
# Evaluate the linearizations of the constraints.
|
| 808 |
+
aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
|
| 809 |
+
xl = self._pb.bounds.xl - self.x_best
|
| 810 |
+
xu = self._pb.bounds.xu - self.x_best
|
| 811 |
+
radius = np.linalg.norm(step)
|
| 812 |
+
soc_step = normal_byrd_omojokun(
|
| 813 |
+
aub,
|
| 814 |
+
bub,
|
| 815 |
+
aeq,
|
| 816 |
+
beq,
|
| 817 |
+
xl,
|
| 818 |
+
xu,
|
| 819 |
+
radius,
|
| 820 |
+
options[Options.DEBUG],
|
| 821 |
+
**self._constants,
|
| 822 |
+
)
|
| 823 |
+
if options[Options.DEBUG]:
|
| 824 |
+
tol = get_arrays_tol(xl, xu)
|
| 825 |
+
if np.any(soc_step + tol < xl) or np.any(xu < soc_step - tol):
|
| 826 |
+
warnings.warn(
|
| 827 |
+
"The second-order correction step does not "
|
| 828 |
+
"respect the bound constraints.",
|
| 829 |
+
RuntimeWarning,
|
| 830 |
+
2,
|
| 831 |
+
)
|
| 832 |
+
if np.linalg.norm(soc_step) > 1.1 * radius:
|
| 833 |
+
warnings.warn(
|
| 834 |
+
"The second-order correction step does not "
|
| 835 |
+
"respect the trust-region constraint.",
|
| 836 |
+
RuntimeWarning,
|
| 837 |
+
2,
|
| 838 |
+
)
|
| 839 |
+
return soc_step
|
| 840 |
+
|
| 841 |
+
def get_reduction_ratio(self, step, fun_val, cub_val, ceq_val):
|
| 842 |
+
"""
|
| 843 |
+
Get the reduction ratio.
|
| 844 |
+
|
| 845 |
+
Parameters
|
| 846 |
+
----------
|
| 847 |
+
step : `numpy.ndarray`, shape (n,)
|
| 848 |
+
Trust-region step.
|
| 849 |
+
fun_val : float
|
| 850 |
+
Objective function value at the trial point.
|
| 851 |
+
cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 852 |
+
Nonlinear inequality constraint values at the trial point.
|
| 853 |
+
ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
|
| 854 |
+
Nonlinear equality constraint values at the trial point.
|
| 855 |
+
|
| 856 |
+
Returns
|
| 857 |
+
-------
|
| 858 |
+
float
|
| 859 |
+
Reduction ratio.
|
| 860 |
+
"""
|
| 861 |
+
merit_old = self.merit(
|
| 862 |
+
self.x_best,
|
| 863 |
+
self.fun_best,
|
| 864 |
+
self.cub_best,
|
| 865 |
+
self.ceq_best,
|
| 866 |
+
)
|
| 867 |
+
merit_new = self.merit(self.x_best + step, fun_val, cub_val, ceq_val)
|
| 868 |
+
merit_model_old = self.merit(
|
| 869 |
+
self.x_best,
|
| 870 |
+
0.0,
|
| 871 |
+
self.models.cub(self.x_best),
|
| 872 |
+
self.models.ceq(self.x_best),
|
| 873 |
+
)
|
| 874 |
+
merit_model_new = self.merit(
|
| 875 |
+
self.x_best + step,
|
| 876 |
+
self.sqp_fun(step),
|
| 877 |
+
self.sqp_cub(step),
|
| 878 |
+
self.sqp_ceq(step),
|
| 879 |
+
)
|
| 880 |
+
if abs(merit_model_old - merit_model_new) > TINY * abs(
|
| 881 |
+
merit_old - merit_new
|
| 882 |
+
):
|
| 883 |
+
return (merit_old - merit_new) / abs(
|
| 884 |
+
merit_model_old - merit_model_new
|
| 885 |
+
)
|
| 886 |
+
else:
|
| 887 |
+
return -1.0
|
| 888 |
+
|
| 889 |
+
def increase_penalty(self, step):
|
| 890 |
+
"""
|
| 891 |
+
Increase the penalty parameter.
|
| 892 |
+
|
| 893 |
+
Parameters
|
| 894 |
+
----------
|
| 895 |
+
step : `numpy.ndarray`, shape (n,)
|
| 896 |
+
Trust-region step.
|
| 897 |
+
"""
|
| 898 |
+
aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
|
| 899 |
+
viol_diff = max(
|
| 900 |
+
np.linalg.norm(
|
| 901 |
+
np.block(
|
| 902 |
+
[
|
| 903 |
+
np.maximum(0.0, -bub),
|
| 904 |
+
beq,
|
| 905 |
+
]
|
| 906 |
+
)
|
| 907 |
+
)
|
| 908 |
+
- np.linalg.norm(
|
| 909 |
+
np.block(
|
| 910 |
+
[
|
| 911 |
+
np.maximum(0.0, aub @ step - bub),
|
| 912 |
+
aeq @ step - beq,
|
| 913 |
+
]
|
| 914 |
+
)
|
| 915 |
+
),
|
| 916 |
+
0.0,
|
| 917 |
+
)
|
| 918 |
+
sqp_val = self.sqp_fun(step)
|
| 919 |
+
|
| 920 |
+
threshold = np.linalg.norm(
|
| 921 |
+
np.block(
|
| 922 |
+
[
|
| 923 |
+
self._lm_linear_ub,
|
| 924 |
+
self._lm_linear_eq,
|
| 925 |
+
self._lm_nonlinear_ub,
|
| 926 |
+
self._lm_nonlinear_eq,
|
| 927 |
+
]
|
| 928 |
+
)
|
| 929 |
+
)
|
| 930 |
+
if abs(viol_diff) > TINY * abs(sqp_val):
|
| 931 |
+
threshold = max(threshold, sqp_val / viol_diff)
|
| 932 |
+
best_index_save = self.best_index
|
| 933 |
+
if (
|
| 934 |
+
self._penalty
|
| 935 |
+
<= self._constants[Constants.PENALTY_INCREASE_THRESHOLD]
|
| 936 |
+
* threshold
|
| 937 |
+
):
|
| 938 |
+
self._penalty = max(
|
| 939 |
+
self._constants[Constants.PENALTY_INCREASE_FACTOR] * threshold,
|
| 940 |
+
1.0,
|
| 941 |
+
)
|
| 942 |
+
self.set_best_index()
|
| 943 |
+
return best_index_save == self.best_index
|
| 944 |
+
|
| 945 |
+
def decrease_penalty(self):
|
| 946 |
+
"""
|
| 947 |
+
Decrease the penalty parameter.
|
| 948 |
+
"""
|
| 949 |
+
self._penalty = min(self._penalty, self._get_low_penalty())
|
| 950 |
+
self.set_best_index()
|
| 951 |
+
|
| 952 |
+
def set_best_index(self):
|
| 953 |
+
"""
|
| 954 |
+
Set the index of the best point.
|
| 955 |
+
"""
|
| 956 |
+
best_index = self.best_index
|
| 957 |
+
m_best = self.merit(
|
| 958 |
+
self.x_best,
|
| 959 |
+
self.models.fun_val[best_index],
|
| 960 |
+
self.models.cub_val[best_index, :],
|
| 961 |
+
self.models.ceq_val[best_index, :],
|
| 962 |
+
)
|
| 963 |
+
r_best = self._pb.maxcv(
|
| 964 |
+
self.x_best,
|
| 965 |
+
self.models.cub_val[best_index, :],
|
| 966 |
+
self.models.ceq_val[best_index, :],
|
| 967 |
+
)
|
| 968 |
+
tol = (
|
| 969 |
+
10.0
|
| 970 |
+
* EPS
|
| 971 |
+
* max(self.models.n, self.models.npt)
|
| 972 |
+
* max(abs(m_best), 1.0)
|
| 973 |
+
)
|
| 974 |
+
for k in range(self.models.npt):
|
| 975 |
+
if k != self.best_index:
|
| 976 |
+
x_val = self.models.interpolation.point(k)
|
| 977 |
+
m_val = self.merit(
|
| 978 |
+
x_val,
|
| 979 |
+
self.models.fun_val[k],
|
| 980 |
+
self.models.cub_val[k, :],
|
| 981 |
+
self.models.ceq_val[k, :],
|
| 982 |
+
)
|
| 983 |
+
r_val = self._pb.maxcv(
|
| 984 |
+
x_val,
|
| 985 |
+
self.models.cub_val[k, :],
|
| 986 |
+
self.models.ceq_val[k, :],
|
| 987 |
+
)
|
| 988 |
+
if m_val < m_best or (m_val < m_best + tol and r_val < r_best):
|
| 989 |
+
best_index = k
|
| 990 |
+
m_best = m_val
|
| 991 |
+
r_best = r_val
|
| 992 |
+
self._best_index = best_index
|
| 993 |
+
|
| 994 |
+
def get_index_to_remove(self, x_new=None):
|
| 995 |
+
"""
|
| 996 |
+
Get the index of the interpolation point to remove.
|
| 997 |
+
|
| 998 |
+
If `x_new` is not provided, the index returned should be used during
|
| 999 |
+
the geometry-improvement phase. Otherwise, the index returned is the
|
| 1000 |
+
best index for included `x_new` in the interpolation set.
|
| 1001 |
+
|
| 1002 |
+
Parameters
|
| 1003 |
+
----------
|
| 1004 |
+
x_new : `numpy.ndarray`, shape (n,), optional
|
| 1005 |
+
New point to be included in the interpolation set.
|
| 1006 |
+
|
| 1007 |
+
Returns
|
| 1008 |
+
-------
|
| 1009 |
+
int
|
| 1010 |
+
Index of the interpolation point to remove.
|
| 1011 |
+
float
|
| 1012 |
+
Distance between `x_best` and the removed point.
|
| 1013 |
+
|
| 1014 |
+
Raises
|
| 1015 |
+
------
|
| 1016 |
+
`numpy.linalg.LinAlgError`
|
| 1017 |
+
If the computation of a determinant fails.
|
| 1018 |
+
"""
|
| 1019 |
+
dist_sq = np.sum(
|
| 1020 |
+
(
|
| 1021 |
+
self.models.interpolation.xpt
|
| 1022 |
+
- self.models.interpolation.xpt[:, self.best_index, np.newaxis]
|
| 1023 |
+
)
|
| 1024 |
+
** 2.0,
|
| 1025 |
+
axis=0,
|
| 1026 |
+
)
|
| 1027 |
+
if x_new is None:
|
| 1028 |
+
sigma = 1.0
|
| 1029 |
+
weights = dist_sq
|
| 1030 |
+
else:
|
| 1031 |
+
sigma = self.models.determinants(x_new)
|
| 1032 |
+
weights = (
|
| 1033 |
+
np.maximum(
|
| 1034 |
+
1.0,
|
| 1035 |
+
dist_sq
|
| 1036 |
+
/ max(
|
| 1037 |
+
self._constants[Constants.LOW_RADIUS_FACTOR]
|
| 1038 |
+
* self.radius,
|
| 1039 |
+
self.resolution,
|
| 1040 |
+
)
|
| 1041 |
+
** 2.0,
|
| 1042 |
+
)
|
| 1043 |
+
** 3.0
|
| 1044 |
+
)
|
| 1045 |
+
weights[self.best_index] = -1.0 # do not remove the best point
|
| 1046 |
+
k_max = np.argmax(weights * np.abs(sigma))
|
| 1047 |
+
return k_max, np.sqrt(dist_sq[k_max])
|
| 1048 |
+
|
| 1049 |
+
def update_radius(self, step, ratio):
|
| 1050 |
+
"""
|
| 1051 |
+
Update the trust-region radius.
|
| 1052 |
+
|
| 1053 |
+
Parameters
|
| 1054 |
+
----------
|
| 1055 |
+
step : `numpy.ndarray`, shape (n,)
|
| 1056 |
+
Trust-region step.
|
| 1057 |
+
ratio : float
|
| 1058 |
+
Reduction ratio.
|
| 1059 |
+
"""
|
| 1060 |
+
s_norm = np.linalg.norm(step)
|
| 1061 |
+
if ratio <= self._constants[Constants.LOW_RATIO]:
|
| 1062 |
+
self.radius *= self._constants[Constants.DECREASE_RADIUS_FACTOR]
|
| 1063 |
+
elif ratio <= self._constants[Constants.HIGH_RATIO]:
|
| 1064 |
+
self.radius = max(
|
| 1065 |
+
self._constants[Constants.DECREASE_RADIUS_FACTOR]
|
| 1066 |
+
* self.radius,
|
| 1067 |
+
s_norm,
|
| 1068 |
+
)
|
| 1069 |
+
else:
|
| 1070 |
+
self.radius = min(
|
| 1071 |
+
self._constants[Constants.INCREASE_RADIUS_FACTOR]
|
| 1072 |
+
* self.radius,
|
| 1073 |
+
max(
|
| 1074 |
+
self._constants[Constants.DECREASE_RADIUS_FACTOR]
|
| 1075 |
+
* self.radius,
|
| 1076 |
+
self._constants[Constants.INCREASE_RADIUS_THRESHOLD]
|
| 1077 |
+
* s_norm,
|
| 1078 |
+
),
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
def enhance_resolution(self, options):
|
| 1082 |
+
"""
|
| 1083 |
+
Enhance the resolution of the trust-region framework.
|
| 1084 |
+
|
| 1085 |
+
Parameters
|
| 1086 |
+
----------
|
| 1087 |
+
options : dict
|
| 1088 |
+
Options of the solver.
|
| 1089 |
+
"""
|
| 1090 |
+
if (
|
| 1091 |
+
self._constants[Constants.LARGE_RESOLUTION_THRESHOLD]
|
| 1092 |
+
* options[Options.RHOEND]
|
| 1093 |
+
< self.resolution
|
| 1094 |
+
):
|
| 1095 |
+
self.resolution *= self._constants[
|
| 1096 |
+
Constants.DECREASE_RESOLUTION_FACTOR
|
| 1097 |
+
]
|
| 1098 |
+
elif (
|
| 1099 |
+
self._constants[Constants.MODERATE_RESOLUTION_THRESHOLD]
|
| 1100 |
+
* options[Options.RHOEND]
|
| 1101 |
+
< self.resolution
|
| 1102 |
+
):
|
| 1103 |
+
self.resolution = np.sqrt(self.resolution
|
| 1104 |
+
* options[Options.RHOEND])
|
| 1105 |
+
else:
|
| 1106 |
+
self.resolution = options[Options.RHOEND]
|
| 1107 |
+
|
| 1108 |
+
# Reduce the trust-region radius.
|
| 1109 |
+
self._radius = max(
|
| 1110 |
+
self._constants[Constants.DECREASE_RADIUS_FACTOR] * self._radius,
|
| 1111 |
+
self.resolution,
|
| 1112 |
+
)
|
| 1113 |
+
|
| 1114 |
+
def shift_x_base(self, options):
|
| 1115 |
+
"""
|
| 1116 |
+
Shift the base point to `x_best`.
|
| 1117 |
+
|
| 1118 |
+
Parameters
|
| 1119 |
+
----------
|
| 1120 |
+
options : dict
|
| 1121 |
+
Options of the solver.
|
| 1122 |
+
"""
|
| 1123 |
+
self.models.shift_x_base(np.copy(self.x_best), options)
|
| 1124 |
+
|
| 1125 |
+
def set_multipliers(self, x):
|
| 1126 |
+
"""
|
| 1127 |
+
Set the Lagrange multipliers.
|
| 1128 |
+
|
| 1129 |
+
This method computes and set the Lagrange multipliers of the linear and
|
| 1130 |
+
nonlinear constraints to be the QP multipliers.
|
| 1131 |
+
|
| 1132 |
+
Parameters
|
| 1133 |
+
----------
|
| 1134 |
+
x : `numpy.ndarray`, shape (n,)
|
| 1135 |
+
Point at which the Lagrange multipliers are computed.
|
| 1136 |
+
"""
|
| 1137 |
+
# Build the constraints of the least-squares problem.
|
| 1138 |
+
incl_linear_ub = self._pb.linear.a_ub @ x >= self._pb.linear.b_ub
|
| 1139 |
+
incl_nonlinear_ub = self.cub_best >= 0.0
|
| 1140 |
+
incl_xl = self._pb.bounds.xl >= x
|
| 1141 |
+
incl_xu = self._pb.bounds.xu <= x
|
| 1142 |
+
m_linear_ub = np.count_nonzero(incl_linear_ub)
|
| 1143 |
+
m_nonlinear_ub = np.count_nonzero(incl_nonlinear_ub)
|
| 1144 |
+
m_xl = np.count_nonzero(incl_xl)
|
| 1145 |
+
m_xu = np.count_nonzero(incl_xu)
|
| 1146 |
+
|
| 1147 |
+
if (
|
| 1148 |
+
m_linear_ub + m_nonlinear_ub + self.m_linear_eq
|
| 1149 |
+
+ self.m_nonlinear_eq > 0
|
| 1150 |
+
):
|
| 1151 |
+
identity = np.eye(self._pb.n)
|
| 1152 |
+
c_jac = np.r_[
|
| 1153 |
+
-identity[incl_xl, :],
|
| 1154 |
+
identity[incl_xu, :],
|
| 1155 |
+
self._pb.linear.a_ub[incl_linear_ub, :],
|
| 1156 |
+
self.models.cub_grad(x, incl_nonlinear_ub),
|
| 1157 |
+
self._pb.linear.a_eq,
|
| 1158 |
+
self.models.ceq_grad(x),
|
| 1159 |
+
]
|
| 1160 |
+
|
| 1161 |
+
# Solve the least-squares problem.
|
| 1162 |
+
g_best = self.models.fun_grad(x)
|
| 1163 |
+
xl_lm = np.full(c_jac.shape[0], -np.inf)
|
| 1164 |
+
xl_lm[: m_xl + m_xu + m_linear_ub + m_nonlinear_ub] = 0.0
|
| 1165 |
+
res = lsq_linear(
|
| 1166 |
+
c_jac.T,
|
| 1167 |
+
-g_best,
|
| 1168 |
+
bounds=(xl_lm, np.inf),
|
| 1169 |
+
method="bvls",
|
| 1170 |
+
)
|
| 1171 |
+
|
| 1172 |
+
# Extract the Lagrange multipliers.
|
| 1173 |
+
self._lm_linear_ub[incl_linear_ub] = res.x[
|
| 1174 |
+
m_xl + m_xu:m_xl + m_xu + m_linear_ub
|
| 1175 |
+
]
|
| 1176 |
+
self._lm_linear_ub[~incl_linear_ub] = 0.0
|
| 1177 |
+
self._lm_nonlinear_ub[incl_nonlinear_ub] = res.x[
|
| 1178 |
+
m_xl
|
| 1179 |
+
+ m_xu
|
| 1180 |
+
+ m_linear_ub:m_xl
|
| 1181 |
+
+ m_xu
|
| 1182 |
+
+ m_linear_ub
|
| 1183 |
+
+ m_nonlinear_ub
|
| 1184 |
+
]
|
| 1185 |
+
self._lm_nonlinear_ub[~incl_nonlinear_ub] = 0.0
|
| 1186 |
+
self._lm_linear_eq[:] = res.x[
|
| 1187 |
+
m_xl
|
| 1188 |
+
+ m_xu
|
| 1189 |
+
+ m_linear_ub
|
| 1190 |
+
+ m_nonlinear_ub:m_xl
|
| 1191 |
+
+ m_xu
|
| 1192 |
+
+ m_linear_ub
|
| 1193 |
+
+ m_nonlinear_ub
|
| 1194 |
+
+ self.m_linear_eq
|
| 1195 |
+
]
|
| 1196 |
+
self._lm_nonlinear_eq[:] = res.x[
|
| 1197 |
+
m_xl + m_xu + m_linear_ub + m_nonlinear_ub + self.m_linear_eq:
|
| 1198 |
+
]
|
| 1199 |
+
|
| 1200 |
+
def _get_low_penalty(self):
|
| 1201 |
+
r_val_ub = np.c_[
|
| 1202 |
+
(
|
| 1203 |
+
self.models.interpolation.x_base[np.newaxis, :]
|
| 1204 |
+
+ self.models.interpolation.xpt.T
|
| 1205 |
+
)
|
| 1206 |
+
@ self._pb.linear.a_ub.T
|
| 1207 |
+
- self._pb.linear.b_ub[np.newaxis, :],
|
| 1208 |
+
self.models.cub_val,
|
| 1209 |
+
]
|
| 1210 |
+
r_val_eq = (
|
| 1211 |
+
self.models.interpolation.x_base[np.newaxis, :]
|
| 1212 |
+
+ self.models.interpolation.xpt.T
|
| 1213 |
+
) @ self._pb.linear.a_eq.T - self._pb.linear.b_eq[np.newaxis, :]
|
| 1214 |
+
r_val_eq = np.block(
|
| 1215 |
+
[
|
| 1216 |
+
r_val_eq,
|
| 1217 |
+
-r_val_eq,
|
| 1218 |
+
self.models.ceq_val,
|
| 1219 |
+
-self.models.ceq_val,
|
| 1220 |
+
]
|
| 1221 |
+
)
|
| 1222 |
+
r_val = np.block([r_val_ub, r_val_eq])
|
| 1223 |
+
c_min = np.nanmin(r_val, axis=0)
|
| 1224 |
+
c_max = np.nanmax(r_val, axis=0)
|
| 1225 |
+
indices = (
|
| 1226 |
+
c_min
|
| 1227 |
+
< self._constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] * c_max
|
| 1228 |
+
)
|
| 1229 |
+
if np.any(indices):
|
| 1230 |
+
f_min = np.nanmin(self.models.fun_val)
|
| 1231 |
+
f_max = np.nanmax(self.models.fun_val)
|
| 1232 |
+
c_min_neg = np.minimum(0.0, c_min[indices])
|
| 1233 |
+
c_diff = np.min(c_max[indices] - c_min_neg)
|
| 1234 |
+
if c_diff > TINY * (f_max - f_min):
|
| 1235 |
+
penalty = (f_max - f_min) / c_diff
|
| 1236 |
+
else:
|
| 1237 |
+
penalty = np.inf
|
| 1238 |
+
else:
|
| 1239 |
+
penalty = 0.0
|
| 1240 |
+
return penalty
|
python_embeded/Lib/site-packages/scipy/_lib/cobyqa/main.py
ADDED
|
@@ -0,0 +1,1506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.optimize import (
|
| 5 |
+
Bounds,
|
| 6 |
+
LinearConstraint,
|
| 7 |
+
NonlinearConstraint,
|
| 8 |
+
OptimizeResult,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
from .framework import TrustRegion
|
| 12 |
+
from .problem import (
|
| 13 |
+
ObjectiveFunction,
|
| 14 |
+
BoundConstraints,
|
| 15 |
+
LinearConstraints,
|
| 16 |
+
NonlinearConstraints,
|
| 17 |
+
Problem,
|
| 18 |
+
)
|
| 19 |
+
from .utils import (
|
| 20 |
+
MaxEvalError,
|
| 21 |
+
TargetSuccess,
|
| 22 |
+
CallbackSuccess,
|
| 23 |
+
FeasibleSuccess,
|
| 24 |
+
exact_1d_array,
|
| 25 |
+
)
|
| 26 |
+
from .settings import (
|
| 27 |
+
ExitStatus,
|
| 28 |
+
Options,
|
| 29 |
+
Constants,
|
| 30 |
+
DEFAULT_OPTIONS,
|
| 31 |
+
DEFAULT_CONSTANTS,
|
| 32 |
+
PRINT_OPTIONS,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def minimize(
|
| 37 |
+
fun,
|
| 38 |
+
x0,
|
| 39 |
+
args=(),
|
| 40 |
+
bounds=None,
|
| 41 |
+
constraints=(),
|
| 42 |
+
callback=None,
|
| 43 |
+
options=None,
|
| 44 |
+
**kwargs,
|
| 45 |
+
):
|
| 46 |
+
r"""
|
| 47 |
+
Minimize a scalar function using the COBYQA method.
|
| 48 |
+
|
| 49 |
+
The Constrained Optimization BY Quadratic Approximations (COBYQA) method is
|
| 50 |
+
a derivative-free optimization method designed to solve general nonlinear
|
| 51 |
+
optimization problems. A complete description of COBYQA is given in [3]_.
|
| 52 |
+
|
| 53 |
+
Parameters
|
| 54 |
+
----------
|
| 55 |
+
fun : {callable, None}
|
| 56 |
+
Objective function to be minimized.
|
| 57 |
+
|
| 58 |
+
``fun(x, *args) -> float``
|
| 59 |
+
|
| 60 |
+
where ``x`` is an array with shape (n,) and `args` is a tuple. If `fun`
|
| 61 |
+
is ``None``, the objective function is assumed to be the zero function,
|
| 62 |
+
resulting in a feasibility problem.
|
| 63 |
+
x0 : array_like, shape (n,)
|
| 64 |
+
Initial guess.
|
| 65 |
+
args : tuple, optional
|
| 66 |
+
Extra arguments passed to the objective function.
|
| 67 |
+
bounds : {`scipy.optimize.Bounds`, array_like, shape (n, 2)}, optional
|
| 68 |
+
Bound constraints of the problem. It can be one of the cases below.
|
| 69 |
+
|
| 70 |
+
#. An instance of `scipy.optimize.Bounds`. For the time being, the
|
| 71 |
+
argument ``keep_feasible`` is disregarded, and all the constraints
|
| 72 |
+
are considered unrelaxable and will be enforced.
|
| 73 |
+
#. An array with shape (n, 2). The bound constraints for ``x[i]`` are
|
| 74 |
+
``bounds[i][0] <= x[i] <= bounds[i][1]``. Set ``bounds[i][0]`` to
|
| 75 |
+
:math:`-\infty` if there is no lower bound, and set ``bounds[i][1]``
|
| 76 |
+
to :math:`\infty` if there is no upper bound.
|
| 77 |
+
|
| 78 |
+
The COBYQA method always respect the bound constraints.
|
| 79 |
+
constraints : {Constraint, list}, optional
|
| 80 |
+
General constraints of the problem. It can be one of the cases below.
|
| 81 |
+
|
| 82 |
+
#. An instance of `scipy.optimize.LinearConstraint`. The argument
|
| 83 |
+
``keep_feasible`` is disregarded.
|
| 84 |
+
#. An instance of `scipy.optimize.NonlinearConstraint`. The arguments
|
| 85 |
+
``jac``, ``hess``, ``keep_feasible``, ``finite_diff_rel_step``, and
|
| 86 |
+
``finite_diff_jac_sparsity`` are disregarded.
|
| 87 |
+
|
| 88 |
+
#. A list, each of whose elements are described in the cases above.
|
| 89 |
+
|
| 90 |
+
callback : callable, optional
|
| 91 |
+
A callback executed at each objective function evaluation. The method
|
| 92 |
+
terminates if a ``StopIteration`` exception is raised by the callback
|
| 93 |
+
function. Its signature can be one of the following:
|
| 94 |
+
|
| 95 |
+
``callback(intermediate_result)``
|
| 96 |
+
|
| 97 |
+
where ``intermediate_result`` is a keyword parameter that contains an
|
| 98 |
+
instance of `scipy.optimize.OptimizeResult`, with attributes ``x``
|
| 99 |
+
and ``fun``, being the point at which the objective function is
|
| 100 |
+
evaluated and the value of the objective function, respectively. The
|
| 101 |
+
name of the parameter must be ``intermediate_result`` for the callback
|
| 102 |
+
to be passed an instance of `scipy.optimize.OptimizeResult`.
|
| 103 |
+
|
| 104 |
+
Alternatively, the callback function can have the signature:
|
| 105 |
+
|
| 106 |
+
``callback(xk)``
|
| 107 |
+
|
| 108 |
+
where ``xk`` is the point at which the objective function is evaluated.
|
| 109 |
+
Introspection is used to determine which of the signatures to invoke.
|
| 110 |
+
options : dict, optional
|
| 111 |
+
Options passed to the solver. Accepted keys are:
|
| 112 |
+
|
| 113 |
+
disp : bool, optional
|
| 114 |
+
Whether to print information about the optimization procedure.
|
| 115 |
+
Default is ``False``.
|
| 116 |
+
maxfev : int, optional
|
| 117 |
+
Maximum number of function evaluations. Default is ``500 * n``.
|
| 118 |
+
maxiter : int, optional
|
| 119 |
+
Maximum number of iterations. Default is ``1000 * n``.
|
| 120 |
+
target : float, optional
|
| 121 |
+
Target on the objective function value. The optimization
|
| 122 |
+
procedure is terminated when the objective function value of a
|
| 123 |
+
feasible point is less than or equal to this target. Default is
|
| 124 |
+
``-numpy.inf``.
|
| 125 |
+
feasibility_tol : float, optional
|
| 126 |
+
Tolerance on the constraint violation. If the maximum
|
| 127 |
+
constraint violation at a point is less than or equal to this
|
| 128 |
+
tolerance, the point is considered feasible. Default is
|
| 129 |
+
``numpy.sqrt(numpy.finfo(float).eps)``.
|
| 130 |
+
radius_init : float, optional
|
| 131 |
+
Initial trust-region radius. Typically, this value should be in
|
| 132 |
+
the order of one tenth of the greatest expected change to `x0`.
|
| 133 |
+
Default is ``1.0``.
|
| 134 |
+
radius_final : float, optional
|
| 135 |
+
Final trust-region radius. It should indicate the accuracy
|
| 136 |
+
required in the final values of the variables. Default is
|
| 137 |
+
``1e-6``.
|
| 138 |
+
nb_points : int, optional
|
| 139 |
+
Number of interpolation points used to build the quadratic
|
| 140 |
+
models of the objective and constraint functions. Default is
|
| 141 |
+
``2 * n + 1``.
|
| 142 |
+
scale : bool, optional
|
| 143 |
+
Whether to scale the variables according to the bounds. Default
|
| 144 |
+
is ``False``.
|
| 145 |
+
filter_size : int, optional
|
| 146 |
+
Maximum number of points in the filter. The filter is used to
|
| 147 |
+
select the best point returned by the optimization procedure.
|
| 148 |
+
Default is ``sys.maxsize``.
|
| 149 |
+
store_history : bool, optional
|
| 150 |
+
Whether to store the history of the function evaluations.
|
| 151 |
+
Default is ``False``.
|
| 152 |
+
history_size : int, optional
|
| 153 |
+
Maximum number of function evaluations to store in the history.
|
| 154 |
+
Default is ``sys.maxsize``.
|
| 155 |
+
debug : bool, optional
|
| 156 |
+
Whether to perform additional checks during the optimization
|
| 157 |
+
procedure. This option should be used only for debugging
|
| 158 |
+
purposes and is highly discouraged to general users. Default is
|
| 159 |
+
``False``.
|
| 160 |
+
|
| 161 |
+
Other constants (from the keyword arguments) are described below. They
|
| 162 |
+
are not intended to be changed by general users. They should only be
|
| 163 |
+
changed by users with a deep understanding of the algorithm, who want
|
| 164 |
+
to experiment with different settings.
|
| 165 |
+
|
| 166 |
+
Returns
|
| 167 |
+
-------
|
| 168 |
+
`scipy.optimize.OptimizeResult`
|
| 169 |
+
Result of the optimization procedure, with the following fields:
|
| 170 |
+
|
| 171 |
+
message : str
|
| 172 |
+
Description of the cause of the termination.
|
| 173 |
+
success : bool
|
| 174 |
+
Whether the optimization procedure terminated successfully.
|
| 175 |
+
status : int
|
| 176 |
+
Termination status of the optimization procedure.
|
| 177 |
+
x : `numpy.ndarray`, shape (n,)
|
| 178 |
+
Solution point.
|
| 179 |
+
fun : float
|
| 180 |
+
Objective function value at the solution point.
|
| 181 |
+
maxcv : float
|
| 182 |
+
Maximum constraint violation at the solution point.
|
| 183 |
+
nfev : int
|
| 184 |
+
Number of function evaluations.
|
| 185 |
+
nit : int
|
| 186 |
+
Number of iterations.
|
| 187 |
+
|
| 188 |
+
If ``store_history`` is True, the result also has the following fields:
|
| 189 |
+
|
| 190 |
+
fun_history : `numpy.ndarray`, shape (nfev,)
|
| 191 |
+
History of the objective function values.
|
| 192 |
+
maxcv_history : `numpy.ndarray`, shape (nfev,)
|
| 193 |
+
History of the maximum constraint violations.
|
| 194 |
+
|
| 195 |
+
A description of the termination statuses is given below.
|
| 196 |
+
|
| 197 |
+
.. list-table::
|
| 198 |
+
:widths: 25 75
|
| 199 |
+
:header-rows: 1
|
| 200 |
+
|
| 201 |
+
* - Exit status
|
| 202 |
+
- Description
|
| 203 |
+
* - 0
|
| 204 |
+
- The lower bound for the trust-region radius has been reached.
|
| 205 |
+
* - 1
|
| 206 |
+
- The target objective function value has been reached.
|
| 207 |
+
* - 2
|
| 208 |
+
- All variables are fixed by the bound constraints.
|
| 209 |
+
* - 3
|
| 210 |
+
- The callback requested to stop the optimization procedure.
|
| 211 |
+
* - 4
|
| 212 |
+
- The feasibility problem received has been solved successfully.
|
| 213 |
+
* - 5
|
| 214 |
+
- The maximum number of function evaluations has been exceeded.
|
| 215 |
+
* - 6
|
| 216 |
+
- The maximum number of iterations has been exceeded.
|
| 217 |
+
* - -1
|
| 218 |
+
- The bound constraints are infeasible.
|
| 219 |
+
* - -2
|
| 220 |
+
- A linear algebra error occurred.
|
| 221 |
+
|
| 222 |
+
Other Parameters
|
| 223 |
+
----------------
|
| 224 |
+
decrease_radius_factor : float, optional
|
| 225 |
+
Factor by which the trust-region radius is reduced when the reduction
|
| 226 |
+
ratio is low or negative. Default is ``0.5``.
|
| 227 |
+
increase_radius_factor : float, optional
|
| 228 |
+
Factor by which the trust-region radius is increased when the reduction
|
| 229 |
+
ratio is large. Default is ``numpy.sqrt(2.0)``.
|
| 230 |
+
increase_radius_threshold : float, optional
|
| 231 |
+
Threshold that controls the increase of the trust-region radius when
|
| 232 |
+
the reduction ratio is large. Default is ``2.0``.
|
| 233 |
+
decrease_radius_threshold : float, optional
|
| 234 |
+
Threshold used to determine whether the trust-region radius should be
|
| 235 |
+
reduced to the resolution. Default is ``1.4``.
|
| 236 |
+
decrease_resolution_factor : float, optional
|
| 237 |
+
Factor by which the resolution is reduced when the current value is far
|
| 238 |
+
from its final value. Default is ``0.1``.
|
| 239 |
+
large_resolution_threshold : float, optional
|
| 240 |
+
Threshold used to determine whether the resolution is far from its
|
| 241 |
+
final value. Default is ``250.0``.
|
| 242 |
+
moderate_resolution_threshold : float, optional
|
| 243 |
+
Threshold used to determine whether the resolution is close to its
|
| 244 |
+
final value. Default is ``16.0``.
|
| 245 |
+
low_ratio : float, optional
|
| 246 |
+
Threshold used to determine whether the reduction ratio is low. Default
|
| 247 |
+
is ``0.1``.
|
| 248 |
+
high_ratio : float, optional
|
| 249 |
+
Threshold used to determine whether the reduction ratio is high.
|
| 250 |
+
Default is ``0.7``.
|
| 251 |
+
very_low_ratio : float, optional
|
| 252 |
+
Threshold used to determine whether the reduction ratio is very low.
|
| 253 |
+
This is used to determine whether the models should be reset. Default
|
| 254 |
+
is ``0.01``.
|
| 255 |
+
penalty_increase_threshold : float, optional
|
| 256 |
+
Threshold used to determine whether the penalty parameter should be
|
| 257 |
+
increased. Default is ``1.5``.
|
| 258 |
+
penalty_increase_factor : float, optional
|
| 259 |
+
Factor by which the penalty parameter is increased. Default is ``2.0``.
|
| 260 |
+
short_step_threshold : float, optional
|
| 261 |
+
Factor used to determine whether the trial step is too short. Default
|
| 262 |
+
is ``0.5``.
|
| 263 |
+
low_radius_factor : float, optional
|
| 264 |
+
Factor used to determine which interpolation point should be removed
|
| 265 |
+
from the interpolation set at each iteration. Default is ``0.1``.
|
| 266 |
+
byrd_omojokun_factor : float, optional
|
| 267 |
+
Factor by which the trust-region radius is reduced for the computations
|
| 268 |
+
of the normal step in the Byrd-Omojokun composite-step approach.
|
| 269 |
+
Default is ``0.8``.
|
| 270 |
+
threshold_ratio_constraints : float, optional
|
| 271 |
+
Threshold used to determine which constraints should be taken into
|
| 272 |
+
account when decreasing the penalty parameter. Default is ``2.0``.
|
| 273 |
+
large_shift_factor : float, optional
|
| 274 |
+
Factor used to determine whether the point around which the quadratic
|
| 275 |
+
models are built should be updated. Default is ``10.0``.
|
| 276 |
+
large_gradient_factor : float, optional
|
| 277 |
+
Factor used to determine whether the models should be reset. Default is
|
| 278 |
+
``10.0``.
|
| 279 |
+
resolution_factor : float, optional
|
| 280 |
+
Factor by which the resolution is decreased. Default is ``2.0``.
|
| 281 |
+
improve_tcg : bool, optional
|
| 282 |
+
Whether to improve the steps computed by the truncated conjugate
|
| 283 |
+
gradient method when the trust-region boundary is reached. Default is
|
| 284 |
+
``True``.
|
| 285 |
+
|
| 286 |
+
References
|
| 287 |
+
----------
|
| 288 |
+
.. [1] J. Nocedal and S. J. Wright. *Numerical Optimization*. Springer Ser.
|
| 289 |
+
Oper. Res. Financ. Eng. Springer, New York, NY, USA, second edition,
|
| 290 |
+
2006. `doi:10.1007/978-0-387-40065-5
|
| 291 |
+
<https://doi.org/10.1007/978-0-387-40065-5>`_.
|
| 292 |
+
.. [2] M. J. D. Powell. A direct search optimization method that models the
|
| 293 |
+
objective and constraint functions by linear interpolation. In S. Gomez
|
| 294 |
+
and J.-P. Hennart, editors, *Advances in Optimization and Numerical
|
| 295 |
+
Analysis*, volume 275 of Math. Appl., pages 51--67. Springer, Dordrecht,
|
| 296 |
+
Netherlands, 1994. `doi:10.1007/978-94-015-8330-5_4
|
| 297 |
+
<https://doi.org/10.1007/978-94-015-8330-5_4>`_.
|
| 298 |
+
.. [3] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
|
| 299 |
+
and Software*. PhD thesis, Department of Applied Mathematics, The Hong
|
| 300 |
+
Kong Polytechnic University, Hong Kong, China, 2022. URL:
|
| 301 |
+
https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 302 |
+
|
| 303 |
+
Examples
|
| 304 |
+
--------
|
| 305 |
+
To demonstrate how to use `minimize`, we first minimize the Rosenbrock
|
| 306 |
+
function implemented in `scipy.optimize` in an unconstrained setting.
|
| 307 |
+
|
| 308 |
+
.. testsetup::
|
| 309 |
+
|
| 310 |
+
import numpy as np
|
| 311 |
+
np.set_printoptions(precision=3, suppress=True)
|
| 312 |
+
|
| 313 |
+
>>> from cobyqa import minimize
|
| 314 |
+
>>> from scipy.optimize import rosen
|
| 315 |
+
|
| 316 |
+
To solve the problem using COBYQA, run:
|
| 317 |
+
|
| 318 |
+
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
|
| 319 |
+
>>> res = minimize(rosen, x0)
|
| 320 |
+
>>> res.x
|
| 321 |
+
array([1., 1., 1., 1., 1.])
|
| 322 |
+
|
| 323 |
+
To see how bound and constraints are handled using `minimize`, we solve
|
| 324 |
+
Example 16.4 of [1]_, defined as
|
| 325 |
+
|
| 326 |
+
.. math::
|
| 327 |
+
|
| 328 |
+
\begin{aligned}
|
| 329 |
+
\min_{x \in \mathbb{R}^2} & \quad (x_1 - 1)^2 + (x_2 - 2.5)^2\\
|
| 330 |
+
\text{s.t.} & \quad -x_1 + 2x_2 \le 2,\\
|
| 331 |
+
& \quad x_1 + 2x_2 \le 6,\\
|
| 332 |
+
& \quad x_1 - 2x_2 \le 2,\\
|
| 333 |
+
& \quad x_1 \ge 0,\\
|
| 334 |
+
& \quad x_2 \ge 0.
|
| 335 |
+
\end{aligned}
|
| 336 |
+
|
| 337 |
+
>>> import numpy as np
|
| 338 |
+
>>> from scipy.optimize import Bounds, LinearConstraint
|
| 339 |
+
|
| 340 |
+
Its objective function can be implemented as:
|
| 341 |
+
|
| 342 |
+
>>> def fun(x):
|
| 343 |
+
... return (x[0] - 1.0)**2 + (x[1] - 2.5)**2
|
| 344 |
+
|
| 345 |
+
This problem can be solved using `minimize` as:
|
| 346 |
+
|
| 347 |
+
>>> x0 = [2.0, 0.0]
|
| 348 |
+
>>> bounds = Bounds([0.0, 0.0], np.inf)
|
| 349 |
+
>>> constraints = LinearConstraint([
|
| 350 |
+
... [-1.0, 2.0],
|
| 351 |
+
... [1.0, 2.0],
|
| 352 |
+
... [1.0, -2.0],
|
| 353 |
+
... ], -np.inf, [2.0, 6.0, 2.0])
|
| 354 |
+
>>> res = minimize(fun, x0, bounds=bounds, constraints=constraints)
|
| 355 |
+
>>> res.x
|
| 356 |
+
array([1.4, 1.7])
|
| 357 |
+
|
| 358 |
+
To see how nonlinear constraints are handled, we solve Problem (F) of [2]_,
|
| 359 |
+
defined as
|
| 360 |
+
|
| 361 |
+
.. math::
|
| 362 |
+
|
| 363 |
+
\begin{aligned}
|
| 364 |
+
\min_{x \in \mathbb{R}^2} & \quad -x_1 - x_2\\
|
| 365 |
+
\text{s.t.} & \quad x_1^2 - x_2 \le 0,\\
|
| 366 |
+
& \quad x_1^2 + x_2^2 \le 1.
|
| 367 |
+
\end{aligned}
|
| 368 |
+
|
| 369 |
+
>>> from scipy.optimize import NonlinearConstraint
|
| 370 |
+
|
| 371 |
+
Its objective and constraint functions can be implemented as:
|
| 372 |
+
|
| 373 |
+
>>> def fun(x):
|
| 374 |
+
... return -x[0] - x[1]
|
| 375 |
+
>>>
|
| 376 |
+
>>> def cub(x):
|
| 377 |
+
... return [x[0]**2 - x[1], x[0]**2 + x[1]**2]
|
| 378 |
+
|
| 379 |
+
This problem can be solved using `minimize` as:
|
| 380 |
+
|
| 381 |
+
>>> x0 = [1.0, 1.0]
|
| 382 |
+
>>> constraints = NonlinearConstraint(cub, -np.inf, [0.0, 1.0])
|
| 383 |
+
>>> res = minimize(fun, x0, constraints=constraints)
|
| 384 |
+
>>> res.x
|
| 385 |
+
array([0.707, 0.707])
|
| 386 |
+
|
| 387 |
+
Finally, to see how to supply linear and nonlinear constraints
|
| 388 |
+
simultaneously, we solve Problem (G) of [2]_, defined as
|
| 389 |
+
|
| 390 |
+
.. math::
|
| 391 |
+
|
| 392 |
+
\begin{aligned}
|
| 393 |
+
\min_{x \in \mathbb{R}^3} & \quad x_3\\
|
| 394 |
+
\text{s.t.} & \quad 5x_1 - x_2 + x_3 \ge 0,\\
|
| 395 |
+
& \quad -5x_1 - x_2 + x_3 \ge 0,\\
|
| 396 |
+
& \quad x_1^2 + x_2^2 + 4x_2 \le x_3.
|
| 397 |
+
\end{aligned}
|
| 398 |
+
|
| 399 |
+
Its objective and nonlinear constraint functions can be implemented as:
|
| 400 |
+
|
| 401 |
+
>>> def fun(x):
|
| 402 |
+
... return x[2]
|
| 403 |
+
>>>
|
| 404 |
+
>>> def cub(x):
|
| 405 |
+
... return x[0]**2 + x[1]**2 + 4.0*x[1] - x[2]
|
| 406 |
+
|
| 407 |
+
This problem can be solved using `minimize` as:
|
| 408 |
+
|
| 409 |
+
>>> x0 = [1.0, 1.0, 1.0]
|
| 410 |
+
>>> constraints = [
|
| 411 |
+
... LinearConstraint(
|
| 412 |
+
... [[5.0, -1.0, 1.0], [-5.0, -1.0, 1.0]],
|
| 413 |
+
... [0.0, 0.0],
|
| 414 |
+
... np.inf,
|
| 415 |
+
... ),
|
| 416 |
+
... NonlinearConstraint(cub, -np.inf, 0.0),
|
| 417 |
+
... ]
|
| 418 |
+
>>> res = minimize(fun, x0, constraints=constraints)
|
| 419 |
+
>>> res.x
|
| 420 |
+
array([ 0., -3., -3.])
|
| 421 |
+
"""
|
| 422 |
+
# Get basic options that are needed for the initialization.
|
| 423 |
+
if options is None:
|
| 424 |
+
options = {}
|
| 425 |
+
else:
|
| 426 |
+
options = dict(options)
|
| 427 |
+
verbose = options.get(Options.VERBOSE, DEFAULT_OPTIONS[Options.VERBOSE])
|
| 428 |
+
verbose = bool(verbose)
|
| 429 |
+
feasibility_tol = options.get(
|
| 430 |
+
Options.FEASIBILITY_TOL,
|
| 431 |
+
DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
|
| 432 |
+
)
|
| 433 |
+
feasibility_tol = float(feasibility_tol)
|
| 434 |
+
scale = options.get(Options.SCALE, DEFAULT_OPTIONS[Options.SCALE])
|
| 435 |
+
scale = bool(scale)
|
| 436 |
+
store_history = options.get(
|
| 437 |
+
Options.STORE_HISTORY,
|
| 438 |
+
DEFAULT_OPTIONS[Options.STORE_HISTORY],
|
| 439 |
+
)
|
| 440 |
+
store_history = bool(store_history)
|
| 441 |
+
if Options.HISTORY_SIZE in options and options[Options.HISTORY_SIZE] <= 0:
|
| 442 |
+
raise ValueError("The size of the history must be positive.")
|
| 443 |
+
history_size = options.get(
|
| 444 |
+
Options.HISTORY_SIZE,
|
| 445 |
+
DEFAULT_OPTIONS[Options.HISTORY_SIZE],
|
| 446 |
+
)
|
| 447 |
+
history_size = int(history_size)
|
| 448 |
+
if Options.FILTER_SIZE in options and options[Options.FILTER_SIZE] <= 0:
|
| 449 |
+
raise ValueError("The size of the filter must be positive.")
|
| 450 |
+
filter_size = options.get(
|
| 451 |
+
Options.FILTER_SIZE,
|
| 452 |
+
DEFAULT_OPTIONS[Options.FILTER_SIZE],
|
| 453 |
+
)
|
| 454 |
+
filter_size = int(filter_size)
|
| 455 |
+
debug = options.get(Options.DEBUG, DEFAULT_OPTIONS[Options.DEBUG])
|
| 456 |
+
debug = bool(debug)
|
| 457 |
+
|
| 458 |
+
# Initialize the objective function.
|
| 459 |
+
if not isinstance(args, tuple):
|
| 460 |
+
args = (args,)
|
| 461 |
+
obj = ObjectiveFunction(fun, verbose, debug, *args)
|
| 462 |
+
|
| 463 |
+
# Initialize the bound constraints.
|
| 464 |
+
if not hasattr(x0, "__len__"):
|
| 465 |
+
x0 = [x0]
|
| 466 |
+
n_orig = len(x0)
|
| 467 |
+
bounds = BoundConstraints(_get_bounds(bounds, n_orig))
|
| 468 |
+
|
| 469 |
+
# Initialize the constraints.
|
| 470 |
+
linear_constraints, nonlinear_constraints = _get_constraints(constraints)
|
| 471 |
+
linear = LinearConstraints(linear_constraints, n_orig, debug)
|
| 472 |
+
nonlinear = NonlinearConstraints(nonlinear_constraints, verbose, debug)
|
| 473 |
+
|
| 474 |
+
# Initialize the problem (and remove the fixed variables).
|
| 475 |
+
pb = Problem(
|
| 476 |
+
obj,
|
| 477 |
+
x0,
|
| 478 |
+
bounds,
|
| 479 |
+
linear,
|
| 480 |
+
nonlinear,
|
| 481 |
+
callback,
|
| 482 |
+
feasibility_tol,
|
| 483 |
+
scale,
|
| 484 |
+
store_history,
|
| 485 |
+
history_size,
|
| 486 |
+
filter_size,
|
| 487 |
+
debug,
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# Set the default options.
|
| 491 |
+
_set_default_options(options, pb.n)
|
| 492 |
+
constants = _set_default_constants(**kwargs)
|
| 493 |
+
|
| 494 |
+
# Initialize the models and skip the computations whenever possible.
|
| 495 |
+
if not pb.bounds.is_feasible:
|
| 496 |
+
# The bound constraints are infeasible.
|
| 497 |
+
return _build_result(
|
| 498 |
+
pb,
|
| 499 |
+
0.0,
|
| 500 |
+
False,
|
| 501 |
+
ExitStatus.INFEASIBLE_ERROR,
|
| 502 |
+
0,
|
| 503 |
+
options,
|
| 504 |
+
)
|
| 505 |
+
elif pb.n == 0:
|
| 506 |
+
# All variables are fixed by the bound constraints.
|
| 507 |
+
return _build_result(
|
| 508 |
+
pb,
|
| 509 |
+
0.0,
|
| 510 |
+
True,
|
| 511 |
+
ExitStatus.FIXED_SUCCESS,
|
| 512 |
+
0,
|
| 513 |
+
options,
|
| 514 |
+
)
|
| 515 |
+
if verbose:
|
| 516 |
+
print("Starting the optimization procedure.")
|
| 517 |
+
print(f"Initial trust-region radius: {options[Options.RHOBEG]}.")
|
| 518 |
+
print(f"Final trust-region radius: {options[Options.RHOEND]}.")
|
| 519 |
+
print(
|
| 520 |
+
f"Maximum number of function evaluations: "
|
| 521 |
+
f"{options[Options.MAX_EVAL]}."
|
| 522 |
+
)
|
| 523 |
+
print(f"Maximum number of iterations: {options[Options.MAX_ITER]}.")
|
| 524 |
+
print()
|
| 525 |
+
try:
|
| 526 |
+
framework = TrustRegion(pb, options, constants)
|
| 527 |
+
except TargetSuccess:
|
| 528 |
+
# The target on the objective function value has been reached
|
| 529 |
+
return _build_result(
|
| 530 |
+
pb,
|
| 531 |
+
0.0,
|
| 532 |
+
True,
|
| 533 |
+
ExitStatus.TARGET_SUCCESS,
|
| 534 |
+
0,
|
| 535 |
+
options,
|
| 536 |
+
)
|
| 537 |
+
except CallbackSuccess:
|
| 538 |
+
# The callback raised a StopIteration exception.
|
| 539 |
+
return _build_result(
|
| 540 |
+
pb,
|
| 541 |
+
0.0,
|
| 542 |
+
True,
|
| 543 |
+
ExitStatus.CALLBACK_SUCCESS,
|
| 544 |
+
0,
|
| 545 |
+
options,
|
| 546 |
+
)
|
| 547 |
+
except FeasibleSuccess:
|
| 548 |
+
# The feasibility problem has been solved successfully.
|
| 549 |
+
return _build_result(
|
| 550 |
+
pb,
|
| 551 |
+
0.0,
|
| 552 |
+
True,
|
| 553 |
+
ExitStatus.FEASIBLE_SUCCESS,
|
| 554 |
+
0,
|
| 555 |
+
options,
|
| 556 |
+
)
|
| 557 |
+
except MaxEvalError:
|
| 558 |
+
# The maximum number of function evaluations has been exceeded.
|
| 559 |
+
return _build_result(
|
| 560 |
+
pb,
|
| 561 |
+
0.0,
|
| 562 |
+
False,
|
| 563 |
+
ExitStatus.MAX_ITER_WARNING,
|
| 564 |
+
0,
|
| 565 |
+
options,
|
| 566 |
+
)
|
| 567 |
+
except np.linalg.LinAlgError:
|
| 568 |
+
# The construction of the initial interpolation set failed.
|
| 569 |
+
return _build_result(
|
| 570 |
+
pb,
|
| 571 |
+
0.0,
|
| 572 |
+
False,
|
| 573 |
+
ExitStatus.LINALG_ERROR,
|
| 574 |
+
0,
|
| 575 |
+
options,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
# Start the optimization procedure.
|
| 579 |
+
success = False
|
| 580 |
+
n_iter = 0
|
| 581 |
+
k_new = None
|
| 582 |
+
n_short_steps = 0
|
| 583 |
+
n_very_short_steps = 0
|
| 584 |
+
n_alt_models = 0
|
| 585 |
+
while True:
|
| 586 |
+
# Stop the optimization procedure if the maximum number of iterations
|
| 587 |
+
# has been exceeded. We do not write the main loop as a for loop
|
| 588 |
+
# because we want to access the number of iterations outside the loop.
|
| 589 |
+
if n_iter >= options[Options.MAX_ITER]:
|
| 590 |
+
status = ExitStatus.MAX_ITER_WARNING
|
| 591 |
+
break
|
| 592 |
+
n_iter += 1
|
| 593 |
+
|
| 594 |
+
# Update the point around which the quadratic models are built.
|
| 595 |
+
if (
|
| 596 |
+
np.linalg.norm(
|
| 597 |
+
framework.x_best - framework.models.interpolation.x_base
|
| 598 |
+
)
|
| 599 |
+
>= constants[Constants.LARGE_SHIFT_FACTOR] * framework.radius
|
| 600 |
+
):
|
| 601 |
+
framework.shift_x_base(options)
|
| 602 |
+
|
| 603 |
+
# Evaluate the trial step.
|
| 604 |
+
radius_save = framework.radius
|
| 605 |
+
normal_step, tangential_step = framework.get_trust_region_step(options)
|
| 606 |
+
step = normal_step + tangential_step
|
| 607 |
+
s_norm = np.linalg.norm(step)
|
| 608 |
+
|
| 609 |
+
# If the trial step is too short, we do not attempt to evaluate the
|
| 610 |
+
# objective and constraint functions. Instead, we reduce the
|
| 611 |
+
# trust-region radius and check whether the resolution should be
|
| 612 |
+
# enhanced and whether the geometry of the interpolation set should be
|
| 613 |
+
# improved. Otherwise, we entertain a classical iteration. The
|
| 614 |
+
# criterion for performing an exceptional jump is taken from NEWUOA.
|
| 615 |
+
if (
|
| 616 |
+
s_norm
|
| 617 |
+
<= constants[Constants.SHORT_STEP_THRESHOLD] * framework.resolution
|
| 618 |
+
):
|
| 619 |
+
framework.radius *= constants[Constants.DECREASE_RESOLUTION_FACTOR]
|
| 620 |
+
if radius_save > framework.resolution:
|
| 621 |
+
n_short_steps = 0
|
| 622 |
+
n_very_short_steps = 0
|
| 623 |
+
else:
|
| 624 |
+
n_short_steps += 1
|
| 625 |
+
n_very_short_steps += 1
|
| 626 |
+
if s_norm > 0.1 * framework.resolution:
|
| 627 |
+
n_very_short_steps = 0
|
| 628 |
+
enhance_resolution = n_short_steps >= 5 or n_very_short_steps >= 3
|
| 629 |
+
if enhance_resolution:
|
| 630 |
+
n_short_steps = 0
|
| 631 |
+
n_very_short_steps = 0
|
| 632 |
+
improve_geometry = False
|
| 633 |
+
else:
|
| 634 |
+
try:
|
| 635 |
+
k_new, dist_new = framework.get_index_to_remove()
|
| 636 |
+
except np.linalg.LinAlgError:
|
| 637 |
+
status = ExitStatus.LINALG_ERROR
|
| 638 |
+
break
|
| 639 |
+
improve_geometry = dist_new > max(
|
| 640 |
+
framework.radius,
|
| 641 |
+
constants[Constants.RESOLUTION_FACTOR]
|
| 642 |
+
* framework.resolution,
|
| 643 |
+
)
|
| 644 |
+
else:
|
| 645 |
+
# Increase the penalty parameter if necessary.
|
| 646 |
+
same_best_point = framework.increase_penalty(step)
|
| 647 |
+
if same_best_point:
|
| 648 |
+
# Evaluate the objective and constraint functions.
|
| 649 |
+
try:
|
| 650 |
+
fun_val, cub_val, ceq_val = _eval(
|
| 651 |
+
pb,
|
| 652 |
+
framework,
|
| 653 |
+
step,
|
| 654 |
+
options,
|
| 655 |
+
)
|
| 656 |
+
except TargetSuccess:
|
| 657 |
+
status = ExitStatus.TARGET_SUCCESS
|
| 658 |
+
success = True
|
| 659 |
+
break
|
| 660 |
+
except FeasibleSuccess:
|
| 661 |
+
status = ExitStatus.FEASIBLE_SUCCESS
|
| 662 |
+
success = True
|
| 663 |
+
break
|
| 664 |
+
except CallbackSuccess:
|
| 665 |
+
status = ExitStatus.CALLBACK_SUCCESS
|
| 666 |
+
success = True
|
| 667 |
+
break
|
| 668 |
+
except MaxEvalError:
|
| 669 |
+
status = ExitStatus.MAX_EVAL_WARNING
|
| 670 |
+
break
|
| 671 |
+
|
| 672 |
+
# Perform a second-order correction step if necessary.
|
| 673 |
+
merit_old = framework.merit(
|
| 674 |
+
framework.x_best,
|
| 675 |
+
framework.fun_best,
|
| 676 |
+
framework.cub_best,
|
| 677 |
+
framework.ceq_best,
|
| 678 |
+
)
|
| 679 |
+
merit_new = framework.merit(
|
| 680 |
+
framework.x_best + step, fun_val, cub_val, ceq_val
|
| 681 |
+
)
|
| 682 |
+
if (
|
| 683 |
+
pb.type == "nonlinearly constrained"
|
| 684 |
+
and merit_new > merit_old
|
| 685 |
+
and np.linalg.norm(normal_step)
|
| 686 |
+
> constants[Constants.BYRD_OMOJOKUN_FACTOR] ** 2.0
|
| 687 |
+
* framework.radius
|
| 688 |
+
):
|
| 689 |
+
soc_step = framework.get_second_order_correction_step(
|
| 690 |
+
step, options
|
| 691 |
+
)
|
| 692 |
+
if np.linalg.norm(soc_step) > 0.0:
|
| 693 |
+
step += soc_step
|
| 694 |
+
|
| 695 |
+
# Evaluate the objective and constraint functions.
|
| 696 |
+
try:
|
| 697 |
+
fun_val, cub_val, ceq_val = _eval(
|
| 698 |
+
pb,
|
| 699 |
+
framework,
|
| 700 |
+
step,
|
| 701 |
+
options,
|
| 702 |
+
)
|
| 703 |
+
except TargetSuccess:
|
| 704 |
+
status = ExitStatus.TARGET_SUCCESS
|
| 705 |
+
success = True
|
| 706 |
+
break
|
| 707 |
+
except FeasibleSuccess:
|
| 708 |
+
status = ExitStatus.FEASIBLE_SUCCESS
|
| 709 |
+
success = True
|
| 710 |
+
break
|
| 711 |
+
except CallbackSuccess:
|
| 712 |
+
status = ExitStatus.CALLBACK_SUCCESS
|
| 713 |
+
success = True
|
| 714 |
+
break
|
| 715 |
+
except MaxEvalError:
|
| 716 |
+
status = ExitStatus.MAX_EVAL_WARNING
|
| 717 |
+
break
|
| 718 |
+
|
| 719 |
+
# Calculate the reduction ratio.
|
| 720 |
+
ratio = framework.get_reduction_ratio(
|
| 721 |
+
step,
|
| 722 |
+
fun_val,
|
| 723 |
+
cub_val,
|
| 724 |
+
ceq_val,
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
# Choose an interpolation point to remove.
|
| 728 |
+
try:
|
| 729 |
+
k_new = framework.get_index_to_remove(
|
| 730 |
+
framework.x_best + step
|
| 731 |
+
)[0]
|
| 732 |
+
except np.linalg.LinAlgError:
|
| 733 |
+
status = ExitStatus.LINALG_ERROR
|
| 734 |
+
break
|
| 735 |
+
|
| 736 |
+
# Update the interpolation set.
|
| 737 |
+
try:
|
| 738 |
+
ill_conditioned = framework.models.update_interpolation(
|
| 739 |
+
k_new, framework.x_best + step, fun_val, cub_val,
|
| 740 |
+
ceq_val
|
| 741 |
+
)
|
| 742 |
+
except np.linalg.LinAlgError:
|
| 743 |
+
status = ExitStatus.LINALG_ERROR
|
| 744 |
+
break
|
| 745 |
+
framework.set_best_index()
|
| 746 |
+
|
| 747 |
+
# Update the trust-region radius.
|
| 748 |
+
framework.update_radius(step, ratio)
|
| 749 |
+
|
| 750 |
+
# Attempt to replace the models by the alternative ones.
|
| 751 |
+
if framework.radius <= framework.resolution:
|
| 752 |
+
if ratio >= constants[Constants.VERY_LOW_RATIO]:
|
| 753 |
+
n_alt_models = 0
|
| 754 |
+
else:
|
| 755 |
+
n_alt_models += 1
|
| 756 |
+
grad = framework.models.fun_grad(framework.x_best)
|
| 757 |
+
try:
|
| 758 |
+
grad_alt = framework.models.fun_alt_grad(
|
| 759 |
+
framework.x_best
|
| 760 |
+
)
|
| 761 |
+
except np.linalg.LinAlgError:
|
| 762 |
+
status = ExitStatus.LINALG_ERROR
|
| 763 |
+
break
|
| 764 |
+
if np.linalg.norm(grad) < constants[
|
| 765 |
+
Constants.LARGE_GRADIENT_FACTOR
|
| 766 |
+
] * np.linalg.norm(grad_alt):
|
| 767 |
+
n_alt_models = 0
|
| 768 |
+
if n_alt_models >= 3:
|
| 769 |
+
try:
|
| 770 |
+
framework.models.reset_models()
|
| 771 |
+
except np.linalg.LinAlgError:
|
| 772 |
+
status = ExitStatus.LINALG_ERROR
|
| 773 |
+
break
|
| 774 |
+
n_alt_models = 0
|
| 775 |
+
|
| 776 |
+
# Update the Lagrange multipliers.
|
| 777 |
+
framework.set_multipliers(framework.x_best + step)
|
| 778 |
+
|
| 779 |
+
# Check whether the resolution should be enhanced.
|
| 780 |
+
try:
|
| 781 |
+
k_new, dist_new = framework.get_index_to_remove()
|
| 782 |
+
except np.linalg.LinAlgError:
|
| 783 |
+
status = ExitStatus.LINALG_ERROR
|
| 784 |
+
break
|
| 785 |
+
improve_geometry = (
|
| 786 |
+
ill_conditioned
|
| 787 |
+
or ratio <= constants[Constants.LOW_RATIO]
|
| 788 |
+
and dist_new
|
| 789 |
+
> max(
|
| 790 |
+
framework.radius,
|
| 791 |
+
constants[Constants.RESOLUTION_FACTOR]
|
| 792 |
+
* framework.resolution,
|
| 793 |
+
)
|
| 794 |
+
)
|
| 795 |
+
enhance_resolution = (
|
| 796 |
+
radius_save <= framework.resolution
|
| 797 |
+
and ratio <= constants[Constants.LOW_RATIO]
|
| 798 |
+
and not improve_geometry
|
| 799 |
+
)
|
| 800 |
+
else:
|
| 801 |
+
# When increasing the penalty parameter, the best point so far
|
| 802 |
+
# may change. In this case, we restart the iteration.
|
| 803 |
+
enhance_resolution = False
|
| 804 |
+
improve_geometry = False
|
| 805 |
+
|
| 806 |
+
# Reduce the resolution if necessary.
|
| 807 |
+
if enhance_resolution:
|
| 808 |
+
if framework.resolution <= options[Options.RHOEND]:
|
| 809 |
+
success = True
|
| 810 |
+
status = ExitStatus.RADIUS_SUCCESS
|
| 811 |
+
break
|
| 812 |
+
framework.enhance_resolution(options)
|
| 813 |
+
framework.decrease_penalty()
|
| 814 |
+
|
| 815 |
+
if verbose:
|
| 816 |
+
maxcv_val = pb.maxcv(
|
| 817 |
+
framework.x_best, framework.cub_best, framework.ceq_best
|
| 818 |
+
)
|
| 819 |
+
_print_step(
|
| 820 |
+
f"New trust-region radius: {framework.resolution}",
|
| 821 |
+
pb,
|
| 822 |
+
pb.build_x(framework.x_best),
|
| 823 |
+
framework.fun_best,
|
| 824 |
+
maxcv_val,
|
| 825 |
+
pb.n_eval,
|
| 826 |
+
n_iter,
|
| 827 |
+
)
|
| 828 |
+
print()
|
| 829 |
+
|
| 830 |
+
# Improve the geometry of the interpolation set if necessary.
|
| 831 |
+
if improve_geometry:
|
| 832 |
+
try:
|
| 833 |
+
step = framework.get_geometry_step(k_new, options)
|
| 834 |
+
except np.linalg.LinAlgError:
|
| 835 |
+
status = ExitStatus.LINALG_ERROR
|
| 836 |
+
break
|
| 837 |
+
|
| 838 |
+
# Evaluate the objective and constraint functions.
|
| 839 |
+
try:
|
| 840 |
+
fun_val, cub_val, ceq_val = _eval(pb, framework, step, options)
|
| 841 |
+
except TargetSuccess:
|
| 842 |
+
status = ExitStatus.TARGET_SUCCESS
|
| 843 |
+
success = True
|
| 844 |
+
break
|
| 845 |
+
except FeasibleSuccess:
|
| 846 |
+
status = ExitStatus.FEASIBLE_SUCCESS
|
| 847 |
+
success = True
|
| 848 |
+
break
|
| 849 |
+
except CallbackSuccess:
|
| 850 |
+
status = ExitStatus.CALLBACK_SUCCESS
|
| 851 |
+
success = True
|
| 852 |
+
break
|
| 853 |
+
except MaxEvalError:
|
| 854 |
+
status = ExitStatus.MAX_EVAL_WARNING
|
| 855 |
+
break
|
| 856 |
+
|
| 857 |
+
# Update the interpolation set.
|
| 858 |
+
try:
|
| 859 |
+
framework.models.update_interpolation(
|
| 860 |
+
k_new,
|
| 861 |
+
framework.x_best + step,
|
| 862 |
+
fun_val,
|
| 863 |
+
cub_val,
|
| 864 |
+
ceq_val,
|
| 865 |
+
)
|
| 866 |
+
except np.linalg.LinAlgError:
|
| 867 |
+
status = ExitStatus.LINALG_ERROR
|
| 868 |
+
break
|
| 869 |
+
framework.set_best_index()
|
| 870 |
+
|
| 871 |
+
return _build_result(
|
| 872 |
+
pb,
|
| 873 |
+
framework.penalty,
|
| 874 |
+
success,
|
| 875 |
+
status,
|
| 876 |
+
n_iter,
|
| 877 |
+
options,
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
def _get_bounds(bounds, n):
|
| 882 |
+
"""
|
| 883 |
+
Uniformize the bounds.
|
| 884 |
+
"""
|
| 885 |
+
if bounds is None:
|
| 886 |
+
return Bounds(np.full(n, -np.inf), np.full(n, np.inf))
|
| 887 |
+
elif isinstance(bounds, Bounds):
|
| 888 |
+
if bounds.lb.shape != (n,) or bounds.ub.shape != (n,):
|
| 889 |
+
raise ValueError(f"The bounds must have {n} elements.")
|
| 890 |
+
return Bounds(bounds.lb, bounds.ub)
|
| 891 |
+
elif hasattr(bounds, "__len__"):
|
| 892 |
+
bounds = np.asarray(bounds)
|
| 893 |
+
if bounds.shape != (n, 2):
|
| 894 |
+
raise ValueError(
|
| 895 |
+
"The shape of the bounds is not compatible with "
|
| 896 |
+
"the number of variables."
|
| 897 |
+
)
|
| 898 |
+
return Bounds(bounds[:, 0], bounds[:, 1])
|
| 899 |
+
else:
|
| 900 |
+
raise TypeError(
|
| 901 |
+
"The bounds must be an instance of "
|
| 902 |
+
"scipy.optimize.Bounds or an array-like object."
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
def _get_constraints(constraints):
|
| 907 |
+
"""
|
| 908 |
+
Extract the linear and nonlinear constraints.
|
| 909 |
+
"""
|
| 910 |
+
if isinstance(constraints, dict) or not hasattr(constraints, "__len__"):
|
| 911 |
+
constraints = (constraints,)
|
| 912 |
+
|
| 913 |
+
# Extract the linear and nonlinear constraints.
|
| 914 |
+
linear_constraints = []
|
| 915 |
+
nonlinear_constraints = []
|
| 916 |
+
for constraint in constraints:
|
| 917 |
+
if isinstance(constraint, LinearConstraint):
|
| 918 |
+
lb = exact_1d_array(
|
| 919 |
+
constraint.lb,
|
| 920 |
+
"The lower bound of the linear constraints must be a vector.",
|
| 921 |
+
)
|
| 922 |
+
ub = exact_1d_array(
|
| 923 |
+
constraint.ub,
|
| 924 |
+
"The upper bound of the linear constraints must be a vector.",
|
| 925 |
+
)
|
| 926 |
+
linear_constraints.append(
|
| 927 |
+
LinearConstraint(
|
| 928 |
+
constraint.A,
|
| 929 |
+
*np.broadcast_arrays(lb, ub),
|
| 930 |
+
)
|
| 931 |
+
)
|
| 932 |
+
elif isinstance(constraint, NonlinearConstraint):
|
| 933 |
+
lb = exact_1d_array(
|
| 934 |
+
constraint.lb,
|
| 935 |
+
"The lower bound of the "
|
| 936 |
+
"nonlinear constraints must be a "
|
| 937 |
+
"vector.",
|
| 938 |
+
)
|
| 939 |
+
ub = exact_1d_array(
|
| 940 |
+
constraint.ub,
|
| 941 |
+
"The upper bound of the "
|
| 942 |
+
"nonlinear constraints must be a "
|
| 943 |
+
"vector.",
|
| 944 |
+
)
|
| 945 |
+
nonlinear_constraints.append(
|
| 946 |
+
NonlinearConstraint(
|
| 947 |
+
constraint.fun,
|
| 948 |
+
*np.broadcast_arrays(lb, ub),
|
| 949 |
+
)
|
| 950 |
+
)
|
| 951 |
+
elif isinstance(constraint, dict):
|
| 952 |
+
if "type" not in constraint or constraint["type"] not in (
|
| 953 |
+
"eq",
|
| 954 |
+
"ineq",
|
| 955 |
+
):
|
| 956 |
+
raise ValueError('The constraint type must be "eq" or "ineq".')
|
| 957 |
+
if "fun" not in constraint or not callable(constraint["fun"]):
|
| 958 |
+
raise ValueError("The constraint function must be callable.")
|
| 959 |
+
nonlinear_constraints.append(
|
| 960 |
+
{
|
| 961 |
+
"fun": constraint["fun"],
|
| 962 |
+
"type": constraint["type"],
|
| 963 |
+
"args": constraint.get("args", ()),
|
| 964 |
+
}
|
| 965 |
+
)
|
| 966 |
+
else:
|
| 967 |
+
raise TypeError(
|
| 968 |
+
"The constraints must be instances of "
|
| 969 |
+
"scipy.optimize.LinearConstraint, "
|
| 970 |
+
"scipy.optimize.NonlinearConstraint, or dict."
|
| 971 |
+
)
|
| 972 |
+
return linear_constraints, nonlinear_constraints
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def _set_default_options(options, n):
|
| 976 |
+
"""
|
| 977 |
+
Set the default options.
|
| 978 |
+
"""
|
| 979 |
+
if Options.RHOBEG in options and options[Options.RHOBEG] <= 0.0:
|
| 980 |
+
raise ValueError("The initial trust-region radius must be positive.")
|
| 981 |
+
if Options.RHOEND in options and options[Options.RHOEND] < 0.0:
|
| 982 |
+
raise ValueError("The final trust-region radius must be nonnegative.")
|
| 983 |
+
if Options.RHOBEG in options and Options.RHOEND in options:
|
| 984 |
+
if options[Options.RHOBEG] < options[Options.RHOEND]:
|
| 985 |
+
raise ValueError(
|
| 986 |
+
"The initial trust-region radius must be greater "
|
| 987 |
+
"than or equal to the final trust-region radius."
|
| 988 |
+
)
|
| 989 |
+
elif Options.RHOBEG in options:
|
| 990 |
+
options[Options.RHOEND.value] = np.min(
|
| 991 |
+
[
|
| 992 |
+
DEFAULT_OPTIONS[Options.RHOEND],
|
| 993 |
+
options[Options.RHOBEG],
|
| 994 |
+
]
|
| 995 |
+
)
|
| 996 |
+
elif Options.RHOEND in options:
|
| 997 |
+
options[Options.RHOBEG.value] = np.max(
|
| 998 |
+
[
|
| 999 |
+
DEFAULT_OPTIONS[Options.RHOBEG],
|
| 1000 |
+
options[Options.RHOEND],
|
| 1001 |
+
]
|
| 1002 |
+
)
|
| 1003 |
+
else:
|
| 1004 |
+
options[Options.RHOBEG.value] = DEFAULT_OPTIONS[Options.RHOBEG]
|
| 1005 |
+
options[Options.RHOEND.value] = DEFAULT_OPTIONS[Options.RHOEND]
|
| 1006 |
+
options[Options.RHOBEG.value] = float(options[Options.RHOBEG])
|
| 1007 |
+
options[Options.RHOEND.value] = float(options[Options.RHOEND])
|
| 1008 |
+
if Options.NPT in options and options[Options.NPT] <= 0:
|
| 1009 |
+
raise ValueError("The number of interpolation points must be "
|
| 1010 |
+
"positive.")
|
| 1011 |
+
if (
|
| 1012 |
+
Options.NPT in options
|
| 1013 |
+
and options[Options.NPT] > ((n + 1) * (n + 2)) // 2
|
| 1014 |
+
):
|
| 1015 |
+
raise ValueError(
|
| 1016 |
+
f"The number of interpolation points must be at most "
|
| 1017 |
+
f"{((n + 1) * (n + 2)) // 2}."
|
| 1018 |
+
)
|
| 1019 |
+
options.setdefault(Options.NPT.value, DEFAULT_OPTIONS[Options.NPT](n))
|
| 1020 |
+
options[Options.NPT.value] = int(options[Options.NPT])
|
| 1021 |
+
if Options.MAX_EVAL in options and options[Options.MAX_EVAL] <= 0:
|
| 1022 |
+
raise ValueError(
|
| 1023 |
+
"The maximum number of function evaluations must be positive."
|
| 1024 |
+
)
|
| 1025 |
+
options.setdefault(
|
| 1026 |
+
Options.MAX_EVAL.value,
|
| 1027 |
+
np.max(
|
| 1028 |
+
[
|
| 1029 |
+
DEFAULT_OPTIONS[Options.MAX_EVAL](n),
|
| 1030 |
+
options[Options.NPT] + 1,
|
| 1031 |
+
]
|
| 1032 |
+
),
|
| 1033 |
+
)
|
| 1034 |
+
options[Options.MAX_EVAL.value] = int(options[Options.MAX_EVAL])
|
| 1035 |
+
if Options.MAX_ITER in options and options[Options.MAX_ITER] <= 0:
|
| 1036 |
+
raise ValueError("The maximum number of iterations must be positive.")
|
| 1037 |
+
options.setdefault(
|
| 1038 |
+
Options.MAX_ITER.value,
|
| 1039 |
+
DEFAULT_OPTIONS[Options.MAX_ITER](n),
|
| 1040 |
+
)
|
| 1041 |
+
options[Options.MAX_ITER.value] = int(options[Options.MAX_ITER])
|
| 1042 |
+
options.setdefault(Options.TARGET.value, DEFAULT_OPTIONS[Options.TARGET])
|
| 1043 |
+
options[Options.TARGET.value] = float(options[Options.TARGET])
|
| 1044 |
+
options.setdefault(
|
| 1045 |
+
Options.FEASIBILITY_TOL.value,
|
| 1046 |
+
DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
|
| 1047 |
+
)
|
| 1048 |
+
options[Options.FEASIBILITY_TOL.value] = float(
|
| 1049 |
+
options[Options.FEASIBILITY_TOL]
|
| 1050 |
+
)
|
| 1051 |
+
options.setdefault(Options.VERBOSE.value, DEFAULT_OPTIONS[Options.VERBOSE])
|
| 1052 |
+
options[Options.VERBOSE.value] = bool(options[Options.VERBOSE])
|
| 1053 |
+
options.setdefault(Options.SCALE.value, DEFAULT_OPTIONS[Options.SCALE])
|
| 1054 |
+
options[Options.SCALE.value] = bool(options[Options.SCALE])
|
| 1055 |
+
options.setdefault(
|
| 1056 |
+
Options.FILTER_SIZE.value,
|
| 1057 |
+
DEFAULT_OPTIONS[Options.FILTER_SIZE],
|
| 1058 |
+
)
|
| 1059 |
+
options[Options.FILTER_SIZE.value] = int(options[Options.FILTER_SIZE])
|
| 1060 |
+
options.setdefault(
|
| 1061 |
+
Options.STORE_HISTORY.value,
|
| 1062 |
+
DEFAULT_OPTIONS[Options.STORE_HISTORY],
|
| 1063 |
+
)
|
| 1064 |
+
options[Options.STORE_HISTORY.value] = bool(options[Options.STORE_HISTORY])
|
| 1065 |
+
options.setdefault(
|
| 1066 |
+
Options.HISTORY_SIZE.value,
|
| 1067 |
+
DEFAULT_OPTIONS[Options.HISTORY_SIZE],
|
| 1068 |
+
)
|
| 1069 |
+
options[Options.HISTORY_SIZE.value] = int(options[Options.HISTORY_SIZE])
|
| 1070 |
+
options.setdefault(Options.DEBUG.value, DEFAULT_OPTIONS[Options.DEBUG])
|
| 1071 |
+
options[Options.DEBUG.value] = bool(options[Options.DEBUG])
|
| 1072 |
+
|
| 1073 |
+
# Check whether they are any unknown options.
|
| 1074 |
+
for key in options:
|
| 1075 |
+
if key not in Options.__members__.values():
|
| 1076 |
+
warnings.warn(f"Unknown option: {key}.", RuntimeWarning, 3)
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
def _set_default_constants(**kwargs):
|
| 1080 |
+
"""
|
| 1081 |
+
Set the default constants.
|
| 1082 |
+
"""
|
| 1083 |
+
constants = dict(kwargs)
|
| 1084 |
+
constants.setdefault(
|
| 1085 |
+
Constants.DECREASE_RADIUS_FACTOR.value,
|
| 1086 |
+
DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_FACTOR],
|
| 1087 |
+
)
|
| 1088 |
+
constants[Constants.DECREASE_RADIUS_FACTOR.value] = float(
|
| 1089 |
+
constants[Constants.DECREASE_RADIUS_FACTOR]
|
| 1090 |
+
)
|
| 1091 |
+
if (
|
| 1092 |
+
constants[Constants.DECREASE_RADIUS_FACTOR] <= 0.0
|
| 1093 |
+
or constants[Constants.DECREASE_RADIUS_FACTOR] >= 1.0
|
| 1094 |
+
):
|
| 1095 |
+
raise ValueError(
|
| 1096 |
+
"The constant decrease_radius_factor must be in the interval "
|
| 1097 |
+
"(0, 1)."
|
| 1098 |
+
)
|
| 1099 |
+
constants.setdefault(
|
| 1100 |
+
Constants.INCREASE_RADIUS_THRESHOLD.value,
|
| 1101 |
+
DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_THRESHOLD],
|
| 1102 |
+
)
|
| 1103 |
+
constants[Constants.INCREASE_RADIUS_THRESHOLD.value] = float(
|
| 1104 |
+
constants[Constants.INCREASE_RADIUS_THRESHOLD]
|
| 1105 |
+
)
|
| 1106 |
+
if constants[Constants.INCREASE_RADIUS_THRESHOLD] <= 1.0:
|
| 1107 |
+
raise ValueError(
|
| 1108 |
+
"The constant increase_radius_threshold must be greater than 1."
|
| 1109 |
+
)
|
| 1110 |
+
if (
|
| 1111 |
+
Constants.INCREASE_RADIUS_FACTOR in constants
|
| 1112 |
+
and constants[Constants.INCREASE_RADIUS_FACTOR] <= 1.0
|
| 1113 |
+
):
|
| 1114 |
+
raise ValueError(
|
| 1115 |
+
"The constant increase_radius_factor must be greater than 1."
|
| 1116 |
+
)
|
| 1117 |
+
if (
|
| 1118 |
+
Constants.DECREASE_RADIUS_THRESHOLD in constants
|
| 1119 |
+
and constants[Constants.DECREASE_RADIUS_THRESHOLD] <= 1.0
|
| 1120 |
+
):
|
| 1121 |
+
raise ValueError(
|
| 1122 |
+
"The constant decrease_radius_threshold must be greater than 1."
|
| 1123 |
+
)
|
| 1124 |
+
if (
|
| 1125 |
+
Constants.INCREASE_RADIUS_FACTOR in constants
|
| 1126 |
+
and Constants.DECREASE_RADIUS_THRESHOLD in constants
|
| 1127 |
+
):
|
| 1128 |
+
if (
|
| 1129 |
+
constants[Constants.DECREASE_RADIUS_THRESHOLD]
|
| 1130 |
+
>= constants[Constants.INCREASE_RADIUS_FACTOR]
|
| 1131 |
+
):
|
| 1132 |
+
raise ValueError(
|
| 1133 |
+
"The constant decrease_radius_threshold must be "
|
| 1134 |
+
"less than increase_radius_factor."
|
| 1135 |
+
)
|
| 1136 |
+
elif Constants.INCREASE_RADIUS_FACTOR in constants:
|
| 1137 |
+
constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = np.min(
|
| 1138 |
+
[
|
| 1139 |
+
DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD],
|
| 1140 |
+
0.5 * (1.0 + constants[Constants.INCREASE_RADIUS_FACTOR]),
|
| 1141 |
+
]
|
| 1142 |
+
)
|
| 1143 |
+
elif Constants.DECREASE_RADIUS_THRESHOLD in constants:
|
| 1144 |
+
constants[Constants.INCREASE_RADIUS_FACTOR.value] = np.max(
|
| 1145 |
+
[
|
| 1146 |
+
DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_FACTOR],
|
| 1147 |
+
2.0 * constants[Constants.DECREASE_RADIUS_THRESHOLD],
|
| 1148 |
+
]
|
| 1149 |
+
)
|
| 1150 |
+
else:
|
| 1151 |
+
constants[Constants.INCREASE_RADIUS_FACTOR.value] = DEFAULT_CONSTANTS[
|
| 1152 |
+
Constants.INCREASE_RADIUS_FACTOR
|
| 1153 |
+
]
|
| 1154 |
+
constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = (
|
| 1155 |
+
DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD])
|
| 1156 |
+
constants.setdefault(
|
| 1157 |
+
Constants.DECREASE_RESOLUTION_FACTOR.value,
|
| 1158 |
+
DEFAULT_CONSTANTS[Constants.DECREASE_RESOLUTION_FACTOR],
|
| 1159 |
+
)
|
| 1160 |
+
constants[Constants.DECREASE_RESOLUTION_FACTOR.value] = float(
|
| 1161 |
+
constants[Constants.DECREASE_RESOLUTION_FACTOR]
|
| 1162 |
+
)
|
| 1163 |
+
if (
|
| 1164 |
+
constants[Constants.DECREASE_RESOLUTION_FACTOR] <= 0.0
|
| 1165 |
+
or constants[Constants.DECREASE_RESOLUTION_FACTOR] >= 1.0
|
| 1166 |
+
):
|
| 1167 |
+
raise ValueError(
|
| 1168 |
+
"The constant decrease_resolution_factor must be in the interval "
|
| 1169 |
+
"(0, 1)."
|
| 1170 |
+
)
|
| 1171 |
+
if (
|
| 1172 |
+
Constants.LARGE_RESOLUTION_THRESHOLD in constants
|
| 1173 |
+
and constants[Constants.LARGE_RESOLUTION_THRESHOLD] <= 1.0
|
| 1174 |
+
):
|
| 1175 |
+
raise ValueError(
|
| 1176 |
+
"The constant large_resolution_threshold must be greater than 1."
|
| 1177 |
+
)
|
| 1178 |
+
if (
|
| 1179 |
+
Constants.MODERATE_RESOLUTION_THRESHOLD in constants
|
| 1180 |
+
and constants[Constants.MODERATE_RESOLUTION_THRESHOLD] <= 1.0
|
| 1181 |
+
):
|
| 1182 |
+
raise ValueError(
|
| 1183 |
+
"The constant moderate_resolution_threshold must be greater than "
|
| 1184 |
+
"1."
|
| 1185 |
+
)
|
| 1186 |
+
if (
|
| 1187 |
+
Constants.LARGE_RESOLUTION_THRESHOLD in constants
|
| 1188 |
+
and Constants.MODERATE_RESOLUTION_THRESHOLD in constants
|
| 1189 |
+
):
|
| 1190 |
+
if (
|
| 1191 |
+
constants[Constants.MODERATE_RESOLUTION_THRESHOLD]
|
| 1192 |
+
> constants[Constants.LARGE_RESOLUTION_THRESHOLD]
|
| 1193 |
+
):
|
| 1194 |
+
raise ValueError(
|
| 1195 |
+
"The constant moderate_resolution_threshold "
|
| 1196 |
+
"must be at most large_resolution_threshold."
|
| 1197 |
+
)
|
| 1198 |
+
elif Constants.LARGE_RESOLUTION_THRESHOLD in constants:
|
| 1199 |
+
constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = np.min(
|
| 1200 |
+
[
|
| 1201 |
+
DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD],
|
| 1202 |
+
constants[Constants.LARGE_RESOLUTION_THRESHOLD],
|
| 1203 |
+
]
|
| 1204 |
+
)
|
| 1205 |
+
elif Constants.MODERATE_RESOLUTION_THRESHOLD in constants:
|
| 1206 |
+
constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = np.max(
|
| 1207 |
+
[
|
| 1208 |
+
DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD],
|
| 1209 |
+
constants[Constants.MODERATE_RESOLUTION_THRESHOLD],
|
| 1210 |
+
]
|
| 1211 |
+
)
|
| 1212 |
+
else:
|
| 1213 |
+
constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = (
|
| 1214 |
+
DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD]
|
| 1215 |
+
)
|
| 1216 |
+
constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = (
|
| 1217 |
+
DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD]
|
| 1218 |
+
)
|
| 1219 |
+
if Constants.LOW_RATIO in constants and (
|
| 1220 |
+
constants[Constants.LOW_RATIO] <= 0.0
|
| 1221 |
+
or constants[Constants.LOW_RATIO] >= 1.0
|
| 1222 |
+
):
|
| 1223 |
+
raise ValueError(
|
| 1224 |
+
"The constant low_ratio must be in the interval (0, 1)."
|
| 1225 |
+
)
|
| 1226 |
+
if Constants.HIGH_RATIO in constants and (
|
| 1227 |
+
constants[Constants.HIGH_RATIO] <= 0.0
|
| 1228 |
+
or constants[Constants.HIGH_RATIO] >= 1.0
|
| 1229 |
+
):
|
| 1230 |
+
raise ValueError(
|
| 1231 |
+
"The constant high_ratio must be in the interval (0, 1)."
|
| 1232 |
+
)
|
| 1233 |
+
if Constants.LOW_RATIO in constants and Constants.HIGH_RATIO in constants:
|
| 1234 |
+
if constants[Constants.LOW_RATIO] > constants[Constants.HIGH_RATIO]:
|
| 1235 |
+
raise ValueError(
|
| 1236 |
+
"The constant low_ratio must be at most high_ratio."
|
| 1237 |
+
)
|
| 1238 |
+
elif Constants.LOW_RATIO in constants:
|
| 1239 |
+
constants[Constants.HIGH_RATIO.value] = np.max(
|
| 1240 |
+
[
|
| 1241 |
+
DEFAULT_CONSTANTS[Constants.HIGH_RATIO],
|
| 1242 |
+
constants[Constants.LOW_RATIO],
|
| 1243 |
+
]
|
| 1244 |
+
)
|
| 1245 |
+
elif Constants.HIGH_RATIO in constants:
|
| 1246 |
+
constants[Constants.LOW_RATIO.value] = np.min(
|
| 1247 |
+
[
|
| 1248 |
+
DEFAULT_CONSTANTS[Constants.LOW_RATIO],
|
| 1249 |
+
constants[Constants.HIGH_RATIO],
|
| 1250 |
+
]
|
| 1251 |
+
)
|
| 1252 |
+
else:
|
| 1253 |
+
constants[Constants.LOW_RATIO.value] = DEFAULT_CONSTANTS[
|
| 1254 |
+
Constants.LOW_RATIO
|
| 1255 |
+
]
|
| 1256 |
+
constants[Constants.HIGH_RATIO.value] = DEFAULT_CONSTANTS[
|
| 1257 |
+
Constants.HIGH_RATIO
|
| 1258 |
+
]
|
| 1259 |
+
constants.setdefault(
|
| 1260 |
+
Constants.VERY_LOW_RATIO.value,
|
| 1261 |
+
DEFAULT_CONSTANTS[Constants.VERY_LOW_RATIO],
|
| 1262 |
+
)
|
| 1263 |
+
constants[Constants.VERY_LOW_RATIO.value] = float(
|
| 1264 |
+
constants[Constants.VERY_LOW_RATIO]
|
| 1265 |
+
)
|
| 1266 |
+
if (
|
| 1267 |
+
constants[Constants.VERY_LOW_RATIO] <= 0.0
|
| 1268 |
+
or constants[Constants.VERY_LOW_RATIO] >= 1.0
|
| 1269 |
+
):
|
| 1270 |
+
raise ValueError(
|
| 1271 |
+
"The constant very_low_ratio must be in the interval (0, 1)."
|
| 1272 |
+
)
|
| 1273 |
+
if (
|
| 1274 |
+
Constants.PENALTY_INCREASE_THRESHOLD in constants
|
| 1275 |
+
and constants[Constants.PENALTY_INCREASE_THRESHOLD] < 1.0
|
| 1276 |
+
):
|
| 1277 |
+
raise ValueError(
|
| 1278 |
+
"The constant penalty_increase_threshold must be "
|
| 1279 |
+
"greater than or equal to 1."
|
| 1280 |
+
)
|
| 1281 |
+
if (
|
| 1282 |
+
Constants.PENALTY_INCREASE_FACTOR in constants
|
| 1283 |
+
and constants[Constants.PENALTY_INCREASE_FACTOR] <= 1.0
|
| 1284 |
+
):
|
| 1285 |
+
raise ValueError(
|
| 1286 |
+
"The constant penalty_increase_factor must be greater than 1."
|
| 1287 |
+
)
|
| 1288 |
+
if (
|
| 1289 |
+
Constants.PENALTY_INCREASE_THRESHOLD in constants
|
| 1290 |
+
and Constants.PENALTY_INCREASE_FACTOR in constants
|
| 1291 |
+
):
|
| 1292 |
+
if (
|
| 1293 |
+
constants[Constants.PENALTY_INCREASE_FACTOR]
|
| 1294 |
+
< constants[Constants.PENALTY_INCREASE_THRESHOLD]
|
| 1295 |
+
):
|
| 1296 |
+
raise ValueError(
|
| 1297 |
+
"The constant penalty_increase_factor must be "
|
| 1298 |
+
"greater than or equal to "
|
| 1299 |
+
"penalty_increase_threshold."
|
| 1300 |
+
)
|
| 1301 |
+
elif Constants.PENALTY_INCREASE_THRESHOLD in constants:
|
| 1302 |
+
constants[Constants.PENALTY_INCREASE_FACTOR.value] = np.max(
|
| 1303 |
+
[
|
| 1304 |
+
DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_FACTOR],
|
| 1305 |
+
constants[Constants.PENALTY_INCREASE_THRESHOLD],
|
| 1306 |
+
]
|
| 1307 |
+
)
|
| 1308 |
+
elif Constants.PENALTY_INCREASE_FACTOR in constants:
|
| 1309 |
+
constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = np.min(
|
| 1310 |
+
[
|
| 1311 |
+
DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD],
|
| 1312 |
+
constants[Constants.PENALTY_INCREASE_FACTOR],
|
| 1313 |
+
]
|
| 1314 |
+
)
|
| 1315 |
+
else:
|
| 1316 |
+
constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = (
|
| 1317 |
+
DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD]
|
| 1318 |
+
)
|
| 1319 |
+
constants[Constants.PENALTY_INCREASE_FACTOR.value] = DEFAULT_CONSTANTS[
|
| 1320 |
+
Constants.PENALTY_INCREASE_FACTOR
|
| 1321 |
+
]
|
| 1322 |
+
constants.setdefault(
|
| 1323 |
+
Constants.SHORT_STEP_THRESHOLD.value,
|
| 1324 |
+
DEFAULT_CONSTANTS[Constants.SHORT_STEP_THRESHOLD],
|
| 1325 |
+
)
|
| 1326 |
+
constants[Constants.SHORT_STEP_THRESHOLD.value] = float(
|
| 1327 |
+
constants[Constants.SHORT_STEP_THRESHOLD]
|
| 1328 |
+
)
|
| 1329 |
+
if (
|
| 1330 |
+
constants[Constants.SHORT_STEP_THRESHOLD] <= 0.0
|
| 1331 |
+
or constants[Constants.SHORT_STEP_THRESHOLD] >= 1.0
|
| 1332 |
+
):
|
| 1333 |
+
raise ValueError(
|
| 1334 |
+
"The constant short_step_threshold must be in the interval (0, 1)."
|
| 1335 |
+
)
|
| 1336 |
+
constants.setdefault(
|
| 1337 |
+
Constants.LOW_RADIUS_FACTOR.value,
|
| 1338 |
+
DEFAULT_CONSTANTS[Constants.LOW_RADIUS_FACTOR],
|
| 1339 |
+
)
|
| 1340 |
+
constants[Constants.LOW_RADIUS_FACTOR.value] = float(
|
| 1341 |
+
constants[Constants.LOW_RADIUS_FACTOR]
|
| 1342 |
+
)
|
| 1343 |
+
if (
|
| 1344 |
+
constants[Constants.LOW_RADIUS_FACTOR] <= 0.0
|
| 1345 |
+
or constants[Constants.LOW_RADIUS_FACTOR] >= 1.0
|
| 1346 |
+
):
|
| 1347 |
+
raise ValueError(
|
| 1348 |
+
"The constant low_radius_factor must be in the interval (0, 1)."
|
| 1349 |
+
)
|
| 1350 |
+
constants.setdefault(
|
| 1351 |
+
Constants.BYRD_OMOJOKUN_FACTOR.value,
|
| 1352 |
+
DEFAULT_CONSTANTS[Constants.BYRD_OMOJOKUN_FACTOR],
|
| 1353 |
+
)
|
| 1354 |
+
constants[Constants.BYRD_OMOJOKUN_FACTOR.value] = float(
|
| 1355 |
+
constants[Constants.BYRD_OMOJOKUN_FACTOR]
|
| 1356 |
+
)
|
| 1357 |
+
if (
|
| 1358 |
+
constants[Constants.BYRD_OMOJOKUN_FACTOR] <= 0.0
|
| 1359 |
+
or constants[Constants.BYRD_OMOJOKUN_FACTOR] >= 1.0
|
| 1360 |
+
):
|
| 1361 |
+
raise ValueError(
|
| 1362 |
+
"The constant byrd_omojokun_factor must be in the interval (0, 1)."
|
| 1363 |
+
)
|
| 1364 |
+
constants.setdefault(
|
| 1365 |
+
Constants.THRESHOLD_RATIO_CONSTRAINTS.value,
|
| 1366 |
+
DEFAULT_CONSTANTS[Constants.THRESHOLD_RATIO_CONSTRAINTS],
|
| 1367 |
+
)
|
| 1368 |
+
constants[Constants.THRESHOLD_RATIO_CONSTRAINTS.value] = float(
|
| 1369 |
+
constants[Constants.THRESHOLD_RATIO_CONSTRAINTS]
|
| 1370 |
+
)
|
| 1371 |
+
if constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] <= 1.0:
|
| 1372 |
+
raise ValueError(
|
| 1373 |
+
"The constant threshold_ratio_constraints must be greater than 1."
|
| 1374 |
+
)
|
| 1375 |
+
constants.setdefault(
|
| 1376 |
+
Constants.LARGE_SHIFT_FACTOR.value,
|
| 1377 |
+
DEFAULT_CONSTANTS[Constants.LARGE_SHIFT_FACTOR],
|
| 1378 |
+
)
|
| 1379 |
+
constants[Constants.LARGE_SHIFT_FACTOR.value] = float(
|
| 1380 |
+
constants[Constants.LARGE_SHIFT_FACTOR]
|
| 1381 |
+
)
|
| 1382 |
+
if constants[Constants.LARGE_SHIFT_FACTOR] < 0.0:
|
| 1383 |
+
raise ValueError("The constant large_shift_factor must be "
|
| 1384 |
+
"nonnegative.")
|
| 1385 |
+
constants.setdefault(
|
| 1386 |
+
Constants.LARGE_GRADIENT_FACTOR.value,
|
| 1387 |
+
DEFAULT_CONSTANTS[Constants.LARGE_GRADIENT_FACTOR],
|
| 1388 |
+
)
|
| 1389 |
+
constants[Constants.LARGE_GRADIENT_FACTOR.value] = float(
|
| 1390 |
+
constants[Constants.LARGE_GRADIENT_FACTOR]
|
| 1391 |
+
)
|
| 1392 |
+
if constants[Constants.LARGE_GRADIENT_FACTOR] <= 1.0:
|
| 1393 |
+
raise ValueError(
|
| 1394 |
+
"The constant large_gradient_factor must be greater than 1."
|
| 1395 |
+
)
|
| 1396 |
+
constants.setdefault(
|
| 1397 |
+
Constants.RESOLUTION_FACTOR.value,
|
| 1398 |
+
DEFAULT_CONSTANTS[Constants.RESOLUTION_FACTOR],
|
| 1399 |
+
)
|
| 1400 |
+
constants[Constants.RESOLUTION_FACTOR.value] = float(
|
| 1401 |
+
constants[Constants.RESOLUTION_FACTOR]
|
| 1402 |
+
)
|
| 1403 |
+
if constants[Constants.RESOLUTION_FACTOR] <= 1.0:
|
| 1404 |
+
raise ValueError(
|
| 1405 |
+
"The constant resolution_factor must be greater than 1."
|
| 1406 |
+
)
|
| 1407 |
+
constants.setdefault(
|
| 1408 |
+
Constants.IMPROVE_TCG.value,
|
| 1409 |
+
DEFAULT_CONSTANTS[Constants.IMPROVE_TCG],
|
| 1410 |
+
)
|
| 1411 |
+
constants[Constants.IMPROVE_TCG.value] = bool(
|
| 1412 |
+
constants[Constants.IMPROVE_TCG]
|
| 1413 |
+
)
|
| 1414 |
+
|
| 1415 |
+
# Check whether they are any unknown options.
|
| 1416 |
+
for key in kwargs:
|
| 1417 |
+
if key not in Constants.__members__.values():
|
| 1418 |
+
warnings.warn(f"Unknown constant: {key}.", RuntimeWarning, 3)
|
| 1419 |
+
return constants
|
| 1420 |
+
|
| 1421 |
+
|
| 1422 |
+
def _eval(pb, framework, step, options):
|
| 1423 |
+
"""
|
| 1424 |
+
Evaluate the objective and constraint functions.
|
| 1425 |
+
"""
|
| 1426 |
+
if pb.n_eval >= options[Options.MAX_EVAL]:
|
| 1427 |
+
raise MaxEvalError
|
| 1428 |
+
x_eval = framework.x_best + step
|
| 1429 |
+
fun_val, cub_val, ceq_val = pb(x_eval, framework.penalty)
|
| 1430 |
+
r_val = pb.maxcv(x_eval, cub_val, ceq_val)
|
| 1431 |
+
if (
|
| 1432 |
+
fun_val <= options[Options.TARGET]
|
| 1433 |
+
and r_val <= options[Options.FEASIBILITY_TOL]
|
| 1434 |
+
):
|
| 1435 |
+
raise TargetSuccess
|
| 1436 |
+
if pb.is_feasibility and r_val <= options[Options.FEASIBILITY_TOL]:
|
| 1437 |
+
raise FeasibleSuccess
|
| 1438 |
+
return fun_val, cub_val, ceq_val
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
def _build_result(pb, penalty, success, status, n_iter, options):
|
| 1442 |
+
"""
|
| 1443 |
+
Build the result of the optimization process.
|
| 1444 |
+
"""
|
| 1445 |
+
# Build the result.
|
| 1446 |
+
x, fun, maxcv = pb.best_eval(penalty)
|
| 1447 |
+
success = success and np.isfinite(fun) and np.isfinite(maxcv)
|
| 1448 |
+
if status not in [ExitStatus.TARGET_SUCCESS, ExitStatus.FEASIBLE_SUCCESS]:
|
| 1449 |
+
success = success and maxcv <= options[Options.FEASIBILITY_TOL]
|
| 1450 |
+
result = OptimizeResult()
|
| 1451 |
+
result.message = {
|
| 1452 |
+
ExitStatus.RADIUS_SUCCESS: "The lower bound for the trust-region "
|
| 1453 |
+
"radius has been reached",
|
| 1454 |
+
ExitStatus.TARGET_SUCCESS: "The target objective function value has "
|
| 1455 |
+
"been reached",
|
| 1456 |
+
ExitStatus.FIXED_SUCCESS: "All variables are fixed by the bound "
|
| 1457 |
+
"constraints",
|
| 1458 |
+
ExitStatus.CALLBACK_SUCCESS: "The callback requested to stop the "
|
| 1459 |
+
"optimization procedure",
|
| 1460 |
+
ExitStatus.FEASIBLE_SUCCESS: "The feasibility problem received has "
|
| 1461 |
+
"been solved successfully",
|
| 1462 |
+
ExitStatus.MAX_EVAL_WARNING: "The maximum number of function "
|
| 1463 |
+
"evaluations has been exceeded",
|
| 1464 |
+
ExitStatus.MAX_ITER_WARNING: "The maximum number of iterations has "
|
| 1465 |
+
"been exceeded",
|
| 1466 |
+
ExitStatus.INFEASIBLE_ERROR: "The bound constraints are infeasible",
|
| 1467 |
+
ExitStatus.LINALG_ERROR: "A linear algebra error occurred",
|
| 1468 |
+
}.get(status, "Unknown exit status")
|
| 1469 |
+
result.success = success
|
| 1470 |
+
result.status = status.value
|
| 1471 |
+
result.x = pb.build_x(x)
|
| 1472 |
+
result.fun = fun
|
| 1473 |
+
result.maxcv = maxcv
|
| 1474 |
+
result.nfev = pb.n_eval
|
| 1475 |
+
result.nit = n_iter
|
| 1476 |
+
if options[Options.STORE_HISTORY]:
|
| 1477 |
+
result.fun_history = pb.fun_history
|
| 1478 |
+
result.maxcv_history = pb.maxcv_history
|
| 1479 |
+
|
| 1480 |
+
# Print the result if requested.
|
| 1481 |
+
if options[Options.VERBOSE]:
|
| 1482 |
+
_print_step(
|
| 1483 |
+
result.message,
|
| 1484 |
+
pb,
|
| 1485 |
+
result.x,
|
| 1486 |
+
result.fun,
|
| 1487 |
+
result.maxcv,
|
| 1488 |
+
result.nfev,
|
| 1489 |
+
result.nit,
|
| 1490 |
+
)
|
| 1491 |
+
return result
|
| 1492 |
+
|
| 1493 |
+
|
| 1494 |
+
def _print_step(message, pb, x, fun_val, r_val, n_eval, n_iter):
|
| 1495 |
+
"""
|
| 1496 |
+
Print information about the current state of the optimization process.
|
| 1497 |
+
"""
|
| 1498 |
+
print()
|
| 1499 |
+
print(f"{message}.")
|
| 1500 |
+
print(f"Number of function evaluations: {n_eval}.")
|
| 1501 |
+
print(f"Number of iterations: {n_iter}.")
|
| 1502 |
+
if not pb.is_feasibility:
|
| 1503 |
+
print(f"Least value of {pb.fun_name}: {fun_val}.")
|
| 1504 |
+
print(f"Maximum constraint violation: {r_val}.")
|
| 1505 |
+
with np.printoptions(**PRINT_OPTIONS):
|
| 1506 |
+
print(f"Corresponding point: {x}.")
|
python_embeded/Lib/site-packages/scipy/_lib/cobyqa/models.py
ADDED
|
@@ -0,0 +1,1529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.linalg import eigh
|
| 5 |
+
|
| 6 |
+
from .settings import Options
|
| 7 |
+
from .utils import MaxEvalError, TargetSuccess, FeasibleSuccess
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
EPS = np.finfo(float).eps
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Interpolation:
|
| 14 |
+
"""
|
| 15 |
+
Interpolation set.
|
| 16 |
+
|
| 17 |
+
This class stores a base point around which the models are expanded and the
|
| 18 |
+
interpolation points. The coordinates of the interpolation points are
|
| 19 |
+
relative to the base point.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, pb, options):
|
| 23 |
+
"""
|
| 24 |
+
Initialize the interpolation set.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
pb : `cobyqa.problem.Problem`
|
| 29 |
+
Problem to be solved.
|
| 30 |
+
options : dict
|
| 31 |
+
Options of the solver.
|
| 32 |
+
"""
|
| 33 |
+
# Reduce the initial trust-region radius if necessary.
|
| 34 |
+
self._debug = options[Options.DEBUG]
|
| 35 |
+
max_radius = 0.5 * np.min(pb.bounds.xu - pb.bounds.xl)
|
| 36 |
+
if options[Options.RHOBEG] > max_radius:
|
| 37 |
+
options[Options.RHOBEG.value] = max_radius
|
| 38 |
+
options[Options.RHOEND.value] = np.min(
|
| 39 |
+
[
|
| 40 |
+
options[Options.RHOEND],
|
| 41 |
+
max_radius,
|
| 42 |
+
]
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# Set the initial point around which the models are expanded.
|
| 46 |
+
self._x_base = np.copy(pb.x0)
|
| 47 |
+
very_close_xl_idx = (
|
| 48 |
+
self.x_base <= pb.bounds.xl + 0.5 * options[Options.RHOBEG]
|
| 49 |
+
)
|
| 50 |
+
self.x_base[very_close_xl_idx] = pb.bounds.xl[very_close_xl_idx]
|
| 51 |
+
close_xl_idx = (
|
| 52 |
+
pb.bounds.xl + 0.5 * options[Options.RHOBEG] < self.x_base
|
| 53 |
+
) & (self.x_base <= pb.bounds.xl + options[Options.RHOBEG])
|
| 54 |
+
self.x_base[close_xl_idx] = np.minimum(
|
| 55 |
+
pb.bounds.xl[close_xl_idx] + options[Options.RHOBEG],
|
| 56 |
+
pb.bounds.xu[close_xl_idx],
|
| 57 |
+
)
|
| 58 |
+
very_close_xu_idx = (
|
| 59 |
+
self.x_base >= pb.bounds.xu - 0.5 * options[Options.RHOBEG]
|
| 60 |
+
)
|
| 61 |
+
self.x_base[very_close_xu_idx] = pb.bounds.xu[very_close_xu_idx]
|
| 62 |
+
close_xu_idx = (
|
| 63 |
+
self.x_base < pb.bounds.xu - 0.5 * options[Options.RHOBEG]
|
| 64 |
+
) & (pb.bounds.xu - options[Options.RHOBEG] <= self.x_base)
|
| 65 |
+
self.x_base[close_xu_idx] = np.maximum(
|
| 66 |
+
pb.bounds.xu[close_xu_idx] - options[Options.RHOBEG],
|
| 67 |
+
pb.bounds.xl[close_xu_idx],
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Set the initial interpolation set.
|
| 71 |
+
self._xpt = np.zeros((pb.n, options[Options.NPT]))
|
| 72 |
+
for k in range(1, options[Options.NPT]):
|
| 73 |
+
if k <= pb.n:
|
| 74 |
+
if very_close_xu_idx[k - 1]:
|
| 75 |
+
self.xpt[k - 1, k] = -options[Options.RHOBEG]
|
| 76 |
+
else:
|
| 77 |
+
self.xpt[k - 1, k] = options[Options.RHOBEG]
|
| 78 |
+
elif k <= 2 * pb.n:
|
| 79 |
+
if very_close_xl_idx[k - pb.n - 1]:
|
| 80 |
+
self.xpt[k - pb.n - 1, k] = 2.0 * options[Options.RHOBEG]
|
| 81 |
+
elif very_close_xu_idx[k - pb.n - 1]:
|
| 82 |
+
self.xpt[k - pb.n - 1, k] = -2.0 * options[Options.RHOBEG]
|
| 83 |
+
else:
|
| 84 |
+
self.xpt[k - pb.n - 1, k] = -options[Options.RHOBEG]
|
| 85 |
+
else:
|
| 86 |
+
spread = (k - pb.n - 1) // pb.n
|
| 87 |
+
k1 = k - (1 + spread) * pb.n - 1
|
| 88 |
+
k2 = (k1 + spread) % pb.n
|
| 89 |
+
self.xpt[k1, k] = self.xpt[k1, k1 + 1]
|
| 90 |
+
self.xpt[k2, k] = self.xpt[k2, k2 + 1]
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def n(self):
|
| 94 |
+
"""
|
| 95 |
+
Number of variables.
|
| 96 |
+
|
| 97 |
+
Returns
|
| 98 |
+
-------
|
| 99 |
+
int
|
| 100 |
+
Number of variables.
|
| 101 |
+
"""
|
| 102 |
+
return self.xpt.shape[0]
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def npt(self):
|
| 106 |
+
"""
|
| 107 |
+
Number of interpolation points.
|
| 108 |
+
|
| 109 |
+
Returns
|
| 110 |
+
-------
|
| 111 |
+
int
|
| 112 |
+
Number of interpolation points.
|
| 113 |
+
"""
|
| 114 |
+
return self.xpt.shape[1]
|
| 115 |
+
|
| 116 |
+
@property
|
| 117 |
+
def xpt(self):
|
| 118 |
+
"""
|
| 119 |
+
Interpolation points.
|
| 120 |
+
|
| 121 |
+
Returns
|
| 122 |
+
-------
|
| 123 |
+
`numpy.ndarray`, shape (n, npt)
|
| 124 |
+
Interpolation points.
|
| 125 |
+
"""
|
| 126 |
+
return self._xpt
|
| 127 |
+
|
| 128 |
+
@xpt.setter
|
| 129 |
+
def xpt(self, xpt):
|
| 130 |
+
"""
|
| 131 |
+
Set the interpolation points.
|
| 132 |
+
|
| 133 |
+
Parameters
|
| 134 |
+
----------
|
| 135 |
+
xpt : `numpy.ndarray`, shape (n, npt)
|
| 136 |
+
New interpolation points.
|
| 137 |
+
"""
|
| 138 |
+
if self._debug:
|
| 139 |
+
assert xpt.shape == (
|
| 140 |
+
self.n,
|
| 141 |
+
self.npt,
|
| 142 |
+
), "The shape of `xpt` is not valid."
|
| 143 |
+
self._xpt = xpt
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def x_base(self):
|
| 147 |
+
"""
|
| 148 |
+
Base point around which the models are expanded.
|
| 149 |
+
|
| 150 |
+
Returns
|
| 151 |
+
-------
|
| 152 |
+
`numpy.ndarray`, shape (n,)
|
| 153 |
+
Base point around which the models are expanded.
|
| 154 |
+
"""
|
| 155 |
+
return self._x_base
|
| 156 |
+
|
| 157 |
+
@x_base.setter
|
| 158 |
+
def x_base(self, x_base):
|
| 159 |
+
"""
|
| 160 |
+
Set the base point around which the models are expanded.
|
| 161 |
+
|
| 162 |
+
Parameters
|
| 163 |
+
----------
|
| 164 |
+
x_base : `numpy.ndarray`, shape (n,)
|
| 165 |
+
New base point around which the models are expanded.
|
| 166 |
+
"""
|
| 167 |
+
if self._debug:
|
| 168 |
+
assert x_base.shape == (
|
| 169 |
+
self.n,
|
| 170 |
+
), "The shape of `x_base` is not valid."
|
| 171 |
+
self._x_base = x_base
|
| 172 |
+
|
| 173 |
+
def point(self, k):
|
| 174 |
+
"""
|
| 175 |
+
Get the `k`-th interpolation point.
|
| 176 |
+
|
| 177 |
+
The return point is relative to the origin.
|
| 178 |
+
|
| 179 |
+
Parameters
|
| 180 |
+
----------
|
| 181 |
+
k : int
|
| 182 |
+
Index of the interpolation point.
|
| 183 |
+
|
| 184 |
+
Returns
|
| 185 |
+
-------
|
| 186 |
+
`numpy.ndarray`, shape (n,)
|
| 187 |
+
`k`-th interpolation point.
|
| 188 |
+
"""
|
| 189 |
+
if self._debug:
|
| 190 |
+
assert 0 <= k < self.npt, "The index `k` is not valid."
|
| 191 |
+
return self.x_base + self.xpt[:, k]
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
_cache = {"xpt": None, "a": None, "right_scaling": None, "eigh": None}
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def build_system(interpolation):
|
| 198 |
+
"""
|
| 199 |
+
Build the left-hand side matrix of the interpolation system. The
|
| 200 |
+
matrix below stores W * diag(right_scaling),
|
| 201 |
+
where W is the theoretical matrix of the interpolation system. The
|
| 202 |
+
right scaling matrices is chosen to keep the elements in
|
| 203 |
+
the matrix well-balanced.
|
| 204 |
+
|
| 205 |
+
Parameters
|
| 206 |
+
----------
|
| 207 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 208 |
+
Interpolation set.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
# Compute the scaled directions from the base point to the
|
| 212 |
+
# interpolation points. We scale the directions to avoid numerical
|
| 213 |
+
# difficulties.
|
| 214 |
+
if _cache["xpt"] is not None and np.array_equal(
|
| 215 |
+
interpolation.xpt, _cache["xpt"]
|
| 216 |
+
):
|
| 217 |
+
return _cache["a"], _cache["right_scaling"], _cache["eigh"]
|
| 218 |
+
|
| 219 |
+
scale = np.max(np.linalg.norm(interpolation.xpt, axis=0), initial=EPS)
|
| 220 |
+
xpt_scale = interpolation.xpt / scale
|
| 221 |
+
|
| 222 |
+
n, npt = xpt_scale.shape
|
| 223 |
+
a = np.zeros((npt + n + 1, npt + n + 1))
|
| 224 |
+
a[:npt, :npt] = 0.5 * (xpt_scale.T @ xpt_scale) ** 2.0
|
| 225 |
+
a[:npt, npt] = 1.0
|
| 226 |
+
a[:npt, npt + 1:] = xpt_scale.T
|
| 227 |
+
a[npt, :npt] = 1.0
|
| 228 |
+
a[npt + 1:, :npt] = xpt_scale
|
| 229 |
+
|
| 230 |
+
# Build the left and right scaling diagonal matrices.
|
| 231 |
+
right_scaling = np.empty(npt + n + 1)
|
| 232 |
+
right_scaling[:npt] = 1.0 / scale**2.0
|
| 233 |
+
right_scaling[npt] = scale**2.0
|
| 234 |
+
right_scaling[npt + 1:] = scale
|
| 235 |
+
|
| 236 |
+
eig_values, eig_vectors = eigh(a, check_finite=False)
|
| 237 |
+
|
| 238 |
+
_cache["xpt"] = np.copy(interpolation.xpt)
|
| 239 |
+
_cache["a"] = np.copy(a)
|
| 240 |
+
_cache["right_scaling"] = np.copy(right_scaling)
|
| 241 |
+
_cache["eigh"] = (eig_values, eig_vectors)
|
| 242 |
+
|
| 243 |
+
return a, right_scaling, (eig_values, eig_vectors)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class Quadratic:
|
| 247 |
+
"""
|
| 248 |
+
Quadratic model.
|
| 249 |
+
|
| 250 |
+
This class stores the Hessian matrix of the quadratic model using the
|
| 251 |
+
implicit/explicit representation designed by Powell for NEWUOA [1]_.
|
| 252 |
+
|
| 253 |
+
References
|
| 254 |
+
----------
|
| 255 |
+
.. [1] M. J. D. Powell. The NEWUOA software for unconstrained optimization
|
| 256 |
+
without derivatives. In G. Di Pillo and M. Roma, editors, *Large-Scale
|
| 257 |
+
Nonlinear Optimization*, volume 83 of Nonconvex Optim. Appl., pages
|
| 258 |
+
255--297. Springer, Boston, MA, USA, 2006. `doi:10.1007/0-387-30065-1_16
|
| 259 |
+
<https://doi.org/10.1007/0-387-30065-1_16>`_.
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
def __init__(self, interpolation, values, debug):
|
| 263 |
+
"""
|
| 264 |
+
Initialize the quadratic model.
|
| 265 |
+
|
| 266 |
+
Parameters
|
| 267 |
+
----------
|
| 268 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 269 |
+
Interpolation set.
|
| 270 |
+
values : `numpy.ndarray`, shape (npt,)
|
| 271 |
+
Values of the interpolated function at the interpolation points.
|
| 272 |
+
debug : bool
|
| 273 |
+
Whether to make debugging tests during the execution.
|
| 274 |
+
|
| 275 |
+
Raises
|
| 276 |
+
------
|
| 277 |
+
`numpy.linalg.LinAlgError`
|
| 278 |
+
If the interpolation system is ill-defined.
|
| 279 |
+
"""
|
| 280 |
+
self._debug = debug
|
| 281 |
+
if self._debug:
|
| 282 |
+
assert values.shape == (
|
| 283 |
+
interpolation.npt,
|
| 284 |
+
), "The shape of `values` is not valid."
|
| 285 |
+
if interpolation.npt < interpolation.n + 1:
|
| 286 |
+
raise ValueError(
|
| 287 |
+
f"The number of interpolation points must be at least "
|
| 288 |
+
f"{interpolation.n + 1}."
|
| 289 |
+
)
|
| 290 |
+
self._const, self._grad, self._i_hess, _ = self._get_model(
|
| 291 |
+
interpolation,
|
| 292 |
+
values,
|
| 293 |
+
)
|
| 294 |
+
self._e_hess = np.zeros((self.n, self.n))
|
| 295 |
+
|
| 296 |
+
def __call__(self, x, interpolation):
|
| 297 |
+
"""
|
| 298 |
+
Evaluate the quadratic model at a given point.
|
| 299 |
+
|
| 300 |
+
Parameters
|
| 301 |
+
----------
|
| 302 |
+
x : `numpy.ndarray`, shape (n,)
|
| 303 |
+
Point at which the quadratic model is evaluated.
|
| 304 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 305 |
+
Interpolation set.
|
| 306 |
+
|
| 307 |
+
Returns
|
| 308 |
+
-------
|
| 309 |
+
float
|
| 310 |
+
Value of the quadratic model at `x`.
|
| 311 |
+
"""
|
| 312 |
+
if self._debug:
|
| 313 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 314 |
+
x_diff = x - interpolation.x_base
|
| 315 |
+
return (
|
| 316 |
+
self._const
|
| 317 |
+
+ self._grad @ x_diff
|
| 318 |
+
+ 0.5
|
| 319 |
+
* (
|
| 320 |
+
self._i_hess @ (interpolation.xpt.T @ x_diff) ** 2.0
|
| 321 |
+
+ x_diff @ self._e_hess @ x_diff
|
| 322 |
+
)
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def n(self):
|
| 327 |
+
"""
|
| 328 |
+
Number of variables.
|
| 329 |
+
|
| 330 |
+
Returns
|
| 331 |
+
-------
|
| 332 |
+
int
|
| 333 |
+
Number of variables.
|
| 334 |
+
"""
|
| 335 |
+
return self._grad.size
|
| 336 |
+
|
| 337 |
+
@property
|
| 338 |
+
def npt(self):
|
| 339 |
+
"""
|
| 340 |
+
Number of interpolation points used to define the quadratic model.
|
| 341 |
+
|
| 342 |
+
Returns
|
| 343 |
+
-------
|
| 344 |
+
int
|
| 345 |
+
Number of interpolation points used to define the quadratic model.
|
| 346 |
+
"""
|
| 347 |
+
return self._i_hess.size
|
| 348 |
+
|
| 349 |
+
def grad(self, x, interpolation):
|
| 350 |
+
"""
|
| 351 |
+
Evaluate the gradient of the quadratic model at a given point.
|
| 352 |
+
|
| 353 |
+
Parameters
|
| 354 |
+
----------
|
| 355 |
+
x : `numpy.ndarray`, shape (n,)
|
| 356 |
+
Point at which the gradient of the quadratic model is evaluated.
|
| 357 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 358 |
+
Interpolation set.
|
| 359 |
+
|
| 360 |
+
Returns
|
| 361 |
+
-------
|
| 362 |
+
`numpy.ndarray`, shape (n,)
|
| 363 |
+
Gradient of the quadratic model at `x`.
|
| 364 |
+
"""
|
| 365 |
+
if self._debug:
|
| 366 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 367 |
+
x_diff = x - interpolation.x_base
|
| 368 |
+
return self._grad + self.hess_prod(x_diff, interpolation)
|
| 369 |
+
|
| 370 |
+
def hess(self, interpolation):
|
| 371 |
+
"""
|
| 372 |
+
Evaluate the Hessian matrix of the quadratic model.
|
| 373 |
+
|
| 374 |
+
Parameters
|
| 375 |
+
----------
|
| 376 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 377 |
+
Interpolation set.
|
| 378 |
+
|
| 379 |
+
Returns
|
| 380 |
+
-------
|
| 381 |
+
`numpy.ndarray`, shape (n, n)
|
| 382 |
+
Hessian matrix of the quadratic model.
|
| 383 |
+
"""
|
| 384 |
+
return self._e_hess + interpolation.xpt @ (
|
| 385 |
+
self._i_hess[:, np.newaxis] * interpolation.xpt.T
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def hess_prod(self, v, interpolation):
|
| 389 |
+
"""
|
| 390 |
+
Evaluate the right product of the Hessian matrix of the quadratic model
|
| 391 |
+
with a given vector.
|
| 392 |
+
|
| 393 |
+
Parameters
|
| 394 |
+
----------
|
| 395 |
+
v : `numpy.ndarray`, shape (n,)
|
| 396 |
+
Vector with which the Hessian matrix of the quadratic model is
|
| 397 |
+
multiplied from the right.
|
| 398 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 399 |
+
Interpolation set.
|
| 400 |
+
|
| 401 |
+
Returns
|
| 402 |
+
-------
|
| 403 |
+
`numpy.ndarray`, shape (n,)
|
| 404 |
+
Right product of the Hessian matrix of the quadratic model with
|
| 405 |
+
`v`.
|
| 406 |
+
"""
|
| 407 |
+
if self._debug:
|
| 408 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 409 |
+
return self._e_hess @ v + interpolation.xpt @ (
|
| 410 |
+
self._i_hess * (interpolation.xpt.T @ v)
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
def curv(self, v, interpolation):
|
| 414 |
+
"""
|
| 415 |
+
Evaluate the curvature of the quadratic model along a given direction.
|
| 416 |
+
|
| 417 |
+
Parameters
|
| 418 |
+
----------
|
| 419 |
+
v : `numpy.ndarray`, shape (n,)
|
| 420 |
+
Direction along which the curvature of the quadratic model is
|
| 421 |
+
evaluated.
|
| 422 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 423 |
+
Interpolation set.
|
| 424 |
+
|
| 425 |
+
Returns
|
| 426 |
+
-------
|
| 427 |
+
float
|
| 428 |
+
Curvature of the quadratic model along `v`.
|
| 429 |
+
"""
|
| 430 |
+
if self._debug:
|
| 431 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 432 |
+
return (
|
| 433 |
+
v @ self._e_hess @ v
|
| 434 |
+
+ self._i_hess @ (interpolation.xpt.T @ v) ** 2.0
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
def update(self, interpolation, k_new, dir_old, values_diff):
|
| 438 |
+
"""
|
| 439 |
+
Update the quadratic model.
|
| 440 |
+
|
| 441 |
+
This method applies the derivative-free symmetric Broyden update to the
|
| 442 |
+
quadratic model. The `knew`-th interpolation point must be updated
|
| 443 |
+
before calling this method.
|
| 444 |
+
|
| 445 |
+
Parameters
|
| 446 |
+
----------
|
| 447 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 448 |
+
Updated interpolation set.
|
| 449 |
+
k_new : int
|
| 450 |
+
Index of the updated interpolation point.
|
| 451 |
+
dir_old : `numpy.ndarray`, shape (n,)
|
| 452 |
+
Value of ``interpolation.xpt[:, k_new]`` before the update.
|
| 453 |
+
values_diff : `numpy.ndarray`, shape (npt,)
|
| 454 |
+
Differences between the values of the interpolated nonlinear
|
| 455 |
+
function and the previous quadratic model at the updated
|
| 456 |
+
interpolation points.
|
| 457 |
+
|
| 458 |
+
Raises
|
| 459 |
+
------
|
| 460 |
+
`numpy.linalg.LinAlgError`
|
| 461 |
+
If the interpolation system is ill-defined.
|
| 462 |
+
"""
|
| 463 |
+
if self._debug:
|
| 464 |
+
assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
|
| 465 |
+
assert dir_old.shape == (
|
| 466 |
+
self.n,
|
| 467 |
+
), "The shape of `dir_old` is not valid."
|
| 468 |
+
assert values_diff.shape == (
|
| 469 |
+
self.npt,
|
| 470 |
+
), "The shape of `values_diff` is not valid."
|
| 471 |
+
|
| 472 |
+
# Forward the k_new-th element of the implicit Hessian matrix to the
|
| 473 |
+
# explicit Hessian matrix. This must be done because the implicit
|
| 474 |
+
# Hessian matrix is related to the interpolation points, and the
|
| 475 |
+
# k_new-th interpolation point is modified.
|
| 476 |
+
self._e_hess += self._i_hess[k_new] * np.outer(dir_old, dir_old)
|
| 477 |
+
self._i_hess[k_new] = 0.0
|
| 478 |
+
|
| 479 |
+
# Update the quadratic model.
|
| 480 |
+
const, grad, i_hess, ill_conditioned = self._get_model(
|
| 481 |
+
interpolation,
|
| 482 |
+
values_diff,
|
| 483 |
+
)
|
| 484 |
+
self._const += const
|
| 485 |
+
self._grad += grad
|
| 486 |
+
self._i_hess += i_hess
|
| 487 |
+
return ill_conditioned
|
| 488 |
+
|
| 489 |
+
def shift_x_base(self, interpolation, new_x_base):
|
| 490 |
+
"""
|
| 491 |
+
Shift the point around which the quadratic model is defined.
|
| 492 |
+
|
| 493 |
+
Parameters
|
| 494 |
+
----------
|
| 495 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 496 |
+
Previous interpolation set.
|
| 497 |
+
new_x_base : `numpy.ndarray`, shape (n,)
|
| 498 |
+
Point that will replace ``interpolation.x_base``.
|
| 499 |
+
"""
|
| 500 |
+
if self._debug:
|
| 501 |
+
assert new_x_base.shape == (
|
| 502 |
+
self.n,
|
| 503 |
+
), "The shape of `new_x_base` is not valid."
|
| 504 |
+
self._const = self(new_x_base, interpolation)
|
| 505 |
+
self._grad = self.grad(new_x_base, interpolation)
|
| 506 |
+
shift = new_x_base - interpolation.x_base
|
| 507 |
+
update = np.outer(
|
| 508 |
+
shift,
|
| 509 |
+
(interpolation.xpt - 0.5 * shift[:, np.newaxis]) @ self._i_hess,
|
| 510 |
+
)
|
| 511 |
+
self._e_hess += update + update.T
|
| 512 |
+
|
| 513 |
+
@staticmethod
|
| 514 |
+
def solve_systems(interpolation, rhs):
|
| 515 |
+
"""
|
| 516 |
+
Solve the interpolation systems.
|
| 517 |
+
|
| 518 |
+
Parameters
|
| 519 |
+
----------
|
| 520 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 521 |
+
Interpolation set.
|
| 522 |
+
rhs : `numpy.ndarray`, shape (npt + n + 1, m)
|
| 523 |
+
Right-hand side vectors of the ``m`` interpolation systems.
|
| 524 |
+
|
| 525 |
+
Returns
|
| 526 |
+
-------
|
| 527 |
+
`numpy.ndarray`, shape (npt + n + 1, m)
|
| 528 |
+
Solutions of the interpolation systems.
|
| 529 |
+
`numpy.ndarray`, shape (m, )
|
| 530 |
+
Whether the interpolation systems are ill-conditioned.
|
| 531 |
+
|
| 532 |
+
Raises
|
| 533 |
+
------
|
| 534 |
+
`numpy.linalg.LinAlgError`
|
| 535 |
+
If the interpolation systems are ill-defined.
|
| 536 |
+
"""
|
| 537 |
+
n, npt = interpolation.xpt.shape
|
| 538 |
+
assert (
|
| 539 |
+
rhs.ndim == 2 and rhs.shape[0] == npt + n + 1
|
| 540 |
+
), "The shape of `rhs` is not valid."
|
| 541 |
+
|
| 542 |
+
# Build the left-hand side matrix of the interpolation system. The
|
| 543 |
+
# matrix below stores diag(left_scaling) * W * diag(right_scaling),
|
| 544 |
+
# where W is the theoretical matrix of the interpolation system. The
|
| 545 |
+
# left and right scaling matrices are chosen to keep the elements in
|
| 546 |
+
# the matrix well-balanced.
|
| 547 |
+
a, right_scaling, eig = build_system(interpolation)
|
| 548 |
+
|
| 549 |
+
# Build the solution. After a discussion with Mike Saunders and Alexis
|
| 550 |
+
# Montoison during their visit to the Hong Kong Polytechnic University
|
| 551 |
+
# in 2024, we decided to use the eigendecomposition of the symmetric
|
| 552 |
+
# matrix a. This is more stable than the previously employed LBL
|
| 553 |
+
# decomposition, and allows us to directly detect ill-conditioning of
|
| 554 |
+
# the system and to build the least-squares solution if necessary.
|
| 555 |
+
# Numerical experiments have shown that this strategy improves the
|
| 556 |
+
# performance of the solver.
|
| 557 |
+
rhs_scaled = rhs * right_scaling[:, np.newaxis]
|
| 558 |
+
if not (np.all(np.isfinite(a)) and np.all(np.isfinite(rhs_scaled))):
|
| 559 |
+
raise np.linalg.LinAlgError(
|
| 560 |
+
"The interpolation system is ill-defined."
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
# calculated in build_system
|
| 564 |
+
eig_values, eig_vectors = eig
|
| 565 |
+
|
| 566 |
+
large_eig_values = np.abs(eig_values) > EPS
|
| 567 |
+
eig_vectors = eig_vectors[:, large_eig_values]
|
| 568 |
+
inv_eig_values = 1.0 / eig_values[large_eig_values]
|
| 569 |
+
ill_conditioned = ~np.all(large_eig_values, 0)
|
| 570 |
+
left_scaled_solutions = eig_vectors @ (
|
| 571 |
+
(eig_vectors.T @ rhs_scaled) * inv_eig_values[:, np.newaxis]
|
| 572 |
+
)
|
| 573 |
+
return (
|
| 574 |
+
left_scaled_solutions * right_scaling[:, np.newaxis],
|
| 575 |
+
ill_conditioned,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
@staticmethod
|
| 579 |
+
def _get_model(interpolation, values):
|
| 580 |
+
"""
|
| 581 |
+
Solve the interpolation system.
|
| 582 |
+
|
| 583 |
+
Parameters
|
| 584 |
+
----------
|
| 585 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 586 |
+
Interpolation set.
|
| 587 |
+
values : `numpy.ndarray`, shape (npt,)
|
| 588 |
+
Values of the interpolated function at the interpolation points.
|
| 589 |
+
|
| 590 |
+
Returns
|
| 591 |
+
-------
|
| 592 |
+
float
|
| 593 |
+
Constant term of the quadratic model.
|
| 594 |
+
`numpy.ndarray`, shape (n,)
|
| 595 |
+
Gradient of the quadratic model at ``interpolation.x_base``.
|
| 596 |
+
`numpy.ndarray`, shape (npt,)
|
| 597 |
+
Implicit Hessian matrix of the quadratic model.
|
| 598 |
+
|
| 599 |
+
Raises
|
| 600 |
+
------
|
| 601 |
+
`numpy.linalg.LinAlgError`
|
| 602 |
+
If the interpolation system is ill-defined.
|
| 603 |
+
"""
|
| 604 |
+
assert values.shape == (
|
| 605 |
+
interpolation.npt,
|
| 606 |
+
), "The shape of `values` is not valid."
|
| 607 |
+
n, npt = interpolation.xpt.shape
|
| 608 |
+
x, ill_conditioned = Quadratic.solve_systems(
|
| 609 |
+
interpolation,
|
| 610 |
+
np.block(
|
| 611 |
+
[
|
| 612 |
+
[
|
| 613 |
+
values,
|
| 614 |
+
np.zeros(n + 1),
|
| 615 |
+
]
|
| 616 |
+
]
|
| 617 |
+
).T,
|
| 618 |
+
)
|
| 619 |
+
return x[npt, 0], x[npt + 1:, 0], x[:npt, 0], ill_conditioned
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class Models:
|
| 623 |
+
"""
|
| 624 |
+
Models for a nonlinear optimization problem.
|
| 625 |
+
"""
|
| 626 |
+
|
| 627 |
+
def __init__(self, pb, options, penalty):
|
| 628 |
+
"""
|
| 629 |
+
Initialize the models.
|
| 630 |
+
|
| 631 |
+
Parameters
|
| 632 |
+
----------
|
| 633 |
+
pb : `cobyqa.problem.Problem`
|
| 634 |
+
Problem to be solved.
|
| 635 |
+
options : dict
|
| 636 |
+
Options of the solver.
|
| 637 |
+
penalty : float
|
| 638 |
+
Penalty parameter used to select the point in the filter to forward
|
| 639 |
+
to the callback function.
|
| 640 |
+
|
| 641 |
+
Raises
|
| 642 |
+
------
|
| 643 |
+
`cobyqa.utils.MaxEvalError`
|
| 644 |
+
If the maximum number of evaluations is reached.
|
| 645 |
+
`cobyqa.utils.TargetSuccess`
|
| 646 |
+
If a nearly feasible point has been found with an objective
|
| 647 |
+
function value below the target.
|
| 648 |
+
`cobyqa.utils.FeasibleSuccess`
|
| 649 |
+
If a feasible point has been found for a feasibility problem.
|
| 650 |
+
`numpy.linalg.LinAlgError`
|
| 651 |
+
If the interpolation system is ill-defined.
|
| 652 |
+
"""
|
| 653 |
+
# Set the initial interpolation set.
|
| 654 |
+
self._debug = options[Options.DEBUG]
|
| 655 |
+
self._interpolation = Interpolation(pb, options)
|
| 656 |
+
|
| 657 |
+
# Evaluate the nonlinear functions at the initial interpolation points.
|
| 658 |
+
x_eval = self.interpolation.point(0)
|
| 659 |
+
fun_init, cub_init, ceq_init = pb(x_eval, penalty)
|
| 660 |
+
self._fun_val = np.full(options[Options.NPT], np.nan)
|
| 661 |
+
self._cub_val = np.full((options[Options.NPT], cub_init.size), np.nan)
|
| 662 |
+
self._ceq_val = np.full((options[Options.NPT], ceq_init.size), np.nan)
|
| 663 |
+
for k in range(options[Options.NPT]):
|
| 664 |
+
if k >= options[Options.MAX_EVAL]:
|
| 665 |
+
raise MaxEvalError
|
| 666 |
+
if k == 0:
|
| 667 |
+
self.fun_val[k] = fun_init
|
| 668 |
+
self.cub_val[k, :] = cub_init
|
| 669 |
+
self.ceq_val[k, :] = ceq_init
|
| 670 |
+
else:
|
| 671 |
+
x_eval = self.interpolation.point(k)
|
| 672 |
+
self.fun_val[k], self.cub_val[k, :], self.ceq_val[k, :] = pb(
|
| 673 |
+
x_eval,
|
| 674 |
+
penalty,
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
# Stop the iterations if the problem is a feasibility problem and
|
| 678 |
+
# the current interpolation point is feasible.
|
| 679 |
+
if (
|
| 680 |
+
pb.is_feasibility
|
| 681 |
+
and pb.maxcv(
|
| 682 |
+
self.interpolation.point(k),
|
| 683 |
+
self.cub_val[k, :],
|
| 684 |
+
self.ceq_val[k, :],
|
| 685 |
+
)
|
| 686 |
+
<= options[Options.FEASIBILITY_TOL]
|
| 687 |
+
):
|
| 688 |
+
raise FeasibleSuccess
|
| 689 |
+
|
| 690 |
+
# Stop the iterations if the current interpolation point is nearly
|
| 691 |
+
# feasible and has an objective function value below the target.
|
| 692 |
+
if (
|
| 693 |
+
self._fun_val[k] <= options[Options.TARGET]
|
| 694 |
+
and pb.maxcv(
|
| 695 |
+
self.interpolation.point(k),
|
| 696 |
+
self.cub_val[k, :],
|
| 697 |
+
self.ceq_val[k, :],
|
| 698 |
+
)
|
| 699 |
+
<= options[Options.FEASIBILITY_TOL]
|
| 700 |
+
):
|
| 701 |
+
raise TargetSuccess
|
| 702 |
+
|
| 703 |
+
# Build the initial quadratic models.
|
| 704 |
+
self._fun = Quadratic(
|
| 705 |
+
self.interpolation,
|
| 706 |
+
self._fun_val,
|
| 707 |
+
options[Options.DEBUG],
|
| 708 |
+
)
|
| 709 |
+
self._cub = np.empty(self.m_nonlinear_ub, dtype=Quadratic)
|
| 710 |
+
self._ceq = np.empty(self.m_nonlinear_eq, dtype=Quadratic)
|
| 711 |
+
for i in range(self.m_nonlinear_ub):
|
| 712 |
+
self._cub[i] = Quadratic(
|
| 713 |
+
self.interpolation,
|
| 714 |
+
self.cub_val[:, i],
|
| 715 |
+
options[Options.DEBUG],
|
| 716 |
+
)
|
| 717 |
+
for i in range(self.m_nonlinear_eq):
|
| 718 |
+
self._ceq[i] = Quadratic(
|
| 719 |
+
self.interpolation,
|
| 720 |
+
self.ceq_val[:, i],
|
| 721 |
+
options[Options.DEBUG],
|
| 722 |
+
)
|
| 723 |
+
if self._debug:
|
| 724 |
+
self._check_interpolation_conditions()
|
| 725 |
+
|
| 726 |
+
@property
|
| 727 |
+
def n(self):
|
| 728 |
+
"""
|
| 729 |
+
Dimension of the problem.
|
| 730 |
+
|
| 731 |
+
Returns
|
| 732 |
+
-------
|
| 733 |
+
int
|
| 734 |
+
Dimension of the problem.
|
| 735 |
+
"""
|
| 736 |
+
return self.interpolation.n
|
| 737 |
+
|
| 738 |
+
@property
|
| 739 |
+
def npt(self):
|
| 740 |
+
"""
|
| 741 |
+
Number of interpolation points.
|
| 742 |
+
|
| 743 |
+
Returns
|
| 744 |
+
-------
|
| 745 |
+
int
|
| 746 |
+
Number of interpolation points.
|
| 747 |
+
"""
|
| 748 |
+
return self.interpolation.npt
|
| 749 |
+
|
| 750 |
+
@property
|
| 751 |
+
def m_nonlinear_ub(self):
|
| 752 |
+
"""
|
| 753 |
+
Number of nonlinear inequality constraints.
|
| 754 |
+
|
| 755 |
+
Returns
|
| 756 |
+
-------
|
| 757 |
+
int
|
| 758 |
+
Number of nonlinear inequality constraints.
|
| 759 |
+
"""
|
| 760 |
+
return self.cub_val.shape[1]
|
| 761 |
+
|
| 762 |
+
@property
|
| 763 |
+
def m_nonlinear_eq(self):
|
| 764 |
+
"""
|
| 765 |
+
Number of nonlinear equality constraints.
|
| 766 |
+
|
| 767 |
+
Returns
|
| 768 |
+
-------
|
| 769 |
+
int
|
| 770 |
+
Number of nonlinear equality constraints.
|
| 771 |
+
"""
|
| 772 |
+
return self.ceq_val.shape[1]
|
| 773 |
+
|
| 774 |
+
@property
|
| 775 |
+
def interpolation(self):
|
| 776 |
+
"""
|
| 777 |
+
Interpolation set.
|
| 778 |
+
|
| 779 |
+
Returns
|
| 780 |
+
-------
|
| 781 |
+
`cobyqa.models.Interpolation`
|
| 782 |
+
Interpolation set.
|
| 783 |
+
"""
|
| 784 |
+
return self._interpolation
|
| 785 |
+
|
| 786 |
+
@property
|
| 787 |
+
def fun_val(self):
|
| 788 |
+
"""
|
| 789 |
+
Values of the objective function at the interpolation points.
|
| 790 |
+
|
| 791 |
+
Returns
|
| 792 |
+
-------
|
| 793 |
+
`numpy.ndarray`, shape (npt,)
|
| 794 |
+
Values of the objective function at the interpolation points.
|
| 795 |
+
"""
|
| 796 |
+
return self._fun_val
|
| 797 |
+
|
| 798 |
+
@property
|
| 799 |
+
def cub_val(self):
|
| 800 |
+
"""
|
| 801 |
+
Values of the nonlinear inequality constraint functions at the
|
| 802 |
+
interpolation points.
|
| 803 |
+
|
| 804 |
+
Returns
|
| 805 |
+
-------
|
| 806 |
+
`numpy.ndarray`, shape (npt, m_nonlinear_ub)
|
| 807 |
+
Values of the nonlinear inequality constraint functions at the
|
| 808 |
+
interpolation points.
|
| 809 |
+
"""
|
| 810 |
+
return self._cub_val
|
| 811 |
+
|
| 812 |
+
@property
|
| 813 |
+
def ceq_val(self):
|
| 814 |
+
"""
|
| 815 |
+
Values of the nonlinear equality constraint functions at the
|
| 816 |
+
interpolation points.
|
| 817 |
+
|
| 818 |
+
Returns
|
| 819 |
+
-------
|
| 820 |
+
`numpy.ndarray`, shape (npt, m_nonlinear_eq)
|
| 821 |
+
Values of the nonlinear equality constraint functions at the
|
| 822 |
+
interpolation points.
|
| 823 |
+
"""
|
| 824 |
+
return self._ceq_val
|
| 825 |
+
|
| 826 |
+
def fun(self, x):
|
| 827 |
+
"""
|
| 828 |
+
Evaluate the quadratic model of the objective function at a given
|
| 829 |
+
point.
|
| 830 |
+
|
| 831 |
+
Parameters
|
| 832 |
+
----------
|
| 833 |
+
x : `numpy.ndarray`, shape (n,)
|
| 834 |
+
Point at which to evaluate the quadratic model of the objective
|
| 835 |
+
function.
|
| 836 |
+
|
| 837 |
+
Returns
|
| 838 |
+
-------
|
| 839 |
+
float
|
| 840 |
+
Value of the quadratic model of the objective function at `x`.
|
| 841 |
+
"""
|
| 842 |
+
if self._debug:
|
| 843 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 844 |
+
return self._fun(x, self.interpolation)
|
| 845 |
+
|
| 846 |
+
def fun_grad(self, x):
|
| 847 |
+
"""
|
| 848 |
+
Evaluate the gradient of the quadratic model of the objective function
|
| 849 |
+
at a given point.
|
| 850 |
+
|
| 851 |
+
Parameters
|
| 852 |
+
----------
|
| 853 |
+
x : `numpy.ndarray`, shape (n,)
|
| 854 |
+
Point at which to evaluate the gradient of the quadratic model of
|
| 855 |
+
the objective function.
|
| 856 |
+
|
| 857 |
+
Returns
|
| 858 |
+
-------
|
| 859 |
+
`numpy.ndarray`, shape (n,)
|
| 860 |
+
Gradient of the quadratic model of the objective function at `x`.
|
| 861 |
+
"""
|
| 862 |
+
if self._debug:
|
| 863 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 864 |
+
return self._fun.grad(x, self.interpolation)
|
| 865 |
+
|
| 866 |
+
def fun_hess(self):
|
| 867 |
+
"""
|
| 868 |
+
Evaluate the Hessian matrix of the quadratic model of the objective
|
| 869 |
+
function.
|
| 870 |
+
|
| 871 |
+
Returns
|
| 872 |
+
-------
|
| 873 |
+
`numpy.ndarray`, shape (n, n)
|
| 874 |
+
Hessian matrix of the quadratic model of the objective function.
|
| 875 |
+
"""
|
| 876 |
+
return self._fun.hess(self.interpolation)
|
| 877 |
+
|
| 878 |
+
def fun_hess_prod(self, v):
|
| 879 |
+
"""
|
| 880 |
+
Evaluate the right product of the Hessian matrix of the quadratic model
|
| 881 |
+
of the objective function with a given vector.
|
| 882 |
+
|
| 883 |
+
Parameters
|
| 884 |
+
----------
|
| 885 |
+
v : `numpy.ndarray`, shape (n,)
|
| 886 |
+
Vector with which the Hessian matrix of the quadratic model of the
|
| 887 |
+
objective function is multiplied from the right.
|
| 888 |
+
|
| 889 |
+
Returns
|
| 890 |
+
-------
|
| 891 |
+
`numpy.ndarray`, shape (n,)
|
| 892 |
+
Right product of the Hessian matrix of the quadratic model of the
|
| 893 |
+
objective function with `v`.
|
| 894 |
+
"""
|
| 895 |
+
if self._debug:
|
| 896 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 897 |
+
return self._fun.hess_prod(v, self.interpolation)
|
| 898 |
+
|
| 899 |
+
def fun_curv(self, v):
|
| 900 |
+
"""
|
| 901 |
+
Evaluate the curvature of the quadratic model of the objective function
|
| 902 |
+
along a given direction.
|
| 903 |
+
|
| 904 |
+
Parameters
|
| 905 |
+
----------
|
| 906 |
+
v : `numpy.ndarray`, shape (n,)
|
| 907 |
+
Direction along which the curvature of the quadratic model of the
|
| 908 |
+
objective function is evaluated.
|
| 909 |
+
|
| 910 |
+
Returns
|
| 911 |
+
-------
|
| 912 |
+
float
|
| 913 |
+
Curvature of the quadratic model of the objective function along
|
| 914 |
+
`v`.
|
| 915 |
+
"""
|
| 916 |
+
if self._debug:
|
| 917 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 918 |
+
return self._fun.curv(v, self.interpolation)
|
| 919 |
+
|
| 920 |
+
def fun_alt_grad(self, x):
|
| 921 |
+
"""
|
| 922 |
+
Evaluate the gradient of the alternative quadratic model of the
|
| 923 |
+
objective function at a given point.
|
| 924 |
+
|
| 925 |
+
Parameters
|
| 926 |
+
----------
|
| 927 |
+
x : `numpy.ndarray`, shape (n,)
|
| 928 |
+
Point at which to evaluate the gradient of the alternative
|
| 929 |
+
quadratic model of the objective function.
|
| 930 |
+
|
| 931 |
+
Returns
|
| 932 |
+
-------
|
| 933 |
+
`numpy.ndarray`, shape (n,)
|
| 934 |
+
Gradient of the alternative quadratic model of the objective
|
| 935 |
+
function at `x`.
|
| 936 |
+
|
| 937 |
+
Raises
|
| 938 |
+
------
|
| 939 |
+
`numpy.linalg.LinAlgError`
|
| 940 |
+
If the interpolation system is ill-defined.
|
| 941 |
+
"""
|
| 942 |
+
if self._debug:
|
| 943 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 944 |
+
model = Quadratic(self.interpolation, self.fun_val, self._debug)
|
| 945 |
+
return model.grad(x, self.interpolation)
|
| 946 |
+
|
| 947 |
+
def cub(self, x, mask=None):
|
| 948 |
+
"""
|
| 949 |
+
Evaluate the quadratic models of the nonlinear inequality functions at
|
| 950 |
+
a given point.
|
| 951 |
+
|
| 952 |
+
Parameters
|
| 953 |
+
----------
|
| 954 |
+
x : `numpy.ndarray`, shape (n,)
|
| 955 |
+
Point at which to evaluate the quadratic models of the nonlinear
|
| 956 |
+
inequality functions.
|
| 957 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 958 |
+
Mask of the quadratic models to consider.
|
| 959 |
+
|
| 960 |
+
Returns
|
| 961 |
+
-------
|
| 962 |
+
`numpy.ndarray`
|
| 963 |
+
Values of the quadratic model of the nonlinear inequality
|
| 964 |
+
functions.
|
| 965 |
+
"""
|
| 966 |
+
if self._debug:
|
| 967 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 968 |
+
assert mask is None or mask.shape == (
|
| 969 |
+
self.m_nonlinear_ub,
|
| 970 |
+
), "The shape of `mask` is not valid."
|
| 971 |
+
return np.array(
|
| 972 |
+
[model(x, self.interpolation) for model in self._get_cub(mask)]
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
def cub_grad(self, x, mask=None):
|
| 976 |
+
"""
|
| 977 |
+
Evaluate the gradients of the quadratic models of the nonlinear
|
| 978 |
+
inequality functions at a given point.
|
| 979 |
+
|
| 980 |
+
Parameters
|
| 981 |
+
----------
|
| 982 |
+
x : `numpy.ndarray`, shape (n,)
|
| 983 |
+
Point at which to evaluate the gradients of the quadratic models of
|
| 984 |
+
the nonlinear inequality functions.
|
| 985 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 986 |
+
Mask of the quadratic models to consider.
|
| 987 |
+
|
| 988 |
+
Returns
|
| 989 |
+
-------
|
| 990 |
+
`numpy.ndarray`
|
| 991 |
+
Gradients of the quadratic model of the nonlinear inequality
|
| 992 |
+
functions.
|
| 993 |
+
"""
|
| 994 |
+
if self._debug:
|
| 995 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 996 |
+
assert mask is None or mask.shape == (
|
| 997 |
+
self.m_nonlinear_ub,
|
| 998 |
+
), "The shape of `mask` is not valid."
|
| 999 |
+
return np.reshape(
|
| 1000 |
+
[model.grad(x, self.interpolation)
|
| 1001 |
+
for model in self._get_cub(mask)],
|
| 1002 |
+
(-1, self.n),
|
| 1003 |
+
)
|
| 1004 |
+
|
| 1005 |
+
def cub_hess(self, mask=None):
|
| 1006 |
+
"""
|
| 1007 |
+
Evaluate the Hessian matrices of the quadratic models of the nonlinear
|
| 1008 |
+
inequality functions.
|
| 1009 |
+
|
| 1010 |
+
Parameters
|
| 1011 |
+
----------
|
| 1012 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1013 |
+
Mask of the quadratic models to consider.
|
| 1014 |
+
|
| 1015 |
+
Returns
|
| 1016 |
+
-------
|
| 1017 |
+
`numpy.ndarray`
|
| 1018 |
+
Hessian matrices of the quadratic models of the nonlinear
|
| 1019 |
+
inequality functions.
|
| 1020 |
+
"""
|
| 1021 |
+
if self._debug:
|
| 1022 |
+
assert mask is None or mask.shape == (
|
| 1023 |
+
self.m_nonlinear_ub,
|
| 1024 |
+
), "The shape of `mask` is not valid."
|
| 1025 |
+
return np.reshape(
|
| 1026 |
+
[model.hess(self.interpolation) for model in self._get_cub(mask)],
|
| 1027 |
+
(-1, self.n, self.n),
|
| 1028 |
+
)
|
| 1029 |
+
|
| 1030 |
+
def cub_hess_prod(self, v, mask=None):
|
| 1031 |
+
"""
|
| 1032 |
+
Evaluate the right product of the Hessian matrices of the quadratic
|
| 1033 |
+
models of the nonlinear inequality functions with a given vector.
|
| 1034 |
+
|
| 1035 |
+
Parameters
|
| 1036 |
+
----------
|
| 1037 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1038 |
+
Vector with which the Hessian matrices of the quadratic models of
|
| 1039 |
+
the nonlinear inequality functions are multiplied from the right.
|
| 1040 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1041 |
+
Mask of the quadratic models to consider.
|
| 1042 |
+
|
| 1043 |
+
Returns
|
| 1044 |
+
-------
|
| 1045 |
+
`numpy.ndarray`
|
| 1046 |
+
Right products of the Hessian matrices of the quadratic models of
|
| 1047 |
+
the nonlinear inequality functions with `v`.
|
| 1048 |
+
"""
|
| 1049 |
+
if self._debug:
|
| 1050 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1051 |
+
assert mask is None or mask.shape == (
|
| 1052 |
+
self.m_nonlinear_ub,
|
| 1053 |
+
), "The shape of `mask` is not valid."
|
| 1054 |
+
return np.reshape(
|
| 1055 |
+
[
|
| 1056 |
+
model.hess_prod(v, self.interpolation)
|
| 1057 |
+
for model in self._get_cub(mask)
|
| 1058 |
+
],
|
| 1059 |
+
(-1, self.n),
|
| 1060 |
+
)
|
| 1061 |
+
|
| 1062 |
+
def cub_curv(self, v, mask=None):
|
| 1063 |
+
"""
|
| 1064 |
+
Evaluate the curvature of the quadratic models of the nonlinear
|
| 1065 |
+
inequality functions along a given direction.
|
| 1066 |
+
|
| 1067 |
+
Parameters
|
| 1068 |
+
----------
|
| 1069 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1070 |
+
Direction along which the curvature of the quadratic models of the
|
| 1071 |
+
nonlinear inequality functions is evaluated.
|
| 1072 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1073 |
+
Mask of the quadratic models to consider.
|
| 1074 |
+
|
| 1075 |
+
Returns
|
| 1076 |
+
-------
|
| 1077 |
+
`numpy.ndarray`
|
| 1078 |
+
Curvature of the quadratic models of the nonlinear inequality
|
| 1079 |
+
functions along `v`.
|
| 1080 |
+
"""
|
| 1081 |
+
if self._debug:
|
| 1082 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1083 |
+
assert mask is None or mask.shape == (
|
| 1084 |
+
self.m_nonlinear_ub,
|
| 1085 |
+
), "The shape of `mask` is not valid."
|
| 1086 |
+
return np.array(
|
| 1087 |
+
[model.curv(v, self.interpolation)
|
| 1088 |
+
for model in self._get_cub(mask)]
|
| 1089 |
+
)
|
| 1090 |
+
|
| 1091 |
+
def ceq(self, x, mask=None):
|
| 1092 |
+
"""
|
| 1093 |
+
Evaluate the quadratic models of the nonlinear equality functions at a
|
| 1094 |
+
given point.
|
| 1095 |
+
|
| 1096 |
+
Parameters
|
| 1097 |
+
----------
|
| 1098 |
+
x : `numpy.ndarray`, shape (n,)
|
| 1099 |
+
Point at which to evaluate the quadratic models of the nonlinear
|
| 1100 |
+
equality functions.
|
| 1101 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1102 |
+
Mask of the quadratic models to consider.
|
| 1103 |
+
|
| 1104 |
+
Returns
|
| 1105 |
+
-------
|
| 1106 |
+
`numpy.ndarray`
|
| 1107 |
+
Values of the quadratic model of the nonlinear equality functions.
|
| 1108 |
+
"""
|
| 1109 |
+
if self._debug:
|
| 1110 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 1111 |
+
assert mask is None or mask.shape == (
|
| 1112 |
+
self.m_nonlinear_eq,
|
| 1113 |
+
), "The shape of `mask` is not valid."
|
| 1114 |
+
return np.array(
|
| 1115 |
+
[model(x, self.interpolation) for model in self._get_ceq(mask)]
|
| 1116 |
+
)
|
| 1117 |
+
|
| 1118 |
+
def ceq_grad(self, x, mask=None):
|
| 1119 |
+
"""
|
| 1120 |
+
Evaluate the gradients of the quadratic models of the nonlinear
|
| 1121 |
+
equality functions at a given point.
|
| 1122 |
+
|
| 1123 |
+
Parameters
|
| 1124 |
+
----------
|
| 1125 |
+
x : `numpy.ndarray`, shape (n,)
|
| 1126 |
+
Point at which to evaluate the gradients of the quadratic models of
|
| 1127 |
+
the nonlinear equality functions.
|
| 1128 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1129 |
+
Mask of the quadratic models to consider.
|
| 1130 |
+
|
| 1131 |
+
Returns
|
| 1132 |
+
-------
|
| 1133 |
+
`numpy.ndarray`
|
| 1134 |
+
Gradients of the quadratic model of the nonlinear equality
|
| 1135 |
+
functions.
|
| 1136 |
+
"""
|
| 1137 |
+
if self._debug:
|
| 1138 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 1139 |
+
assert mask is None or mask.shape == (
|
| 1140 |
+
self.m_nonlinear_eq,
|
| 1141 |
+
), "The shape of `mask` is not valid."
|
| 1142 |
+
return np.reshape(
|
| 1143 |
+
[model.grad(x, self.interpolation)
|
| 1144 |
+
for model in self._get_ceq(mask)],
|
| 1145 |
+
(-1, self.n),
|
| 1146 |
+
)
|
| 1147 |
+
|
| 1148 |
+
def ceq_hess(self, mask=None):
|
| 1149 |
+
"""
|
| 1150 |
+
Evaluate the Hessian matrices of the quadratic models of the nonlinear
|
| 1151 |
+
equality functions.
|
| 1152 |
+
|
| 1153 |
+
Parameters
|
| 1154 |
+
----------
|
| 1155 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1156 |
+
Mask of the quadratic models to consider.
|
| 1157 |
+
|
| 1158 |
+
Returns
|
| 1159 |
+
-------
|
| 1160 |
+
`numpy.ndarray`
|
| 1161 |
+
Hessian matrices of the quadratic models of the nonlinear equality
|
| 1162 |
+
functions.
|
| 1163 |
+
"""
|
| 1164 |
+
if self._debug:
|
| 1165 |
+
assert mask is None or mask.shape == (
|
| 1166 |
+
self.m_nonlinear_eq,
|
| 1167 |
+
), "The shape of `mask` is not valid."
|
| 1168 |
+
return np.reshape(
|
| 1169 |
+
[model.hess(self.interpolation) for model in self._get_ceq(mask)],
|
| 1170 |
+
(-1, self.n, self.n),
|
| 1171 |
+
)
|
| 1172 |
+
|
| 1173 |
+
def ceq_hess_prod(self, v, mask=None):
|
| 1174 |
+
"""
|
| 1175 |
+
Evaluate the right product of the Hessian matrices of the quadratic
|
| 1176 |
+
models of the nonlinear equality functions with a given vector.
|
| 1177 |
+
|
| 1178 |
+
Parameters
|
| 1179 |
+
----------
|
| 1180 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1181 |
+
Vector with which the Hessian matrices of the quadratic models of
|
| 1182 |
+
the nonlinear equality functions are multiplied from the right.
|
| 1183 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1184 |
+
Mask of the quadratic models to consider.
|
| 1185 |
+
|
| 1186 |
+
Returns
|
| 1187 |
+
-------
|
| 1188 |
+
`numpy.ndarray`
|
| 1189 |
+
Right products of the Hessian matrices of the quadratic models of
|
| 1190 |
+
the nonlinear equality functions with `v`.
|
| 1191 |
+
"""
|
| 1192 |
+
if self._debug:
|
| 1193 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1194 |
+
assert mask is None or mask.shape == (
|
| 1195 |
+
self.m_nonlinear_eq,
|
| 1196 |
+
), "The shape of `mask` is not valid."
|
| 1197 |
+
return np.reshape(
|
| 1198 |
+
[
|
| 1199 |
+
model.hess_prod(v, self.interpolation)
|
| 1200 |
+
for model in self._get_ceq(mask)
|
| 1201 |
+
],
|
| 1202 |
+
(-1, self.n),
|
| 1203 |
+
)
|
| 1204 |
+
|
| 1205 |
+
def ceq_curv(self, v, mask=None):
|
| 1206 |
+
"""
|
| 1207 |
+
Evaluate the curvature of the quadratic models of the nonlinear
|
| 1208 |
+
equality functions along a given direction.
|
| 1209 |
+
|
| 1210 |
+
Parameters
|
| 1211 |
+
----------
|
| 1212 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1213 |
+
Direction along which the curvature of the quadratic models of the
|
| 1214 |
+
nonlinear equality functions is evaluated.
|
| 1215 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1216 |
+
Mask of the quadratic models to consider.
|
| 1217 |
+
|
| 1218 |
+
Returns
|
| 1219 |
+
-------
|
| 1220 |
+
`numpy.ndarray`
|
| 1221 |
+
Curvature of the quadratic models of the nonlinear equality
|
| 1222 |
+
functions along `v`.
|
| 1223 |
+
"""
|
| 1224 |
+
if self._debug:
|
| 1225 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1226 |
+
assert mask is None or mask.shape == (
|
| 1227 |
+
self.m_nonlinear_eq,
|
| 1228 |
+
), "The shape of `mask` is not valid."
|
| 1229 |
+
return np.array(
|
| 1230 |
+
[model.curv(v, self.interpolation)
|
| 1231 |
+
for model in self._get_ceq(mask)]
|
| 1232 |
+
)
|
| 1233 |
+
|
| 1234 |
+
def reset_models(self):
|
| 1235 |
+
"""
|
| 1236 |
+
Set the quadratic models of the objective function, nonlinear
|
| 1237 |
+
inequality constraints, and nonlinear equality constraints to the
|
| 1238 |
+
alternative quadratic models.
|
| 1239 |
+
|
| 1240 |
+
Raises
|
| 1241 |
+
------
|
| 1242 |
+
`numpy.linalg.LinAlgError`
|
| 1243 |
+
If the interpolation system is ill-defined.
|
| 1244 |
+
"""
|
| 1245 |
+
self._fun = Quadratic(self.interpolation, self.fun_val, self._debug)
|
| 1246 |
+
for i in range(self.m_nonlinear_ub):
|
| 1247 |
+
self._cub[i] = Quadratic(
|
| 1248 |
+
self.interpolation,
|
| 1249 |
+
self.cub_val[:, i],
|
| 1250 |
+
self._debug,
|
| 1251 |
+
)
|
| 1252 |
+
for i in range(self.m_nonlinear_eq):
|
| 1253 |
+
self._ceq[i] = Quadratic(
|
| 1254 |
+
self.interpolation,
|
| 1255 |
+
self.ceq_val[:, i],
|
| 1256 |
+
self._debug,
|
| 1257 |
+
)
|
| 1258 |
+
if self._debug:
|
| 1259 |
+
self._check_interpolation_conditions()
|
| 1260 |
+
|
| 1261 |
+
def update_interpolation(self, k_new, x_new, fun_val, cub_val, ceq_val):
|
| 1262 |
+
"""
|
| 1263 |
+
Update the interpolation set.
|
| 1264 |
+
|
| 1265 |
+
This method updates the interpolation set by replacing the `knew`-th
|
| 1266 |
+
interpolation point with `xnew`. It also updates the function values
|
| 1267 |
+
and the quadratic models.
|
| 1268 |
+
|
| 1269 |
+
Parameters
|
| 1270 |
+
----------
|
| 1271 |
+
k_new : int
|
| 1272 |
+
Index of the updated interpolation point.
|
| 1273 |
+
x_new : `numpy.ndarray`, shape (n,)
|
| 1274 |
+
New interpolation point. Its value is interpreted as relative to
|
| 1275 |
+
the origin, not the base point.
|
| 1276 |
+
fun_val : float
|
| 1277 |
+
Value of the objective function at `x_new`.
|
| 1278 |
+
Objective function value at `x_new`.
|
| 1279 |
+
cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 1280 |
+
Values of the nonlinear inequality constraints at `x_new`.
|
| 1281 |
+
ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
|
| 1282 |
+
Values of the nonlinear equality constraints at `x_new`.
|
| 1283 |
+
|
| 1284 |
+
Raises
|
| 1285 |
+
------
|
| 1286 |
+
`numpy.linalg.LinAlgError`
|
| 1287 |
+
If the interpolation system is ill-defined.
|
| 1288 |
+
"""
|
| 1289 |
+
if self._debug:
|
| 1290 |
+
assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
|
| 1291 |
+
assert x_new.shape == (self.n,), \
|
| 1292 |
+
"The shape of `x_new` is not valid."
|
| 1293 |
+
assert isinstance(fun_val, float), \
|
| 1294 |
+
"The function value is not valid."
|
| 1295 |
+
assert cub_val.shape == (
|
| 1296 |
+
self.m_nonlinear_ub,
|
| 1297 |
+
), "The shape of `cub_val` is not valid."
|
| 1298 |
+
assert ceq_val.shape == (
|
| 1299 |
+
self.m_nonlinear_eq,
|
| 1300 |
+
), "The shape of `ceq_val` is not valid."
|
| 1301 |
+
|
| 1302 |
+
# Compute the updates in the interpolation conditions.
|
| 1303 |
+
fun_diff = np.zeros(self.npt)
|
| 1304 |
+
cub_diff = np.zeros(self.cub_val.shape)
|
| 1305 |
+
ceq_diff = np.zeros(self.ceq_val.shape)
|
| 1306 |
+
fun_diff[k_new] = fun_val - self.fun(x_new)
|
| 1307 |
+
cub_diff[k_new, :] = cub_val - self.cub(x_new)
|
| 1308 |
+
ceq_diff[k_new, :] = ceq_val - self.ceq(x_new)
|
| 1309 |
+
|
| 1310 |
+
# Update the function values.
|
| 1311 |
+
self.fun_val[k_new] = fun_val
|
| 1312 |
+
self.cub_val[k_new, :] = cub_val
|
| 1313 |
+
self.ceq_val[k_new, :] = ceq_val
|
| 1314 |
+
|
| 1315 |
+
# Update the interpolation set.
|
| 1316 |
+
dir_old = np.copy(self.interpolation.xpt[:, k_new])
|
| 1317 |
+
self.interpolation.xpt[:, k_new] = x_new - self.interpolation.x_base
|
| 1318 |
+
|
| 1319 |
+
# Update the quadratic models.
|
| 1320 |
+
ill_conditioned = self._fun.update(
|
| 1321 |
+
self.interpolation,
|
| 1322 |
+
k_new,
|
| 1323 |
+
dir_old,
|
| 1324 |
+
fun_diff,
|
| 1325 |
+
)
|
| 1326 |
+
for i in range(self.m_nonlinear_ub):
|
| 1327 |
+
ill_conditioned = ill_conditioned or self._cub[i].update(
|
| 1328 |
+
self.interpolation,
|
| 1329 |
+
k_new,
|
| 1330 |
+
dir_old,
|
| 1331 |
+
cub_diff[:, i],
|
| 1332 |
+
)
|
| 1333 |
+
for i in range(self.m_nonlinear_eq):
|
| 1334 |
+
ill_conditioned = ill_conditioned or self._ceq[i].update(
|
| 1335 |
+
self.interpolation,
|
| 1336 |
+
k_new,
|
| 1337 |
+
dir_old,
|
| 1338 |
+
ceq_diff[:, i],
|
| 1339 |
+
)
|
| 1340 |
+
if self._debug:
|
| 1341 |
+
self._check_interpolation_conditions()
|
| 1342 |
+
return ill_conditioned
|
| 1343 |
+
|
| 1344 |
+
def determinants(self, x_new, k_new=None):
|
| 1345 |
+
"""
|
| 1346 |
+
Compute the normalized determinants of the new interpolation systems.
|
| 1347 |
+
|
| 1348 |
+
Parameters
|
| 1349 |
+
----------
|
| 1350 |
+
x_new : `numpy.ndarray`, shape (n,)
|
| 1351 |
+
New interpolation point. Its value is interpreted as relative to
|
| 1352 |
+
the origin, not the base point.
|
| 1353 |
+
k_new : int, optional
|
| 1354 |
+
Index of the updated interpolation point. If `k_new` is not
|
| 1355 |
+
specified, all the possible determinants are computed.
|
| 1356 |
+
|
| 1357 |
+
Returns
|
| 1358 |
+
-------
|
| 1359 |
+
{float, `numpy.ndarray`, shape (npt,)}
|
| 1360 |
+
Determinant(s) of the new interpolation system.
|
| 1361 |
+
|
| 1362 |
+
Raises
|
| 1363 |
+
------
|
| 1364 |
+
`numpy.linalg.LinAlgError`
|
| 1365 |
+
If the interpolation system is ill-defined.
|
| 1366 |
+
|
| 1367 |
+
Notes
|
| 1368 |
+
-----
|
| 1369 |
+
The determinants are normalized by the determinant of the current
|
| 1370 |
+
interpolation system. For stability reasons, the calculations are done
|
| 1371 |
+
using the formula (2.12) in [1]_.
|
| 1372 |
+
|
| 1373 |
+
References
|
| 1374 |
+
----------
|
| 1375 |
+
.. [1] M. J. D. Powell. On updating the inverse of a KKT matrix.
|
| 1376 |
+
Technical Report DAMTP 2004/NA01, Department of Applied Mathematics
|
| 1377 |
+
and Theoretical Physics, University of Cambridge, Cambridge, UK,
|
| 1378 |
+
2004.
|
| 1379 |
+
"""
|
| 1380 |
+
if self._debug:
|
| 1381 |
+
assert x_new.shape == (self.n,), \
|
| 1382 |
+
"The shape of `x_new` is not valid."
|
| 1383 |
+
assert (
|
| 1384 |
+
k_new is None or 0 <= k_new < self.npt
|
| 1385 |
+
), "The index `k_new` is not valid."
|
| 1386 |
+
|
| 1387 |
+
# Compute the values independent of k_new.
|
| 1388 |
+
shift = x_new - self.interpolation.x_base
|
| 1389 |
+
new_col = np.empty((self.npt + self.n + 1, 1))
|
| 1390 |
+
new_col[: self.npt, 0] = (
|
| 1391 |
+
0.5 * (self.interpolation.xpt.T @ shift) ** 2.0)
|
| 1392 |
+
new_col[self.npt, 0] = 1.0
|
| 1393 |
+
new_col[self.npt + 1:, 0] = shift
|
| 1394 |
+
inv_new_col = Quadratic.solve_systems(self.interpolation, new_col)[0]
|
| 1395 |
+
beta = 0.5 * (shift @ shift) ** 2.0 - new_col[:, 0] @ inv_new_col[:, 0]
|
| 1396 |
+
|
| 1397 |
+
# Compute the values that depend on k.
|
| 1398 |
+
if k_new is None:
|
| 1399 |
+
coord_vec = np.eye(self.npt + self.n + 1, self.npt)
|
| 1400 |
+
alpha = np.diag(
|
| 1401 |
+
Quadratic.solve_systems(
|
| 1402 |
+
self.interpolation,
|
| 1403 |
+
coord_vec,
|
| 1404 |
+
)[0]
|
| 1405 |
+
)
|
| 1406 |
+
tau = inv_new_col[: self.npt, 0]
|
| 1407 |
+
else:
|
| 1408 |
+
coord_vec = np.eye(self.npt + self.n + 1, 1, -k_new)
|
| 1409 |
+
alpha = Quadratic.solve_systems(
|
| 1410 |
+
self.interpolation,
|
| 1411 |
+
coord_vec,
|
| 1412 |
+
)[
|
| 1413 |
+
0
|
| 1414 |
+
][k_new, 0]
|
| 1415 |
+
tau = inv_new_col[k_new, 0]
|
| 1416 |
+
return alpha * beta + tau**2.0
|
| 1417 |
+
|
| 1418 |
+
def shift_x_base(self, new_x_base, options):
|
| 1419 |
+
"""
|
| 1420 |
+
Shift the base point without changing the interpolation set.
|
| 1421 |
+
|
| 1422 |
+
Parameters
|
| 1423 |
+
----------
|
| 1424 |
+
new_x_base : `numpy.ndarray`, shape (n,)
|
| 1425 |
+
New base point.
|
| 1426 |
+
options : dict
|
| 1427 |
+
Options of the solver.
|
| 1428 |
+
"""
|
| 1429 |
+
if self._debug:
|
| 1430 |
+
assert new_x_base.shape == (
|
| 1431 |
+
self.n,
|
| 1432 |
+
), "The shape of `new_x_base` is not valid."
|
| 1433 |
+
|
| 1434 |
+
# Update the models.
|
| 1435 |
+
self._fun.shift_x_base(self.interpolation, new_x_base)
|
| 1436 |
+
for model in self._cub:
|
| 1437 |
+
model.shift_x_base(self.interpolation, new_x_base)
|
| 1438 |
+
for model in self._ceq:
|
| 1439 |
+
model.shift_x_base(self.interpolation, new_x_base)
|
| 1440 |
+
|
| 1441 |
+
# Update the base point and the interpolation points.
|
| 1442 |
+
shift = new_x_base - self.interpolation.x_base
|
| 1443 |
+
self.interpolation.x_base += shift
|
| 1444 |
+
self.interpolation.xpt -= shift[:, np.newaxis]
|
| 1445 |
+
if options[Options.DEBUG]:
|
| 1446 |
+
self._check_interpolation_conditions()
|
| 1447 |
+
|
| 1448 |
+
def _get_cub(self, mask=None):
|
| 1449 |
+
"""
|
| 1450 |
+
Get the quadratic models of the nonlinear inequality constraints.
|
| 1451 |
+
|
| 1452 |
+
Parameters
|
| 1453 |
+
----------
|
| 1454 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1455 |
+
Mask of the quadratic models to return.
|
| 1456 |
+
|
| 1457 |
+
Returns
|
| 1458 |
+
-------
|
| 1459 |
+
`numpy.ndarray`
|
| 1460 |
+
Quadratic models of the nonlinear inequality constraints.
|
| 1461 |
+
"""
|
| 1462 |
+
return self._cub if mask is None else self._cub[mask]
|
| 1463 |
+
|
| 1464 |
+
def _get_ceq(self, mask=None):
|
| 1465 |
+
"""
|
| 1466 |
+
Get the quadratic models of the nonlinear equality constraints.
|
| 1467 |
+
|
| 1468 |
+
Parameters
|
| 1469 |
+
----------
|
| 1470 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1471 |
+
Mask of the quadratic models to return.
|
| 1472 |
+
|
| 1473 |
+
Returns
|
| 1474 |
+
-------
|
| 1475 |
+
`numpy.ndarray`
|
| 1476 |
+
Quadratic models of the nonlinear equality constraints.
|
| 1477 |
+
"""
|
| 1478 |
+
return self._ceq if mask is None else self._ceq[mask]
|
| 1479 |
+
|
| 1480 |
+
def _check_interpolation_conditions(self):
|
| 1481 |
+
"""
|
| 1482 |
+
Check the interpolation conditions of all quadratic models.
|
| 1483 |
+
"""
|
| 1484 |
+
error_fun = 0.0
|
| 1485 |
+
error_cub = 0.0
|
| 1486 |
+
error_ceq = 0.0
|
| 1487 |
+
for k in range(self.npt):
|
| 1488 |
+
error_fun = np.max(
|
| 1489 |
+
[
|
| 1490 |
+
error_fun,
|
| 1491 |
+
np.abs(
|
| 1492 |
+
self.fun(self.interpolation.point(k)) - self.fun_val[k]
|
| 1493 |
+
),
|
| 1494 |
+
]
|
| 1495 |
+
)
|
| 1496 |
+
error_cub = np.max(
|
| 1497 |
+
np.abs(
|
| 1498 |
+
self.cub(self.interpolation.point(k)) - self.cub_val[k, :]
|
| 1499 |
+
),
|
| 1500 |
+
initial=error_cub,
|
| 1501 |
+
)
|
| 1502 |
+
error_ceq = np.max(
|
| 1503 |
+
np.abs(
|
| 1504 |
+
self.ceq(self.interpolation.point(k)) - self.ceq_val[k, :]
|
| 1505 |
+
),
|
| 1506 |
+
initial=error_ceq,
|
| 1507 |
+
)
|
| 1508 |
+
tol = 10.0 * np.sqrt(EPS) * max(self.n, self.npt)
|
| 1509 |
+
if error_fun > tol * np.max(np.abs(self.fun_val), initial=1.0):
|
| 1510 |
+
warnings.warn(
|
| 1511 |
+
"The interpolation conditions for the objective function are "
|
| 1512 |
+
"not satisfied.",
|
| 1513 |
+
RuntimeWarning,
|
| 1514 |
+
2,
|
| 1515 |
+
)
|
| 1516 |
+
if error_cub > tol * np.max(np.abs(self.cub_val), initial=1.0):
|
| 1517 |
+
warnings.warn(
|
| 1518 |
+
"The interpolation conditions for the inequality constraint "
|
| 1519 |
+
"function are not satisfied.",
|
| 1520 |
+
RuntimeWarning,
|
| 1521 |
+
2,
|
| 1522 |
+
)
|
| 1523 |
+
if error_ceq > tol * np.max(np.abs(self.ceq_val), initial=1.0):
|
| 1524 |
+
warnings.warn(
|
| 1525 |
+
"The interpolation conditions for the equality constraint "
|
| 1526 |
+
"function are not satisfied.",
|
| 1527 |
+
RuntimeWarning,
|
| 1528 |
+
2,
|
| 1529 |
+
)
|
python_embeded/Lib/site-packages/scipy/_lib/cobyqa/problem.py
ADDED
|
@@ -0,0 +1,1296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import suppress
|
| 2 |
+
from inspect import signature
|
| 3 |
+
import copy
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from scipy.optimize import (
|
| 7 |
+
Bounds,
|
| 8 |
+
LinearConstraint,
|
| 9 |
+
NonlinearConstraint,
|
| 10 |
+
OptimizeResult,
|
| 11 |
+
)
|
| 12 |
+
from scipy.optimize._constraints import PreparedConstraint
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
from .settings import PRINT_OPTIONS, BARRIER
|
| 16 |
+
from .utils import CallbackSuccess, get_arrays_tol
|
| 17 |
+
from .utils import exact_1d_array
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ObjectiveFunction:
|
| 21 |
+
"""
|
| 22 |
+
Real-valued objective function.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, fun, verbose, debug, *args):
|
| 26 |
+
"""
|
| 27 |
+
Initialize the objective function.
|
| 28 |
+
|
| 29 |
+
Parameters
|
| 30 |
+
----------
|
| 31 |
+
fun : {callable, None}
|
| 32 |
+
Function to evaluate, or None.
|
| 33 |
+
|
| 34 |
+
``fun(x, *args) -> float``
|
| 35 |
+
|
| 36 |
+
where ``x`` is an array with shape (n,) and `args` is a tuple.
|
| 37 |
+
verbose : bool
|
| 38 |
+
Whether to print the function evaluations.
|
| 39 |
+
debug : bool
|
| 40 |
+
Whether to make debugging tests during the execution.
|
| 41 |
+
*args : tuple
|
| 42 |
+
Additional arguments to be passed to the function.
|
| 43 |
+
"""
|
| 44 |
+
if debug:
|
| 45 |
+
assert fun is None or callable(fun)
|
| 46 |
+
assert isinstance(verbose, bool)
|
| 47 |
+
assert isinstance(debug, bool)
|
| 48 |
+
|
| 49 |
+
self._fun = fun
|
| 50 |
+
self._verbose = verbose
|
| 51 |
+
self._args = args
|
| 52 |
+
self._n_eval = 0
|
| 53 |
+
|
| 54 |
+
def __call__(self, x):
|
| 55 |
+
"""
|
| 56 |
+
Evaluate the objective function.
|
| 57 |
+
|
| 58 |
+
Parameters
|
| 59 |
+
----------
|
| 60 |
+
x : array_like, shape (n,)
|
| 61 |
+
Point at which the objective function is evaluated.
|
| 62 |
+
|
| 63 |
+
Returns
|
| 64 |
+
-------
|
| 65 |
+
float
|
| 66 |
+
Function value at `x`.
|
| 67 |
+
"""
|
| 68 |
+
x = np.array(x, dtype=float)
|
| 69 |
+
if self._fun is None:
|
| 70 |
+
f = 0.0
|
| 71 |
+
else:
|
| 72 |
+
f = float(np.squeeze(self._fun(x, *self._args)))
|
| 73 |
+
self._n_eval += 1
|
| 74 |
+
if self._verbose:
|
| 75 |
+
with np.printoptions(**PRINT_OPTIONS):
|
| 76 |
+
print(f"{self.name}({x}) = {f}")
|
| 77 |
+
return f
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def n_eval(self):
|
| 81 |
+
"""
|
| 82 |
+
Number of function evaluations.
|
| 83 |
+
|
| 84 |
+
Returns
|
| 85 |
+
-------
|
| 86 |
+
int
|
| 87 |
+
Number of function evaluations.
|
| 88 |
+
"""
|
| 89 |
+
return self._n_eval
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def name(self):
|
| 93 |
+
"""
|
| 94 |
+
Name of the objective function.
|
| 95 |
+
|
| 96 |
+
Returns
|
| 97 |
+
-------
|
| 98 |
+
str
|
| 99 |
+
Name of the objective function.
|
| 100 |
+
"""
|
| 101 |
+
name = ""
|
| 102 |
+
if self._fun is not None:
|
| 103 |
+
try:
|
| 104 |
+
name = self._fun.__name__
|
| 105 |
+
except AttributeError:
|
| 106 |
+
name = "fun"
|
| 107 |
+
return name
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class BoundConstraints:
|
| 111 |
+
"""
|
| 112 |
+
Bound constraints ``xl <= x <= xu``.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
def __init__(self, bounds):
|
| 116 |
+
"""
|
| 117 |
+
Initialize the bound constraints.
|
| 118 |
+
|
| 119 |
+
Parameters
|
| 120 |
+
----------
|
| 121 |
+
bounds : scipy.optimize.Bounds
|
| 122 |
+
Bound constraints.
|
| 123 |
+
"""
|
| 124 |
+
self._xl = np.array(bounds.lb, float)
|
| 125 |
+
self._xu = np.array(bounds.ub, float)
|
| 126 |
+
|
| 127 |
+
# Remove the ill-defined bounds.
|
| 128 |
+
self.xl[np.isnan(self.xl)] = -np.inf
|
| 129 |
+
self.xu[np.isnan(self.xu)] = np.inf
|
| 130 |
+
|
| 131 |
+
self.is_feasible = (
|
| 132 |
+
np.all(self.xl <= self.xu)
|
| 133 |
+
and np.all(self.xl < np.inf)
|
| 134 |
+
and np.all(self.xu > -np.inf)
|
| 135 |
+
)
|
| 136 |
+
self.m = np.count_nonzero(self.xl > -np.inf) + np.count_nonzero(
|
| 137 |
+
self.xu < np.inf
|
| 138 |
+
)
|
| 139 |
+
self.pcs = PreparedConstraint(bounds, np.ones(bounds.lb.size))
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def xl(self):
|
| 143 |
+
"""
|
| 144 |
+
Lower bound.
|
| 145 |
+
|
| 146 |
+
Returns
|
| 147 |
+
-------
|
| 148 |
+
`numpy.ndarray`, shape (n,)
|
| 149 |
+
Lower bound.
|
| 150 |
+
"""
|
| 151 |
+
return self._xl
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def xu(self):
|
| 155 |
+
"""
|
| 156 |
+
Upper bound.
|
| 157 |
+
|
| 158 |
+
Returns
|
| 159 |
+
-------
|
| 160 |
+
`numpy.ndarray`, shape (n,)
|
| 161 |
+
Upper bound.
|
| 162 |
+
"""
|
| 163 |
+
return self._xu
|
| 164 |
+
|
| 165 |
+
def maxcv(self, x):
|
| 166 |
+
"""
|
| 167 |
+
Evaluate the maximum constraint violation.
|
| 168 |
+
|
| 169 |
+
Parameters
|
| 170 |
+
----------
|
| 171 |
+
x : array_like, shape (n,)
|
| 172 |
+
Point at which the maximum constraint violation is evaluated.
|
| 173 |
+
|
| 174 |
+
Returns
|
| 175 |
+
-------
|
| 176 |
+
float
|
| 177 |
+
Maximum constraint violation at `x`.
|
| 178 |
+
"""
|
| 179 |
+
x = np.asarray(x, dtype=float)
|
| 180 |
+
return self.violation(x)
|
| 181 |
+
|
| 182 |
+
def violation(self, x):
|
| 183 |
+
# shortcut for no bounds
|
| 184 |
+
if self.is_feasible:
|
| 185 |
+
return np.array([0])
|
| 186 |
+
else:
|
| 187 |
+
return self.pcs.violation(x)
|
| 188 |
+
|
| 189 |
+
def project(self, x):
|
| 190 |
+
"""
|
| 191 |
+
Project a point onto the feasible set.
|
| 192 |
+
|
| 193 |
+
Parameters
|
| 194 |
+
----------
|
| 195 |
+
x : array_like, shape (n,)
|
| 196 |
+
Point to be projected.
|
| 197 |
+
|
| 198 |
+
Returns
|
| 199 |
+
-------
|
| 200 |
+
`numpy.ndarray`, shape (n,)
|
| 201 |
+
Projection of `x` onto the feasible set.
|
| 202 |
+
"""
|
| 203 |
+
return np.clip(x, self.xl, self.xu) if self.is_feasible else x
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class LinearConstraints:
|
| 207 |
+
"""
|
| 208 |
+
Linear constraints ``a_ub @ x <= b_ub`` and ``a_eq @ x == b_eq``.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def __init__(self, constraints, n, debug):
|
| 212 |
+
"""
|
| 213 |
+
Initialize the linear constraints.
|
| 214 |
+
|
| 215 |
+
Parameters
|
| 216 |
+
----------
|
| 217 |
+
constraints : list of LinearConstraint
|
| 218 |
+
Linear constraints.
|
| 219 |
+
n : int
|
| 220 |
+
Number of variables.
|
| 221 |
+
debug : bool
|
| 222 |
+
Whether to make debugging tests during the execution.
|
| 223 |
+
"""
|
| 224 |
+
if debug:
|
| 225 |
+
assert isinstance(constraints, list)
|
| 226 |
+
for constraint in constraints:
|
| 227 |
+
assert isinstance(constraint, LinearConstraint)
|
| 228 |
+
assert isinstance(debug, bool)
|
| 229 |
+
|
| 230 |
+
self._a_ub = np.empty((0, n))
|
| 231 |
+
self._b_ub = np.empty(0)
|
| 232 |
+
self._a_eq = np.empty((0, n))
|
| 233 |
+
self._b_eq = np.empty(0)
|
| 234 |
+
for constraint in constraints:
|
| 235 |
+
is_equality = np.abs(
|
| 236 |
+
constraint.ub - constraint.lb
|
| 237 |
+
) <= get_arrays_tol(constraint.lb, constraint.ub)
|
| 238 |
+
if np.any(is_equality):
|
| 239 |
+
self._a_eq = np.vstack((self.a_eq, constraint.A[is_equality]))
|
| 240 |
+
self._b_eq = np.concatenate(
|
| 241 |
+
(
|
| 242 |
+
self.b_eq,
|
| 243 |
+
0.5
|
| 244 |
+
* (
|
| 245 |
+
constraint.lb[is_equality]
|
| 246 |
+
+ constraint.ub[is_equality]
|
| 247 |
+
),
|
| 248 |
+
)
|
| 249 |
+
)
|
| 250 |
+
if not np.all(is_equality):
|
| 251 |
+
self._a_ub = np.vstack(
|
| 252 |
+
(
|
| 253 |
+
self.a_ub,
|
| 254 |
+
constraint.A[~is_equality],
|
| 255 |
+
-constraint.A[~is_equality],
|
| 256 |
+
)
|
| 257 |
+
)
|
| 258 |
+
self._b_ub = np.concatenate(
|
| 259 |
+
(
|
| 260 |
+
self.b_ub,
|
| 261 |
+
constraint.ub[~is_equality],
|
| 262 |
+
-constraint.lb[~is_equality],
|
| 263 |
+
)
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
# Remove the ill-defined constraints.
|
| 267 |
+
self.a_ub[np.isnan(self.a_ub)] = 0.0
|
| 268 |
+
self.a_eq[np.isnan(self.a_eq)] = 0.0
|
| 269 |
+
undef_ub = np.isnan(self.b_ub) | np.isinf(self.b_ub)
|
| 270 |
+
undef_eq = np.isnan(self.b_eq)
|
| 271 |
+
self._a_ub = self.a_ub[~undef_ub, :]
|
| 272 |
+
self._b_ub = self.b_ub[~undef_ub]
|
| 273 |
+
self._a_eq = self.a_eq[~undef_eq, :]
|
| 274 |
+
self._b_eq = self.b_eq[~undef_eq]
|
| 275 |
+
self.pcs = [
|
| 276 |
+
PreparedConstraint(c, np.ones(n)) for c in constraints if c.A.size
|
| 277 |
+
]
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def a_ub(self):
|
| 281 |
+
"""
|
| 282 |
+
Left-hand side matrix of the linear inequality constraints.
|
| 283 |
+
|
| 284 |
+
Returns
|
| 285 |
+
-------
|
| 286 |
+
`numpy.ndarray`, shape (m, n)
|
| 287 |
+
Left-hand side matrix of the linear inequality constraints.
|
| 288 |
+
"""
|
| 289 |
+
return self._a_ub
|
| 290 |
+
|
| 291 |
+
@property
|
| 292 |
+
def b_ub(self):
|
| 293 |
+
"""
|
| 294 |
+
Right-hand side vector of the linear inequality constraints.
|
| 295 |
+
|
| 296 |
+
Returns
|
| 297 |
+
-------
|
| 298 |
+
`numpy.ndarray`, shape (m, n)
|
| 299 |
+
Right-hand side vector of the linear inequality constraints.
|
| 300 |
+
"""
|
| 301 |
+
return self._b_ub
|
| 302 |
+
|
| 303 |
+
@property
|
| 304 |
+
def a_eq(self):
|
| 305 |
+
"""
|
| 306 |
+
Left-hand side matrix of the linear equality constraints.
|
| 307 |
+
|
| 308 |
+
Returns
|
| 309 |
+
-------
|
| 310 |
+
`numpy.ndarray`, shape (m, n)
|
| 311 |
+
Left-hand side matrix of the linear equality constraints.
|
| 312 |
+
"""
|
| 313 |
+
return self._a_eq
|
| 314 |
+
|
| 315 |
+
@property
|
| 316 |
+
def b_eq(self):
|
| 317 |
+
"""
|
| 318 |
+
Right-hand side vector of the linear equality constraints.
|
| 319 |
+
|
| 320 |
+
Returns
|
| 321 |
+
-------
|
| 322 |
+
`numpy.ndarray`, shape (m, n)
|
| 323 |
+
Right-hand side vector of the linear equality constraints.
|
| 324 |
+
"""
|
| 325 |
+
return self._b_eq
|
| 326 |
+
|
| 327 |
+
@property
|
| 328 |
+
def m_ub(self):
|
| 329 |
+
"""
|
| 330 |
+
Number of linear inequality constraints.
|
| 331 |
+
|
| 332 |
+
Returns
|
| 333 |
+
-------
|
| 334 |
+
int
|
| 335 |
+
Number of linear inequality constraints.
|
| 336 |
+
"""
|
| 337 |
+
return self.b_ub.size
|
| 338 |
+
|
| 339 |
+
@property
|
| 340 |
+
def m_eq(self):
|
| 341 |
+
"""
|
| 342 |
+
Number of linear equality constraints.
|
| 343 |
+
|
| 344 |
+
Returns
|
| 345 |
+
-------
|
| 346 |
+
int
|
| 347 |
+
Number of linear equality constraints.
|
| 348 |
+
"""
|
| 349 |
+
return self.b_eq.size
|
| 350 |
+
|
| 351 |
+
def maxcv(self, x):
|
| 352 |
+
"""
|
| 353 |
+
Evaluate the maximum constraint violation.
|
| 354 |
+
|
| 355 |
+
Parameters
|
| 356 |
+
----------
|
| 357 |
+
x : array_like, shape (n,)
|
| 358 |
+
Point at which the maximum constraint violation is evaluated.
|
| 359 |
+
|
| 360 |
+
Returns
|
| 361 |
+
-------
|
| 362 |
+
float
|
| 363 |
+
Maximum constraint violation at `x`.
|
| 364 |
+
"""
|
| 365 |
+
return np.max(self.violation(x), initial=0.0)
|
| 366 |
+
|
| 367 |
+
def violation(self, x):
|
| 368 |
+
if len(self.pcs):
|
| 369 |
+
return np.concatenate([pc.violation(x) for pc in self.pcs])
|
| 370 |
+
return np.array([])
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class NonlinearConstraints:
|
| 374 |
+
"""
|
| 375 |
+
Nonlinear constraints ``c_ub(x) <= 0`` and ``c_eq(x) == b_eq``.
|
| 376 |
+
"""
|
| 377 |
+
|
| 378 |
+
def __init__(self, constraints, verbose, debug):
|
| 379 |
+
"""
|
| 380 |
+
Initialize the nonlinear constraints.
|
| 381 |
+
|
| 382 |
+
Parameters
|
| 383 |
+
----------
|
| 384 |
+
constraints : list
|
| 385 |
+
Nonlinear constraints.
|
| 386 |
+
verbose : bool
|
| 387 |
+
Whether to print the function evaluations.
|
| 388 |
+
debug : bool
|
| 389 |
+
Whether to make debugging tests during the execution.
|
| 390 |
+
"""
|
| 391 |
+
if debug:
|
| 392 |
+
assert isinstance(constraints, list)
|
| 393 |
+
for constraint in constraints:
|
| 394 |
+
assert isinstance(constraint, NonlinearConstraint)
|
| 395 |
+
assert isinstance(verbose, bool)
|
| 396 |
+
assert isinstance(debug, bool)
|
| 397 |
+
|
| 398 |
+
self._constraints = constraints
|
| 399 |
+
self.pcs = []
|
| 400 |
+
self._verbose = verbose
|
| 401 |
+
|
| 402 |
+
# map of indexes for equality and inequality constraints
|
| 403 |
+
self._map_ub = None
|
| 404 |
+
self._map_eq = None
|
| 405 |
+
self._m_ub = self._m_eq = None
|
| 406 |
+
|
| 407 |
+
def __call__(self, x):
|
| 408 |
+
"""
|
| 409 |
+
Calculates the residual (slack) for the constraints.
|
| 410 |
+
|
| 411 |
+
Parameters
|
| 412 |
+
----------
|
| 413 |
+
x : array_like, shape (n,)
|
| 414 |
+
Point at which the constraints are evaluated.
|
| 415 |
+
|
| 416 |
+
Returns
|
| 417 |
+
-------
|
| 418 |
+
`numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 419 |
+
Nonlinear inequality constraint slack values.
|
| 420 |
+
`numpy.ndarray`, shape (m_nonlinear_eq,)
|
| 421 |
+
Nonlinear equality constraint slack values.
|
| 422 |
+
"""
|
| 423 |
+
if not len(self._constraints):
|
| 424 |
+
self._m_eq = self._m_ub = 0
|
| 425 |
+
return np.array([]), np.array([])
|
| 426 |
+
|
| 427 |
+
x = np.array(x, dtype=float)
|
| 428 |
+
# first time around the constraints haven't been prepared
|
| 429 |
+
if not len(self.pcs):
|
| 430 |
+
self._map_ub = []
|
| 431 |
+
self._map_eq = []
|
| 432 |
+
self._m_eq = 0
|
| 433 |
+
self._m_ub = 0
|
| 434 |
+
|
| 435 |
+
for constraint in self._constraints:
|
| 436 |
+
if not callable(constraint.jac):
|
| 437 |
+
# having a callable constraint function prevents
|
| 438 |
+
# constraint.fun from being evaluated when preparing
|
| 439 |
+
# constraint
|
| 440 |
+
c = copy.copy(constraint)
|
| 441 |
+
c.jac = lambda x0: x0
|
| 442 |
+
c.hess = lambda x0, v: 0.0
|
| 443 |
+
pc = PreparedConstraint(c, x)
|
| 444 |
+
else:
|
| 445 |
+
pc = PreparedConstraint(constraint, x)
|
| 446 |
+
# we're going to be using the same x value again immediately
|
| 447 |
+
# after this initialisation
|
| 448 |
+
pc.fun.f_updated = True
|
| 449 |
+
|
| 450 |
+
self.pcs.append(pc)
|
| 451 |
+
idx = np.arange(pc.fun.m)
|
| 452 |
+
|
| 453 |
+
# figure out equality and inequality maps
|
| 454 |
+
lb, ub = pc.bounds[0], pc.bounds[1]
|
| 455 |
+
arr_tol = get_arrays_tol(lb, ub)
|
| 456 |
+
is_equality = np.abs(ub - lb) <= arr_tol
|
| 457 |
+
self._map_eq.append(idx[is_equality])
|
| 458 |
+
self._map_ub.append(idx[~is_equality])
|
| 459 |
+
|
| 460 |
+
# these values will be corrected to their proper values later
|
| 461 |
+
self._m_eq += np.count_nonzero(is_equality)
|
| 462 |
+
self._m_ub += np.count_nonzero(~is_equality)
|
| 463 |
+
|
| 464 |
+
c_ub = []
|
| 465 |
+
c_eq = []
|
| 466 |
+
for i, pc in enumerate(self.pcs):
|
| 467 |
+
val = pc.fun.fun(x)
|
| 468 |
+
if self._verbose:
|
| 469 |
+
with np.printoptions(**PRINT_OPTIONS):
|
| 470 |
+
with suppress(AttributeError):
|
| 471 |
+
fun_name = self._constraints[i].fun.__name__
|
| 472 |
+
print(f"{fun_name}({x}) = {val}")
|
| 473 |
+
|
| 474 |
+
# separate violations into c_eq and c_ub
|
| 475 |
+
eq_idx = self._map_eq[i]
|
| 476 |
+
ub_idx = self._map_ub[i]
|
| 477 |
+
|
| 478 |
+
ub_val = val[ub_idx]
|
| 479 |
+
if len(ub_idx):
|
| 480 |
+
xl = pc.bounds[0][ub_idx]
|
| 481 |
+
xu = pc.bounds[1][ub_idx]
|
| 482 |
+
|
| 483 |
+
# calculate slack within lower bound
|
| 484 |
+
finite_xl = xl > -np.inf
|
| 485 |
+
_v = xl[finite_xl] - ub_val[finite_xl]
|
| 486 |
+
c_ub.append(_v)
|
| 487 |
+
|
| 488 |
+
# calculate slack within lower bound
|
| 489 |
+
finite_xu = xu < np.inf
|
| 490 |
+
_v = ub_val[finite_xu] - xu[finite_xu]
|
| 491 |
+
c_ub.append(_v)
|
| 492 |
+
|
| 493 |
+
# equality constraints taken from midpoint between lb and ub
|
| 494 |
+
eq_val = val[eq_idx]
|
| 495 |
+
if len(eq_idx):
|
| 496 |
+
midpoint = 0.5 * (pc.bounds[1][eq_idx] + pc.bounds[0][eq_idx])
|
| 497 |
+
eq_val -= midpoint
|
| 498 |
+
c_eq.append(eq_val)
|
| 499 |
+
|
| 500 |
+
if self._m_eq:
|
| 501 |
+
c_eq = np.concatenate(c_eq)
|
| 502 |
+
else:
|
| 503 |
+
c_eq = np.array([])
|
| 504 |
+
|
| 505 |
+
if self._m_ub:
|
| 506 |
+
c_ub = np.concatenate(c_ub)
|
| 507 |
+
else:
|
| 508 |
+
c_ub = np.array([])
|
| 509 |
+
|
| 510 |
+
self._m_ub = c_ub.size
|
| 511 |
+
self._m_eq = c_eq.size
|
| 512 |
+
|
| 513 |
+
return c_ub, c_eq
|
| 514 |
+
|
| 515 |
+
@property
|
| 516 |
+
def m_ub(self):
|
| 517 |
+
"""
|
| 518 |
+
Number of nonlinear inequality constraints.
|
| 519 |
+
|
| 520 |
+
Returns
|
| 521 |
+
-------
|
| 522 |
+
int
|
| 523 |
+
Number of nonlinear inequality constraints.
|
| 524 |
+
|
| 525 |
+
Raises
|
| 526 |
+
------
|
| 527 |
+
ValueError
|
| 528 |
+
If the number of nonlinear inequality constraints is unknown.
|
| 529 |
+
"""
|
| 530 |
+
if self._m_ub is None:
|
| 531 |
+
raise ValueError(
|
| 532 |
+
"The number of nonlinear inequality constraints is unknown."
|
| 533 |
+
)
|
| 534 |
+
else:
|
| 535 |
+
return self._m_ub
|
| 536 |
+
|
| 537 |
+
@property
|
| 538 |
+
def m_eq(self):
|
| 539 |
+
"""
|
| 540 |
+
Number of nonlinear equality constraints.
|
| 541 |
+
|
| 542 |
+
Returns
|
| 543 |
+
-------
|
| 544 |
+
int
|
| 545 |
+
Number of nonlinear equality constraints.
|
| 546 |
+
|
| 547 |
+
Raises
|
| 548 |
+
------
|
| 549 |
+
ValueError
|
| 550 |
+
If the number of nonlinear equality constraints is unknown.
|
| 551 |
+
"""
|
| 552 |
+
if self._m_eq is None:
|
| 553 |
+
raise ValueError(
|
| 554 |
+
"The number of nonlinear equality constraints is unknown."
|
| 555 |
+
)
|
| 556 |
+
else:
|
| 557 |
+
return self._m_eq
|
| 558 |
+
|
| 559 |
+
@property
|
| 560 |
+
def n_eval(self):
|
| 561 |
+
"""
|
| 562 |
+
Number of function evaluations.
|
| 563 |
+
|
| 564 |
+
Returns
|
| 565 |
+
-------
|
| 566 |
+
int
|
| 567 |
+
Number of function evaluations.
|
| 568 |
+
"""
|
| 569 |
+
if len(self.pcs):
|
| 570 |
+
return self.pcs[0].fun.nfev
|
| 571 |
+
else:
|
| 572 |
+
return 0
|
| 573 |
+
|
| 574 |
+
def maxcv(self, x, cub_val=None, ceq_val=None):
|
| 575 |
+
"""
|
| 576 |
+
Evaluate the maximum constraint violation.
|
| 577 |
+
|
| 578 |
+
Parameters
|
| 579 |
+
----------
|
| 580 |
+
x : array_like, shape (n,)
|
| 581 |
+
Point at which the maximum constraint violation is evaluated.
|
| 582 |
+
cub_val : array_like, shape (m_nonlinear_ub,), optional
|
| 583 |
+
Values of the nonlinear inequality constraints. If not provided,
|
| 584 |
+
the nonlinear inequality constraints are evaluated at `x`.
|
| 585 |
+
ceq_val : array_like, shape (m_nonlinear_eq,), optional
|
| 586 |
+
Values of the nonlinear equality constraints. If not provided,
|
| 587 |
+
the nonlinear equality constraints are evaluated at `x`.
|
| 588 |
+
|
| 589 |
+
Returns
|
| 590 |
+
-------
|
| 591 |
+
float
|
| 592 |
+
Maximum constraint violation at `x`.
|
| 593 |
+
"""
|
| 594 |
+
return np.max(
|
| 595 |
+
self.violation(x, cub_val=cub_val, ceq_val=ceq_val), initial=0.0
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
def violation(self, x, cub_val=None, ceq_val=None):
|
| 599 |
+
return np.concatenate([pc.violation(x) for pc in self.pcs])
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class Problem:
|
| 603 |
+
"""
|
| 604 |
+
Optimization problem.
|
| 605 |
+
"""
|
| 606 |
+
|
| 607 |
+
def __init__(
|
| 608 |
+
self,
|
| 609 |
+
obj,
|
| 610 |
+
x0,
|
| 611 |
+
bounds,
|
| 612 |
+
linear,
|
| 613 |
+
nonlinear,
|
| 614 |
+
callback,
|
| 615 |
+
feasibility_tol,
|
| 616 |
+
scale,
|
| 617 |
+
store_history,
|
| 618 |
+
history_size,
|
| 619 |
+
filter_size,
|
| 620 |
+
debug,
|
| 621 |
+
):
|
| 622 |
+
"""
|
| 623 |
+
Initialize the nonlinear problem.
|
| 624 |
+
|
| 625 |
+
The problem is preprocessed to remove all the variables that are fixed
|
| 626 |
+
by the bound constraints.
|
| 627 |
+
|
| 628 |
+
Parameters
|
| 629 |
+
----------
|
| 630 |
+
obj : ObjectiveFunction
|
| 631 |
+
Objective function.
|
| 632 |
+
x0 : array_like, shape (n,)
|
| 633 |
+
Initial guess.
|
| 634 |
+
bounds : BoundConstraints
|
| 635 |
+
Bound constraints.
|
| 636 |
+
linear : LinearConstraints
|
| 637 |
+
Linear constraints.
|
| 638 |
+
nonlinear : NonlinearConstraints
|
| 639 |
+
Nonlinear constraints.
|
| 640 |
+
callback : {callable, None}
|
| 641 |
+
Callback function.
|
| 642 |
+
feasibility_tol : float
|
| 643 |
+
Tolerance on the constraint violation.
|
| 644 |
+
scale : bool
|
| 645 |
+
Whether to scale the problem according to the bounds.
|
| 646 |
+
store_history : bool
|
| 647 |
+
Whether to store the function evaluations.
|
| 648 |
+
history_size : int
|
| 649 |
+
Maximum number of function evaluations to store.
|
| 650 |
+
filter_size : int
|
| 651 |
+
Maximum number of points in the filter.
|
| 652 |
+
debug : bool
|
| 653 |
+
Whether to make debugging tests during the execution.
|
| 654 |
+
"""
|
| 655 |
+
if debug:
|
| 656 |
+
assert isinstance(obj, ObjectiveFunction)
|
| 657 |
+
assert isinstance(bounds, BoundConstraints)
|
| 658 |
+
assert isinstance(linear, LinearConstraints)
|
| 659 |
+
assert isinstance(nonlinear, NonlinearConstraints)
|
| 660 |
+
assert isinstance(feasibility_tol, float)
|
| 661 |
+
assert isinstance(scale, bool)
|
| 662 |
+
assert isinstance(store_history, bool)
|
| 663 |
+
assert isinstance(history_size, int)
|
| 664 |
+
if store_history:
|
| 665 |
+
assert history_size > 0
|
| 666 |
+
assert isinstance(filter_size, int)
|
| 667 |
+
assert filter_size > 0
|
| 668 |
+
assert isinstance(debug, bool)
|
| 669 |
+
|
| 670 |
+
self._obj = obj
|
| 671 |
+
self._linear = linear
|
| 672 |
+
self._nonlinear = nonlinear
|
| 673 |
+
if callback is not None:
|
| 674 |
+
if not callable(callback):
|
| 675 |
+
raise TypeError("The callback must be a callable function.")
|
| 676 |
+
self._callback = callback
|
| 677 |
+
|
| 678 |
+
# Check the consistency of the problem.
|
| 679 |
+
x0 = exact_1d_array(x0, "The initial guess must be a vector.")
|
| 680 |
+
n = x0.size
|
| 681 |
+
if bounds.xl.size != n:
|
| 682 |
+
raise ValueError(f"The bounds must have {n} elements.")
|
| 683 |
+
if linear.a_ub.shape[1] != n:
|
| 684 |
+
raise ValueError(
|
| 685 |
+
f"The left-hand side matrices of the linear constraints must "
|
| 686 |
+
f"have {n} columns."
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
# Check which variables are fixed.
|
| 690 |
+
tol = get_arrays_tol(bounds.xl, bounds.xu)
|
| 691 |
+
self._fixed_idx = (bounds.xl <= bounds.xu) & (
|
| 692 |
+
np.abs(bounds.xl - bounds.xu) < tol
|
| 693 |
+
)
|
| 694 |
+
self._fixed_val = 0.5 * (
|
| 695 |
+
bounds.xl[self._fixed_idx] + bounds.xu[self._fixed_idx]
|
| 696 |
+
)
|
| 697 |
+
self._fixed_val = np.clip(
|
| 698 |
+
self._fixed_val,
|
| 699 |
+
bounds.xl[self._fixed_idx],
|
| 700 |
+
bounds.xu[self._fixed_idx],
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
# Set the bound constraints.
|
| 704 |
+
self._orig_bounds = bounds
|
| 705 |
+
self._bounds = BoundConstraints(
|
| 706 |
+
Bounds(bounds.xl[~self._fixed_idx], bounds.xu[~self._fixed_idx])
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
# Set the initial guess.
|
| 710 |
+
self._x0 = self._bounds.project(x0[~self._fixed_idx])
|
| 711 |
+
|
| 712 |
+
# Set the linear constraints.
|
| 713 |
+
b_eq = linear.b_eq - linear.a_eq[:, self._fixed_idx] @ self._fixed_val
|
| 714 |
+
self._linear = LinearConstraints(
|
| 715 |
+
[
|
| 716 |
+
LinearConstraint(
|
| 717 |
+
linear.a_ub[:, ~self._fixed_idx],
|
| 718 |
+
-np.inf,
|
| 719 |
+
linear.b_ub
|
| 720 |
+
- linear.a_ub[:, self._fixed_idx] @ self._fixed_val,
|
| 721 |
+
),
|
| 722 |
+
LinearConstraint(linear.a_eq[:, ~self._fixed_idx], b_eq, b_eq),
|
| 723 |
+
],
|
| 724 |
+
self.n,
|
| 725 |
+
debug,
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
# Scale the problem if necessary.
|
| 729 |
+
scale = (
|
| 730 |
+
scale
|
| 731 |
+
and self._bounds.is_feasible
|
| 732 |
+
and np.all(np.isfinite(self._bounds.xl))
|
| 733 |
+
and np.all(np.isfinite(self._bounds.xu))
|
| 734 |
+
)
|
| 735 |
+
if scale:
|
| 736 |
+
self._scaling_factor = 0.5 * (self._bounds.xu - self._bounds.xl)
|
| 737 |
+
self._scaling_shift = 0.5 * (self._bounds.xu + self._bounds.xl)
|
| 738 |
+
self._bounds = BoundConstraints(
|
| 739 |
+
Bounds(-np.ones(self.n), np.ones(self.n))
|
| 740 |
+
)
|
| 741 |
+
b_eq = self._linear.b_eq - self._linear.a_eq @ self._scaling_shift
|
| 742 |
+
self._linear = LinearConstraints(
|
| 743 |
+
[
|
| 744 |
+
LinearConstraint(
|
| 745 |
+
self._linear.a_ub @ np.diag(self._scaling_factor),
|
| 746 |
+
-np.inf,
|
| 747 |
+
self._linear.b_ub
|
| 748 |
+
- self._linear.a_ub @ self._scaling_shift,
|
| 749 |
+
),
|
| 750 |
+
LinearConstraint(
|
| 751 |
+
self._linear.a_eq @ np.diag(self._scaling_factor),
|
| 752 |
+
b_eq,
|
| 753 |
+
b_eq,
|
| 754 |
+
),
|
| 755 |
+
],
|
| 756 |
+
self.n,
|
| 757 |
+
debug,
|
| 758 |
+
)
|
| 759 |
+
self._x0 = (self._x0 - self._scaling_shift) / self._scaling_factor
|
| 760 |
+
else:
|
| 761 |
+
self._scaling_factor = np.ones(self.n)
|
| 762 |
+
self._scaling_shift = np.zeros(self.n)
|
| 763 |
+
|
| 764 |
+
# Set the initial filter.
|
| 765 |
+
self._feasibility_tol = feasibility_tol
|
| 766 |
+
self._filter_size = filter_size
|
| 767 |
+
self._fun_filter = []
|
| 768 |
+
self._maxcv_filter = []
|
| 769 |
+
self._x_filter = []
|
| 770 |
+
|
| 771 |
+
# Set the initial history.
|
| 772 |
+
self._store_history = store_history
|
| 773 |
+
self._history_size = history_size
|
| 774 |
+
self._fun_history = []
|
| 775 |
+
self._maxcv_history = []
|
| 776 |
+
self._x_history = []
|
| 777 |
+
|
| 778 |
+
def __call__(self, x, penalty=0.0):
|
| 779 |
+
"""
|
| 780 |
+
Evaluate the objective and nonlinear constraint functions.
|
| 781 |
+
|
| 782 |
+
Parameters
|
| 783 |
+
----------
|
| 784 |
+
x : array_like, shape (n,)
|
| 785 |
+
Point at which the functions are evaluated.
|
| 786 |
+
penalty : float, optional
|
| 787 |
+
Penalty parameter used to select the point in the filter to forward
|
| 788 |
+
to the callback function.
|
| 789 |
+
|
| 790 |
+
Returns
|
| 791 |
+
-------
|
| 792 |
+
float
|
| 793 |
+
Objective function value.
|
| 794 |
+
`numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 795 |
+
Nonlinear inequality constraint function values.
|
| 796 |
+
`numpy.ndarray`, shape (m_nonlinear_eq,)
|
| 797 |
+
Nonlinear equality constraint function values.
|
| 798 |
+
|
| 799 |
+
Raises
|
| 800 |
+
------
|
| 801 |
+
`cobyqa.utils.CallbackSuccess`
|
| 802 |
+
If the callback function raises a ``StopIteration``.
|
| 803 |
+
"""
|
| 804 |
+
# Evaluate the objective and nonlinear constraint functions.
|
| 805 |
+
x = np.asarray(x, dtype=float)
|
| 806 |
+
x_full = self.build_x(x)
|
| 807 |
+
fun_val = self._obj(x_full)
|
| 808 |
+
cub_val, ceq_val = self._nonlinear(x_full)
|
| 809 |
+
maxcv_val = self.maxcv(x, cub_val, ceq_val)
|
| 810 |
+
if self._store_history:
|
| 811 |
+
self._fun_history.append(fun_val)
|
| 812 |
+
self._maxcv_history.append(maxcv_val)
|
| 813 |
+
self._x_history.append(x)
|
| 814 |
+
if len(self._fun_history) > self._history_size:
|
| 815 |
+
self._fun_history.pop(0)
|
| 816 |
+
self._maxcv_history.pop(0)
|
| 817 |
+
self._x_history.pop(0)
|
| 818 |
+
|
| 819 |
+
# Add the point to the filter if it is not dominated by any point.
|
| 820 |
+
if np.isnan(fun_val) and np.isnan(maxcv_val):
|
| 821 |
+
include_point = len(self._fun_filter) == 0
|
| 822 |
+
elif np.isnan(fun_val):
|
| 823 |
+
include_point = all(
|
| 824 |
+
np.isnan(fun_filter)
|
| 825 |
+
and maxcv_val < maxcv_filter
|
| 826 |
+
or np.isnan(maxcv_filter)
|
| 827 |
+
for fun_filter, maxcv_filter in zip(
|
| 828 |
+
self._fun_filter,
|
| 829 |
+
self._maxcv_filter,
|
| 830 |
+
)
|
| 831 |
+
)
|
| 832 |
+
elif np.isnan(maxcv_val):
|
| 833 |
+
include_point = all(
|
| 834 |
+
np.isnan(maxcv_filter)
|
| 835 |
+
and fun_val < fun_filter
|
| 836 |
+
or np.isnan(fun_filter)
|
| 837 |
+
for fun_filter, maxcv_filter in zip(
|
| 838 |
+
self._fun_filter,
|
| 839 |
+
self._maxcv_filter,
|
| 840 |
+
)
|
| 841 |
+
)
|
| 842 |
+
else:
|
| 843 |
+
include_point = all(
|
| 844 |
+
fun_val < fun_filter or maxcv_val < maxcv_filter
|
| 845 |
+
for fun_filter, maxcv_filter in zip(
|
| 846 |
+
self._fun_filter,
|
| 847 |
+
self._maxcv_filter,
|
| 848 |
+
)
|
| 849 |
+
)
|
| 850 |
+
if include_point:
|
| 851 |
+
self._fun_filter.append(fun_val)
|
| 852 |
+
self._maxcv_filter.append(maxcv_val)
|
| 853 |
+
self._x_filter.append(x)
|
| 854 |
+
|
| 855 |
+
# Remove the points in the filter that are dominated by the new
|
| 856 |
+
# point. We must iterate in reverse order to avoid problems when
|
| 857 |
+
# removing elements from the list.
|
| 858 |
+
for k in range(len(self._fun_filter) - 2, -1, -1):
|
| 859 |
+
if np.isnan(fun_val):
|
| 860 |
+
remove_point = np.isnan(self._fun_filter[k])
|
| 861 |
+
elif np.isnan(maxcv_val):
|
| 862 |
+
remove_point = np.isnan(self._maxcv_filter[k])
|
| 863 |
+
else:
|
| 864 |
+
remove_point = (
|
| 865 |
+
np.isnan(self._fun_filter[k])
|
| 866 |
+
or np.isnan(self._maxcv_filter[k])
|
| 867 |
+
or fun_val <= self._fun_filter[k]
|
| 868 |
+
and maxcv_val <= self._maxcv_filter[k]
|
| 869 |
+
)
|
| 870 |
+
if remove_point:
|
| 871 |
+
self._fun_filter.pop(k)
|
| 872 |
+
self._maxcv_filter.pop(k)
|
| 873 |
+
self._x_filter.pop(k)
|
| 874 |
+
|
| 875 |
+
# Keep only the most recent points in the filter.
|
| 876 |
+
if len(self._fun_filter) > self._filter_size:
|
| 877 |
+
self._fun_filter.pop(0)
|
| 878 |
+
self._maxcv_filter.pop(0)
|
| 879 |
+
self._x_filter.pop(0)
|
| 880 |
+
|
| 881 |
+
# Evaluate the callback function after updating the filter to ensure
|
| 882 |
+
# that the current point can be returned by the method.
|
| 883 |
+
if self._callback is not None:
|
| 884 |
+
sig = signature(self._callback)
|
| 885 |
+
try:
|
| 886 |
+
x_best, fun_best, _ = self.best_eval(penalty)
|
| 887 |
+
x_best = self.build_x(x_best)
|
| 888 |
+
if set(sig.parameters) == {"intermediate_result"}:
|
| 889 |
+
intermediate_result = OptimizeResult(
|
| 890 |
+
x=x_best,
|
| 891 |
+
fun=fun_best,
|
| 892 |
+
# maxcv=maxcv_best,
|
| 893 |
+
)
|
| 894 |
+
self._callback(intermediate_result=intermediate_result)
|
| 895 |
+
else:
|
| 896 |
+
self._callback(x_best)
|
| 897 |
+
except StopIteration as exc:
|
| 898 |
+
raise CallbackSuccess from exc
|
| 899 |
+
|
| 900 |
+
# Apply the extreme barriers and return.
|
| 901 |
+
if np.isnan(fun_val):
|
| 902 |
+
fun_val = BARRIER
|
| 903 |
+
cub_val[np.isnan(cub_val)] = BARRIER
|
| 904 |
+
ceq_val[np.isnan(ceq_val)] = BARRIER
|
| 905 |
+
fun_val = max(min(fun_val, BARRIER), -BARRIER)
|
| 906 |
+
cub_val = np.maximum(np.minimum(cub_val, BARRIER), -BARRIER)
|
| 907 |
+
ceq_val = np.maximum(np.minimum(ceq_val, BARRIER), -BARRIER)
|
| 908 |
+
return fun_val, cub_val, ceq_val
|
| 909 |
+
|
| 910 |
+
@property
|
| 911 |
+
def n(self):
|
| 912 |
+
"""
|
| 913 |
+
Number of variables.
|
| 914 |
+
|
| 915 |
+
Returns
|
| 916 |
+
-------
|
| 917 |
+
int
|
| 918 |
+
Number of variables.
|
| 919 |
+
"""
|
| 920 |
+
return self.x0.size
|
| 921 |
+
|
| 922 |
+
@property
|
| 923 |
+
def n_orig(self):
|
| 924 |
+
"""
|
| 925 |
+
Number of variables in the original problem (with fixed variables).
|
| 926 |
+
|
| 927 |
+
Returns
|
| 928 |
+
-------
|
| 929 |
+
int
|
| 930 |
+
Number of variables in the original problem (with fixed variables).
|
| 931 |
+
"""
|
| 932 |
+
return self._fixed_idx.size
|
| 933 |
+
|
| 934 |
+
@property
|
| 935 |
+
def x0(self):
|
| 936 |
+
"""
|
| 937 |
+
Initial guess.
|
| 938 |
+
|
| 939 |
+
Returns
|
| 940 |
+
-------
|
| 941 |
+
`numpy.ndarray`, shape (n,)
|
| 942 |
+
Initial guess.
|
| 943 |
+
"""
|
| 944 |
+
return self._x0
|
| 945 |
+
|
| 946 |
+
@property
|
| 947 |
+
def n_eval(self):
|
| 948 |
+
"""
|
| 949 |
+
Number of function evaluations.
|
| 950 |
+
|
| 951 |
+
Returns
|
| 952 |
+
-------
|
| 953 |
+
int
|
| 954 |
+
Number of function evaluations.
|
| 955 |
+
"""
|
| 956 |
+
return self._obj.n_eval
|
| 957 |
+
|
| 958 |
+
@property
|
| 959 |
+
def fun_name(self):
|
| 960 |
+
"""
|
| 961 |
+
Name of the objective function.
|
| 962 |
+
|
| 963 |
+
Returns
|
| 964 |
+
-------
|
| 965 |
+
str
|
| 966 |
+
Name of the objective function.
|
| 967 |
+
"""
|
| 968 |
+
return self._obj.name
|
| 969 |
+
|
| 970 |
+
@property
|
| 971 |
+
def bounds(self):
|
| 972 |
+
"""
|
| 973 |
+
Bound constraints.
|
| 974 |
+
|
| 975 |
+
Returns
|
| 976 |
+
-------
|
| 977 |
+
BoundConstraints
|
| 978 |
+
Bound constraints.
|
| 979 |
+
"""
|
| 980 |
+
return self._bounds
|
| 981 |
+
|
| 982 |
+
@property
|
| 983 |
+
def linear(self):
|
| 984 |
+
"""
|
| 985 |
+
Linear constraints.
|
| 986 |
+
|
| 987 |
+
Returns
|
| 988 |
+
-------
|
| 989 |
+
LinearConstraints
|
| 990 |
+
Linear constraints.
|
| 991 |
+
"""
|
| 992 |
+
return self._linear
|
| 993 |
+
|
| 994 |
+
@property
|
| 995 |
+
def m_bounds(self):
|
| 996 |
+
"""
|
| 997 |
+
Number of bound constraints.
|
| 998 |
+
|
| 999 |
+
Returns
|
| 1000 |
+
-------
|
| 1001 |
+
int
|
| 1002 |
+
Number of bound constraints.
|
| 1003 |
+
"""
|
| 1004 |
+
return self.bounds.m
|
| 1005 |
+
|
| 1006 |
+
@property
|
| 1007 |
+
def m_linear_ub(self):
|
| 1008 |
+
"""
|
| 1009 |
+
Number of linear inequality constraints.
|
| 1010 |
+
|
| 1011 |
+
Returns
|
| 1012 |
+
-------
|
| 1013 |
+
int
|
| 1014 |
+
Number of linear inequality constraints.
|
| 1015 |
+
"""
|
| 1016 |
+
return self.linear.m_ub
|
| 1017 |
+
|
| 1018 |
+
@property
|
| 1019 |
+
def m_linear_eq(self):
|
| 1020 |
+
"""
|
| 1021 |
+
Number of linear equality constraints.
|
| 1022 |
+
|
| 1023 |
+
Returns
|
| 1024 |
+
-------
|
| 1025 |
+
int
|
| 1026 |
+
Number of linear equality constraints.
|
| 1027 |
+
"""
|
| 1028 |
+
return self.linear.m_eq
|
| 1029 |
+
|
| 1030 |
+
@property
|
| 1031 |
+
def m_nonlinear_ub(self):
|
| 1032 |
+
"""
|
| 1033 |
+
Number of nonlinear inequality constraints.
|
| 1034 |
+
|
| 1035 |
+
Returns
|
| 1036 |
+
-------
|
| 1037 |
+
int
|
| 1038 |
+
Number of nonlinear inequality constraints.
|
| 1039 |
+
|
| 1040 |
+
Raises
|
| 1041 |
+
------
|
| 1042 |
+
ValueError
|
| 1043 |
+
If the number of nonlinear inequality constraints is not known.
|
| 1044 |
+
"""
|
| 1045 |
+
return self._nonlinear.m_ub
|
| 1046 |
+
|
| 1047 |
+
@property
|
| 1048 |
+
def m_nonlinear_eq(self):
|
| 1049 |
+
"""
|
| 1050 |
+
Number of nonlinear equality constraints.
|
| 1051 |
+
|
| 1052 |
+
Returns
|
| 1053 |
+
-------
|
| 1054 |
+
int
|
| 1055 |
+
Number of nonlinear equality constraints.
|
| 1056 |
+
|
| 1057 |
+
Raises
|
| 1058 |
+
------
|
| 1059 |
+
ValueError
|
| 1060 |
+
If the number of nonlinear equality constraints is not known.
|
| 1061 |
+
"""
|
| 1062 |
+
return self._nonlinear.m_eq
|
| 1063 |
+
|
| 1064 |
+
@property
|
| 1065 |
+
def fun_history(self):
|
| 1066 |
+
"""
|
| 1067 |
+
History of objective function evaluations.
|
| 1068 |
+
|
| 1069 |
+
Returns
|
| 1070 |
+
-------
|
| 1071 |
+
`numpy.ndarray`, shape (n_eval,)
|
| 1072 |
+
History of objective function evaluations.
|
| 1073 |
+
"""
|
| 1074 |
+
return np.array(self._fun_history, dtype=float)
|
| 1075 |
+
|
| 1076 |
+
@property
|
| 1077 |
+
def maxcv_history(self):
|
| 1078 |
+
"""
|
| 1079 |
+
History of maximum constraint violations.
|
| 1080 |
+
|
| 1081 |
+
Returns
|
| 1082 |
+
-------
|
| 1083 |
+
`numpy.ndarray`, shape (n_eval,)
|
| 1084 |
+
History of maximum constraint violations.
|
| 1085 |
+
"""
|
| 1086 |
+
return np.array(self._maxcv_history, dtype=float)
|
| 1087 |
+
|
| 1088 |
+
@property
|
| 1089 |
+
def type(self):
|
| 1090 |
+
"""
|
| 1091 |
+
Type of the problem.
|
| 1092 |
+
|
| 1093 |
+
The problem can be either 'unconstrained', 'bound-constrained',
|
| 1094 |
+
'linearly constrained', or 'nonlinearly constrained'.
|
| 1095 |
+
|
| 1096 |
+
Returns
|
| 1097 |
+
-------
|
| 1098 |
+
str
|
| 1099 |
+
Type of the problem.
|
| 1100 |
+
"""
|
| 1101 |
+
try:
|
| 1102 |
+
if self.m_nonlinear_ub > 0 or self.m_nonlinear_eq > 0:
|
| 1103 |
+
return "nonlinearly constrained"
|
| 1104 |
+
elif self.m_linear_ub > 0 or self.m_linear_eq > 0:
|
| 1105 |
+
return "linearly constrained"
|
| 1106 |
+
elif self.m_bounds > 0:
|
| 1107 |
+
return "bound-constrained"
|
| 1108 |
+
else:
|
| 1109 |
+
return "unconstrained"
|
| 1110 |
+
except ValueError:
|
| 1111 |
+
# The number of nonlinear constraints is not known. It may be zero
|
| 1112 |
+
# if the user provided a nonlinear inequality and/or equality
|
| 1113 |
+
# constraint function that returns an empty array. However, as this
|
| 1114 |
+
# is not known before the first call to the function, we assume
|
| 1115 |
+
# that the problem is nonlinearly constrained.
|
| 1116 |
+
return "nonlinearly constrained"
|
| 1117 |
+
|
| 1118 |
+
@property
|
| 1119 |
+
def is_feasibility(self):
|
| 1120 |
+
"""
|
| 1121 |
+
Whether the problem is a feasibility problem.
|
| 1122 |
+
|
| 1123 |
+
Returns
|
| 1124 |
+
-------
|
| 1125 |
+
bool
|
| 1126 |
+
Whether the problem is a feasibility problem.
|
| 1127 |
+
"""
|
| 1128 |
+
return self.fun_name == ""
|
| 1129 |
+
|
| 1130 |
+
def build_x(self, x):
|
| 1131 |
+
"""
|
| 1132 |
+
Build the full vector of variables from the reduced vector.
|
| 1133 |
+
|
| 1134 |
+
Parameters
|
| 1135 |
+
----------
|
| 1136 |
+
x : array_like, shape (n,)
|
| 1137 |
+
Reduced vector of variables.
|
| 1138 |
+
|
| 1139 |
+
Returns
|
| 1140 |
+
-------
|
| 1141 |
+
`numpy.ndarray`, shape (n_orig,)
|
| 1142 |
+
Full vector of variables.
|
| 1143 |
+
"""
|
| 1144 |
+
x_full = np.empty(self.n_orig)
|
| 1145 |
+
x_full[self._fixed_idx] = self._fixed_val
|
| 1146 |
+
x_full[~self._fixed_idx] = (x * self._scaling_factor
|
| 1147 |
+
+ self._scaling_shift)
|
| 1148 |
+
return self._orig_bounds.project(x_full)
|
| 1149 |
+
|
| 1150 |
+
def maxcv(self, x, cub_val=None, ceq_val=None):
|
| 1151 |
+
"""
|
| 1152 |
+
Evaluate the maximum constraint violation.
|
| 1153 |
+
|
| 1154 |
+
Parameters
|
| 1155 |
+
----------
|
| 1156 |
+
x : array_like, shape (n,)
|
| 1157 |
+
Point at which the maximum constraint violation is evaluated.
|
| 1158 |
+
cub_val : array_like, shape (m_nonlinear_ub,), optional
|
| 1159 |
+
Values of the nonlinear inequality constraints. If not provided,
|
| 1160 |
+
the nonlinear inequality constraints are evaluated at `x`.
|
| 1161 |
+
ceq_val : array_like, shape (m_nonlinear_eq,), optional
|
| 1162 |
+
Values of the nonlinear equality constraints. If not provided,
|
| 1163 |
+
the nonlinear equality constraints are evaluated at `x`.
|
| 1164 |
+
|
| 1165 |
+
Returns
|
| 1166 |
+
-------
|
| 1167 |
+
float
|
| 1168 |
+
Maximum constraint violation at `x`.
|
| 1169 |
+
"""
|
| 1170 |
+
violation = self.violation(x, cub_val=cub_val, ceq_val=ceq_val)
|
| 1171 |
+
if np.count_nonzero(violation):
|
| 1172 |
+
return np.max(violation, initial=0.0)
|
| 1173 |
+
else:
|
| 1174 |
+
return 0.0
|
| 1175 |
+
|
| 1176 |
+
def violation(self, x, cub_val=None, ceq_val=None):
|
| 1177 |
+
violation = []
|
| 1178 |
+
if not self.bounds.is_feasible:
|
| 1179 |
+
b = self.bounds.violation(x)
|
| 1180 |
+
violation.append(b)
|
| 1181 |
+
|
| 1182 |
+
if len(self.linear.pcs):
|
| 1183 |
+
lc = self.linear.violation(x)
|
| 1184 |
+
violation.append(lc)
|
| 1185 |
+
if len(self._nonlinear.pcs):
|
| 1186 |
+
nlc = self._nonlinear.violation(x, cub_val, ceq_val)
|
| 1187 |
+
violation.append(nlc)
|
| 1188 |
+
|
| 1189 |
+
if len(violation):
|
| 1190 |
+
return np.concatenate(violation)
|
| 1191 |
+
|
| 1192 |
+
def best_eval(self, penalty):
|
| 1193 |
+
"""
|
| 1194 |
+
Return the best point in the filter and the corresponding objective and
|
| 1195 |
+
nonlinear constraint function evaluations.
|
| 1196 |
+
|
| 1197 |
+
Parameters
|
| 1198 |
+
----------
|
| 1199 |
+
penalty : float
|
| 1200 |
+
Penalty parameter
|
| 1201 |
+
|
| 1202 |
+
Returns
|
| 1203 |
+
-------
|
| 1204 |
+
`numpy.ndarray`, shape (n,)
|
| 1205 |
+
Best point.
|
| 1206 |
+
float
|
| 1207 |
+
Corresponding objective function value.
|
| 1208 |
+
float
|
| 1209 |
+
Corresponding maximum constraint violation.
|
| 1210 |
+
"""
|
| 1211 |
+
# If the filter is empty, i.e., if no function evaluation has been
|
| 1212 |
+
# performed, we evaluate the objective and nonlinear constraint
|
| 1213 |
+
# functions at the initial guess.
|
| 1214 |
+
if len(self._fun_filter) == 0:
|
| 1215 |
+
self(self.x0)
|
| 1216 |
+
|
| 1217 |
+
# Find the best point in the filter.
|
| 1218 |
+
fun_filter = np.array(self._fun_filter)
|
| 1219 |
+
maxcv_filter = np.array(self._maxcv_filter)
|
| 1220 |
+
x_filter = np.array(self._x_filter)
|
| 1221 |
+
finite_idx = np.isfinite(maxcv_filter)
|
| 1222 |
+
if np.any(finite_idx):
|
| 1223 |
+
# At least one point has a finite maximum constraint violation.
|
| 1224 |
+
feasible_idx = maxcv_filter <= self._feasibility_tol
|
| 1225 |
+
if np.any(feasible_idx) and not np.all(
|
| 1226 |
+
np.isnan(fun_filter[feasible_idx])
|
| 1227 |
+
):
|
| 1228 |
+
# At least one point is feasible and has a well-defined
|
| 1229 |
+
# objective function value. We select the point with the least
|
| 1230 |
+
# objective function value. If there is a tie, we select the
|
| 1231 |
+
# point with the least maximum constraint violation. If there
|
| 1232 |
+
# is still a tie, we select the most recent point.
|
| 1233 |
+
fun_min_idx = feasible_idx & (
|
| 1234 |
+
fun_filter <= np.nanmin(fun_filter[feasible_idx])
|
| 1235 |
+
)
|
| 1236 |
+
if np.count_nonzero(fun_min_idx) > 1:
|
| 1237 |
+
fun_min_idx &= maxcv_filter <= np.min(
|
| 1238 |
+
maxcv_filter[fun_min_idx]
|
| 1239 |
+
)
|
| 1240 |
+
i = np.flatnonzero(fun_min_idx)[-1]
|
| 1241 |
+
elif np.any(feasible_idx):
|
| 1242 |
+
# At least one point is feasible but no feasible point has a
|
| 1243 |
+
# well-defined objective function value. We select the most
|
| 1244 |
+
# recent feasible point.
|
| 1245 |
+
i = np.flatnonzero(feasible_idx)[-1]
|
| 1246 |
+
else:
|
| 1247 |
+
# No point is feasible. We first compute the merit function
|
| 1248 |
+
# value for each point.
|
| 1249 |
+
merit_filter = np.full_like(fun_filter, np.nan)
|
| 1250 |
+
merit_filter[finite_idx] = (
|
| 1251 |
+
fun_filter[finite_idx] + penalty * maxcv_filter[finite_idx]
|
| 1252 |
+
)
|
| 1253 |
+
if np.all(np.isnan(merit_filter)):
|
| 1254 |
+
# No point has a well-defined merit function value. In
|
| 1255 |
+
# other words, among the points with a well-defined maximum
|
| 1256 |
+
# constraint violation, none has a well-defined objective
|
| 1257 |
+
# function value. We select the point with the least
|
| 1258 |
+
# maximum constraint violation. If there is a tie, we
|
| 1259 |
+
# select the most recent point.
|
| 1260 |
+
min_maxcv_idx = maxcv_filter <= np.nanmin(maxcv_filter)
|
| 1261 |
+
i = np.flatnonzero(min_maxcv_idx)[-1]
|
| 1262 |
+
else:
|
| 1263 |
+
# At least one point has a well-defined merit function
|
| 1264 |
+
# value. We select the point with the least merit function
|
| 1265 |
+
# value. If there is a tie, we select the point with the
|
| 1266 |
+
# least maximum constraint violation. If there is still a
|
| 1267 |
+
# tie, we select the point with the least objective
|
| 1268 |
+
# function value. If there is still a tie, we select the
|
| 1269 |
+
# most recent point.
|
| 1270 |
+
merit_min_idx = merit_filter <= np.nanmin(merit_filter)
|
| 1271 |
+
if np.count_nonzero(merit_min_idx) > 1:
|
| 1272 |
+
merit_min_idx &= maxcv_filter <= np.min(
|
| 1273 |
+
maxcv_filter[merit_min_idx]
|
| 1274 |
+
)
|
| 1275 |
+
|
| 1276 |
+
if np.count_nonzero(merit_min_idx) > 1:
|
| 1277 |
+
merit_min_idx &= fun_filter <= np.min(
|
| 1278 |
+
fun_filter[merit_min_idx]
|
| 1279 |
+
)
|
| 1280 |
+
i = np.flatnonzero(merit_min_idx)[-1]
|
| 1281 |
+
elif not np.all(np.isnan(fun_filter)):
|
| 1282 |
+
# No maximum constraint violation is well-defined but at least one
|
| 1283 |
+
# point has a well-defined objective function value. We select the
|
| 1284 |
+
# point with the least objective function value. If there is a tie,
|
| 1285 |
+
# we select the most recent point.
|
| 1286 |
+
fun_min_idx = fun_filter <= np.nanmin(fun_filter)
|
| 1287 |
+
i = np.flatnonzero(fun_min_idx)[-1]
|
| 1288 |
+
else:
|
| 1289 |
+
# No point has a well-defined maximum constraint violation or
|
| 1290 |
+
# objective function value. We select the most recent point.
|
| 1291 |
+
i = len(fun_filter) - 1
|
| 1292 |
+
return (
|
| 1293 |
+
self.bounds.project(x_filter[i, :]),
|
| 1294 |
+
fun_filter[i],
|
| 1295 |
+
maxcv_filter[i],
|
| 1296 |
+
)
|
python_embeded/Lib/site-packages/scipy/_lib/cobyqa/settings.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from enum import Enum
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Exit status.
|
| 8 |
+
class ExitStatus(Enum):
|
| 9 |
+
"""
|
| 10 |
+
Exit statuses.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
RADIUS_SUCCESS = 0
|
| 14 |
+
TARGET_SUCCESS = 1
|
| 15 |
+
FIXED_SUCCESS = 2
|
| 16 |
+
CALLBACK_SUCCESS = 3
|
| 17 |
+
FEASIBLE_SUCCESS = 4
|
| 18 |
+
MAX_EVAL_WARNING = 5
|
| 19 |
+
MAX_ITER_WARNING = 6
|
| 20 |
+
INFEASIBLE_ERROR = -1
|
| 21 |
+
LINALG_ERROR = -2
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Options(str, Enum):
|
| 25 |
+
"""
|
| 26 |
+
Options.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
DEBUG = "debug"
|
| 30 |
+
FEASIBILITY_TOL = "feasibility_tol"
|
| 31 |
+
FILTER_SIZE = "filter_size"
|
| 32 |
+
HISTORY_SIZE = "history_size"
|
| 33 |
+
MAX_EVAL = "maxfev"
|
| 34 |
+
MAX_ITER = "maxiter"
|
| 35 |
+
NPT = "nb_points"
|
| 36 |
+
RHOBEG = "radius_init"
|
| 37 |
+
RHOEND = "radius_final"
|
| 38 |
+
SCALE = "scale"
|
| 39 |
+
STORE_HISTORY = "store_history"
|
| 40 |
+
TARGET = "target"
|
| 41 |
+
VERBOSE = "disp"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Constants(str, Enum):
|
| 45 |
+
"""
|
| 46 |
+
Constants.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
DECREASE_RADIUS_FACTOR = "decrease_radius_factor"
|
| 50 |
+
INCREASE_RADIUS_FACTOR = "increase_radius_factor"
|
| 51 |
+
INCREASE_RADIUS_THRESHOLD = "increase_radius_threshold"
|
| 52 |
+
DECREASE_RADIUS_THRESHOLD = "decrease_radius_threshold"
|
| 53 |
+
DECREASE_RESOLUTION_FACTOR = "decrease_resolution_factor"
|
| 54 |
+
LARGE_RESOLUTION_THRESHOLD = "large_resolution_threshold"
|
| 55 |
+
MODERATE_RESOLUTION_THRESHOLD = "moderate_resolution_threshold"
|
| 56 |
+
LOW_RATIO = "low_ratio"
|
| 57 |
+
HIGH_RATIO = "high_ratio"
|
| 58 |
+
VERY_LOW_RATIO = "very_low_ratio"
|
| 59 |
+
PENALTY_INCREASE_THRESHOLD = "penalty_increase_threshold"
|
| 60 |
+
PENALTY_INCREASE_FACTOR = "penalty_increase_factor"
|
| 61 |
+
SHORT_STEP_THRESHOLD = "short_step_threshold"
|
| 62 |
+
LOW_RADIUS_FACTOR = "low_radius_factor"
|
| 63 |
+
BYRD_OMOJOKUN_FACTOR = "byrd_omojokun_factor"
|
| 64 |
+
THRESHOLD_RATIO_CONSTRAINTS = "threshold_ratio_constraints"
|
| 65 |
+
LARGE_SHIFT_FACTOR = "large_shift_factor"
|
| 66 |
+
LARGE_GRADIENT_FACTOR = "large_gradient_factor"
|
| 67 |
+
RESOLUTION_FACTOR = "resolution_factor"
|
| 68 |
+
IMPROVE_TCG = "improve_tcg"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# Default options.
|
| 72 |
+
DEFAULT_OPTIONS = {
|
| 73 |
+
Options.DEBUG.value: False,
|
| 74 |
+
Options.FEASIBILITY_TOL.value: np.sqrt(np.finfo(float).eps),
|
| 75 |
+
Options.FILTER_SIZE.value: sys.maxsize,
|
| 76 |
+
Options.HISTORY_SIZE.value: sys.maxsize,
|
| 77 |
+
Options.MAX_EVAL.value: lambda n: 500 * n,
|
| 78 |
+
Options.MAX_ITER.value: lambda n: 1000 * n,
|
| 79 |
+
Options.NPT.value: lambda n: 2 * n + 1,
|
| 80 |
+
Options.RHOBEG.value: 1.0,
|
| 81 |
+
Options.RHOEND.value: 1e-6,
|
| 82 |
+
Options.SCALE.value: False,
|
| 83 |
+
Options.STORE_HISTORY.value: False,
|
| 84 |
+
Options.TARGET.value: -np.inf,
|
| 85 |
+
Options.VERBOSE.value: False,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# Default constants.
|
| 89 |
+
DEFAULT_CONSTANTS = {
|
| 90 |
+
Constants.DECREASE_RADIUS_FACTOR.value: 0.5,
|
| 91 |
+
Constants.INCREASE_RADIUS_FACTOR.value: np.sqrt(2.0),
|
| 92 |
+
Constants.INCREASE_RADIUS_THRESHOLD.value: 2.0,
|
| 93 |
+
Constants.DECREASE_RADIUS_THRESHOLD.value: 1.4,
|
| 94 |
+
Constants.DECREASE_RESOLUTION_FACTOR.value: 0.1,
|
| 95 |
+
Constants.LARGE_RESOLUTION_THRESHOLD.value: 250.0,
|
| 96 |
+
Constants.MODERATE_RESOLUTION_THRESHOLD.value: 16.0,
|
| 97 |
+
Constants.LOW_RATIO.value: 0.1,
|
| 98 |
+
Constants.HIGH_RATIO.value: 0.7,
|
| 99 |
+
Constants.VERY_LOW_RATIO.value: 0.01,
|
| 100 |
+
Constants.PENALTY_INCREASE_THRESHOLD.value: 1.5,
|
| 101 |
+
Constants.PENALTY_INCREASE_FACTOR.value: 2.0,
|
| 102 |
+
Constants.SHORT_STEP_THRESHOLD.value: 0.5,
|
| 103 |
+
Constants.LOW_RADIUS_FACTOR.value: 0.1,
|
| 104 |
+
Constants.BYRD_OMOJOKUN_FACTOR.value: 0.8,
|
| 105 |
+
Constants.THRESHOLD_RATIO_CONSTRAINTS.value: 2.0,
|
| 106 |
+
Constants.LARGE_SHIFT_FACTOR.value: 10.0,
|
| 107 |
+
Constants.LARGE_GRADIENT_FACTOR.value: 10.0,
|
| 108 |
+
Constants.RESOLUTION_FACTOR.value: 2.0,
|
| 109 |
+
Constants.IMPROVE_TCG.value: True,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
# Printing options.
|
| 113 |
+
PRINT_OPTIONS = {
|
| 114 |
+
"threshold": 6,
|
| 115 |
+
"edgeitems": 2,
|
| 116 |
+
"linewidth": sys.maxsize,
|
| 117 |
+
"formatter": {
|
| 118 |
+
"float_kind": lambda x: np.format_float_scientific(
|
| 119 |
+
x,
|
| 120 |
+
precision=3,
|
| 121 |
+
unique=False,
|
| 122 |
+
pad_left=2,
|
| 123 |
+
)
|
| 124 |
+
},
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
# Constants.
|
| 128 |
+
BARRIER = 2.0 ** min(
|
| 129 |
+
100,
|
| 130 |
+
np.finfo(float).maxexp // 2,
|
| 131 |
+
-np.finfo(float).minexp // 2,
|
| 132 |
+
)
|
python_embeded/Lib/site-packages/scipy/_lib/decorator.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ######################### LICENSE ############################ #
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2005-2015, Michele Simionato
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions are
|
| 8 |
+
# met:
|
| 9 |
+
|
| 10 |
+
# Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# Redistributions in bytecode form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 20 |
+
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 21 |
+
# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
| 24 |
+
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 25 |
+
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
| 26 |
+
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
|
| 27 |
+
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
|
| 28 |
+
# DAMAGE.
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
Decorator module, see https://pypi.python.org/pypi/decorator
|
| 32 |
+
for the documentation.
|
| 33 |
+
"""
|
| 34 |
+
import re
|
| 35 |
+
import sys
|
| 36 |
+
import inspect
|
| 37 |
+
import operator
|
| 38 |
+
import itertools
|
| 39 |
+
import collections
|
| 40 |
+
|
| 41 |
+
from inspect import getfullargspec
|
| 42 |
+
|
| 43 |
+
__version__ = '4.0.5'
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_init(cls):
|
| 47 |
+
return cls.__init__
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# getargspec has been deprecated in Python 3.5
|
| 51 |
+
ArgSpec = collections.namedtuple(
|
| 52 |
+
'ArgSpec', 'args varargs varkw defaults')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def getargspec(f):
|
| 56 |
+
"""A replacement for inspect.getargspec"""
|
| 57 |
+
spec = getfullargspec(f)
|
| 58 |
+
return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# basic functionality
|
| 65 |
+
class FunctionMaker:
|
| 66 |
+
"""
|
| 67 |
+
An object with the ability to create functions with a given signature.
|
| 68 |
+
It has attributes name, doc, module, signature, defaults, dict, and
|
| 69 |
+
methods update and make.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
# Atomic get-and-increment provided by the GIL
|
| 73 |
+
_compile_count = itertools.count()
|
| 74 |
+
|
| 75 |
+
def __init__(self, func=None, name=None, signature=None,
|
| 76 |
+
defaults=None, doc=None, module=None, funcdict=None):
|
| 77 |
+
self.shortsignature = signature
|
| 78 |
+
if func:
|
| 79 |
+
# func can be a class or a callable, but not an instance method
|
| 80 |
+
self.name = func.__name__
|
| 81 |
+
if self.name == '<lambda>': # small hack for lambda functions
|
| 82 |
+
self.name = '_lambda_'
|
| 83 |
+
self.doc = func.__doc__
|
| 84 |
+
self.module = func.__module__
|
| 85 |
+
if inspect.isfunction(func):
|
| 86 |
+
argspec = getfullargspec(func)
|
| 87 |
+
self.annotations = getattr(func, '__annotations__', {})
|
| 88 |
+
for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
|
| 89 |
+
'kwonlydefaults'):
|
| 90 |
+
setattr(self, a, getattr(argspec, a))
|
| 91 |
+
for i, arg in enumerate(self.args):
|
| 92 |
+
setattr(self, 'arg%d' % i, arg)
|
| 93 |
+
allargs = list(self.args)
|
| 94 |
+
allshortargs = list(self.args)
|
| 95 |
+
if self.varargs:
|
| 96 |
+
allargs.append('*' + self.varargs)
|
| 97 |
+
allshortargs.append('*' + self.varargs)
|
| 98 |
+
elif self.kwonlyargs:
|
| 99 |
+
allargs.append('*') # single star syntax
|
| 100 |
+
for a in self.kwonlyargs:
|
| 101 |
+
allargs.append(f'{a}=None')
|
| 102 |
+
allshortargs.append(f'{a}={a}')
|
| 103 |
+
if self.varkw:
|
| 104 |
+
allargs.append('**' + self.varkw)
|
| 105 |
+
allshortargs.append('**' + self.varkw)
|
| 106 |
+
self.signature = ', '.join(allargs)
|
| 107 |
+
self.shortsignature = ', '.join(allshortargs)
|
| 108 |
+
self.dict = func.__dict__.copy()
|
| 109 |
+
# func=None happens when decorating a caller
|
| 110 |
+
if name:
|
| 111 |
+
self.name = name
|
| 112 |
+
if signature is not None:
|
| 113 |
+
self.signature = signature
|
| 114 |
+
if defaults:
|
| 115 |
+
self.defaults = defaults
|
| 116 |
+
if doc:
|
| 117 |
+
self.doc = doc
|
| 118 |
+
if module:
|
| 119 |
+
self.module = module
|
| 120 |
+
if funcdict:
|
| 121 |
+
self.dict = funcdict
|
| 122 |
+
# check existence required attributes
|
| 123 |
+
assert hasattr(self, 'name')
|
| 124 |
+
if not hasattr(self, 'signature'):
|
| 125 |
+
raise TypeError(f'You are decorating a non-function: {func}')
|
| 126 |
+
|
| 127 |
+
def update(self, func, **kw):
|
| 128 |
+
"Update the signature of func with the data in self"
|
| 129 |
+
func.__name__ = self.name
|
| 130 |
+
func.__doc__ = getattr(self, 'doc', None)
|
| 131 |
+
func.__dict__ = getattr(self, 'dict', {})
|
| 132 |
+
func.__defaults__ = getattr(self, 'defaults', ())
|
| 133 |
+
func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
|
| 134 |
+
func.__annotations__ = getattr(self, 'annotations', None)
|
| 135 |
+
try:
|
| 136 |
+
frame = sys._getframe(3)
|
| 137 |
+
except AttributeError: # for IronPython and similar implementations
|
| 138 |
+
callermodule = '?'
|
| 139 |
+
else:
|
| 140 |
+
callermodule = frame.f_globals.get('__name__', '?')
|
| 141 |
+
func.__module__ = getattr(self, 'module', callermodule)
|
| 142 |
+
func.__dict__.update(kw)
|
| 143 |
+
|
| 144 |
+
def make(self, src_templ, evaldict=None, addsource=False, **attrs):
|
| 145 |
+
"Make a new function from a given template and update the signature"
|
| 146 |
+
src = src_templ % vars(self) # expand name and signature
|
| 147 |
+
evaldict = evaldict or {}
|
| 148 |
+
mo = DEF.match(src)
|
| 149 |
+
if mo is None:
|
| 150 |
+
raise SyntaxError(f'not a valid function template\n{src}')
|
| 151 |
+
name = mo.group(1) # extract the function name
|
| 152 |
+
names = set([name] + [arg.strip(' *') for arg in
|
| 153 |
+
self.shortsignature.split(',')])
|
| 154 |
+
for n in names:
|
| 155 |
+
if n in ('_func_', '_call_'):
|
| 156 |
+
raise NameError(f'{n} is overridden in\n{src}')
|
| 157 |
+
if not src.endswith('\n'): # add a newline just for safety
|
| 158 |
+
src += '\n' # this is needed in old versions of Python
|
| 159 |
+
|
| 160 |
+
# Ensure each generated function has a unique filename for profilers
|
| 161 |
+
# (such as cProfile) that depend on the tuple of (<filename>,
|
| 162 |
+
# <definition line>, <function name>) being unique.
|
| 163 |
+
filename = '<decorator-gen-%d>' % (next(self._compile_count),)
|
| 164 |
+
try:
|
| 165 |
+
code = compile(src, filename, 'single')
|
| 166 |
+
exec(code, evaldict)
|
| 167 |
+
except: # noqa: E722
|
| 168 |
+
print('Error in generated code:', file=sys.stderr)
|
| 169 |
+
print(src, file=sys.stderr)
|
| 170 |
+
raise
|
| 171 |
+
func = evaldict[name]
|
| 172 |
+
if addsource:
|
| 173 |
+
attrs['__source__'] = src
|
| 174 |
+
self.update(func, **attrs)
|
| 175 |
+
return func
|
| 176 |
+
|
| 177 |
+
@classmethod
|
| 178 |
+
def create(cls, obj, body, evaldict, defaults=None,
|
| 179 |
+
doc=None, module=None, addsource=True, **attrs):
|
| 180 |
+
"""
|
| 181 |
+
Create a function from the strings name, signature, and body.
|
| 182 |
+
evaldict is the evaluation dictionary. If addsource is true, an
|
| 183 |
+
attribute __source__ is added to the result. The attributes attrs
|
| 184 |
+
are added, if any.
|
| 185 |
+
"""
|
| 186 |
+
if isinstance(obj, str): # "name(signature)"
|
| 187 |
+
name, rest = obj.strip().split('(', 1)
|
| 188 |
+
signature = rest[:-1] # strip a right parens
|
| 189 |
+
func = None
|
| 190 |
+
else: # a function
|
| 191 |
+
name = None
|
| 192 |
+
signature = None
|
| 193 |
+
func = obj
|
| 194 |
+
self = cls(func, name, signature, defaults, doc, module)
|
| 195 |
+
ibody = '\n'.join(' ' + line for line in body.splitlines())
|
| 196 |
+
return self.make('def %(name)s(%(signature)s):\n' + ibody,
|
| 197 |
+
evaldict, addsource, **attrs)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def decorate(func, caller):
|
| 201 |
+
"""
|
| 202 |
+
decorate(func, caller) decorates a function using a caller.
|
| 203 |
+
"""
|
| 204 |
+
evaldict = func.__globals__.copy()
|
| 205 |
+
evaldict['_call_'] = caller
|
| 206 |
+
evaldict['_func_'] = func
|
| 207 |
+
fun = FunctionMaker.create(
|
| 208 |
+
func, "return _call_(_func_, %(shortsignature)s)",
|
| 209 |
+
evaldict, __wrapped__=func)
|
| 210 |
+
if hasattr(func, '__qualname__'):
|
| 211 |
+
fun.__qualname__ = func.__qualname__
|
| 212 |
+
return fun
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def decorator(caller, _func=None):
|
| 216 |
+
"""decorator(caller) converts a caller function into a decorator"""
|
| 217 |
+
if _func is not None: # return a decorated function
|
| 218 |
+
# this is obsolete behavior; you should use decorate instead
|
| 219 |
+
return decorate(_func, caller)
|
| 220 |
+
# else return a decorator function
|
| 221 |
+
if inspect.isclass(caller):
|
| 222 |
+
name = caller.__name__.lower()
|
| 223 |
+
callerfunc = get_init(caller)
|
| 224 |
+
doc = (f'decorator({caller.__name__}) converts functions/generators into '
|
| 225 |
+
f'factories of {caller.__name__} objects')
|
| 226 |
+
elif inspect.isfunction(caller):
|
| 227 |
+
if caller.__name__ == '<lambda>':
|
| 228 |
+
name = '_lambda_'
|
| 229 |
+
else:
|
| 230 |
+
name = caller.__name__
|
| 231 |
+
callerfunc = caller
|
| 232 |
+
doc = caller.__doc__
|
| 233 |
+
else: # assume caller is an object with a __call__ method
|
| 234 |
+
name = caller.__class__.__name__.lower()
|
| 235 |
+
callerfunc = caller.__call__.__func__
|
| 236 |
+
doc = caller.__call__.__doc__
|
| 237 |
+
evaldict = callerfunc.__globals__.copy()
|
| 238 |
+
evaldict['_call_'] = caller
|
| 239 |
+
evaldict['_decorate_'] = decorate
|
| 240 |
+
return FunctionMaker.create(
|
| 241 |
+
f'{name}(func)', 'return _decorate_(func, _call_)',
|
| 242 |
+
evaldict, doc=doc, module=caller.__module__,
|
| 243 |
+
__wrapped__=caller)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# ####################### contextmanager ####################### #
|
| 247 |
+
|
| 248 |
+
try: # Python >= 3.2
|
| 249 |
+
from contextlib import _GeneratorContextManager
|
| 250 |
+
except ImportError: # Python >= 2.5
|
| 251 |
+
from contextlib import GeneratorContextManager as _GeneratorContextManager
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class ContextManager(_GeneratorContextManager):
|
| 255 |
+
def __call__(self, func):
|
| 256 |
+
"""Context manager decorator"""
|
| 257 |
+
return FunctionMaker.create(
|
| 258 |
+
func, "with _self_: return _func_(%(shortsignature)s)",
|
| 259 |
+
dict(_self_=self, _func_=func), __wrapped__=func)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
init = getfullargspec(_GeneratorContextManager.__init__)
|
| 263 |
+
n_args = len(init.args)
|
| 264 |
+
if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7
|
| 265 |
+
def __init__(self, g, *a, **k):
|
| 266 |
+
return _GeneratorContextManager.__init__(self, g(*a, **k))
|
| 267 |
+
ContextManager.__init__ = __init__
|
| 268 |
+
elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4
|
| 269 |
+
pass
|
| 270 |
+
elif n_args == 4: # (self, gen, args, kwds) Python 3.5
|
| 271 |
+
def __init__(self, g, *a, **k):
|
| 272 |
+
return _GeneratorContextManager.__init__(self, g, a, k)
|
| 273 |
+
ContextManager.__init__ = __init__
|
| 274 |
+
|
| 275 |
+
contextmanager = decorator(ContextManager)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
# ############################ dispatch_on ############################ #
|
| 279 |
+
|
| 280 |
+
def append(a, vancestors):
|
| 281 |
+
"""
|
| 282 |
+
Append ``a`` to the list of the virtual ancestors, unless it is already
|
| 283 |
+
included.
|
| 284 |
+
"""
|
| 285 |
+
add = True
|
| 286 |
+
for j, va in enumerate(vancestors):
|
| 287 |
+
if issubclass(va, a):
|
| 288 |
+
add = False
|
| 289 |
+
break
|
| 290 |
+
if issubclass(a, va):
|
| 291 |
+
vancestors[j] = a
|
| 292 |
+
add = False
|
| 293 |
+
if add:
|
| 294 |
+
vancestors.append(a)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# inspired from simplegeneric by P.J. Eby and functools.singledispatch
|
| 298 |
+
def dispatch_on(*dispatch_args):
|
| 299 |
+
"""
|
| 300 |
+
Factory of decorators turning a function into a generic function
|
| 301 |
+
dispatching on the given arguments.
|
| 302 |
+
"""
|
| 303 |
+
assert dispatch_args, 'No dispatch args passed'
|
| 304 |
+
dispatch_str = f"({', '.join(dispatch_args)},)"
|
| 305 |
+
|
| 306 |
+
def check(arguments, wrong=operator.ne, msg=''):
|
| 307 |
+
"""Make sure one passes the expected number of arguments"""
|
| 308 |
+
if wrong(len(arguments), len(dispatch_args)):
|
| 309 |
+
raise TypeError(f'Expected {len(dispatch_args)} arguments, '
|
| 310 |
+
'got {len(arguments)}{msg}')
|
| 311 |
+
|
| 312 |
+
def gen_func_dec(func):
|
| 313 |
+
"""Decorator turning a function into a generic function"""
|
| 314 |
+
|
| 315 |
+
# first check the dispatch arguments
|
| 316 |
+
argset = set(getfullargspec(func).args)
|
| 317 |
+
if not set(dispatch_args) <= argset:
|
| 318 |
+
raise NameError(f'Unknown dispatch arguments {dispatch_str}')
|
| 319 |
+
|
| 320 |
+
typemap = {}
|
| 321 |
+
|
| 322 |
+
def vancestors(*types):
|
| 323 |
+
"""
|
| 324 |
+
Get a list of sets of virtual ancestors for the given types
|
| 325 |
+
"""
|
| 326 |
+
check(types)
|
| 327 |
+
ras = [[] for _ in range(len(dispatch_args))]
|
| 328 |
+
for types_ in typemap:
|
| 329 |
+
for t, type_, ra in zip(types, types_, ras):
|
| 330 |
+
if issubclass(t, type_) and type_ not in t.__mro__:
|
| 331 |
+
append(type_, ra)
|
| 332 |
+
return [set(ra) for ra in ras]
|
| 333 |
+
|
| 334 |
+
def ancestors(*types):
|
| 335 |
+
"""
|
| 336 |
+
Get a list of virtual MROs, one for each type
|
| 337 |
+
"""
|
| 338 |
+
check(types)
|
| 339 |
+
lists = []
|
| 340 |
+
for t, vas in zip(types, vancestors(*types)):
|
| 341 |
+
n_vas = len(vas)
|
| 342 |
+
if n_vas > 1:
|
| 343 |
+
raise RuntimeError(
|
| 344 |
+
f'Ambiguous dispatch for {t}: {vas}')
|
| 345 |
+
elif n_vas == 1:
|
| 346 |
+
va, = vas
|
| 347 |
+
mro = type('t', (t, va), {}).__mro__[1:]
|
| 348 |
+
else:
|
| 349 |
+
mro = t.__mro__
|
| 350 |
+
lists.append(mro[:-1]) # discard t and object
|
| 351 |
+
return lists
|
| 352 |
+
|
| 353 |
+
def register(*types):
|
| 354 |
+
"""
|
| 355 |
+
Decorator to register an implementation for the given types
|
| 356 |
+
"""
|
| 357 |
+
check(types)
|
| 358 |
+
|
| 359 |
+
def dec(f):
|
| 360 |
+
check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
|
| 361 |
+
typemap[types] = f
|
| 362 |
+
return f
|
| 363 |
+
return dec
|
| 364 |
+
|
| 365 |
+
def dispatch_info(*types):
|
| 366 |
+
"""
|
| 367 |
+
An utility to introspect the dispatch algorithm
|
| 368 |
+
"""
|
| 369 |
+
check(types)
|
| 370 |
+
lst = [tuple(a.__name__ for a in anc)
|
| 371 |
+
for anc in itertools.product(*ancestors(*types))]
|
| 372 |
+
return lst
|
| 373 |
+
|
| 374 |
+
def _dispatch(dispatch_args, *args, **kw):
|
| 375 |
+
types = tuple(type(arg) for arg in dispatch_args)
|
| 376 |
+
try: # fast path
|
| 377 |
+
f = typemap[types]
|
| 378 |
+
except KeyError:
|
| 379 |
+
pass
|
| 380 |
+
else:
|
| 381 |
+
return f(*args, **kw)
|
| 382 |
+
combinations = itertools.product(*ancestors(*types))
|
| 383 |
+
next(combinations) # the first one has been already tried
|
| 384 |
+
for types_ in combinations:
|
| 385 |
+
f = typemap.get(types_)
|
| 386 |
+
if f is not None:
|
| 387 |
+
return f(*args, **kw)
|
| 388 |
+
|
| 389 |
+
# else call the default implementation
|
| 390 |
+
return func(*args, **kw)
|
| 391 |
+
|
| 392 |
+
return FunctionMaker.create(
|
| 393 |
+
func, f'return _f_({dispatch_str}, %%(shortsignature)s)',
|
| 394 |
+
dict(_f_=_dispatch), register=register, default=func,
|
| 395 |
+
typemap=typemap, vancestors=vancestors, ancestors=ancestors,
|
| 396 |
+
dispatch_info=dispatch_info, __wrapped__=func)
|
| 397 |
+
|
| 398 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from inspect import Parameter, signature
|
| 2 |
+
import functools
|
| 3 |
+
import warnings
|
| 4 |
+
from importlib import import_module
|
| 5 |
+
from scipy._lib._docscrape import FunctionDoc
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = ["_deprecated"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Object to use as default value for arguments to be deprecated. This should
|
| 12 |
+
# be used over 'None' as the user could parse 'None' as a positional argument
|
| 13 |
+
_NoValue = object()
|
| 14 |
+
|
| 15 |
+
def _sub_module_deprecation(*, sub_package, module, private_modules, all,
|
| 16 |
+
attribute, correct_module=None, dep_version="1.16.0"):
|
| 17 |
+
"""Helper function for deprecating modules that are public but were
|
| 18 |
+
intended to be private.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
sub_package : str
|
| 23 |
+
Subpackage the module belongs to eg. stats
|
| 24 |
+
module : str
|
| 25 |
+
Public but intended private module to deprecate
|
| 26 |
+
private_modules : list
|
| 27 |
+
Private replacement(s) for `module`; should contain the
|
| 28 |
+
content of ``all``, possibly spread over several modules.
|
| 29 |
+
all : list
|
| 30 |
+
``__all__`` belonging to `module`
|
| 31 |
+
attribute : str
|
| 32 |
+
The attribute in `module` being accessed
|
| 33 |
+
correct_module : str, optional
|
| 34 |
+
Module in `sub_package` that `attribute` should be imported from.
|
| 35 |
+
Default is that `attribute` should be imported from ``scipy.sub_package``.
|
| 36 |
+
dep_version : str, optional
|
| 37 |
+
Version in which deprecated attributes will be removed.
|
| 38 |
+
"""
|
| 39 |
+
if correct_module is not None:
|
| 40 |
+
correct_import = f"scipy.{sub_package}.{correct_module}"
|
| 41 |
+
else:
|
| 42 |
+
correct_import = f"scipy.{sub_package}"
|
| 43 |
+
|
| 44 |
+
if attribute not in all:
|
| 45 |
+
raise AttributeError(
|
| 46 |
+
f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
|
| 47 |
+
f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
|
| 48 |
+
f"and will be removed in SciPy 2.0.0."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
attr = getattr(import_module(correct_import), attribute, None)
|
| 52 |
+
|
| 53 |
+
if attr is not None:
|
| 54 |
+
message = (
|
| 55 |
+
f"Please import `{attribute}` from the `{correct_import}` namespace; "
|
| 56 |
+
f"the `scipy.{sub_package}.{module}` namespace is deprecated "
|
| 57 |
+
f"and will be removed in SciPy 2.0.0."
|
| 58 |
+
)
|
| 59 |
+
else:
|
| 60 |
+
message = (
|
| 61 |
+
f"`scipy.{sub_package}.{module}.{attribute}` is deprecated along with "
|
| 62 |
+
f"the `scipy.{sub_package}.{module}` namespace. "
|
| 63 |
+
f"`scipy.{sub_package}.{module}.{attribute}` will be removed "
|
| 64 |
+
f"in SciPy {dep_version}, and the `scipy.{sub_package}.{module}` namespace "
|
| 65 |
+
f"will be removed in SciPy 2.0.0."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
warnings.warn(message, category=DeprecationWarning, stacklevel=3)
|
| 69 |
+
|
| 70 |
+
for module in private_modules:
|
| 71 |
+
try:
|
| 72 |
+
return getattr(import_module(f"scipy.{sub_package}.{module}"), attribute)
|
| 73 |
+
except AttributeError as e:
|
| 74 |
+
# still raise an error if the attribute isn't in any of the expected
|
| 75 |
+
# private modules
|
| 76 |
+
if module == private_modules[-1]:
|
| 77 |
+
raise e
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _deprecated(msg, stacklevel=2):
|
| 82 |
+
"""Deprecate a function by emitting a warning on use."""
|
| 83 |
+
def wrap(fun):
|
| 84 |
+
if isinstance(fun, type):
|
| 85 |
+
warnings.warn(
|
| 86 |
+
f"Trying to deprecate class {fun!r}",
|
| 87 |
+
category=RuntimeWarning, stacklevel=2)
|
| 88 |
+
return fun
|
| 89 |
+
|
| 90 |
+
@functools.wraps(fun)
|
| 91 |
+
def call(*args, **kwargs):
|
| 92 |
+
warnings.warn(msg, category=DeprecationWarning,
|
| 93 |
+
stacklevel=stacklevel)
|
| 94 |
+
return fun(*args, **kwargs)
|
| 95 |
+
call.__doc__ = fun.__doc__
|
| 96 |
+
return call
|
| 97 |
+
|
| 98 |
+
return wrap
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class _DeprecationHelperStr:
|
| 102 |
+
"""
|
| 103 |
+
Helper class used by deprecate_cython_api
|
| 104 |
+
"""
|
| 105 |
+
def __init__(self, content, message):
|
| 106 |
+
self._content = content
|
| 107 |
+
self._message = message
|
| 108 |
+
|
| 109 |
+
def __hash__(self):
|
| 110 |
+
return hash(self._content)
|
| 111 |
+
|
| 112 |
+
def __eq__(self, other):
|
| 113 |
+
res = (self._content == other)
|
| 114 |
+
if res:
|
| 115 |
+
warnings.warn(self._message, category=DeprecationWarning,
|
| 116 |
+
stacklevel=2)
|
| 117 |
+
return res
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def deprecate_cython_api(module, routine_name, new_name=None, message=None):
|
| 121 |
+
"""
|
| 122 |
+
Deprecate an exported cdef function in a public Cython API module.
|
| 123 |
+
|
| 124 |
+
Only functions can be deprecated; typedefs etc. cannot.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
----------
|
| 128 |
+
module : module
|
| 129 |
+
Public Cython API module (e.g. scipy.linalg.cython_blas).
|
| 130 |
+
routine_name : str
|
| 131 |
+
Name of the routine to deprecate. May also be a fused-type
|
| 132 |
+
routine (in which case its all specializations are deprecated).
|
| 133 |
+
new_name : str
|
| 134 |
+
New name to include in the deprecation warning message
|
| 135 |
+
message : str
|
| 136 |
+
Additional text in the deprecation warning message
|
| 137 |
+
|
| 138 |
+
Examples
|
| 139 |
+
--------
|
| 140 |
+
Usually, this function would be used in the top-level of the
|
| 141 |
+
module ``.pyx`` file:
|
| 142 |
+
|
| 143 |
+
>>> from scipy._lib.deprecation import deprecate_cython_api
|
| 144 |
+
>>> import scipy.linalg.cython_blas as mod
|
| 145 |
+
>>> deprecate_cython_api(mod, "dgemm", "dgemm_new",
|
| 146 |
+
... message="Deprecated in Scipy 1.5.0")
|
| 147 |
+
>>> del deprecate_cython_api, mod
|
| 148 |
+
|
| 149 |
+
After this, Cython modules that use the deprecated function emit a
|
| 150 |
+
deprecation warning when they are imported.
|
| 151 |
+
|
| 152 |
+
"""
|
| 153 |
+
old_name = f"{module.__name__}.{routine_name}"
|
| 154 |
+
|
| 155 |
+
if new_name is None:
|
| 156 |
+
depdoc = f"`{old_name}` is deprecated!"
|
| 157 |
+
else:
|
| 158 |
+
depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
|
| 159 |
+
|
| 160 |
+
if message is not None:
|
| 161 |
+
depdoc += "\n" + message
|
| 162 |
+
|
| 163 |
+
d = module.__pyx_capi__
|
| 164 |
+
|
| 165 |
+
# Check if the function is a fused-type function with a mangled name
|
| 166 |
+
j = 0
|
| 167 |
+
has_fused = False
|
| 168 |
+
while True:
|
| 169 |
+
fused_name = f"__pyx_fuse_{j}{routine_name}"
|
| 170 |
+
if fused_name in d:
|
| 171 |
+
has_fused = True
|
| 172 |
+
d[_DeprecationHelperStr(fused_name, depdoc)] = d.pop(fused_name)
|
| 173 |
+
j += 1
|
| 174 |
+
else:
|
| 175 |
+
break
|
| 176 |
+
|
| 177 |
+
# If not, apply deprecation to the named routine
|
| 178 |
+
if not has_fused:
|
| 179 |
+
d[_DeprecationHelperStr(routine_name, depdoc)] = d.pop(routine_name)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# taken from scikit-learn, see
|
| 183 |
+
# https://github.com/scikit-learn/scikit-learn/blob/1.3.0/sklearn/utils/validation.py#L38
|
| 184 |
+
def _deprecate_positional_args(func=None, *, version=None,
|
| 185 |
+
deprecated_args=None, custom_message=""):
|
| 186 |
+
"""Decorator for methods that issues warnings for positional arguments.
|
| 187 |
+
|
| 188 |
+
Using the keyword-only argument syntax in pep 3102, arguments after the
|
| 189 |
+
* will issue a warning when passed as a positional argument.
|
| 190 |
+
|
| 191 |
+
Parameters
|
| 192 |
+
----------
|
| 193 |
+
func : callable, default=None
|
| 194 |
+
Function to check arguments on.
|
| 195 |
+
version : callable, default=None
|
| 196 |
+
The version when positional arguments will result in error.
|
| 197 |
+
deprecated_args : set of str, optional
|
| 198 |
+
Arguments to deprecate - whether passed by position or keyword.
|
| 199 |
+
custom_message : str, optional
|
| 200 |
+
Custom message to add to deprecation warning and documentation.
|
| 201 |
+
"""
|
| 202 |
+
if version is None:
|
| 203 |
+
msg = "Need to specify a version where signature will be changed"
|
| 204 |
+
raise ValueError(msg)
|
| 205 |
+
|
| 206 |
+
deprecated_args = set() if deprecated_args is None else set(deprecated_args)
|
| 207 |
+
|
| 208 |
+
def _inner_deprecate_positional_args(f):
|
| 209 |
+
sig = signature(f)
|
| 210 |
+
kwonly_args = []
|
| 211 |
+
all_args = []
|
| 212 |
+
|
| 213 |
+
for name, param in sig.parameters.items():
|
| 214 |
+
if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
|
| 215 |
+
all_args.append(name)
|
| 216 |
+
elif param.kind == Parameter.KEYWORD_ONLY:
|
| 217 |
+
kwonly_args.append(name)
|
| 218 |
+
|
| 219 |
+
def warn_deprecated_args(kwargs):
|
| 220 |
+
intersection = deprecated_args.intersection(kwargs)
|
| 221 |
+
if intersection:
|
| 222 |
+
message = (f"Arguments {intersection} are deprecated, whether passed "
|
| 223 |
+
"by position or keyword. They will be removed in SciPy "
|
| 224 |
+
f"{version}. ")
|
| 225 |
+
message += custom_message
|
| 226 |
+
warnings.warn(message, category=DeprecationWarning, stacklevel=3)
|
| 227 |
+
|
| 228 |
+
@functools.wraps(f)
|
| 229 |
+
def inner_f(*args, **kwargs):
|
| 230 |
+
|
| 231 |
+
extra_args = len(args) - len(all_args)
|
| 232 |
+
if extra_args <= 0:
|
| 233 |
+
warn_deprecated_args(kwargs)
|
| 234 |
+
return f(*args, **kwargs)
|
| 235 |
+
|
| 236 |
+
# extra_args > 0
|
| 237 |
+
kwonly_extra_args = set(kwonly_args[:extra_args]) - deprecated_args
|
| 238 |
+
args_msg = ", ".join(kwonly_extra_args)
|
| 239 |
+
warnings.warn(
|
| 240 |
+
(
|
| 241 |
+
f"You are passing as positional arguments: {args_msg}. "
|
| 242 |
+
"Please change your invocation to use keyword arguments. "
|
| 243 |
+
f"From SciPy {version}, passing these as positional "
|
| 244 |
+
"arguments will result in an error."
|
| 245 |
+
),
|
| 246 |
+
DeprecationWarning,
|
| 247 |
+
stacklevel=2,
|
| 248 |
+
)
|
| 249 |
+
kwargs.update(zip(sig.parameters, args))
|
| 250 |
+
warn_deprecated_args(kwargs)
|
| 251 |
+
return f(**kwargs)
|
| 252 |
+
|
| 253 |
+
doc = FunctionDoc(inner_f)
|
| 254 |
+
kwonly_extra_args = set(kwonly_args) - deprecated_args
|
| 255 |
+
admonition = f"""
|
| 256 |
+
.. deprecated:: {version}
|
| 257 |
+
Use of argument(s) ``{kwonly_extra_args}`` by position is deprecated; beginning in
|
| 258 |
+
SciPy {version}, these will be keyword-only. """
|
| 259 |
+
if deprecated_args:
|
| 260 |
+
admonition += (f"Argument(s) ``{deprecated_args}`` are deprecated, whether "
|
| 261 |
+
"passed by position or keyword; they will be removed in "
|
| 262 |
+
f"SciPy {version}. ")
|
| 263 |
+
admonition += custom_message
|
| 264 |
+
doc['Extended Summary'] += [admonition]
|
| 265 |
+
|
| 266 |
+
doc = str(doc).split("\n", 1)[1] # remove signature
|
| 267 |
+
inner_f.__doc__ = str(doc)
|
| 268 |
+
|
| 269 |
+
return inner_f
|
| 270 |
+
|
| 271 |
+
if func is not None:
|
| 272 |
+
return _inner_deprecate_positional_args(func)
|
| 273 |
+
|
| 274 |
+
return _inner_deprecate_positional_args
|
python_embeded/Lib/site-packages/scipy/_lib/doccer.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities to allow inserting docstring fragments for common
|
| 2 |
+
parameters into function and method docstrings."""
|
| 3 |
+
|
| 4 |
+
from collections.abc import Callable, Iterable, Mapping
|
| 5 |
+
from typing import Protocol, TypeVar
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"docformat",
|
| 10 |
+
"inherit_docstring_from",
|
| 11 |
+
"indentcount_lines",
|
| 12 |
+
"filldoc",
|
| 13 |
+
"unindent_dict",
|
| 14 |
+
"unindent_string",
|
| 15 |
+
"extend_notes_in_docstring",
|
| 16 |
+
"replace_notes_in_docstring",
|
| 17 |
+
"doc_replace",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
_F = TypeVar("_F", bound=Callable[..., object])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Decorator(Protocol):
|
| 24 |
+
"""A decorator of a function."""
|
| 25 |
+
|
| 26 |
+
def __call__(self, func: _F, /) -> _F: ...
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str:
|
| 30 |
+
"""Fill a function docstring from variables in dictionary.
|
| 31 |
+
|
| 32 |
+
Adapt the indent of the inserted docs
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
----------
|
| 36 |
+
docstring : str
|
| 37 |
+
A docstring from a function, possibly with dict formatting strings.
|
| 38 |
+
docdict : dict[str, str], optional
|
| 39 |
+
A dictionary with keys that match the dict formatting strings
|
| 40 |
+
and values that are docstring fragments to be inserted. The
|
| 41 |
+
indentation of the inserted docstrings is set to match the
|
| 42 |
+
minimum indentation of the ``docstring`` by adding this
|
| 43 |
+
indentation to all lines of the inserted string, except the
|
| 44 |
+
first.
|
| 45 |
+
|
| 46 |
+
Returns
|
| 47 |
+
-------
|
| 48 |
+
docstring : str
|
| 49 |
+
string with requested ``docdict`` strings inserted.
|
| 50 |
+
|
| 51 |
+
Examples
|
| 52 |
+
--------
|
| 53 |
+
>>> docformat(' Test string with %(value)s', {'value':'inserted value'})
|
| 54 |
+
' Test string with inserted value'
|
| 55 |
+
>>> docstring = 'First line\\n Second line\\n %(value)s'
|
| 56 |
+
>>> inserted_string = "indented\\nstring"
|
| 57 |
+
>>> docdict = {'value': inserted_string}
|
| 58 |
+
>>> docformat(docstring, docdict)
|
| 59 |
+
'First line\\n Second line\\n indented\\n string'
|
| 60 |
+
"""
|
| 61 |
+
if not docstring:
|
| 62 |
+
return docstring
|
| 63 |
+
if docdict is None:
|
| 64 |
+
docdict = {}
|
| 65 |
+
if not docdict:
|
| 66 |
+
return docstring
|
| 67 |
+
lines = docstring.expandtabs().splitlines()
|
| 68 |
+
# Find the minimum indent of the main docstring, after first line
|
| 69 |
+
if len(lines) < 2:
|
| 70 |
+
icount = 0
|
| 71 |
+
else:
|
| 72 |
+
icount = indentcount_lines(lines[1:])
|
| 73 |
+
indent = " " * icount
|
| 74 |
+
# Insert this indent to dictionary docstrings
|
| 75 |
+
indented = {}
|
| 76 |
+
for name, dstr in docdict.items():
|
| 77 |
+
lines = dstr.expandtabs().splitlines()
|
| 78 |
+
try:
|
| 79 |
+
newlines = [lines[0]]
|
| 80 |
+
for line in lines[1:]:
|
| 81 |
+
newlines.append(indent + line)
|
| 82 |
+
indented[name] = "\n".join(newlines)
|
| 83 |
+
except IndexError:
|
| 84 |
+
indented[name] = dstr
|
| 85 |
+
return docstring % indented
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def inherit_docstring_from(cls: object) -> Decorator:
|
| 89 |
+
"""This decorator modifies the decorated function's docstring by
|
| 90 |
+
replacing occurrences of '%(super)s' with the docstring of the
|
| 91 |
+
method of the same name from the class `cls`.
|
| 92 |
+
|
| 93 |
+
If the decorated method has no docstring, it is simply given the
|
| 94 |
+
docstring of `cls`s method.
|
| 95 |
+
|
| 96 |
+
Parameters
|
| 97 |
+
----------
|
| 98 |
+
cls : type or object
|
| 99 |
+
A class with a method with the same name as the decorated method.
|
| 100 |
+
The docstring of the method in this class replaces '%(super)s' in the
|
| 101 |
+
docstring of the decorated method.
|
| 102 |
+
|
| 103 |
+
Returns
|
| 104 |
+
-------
|
| 105 |
+
decfunc : function
|
| 106 |
+
The decorator function that modifies the __doc__ attribute
|
| 107 |
+
of its argument.
|
| 108 |
+
|
| 109 |
+
Examples
|
| 110 |
+
--------
|
| 111 |
+
In the following, the docstring for Bar.func created using the
|
| 112 |
+
docstring of `Foo.func`.
|
| 113 |
+
|
| 114 |
+
>>> class Foo:
|
| 115 |
+
... def func(self):
|
| 116 |
+
... '''Do something useful.'''
|
| 117 |
+
... return
|
| 118 |
+
...
|
| 119 |
+
>>> class Bar(Foo):
|
| 120 |
+
... @inherit_docstring_from(Foo)
|
| 121 |
+
... def func(self):
|
| 122 |
+
... '''%(super)s
|
| 123 |
+
... Do it fast.
|
| 124 |
+
... '''
|
| 125 |
+
... return
|
| 126 |
+
...
|
| 127 |
+
>>> b = Bar()
|
| 128 |
+
>>> b.func.__doc__
|
| 129 |
+
'Do something useful.\n Do it fast.\n '
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def _doc(func: _F) -> _F:
|
| 133 |
+
cls_docstring = getattr(cls, func.__name__).__doc__
|
| 134 |
+
func_docstring = func.__doc__
|
| 135 |
+
if func_docstring is None:
|
| 136 |
+
func.__doc__ = cls_docstring
|
| 137 |
+
else:
|
| 138 |
+
new_docstring = func_docstring % dict(super=cls_docstring)
|
| 139 |
+
func.__doc__ = new_docstring
|
| 140 |
+
return func
|
| 141 |
+
|
| 142 |
+
return _doc
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def extend_notes_in_docstring(cls: object, notes: str) -> Decorator:
|
| 146 |
+
"""This decorator replaces the decorated function's docstring
|
| 147 |
+
with the docstring from corresponding method in `cls`.
|
| 148 |
+
It extends the 'Notes' section of that docstring to include
|
| 149 |
+
the given `notes`.
|
| 150 |
+
|
| 151 |
+
Parameters
|
| 152 |
+
----------
|
| 153 |
+
cls : type or object
|
| 154 |
+
A class with a method with the same name as the decorated method.
|
| 155 |
+
The docstring of the method in this class replaces the docstring of the
|
| 156 |
+
decorated method.
|
| 157 |
+
notes : str
|
| 158 |
+
Additional notes to append to the 'Notes' section of the docstring.
|
| 159 |
+
|
| 160 |
+
Returns
|
| 161 |
+
-------
|
| 162 |
+
decfunc : function
|
| 163 |
+
The decorator function that modifies the __doc__ attribute
|
| 164 |
+
of its argument.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def _doc(func: _F) -> _F:
|
| 168 |
+
cls_docstring = getattr(cls, func.__name__).__doc__
|
| 169 |
+
# If python is called with -OO option,
|
| 170 |
+
# there is no docstring
|
| 171 |
+
if cls_docstring is None:
|
| 172 |
+
return func
|
| 173 |
+
end_of_notes = cls_docstring.find(" References\n")
|
| 174 |
+
if end_of_notes == -1:
|
| 175 |
+
end_of_notes = cls_docstring.find(" Examples\n")
|
| 176 |
+
if end_of_notes == -1:
|
| 177 |
+
end_of_notes = len(cls_docstring)
|
| 178 |
+
func.__doc__ = (
|
| 179 |
+
cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:]
|
| 180 |
+
)
|
| 181 |
+
return func
|
| 182 |
+
|
| 183 |
+
return _doc
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def replace_notes_in_docstring(cls: object, notes: str) -> Decorator:
|
| 187 |
+
"""This decorator replaces the decorated function's docstring
|
| 188 |
+
with the docstring from corresponding method in `cls`.
|
| 189 |
+
It replaces the 'Notes' section of that docstring with
|
| 190 |
+
the given `notes`.
|
| 191 |
+
|
| 192 |
+
Parameters
|
| 193 |
+
----------
|
| 194 |
+
cls : type or object
|
| 195 |
+
A class with a method with the same name as the decorated method.
|
| 196 |
+
The docstring of the method in this class replaces the docstring of the
|
| 197 |
+
decorated method.
|
| 198 |
+
notes : str
|
| 199 |
+
The notes to replace the existing 'Notes' section with.
|
| 200 |
+
|
| 201 |
+
Returns
|
| 202 |
+
-------
|
| 203 |
+
decfunc : function
|
| 204 |
+
The decorator function that modifies the __doc__ attribute
|
| 205 |
+
of its argument.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
def _doc(func: _F) -> _F:
|
| 209 |
+
cls_docstring = getattr(cls, func.__name__).__doc__
|
| 210 |
+
notes_header = " Notes\n -----\n"
|
| 211 |
+
# If python is called with -OO option,
|
| 212 |
+
# there is no docstring
|
| 213 |
+
if cls_docstring is None:
|
| 214 |
+
return func
|
| 215 |
+
start_of_notes = cls_docstring.find(notes_header)
|
| 216 |
+
end_of_notes = cls_docstring.find(" References\n")
|
| 217 |
+
if end_of_notes == -1:
|
| 218 |
+
end_of_notes = cls_docstring.find(" Examples\n")
|
| 219 |
+
if end_of_notes == -1:
|
| 220 |
+
end_of_notes = len(cls_docstring)
|
| 221 |
+
func.__doc__ = (
|
| 222 |
+
cls_docstring[: start_of_notes + len(notes_header)]
|
| 223 |
+
+ notes
|
| 224 |
+
+ cls_docstring[end_of_notes:]
|
| 225 |
+
)
|
| 226 |
+
return func
|
| 227 |
+
|
| 228 |
+
return _doc
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def indentcount_lines(lines: Iterable[str]) -> int:
|
| 232 |
+
"""Minimum indent for all lines in line list
|
| 233 |
+
|
| 234 |
+
Parameters
|
| 235 |
+
----------
|
| 236 |
+
lines : Iterable[str]
|
| 237 |
+
The lines to find the minimum indent of.
|
| 238 |
+
|
| 239 |
+
Returns
|
| 240 |
+
-------
|
| 241 |
+
indent : int
|
| 242 |
+
The minimum indent.
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
Examples
|
| 246 |
+
--------
|
| 247 |
+
>>> lines = [' one', ' two', ' three']
|
| 248 |
+
>>> indentcount_lines(lines)
|
| 249 |
+
1
|
| 250 |
+
>>> lines = []
|
| 251 |
+
>>> indentcount_lines(lines)
|
| 252 |
+
0
|
| 253 |
+
>>> lines = [' one']
|
| 254 |
+
>>> indentcount_lines(lines)
|
| 255 |
+
1
|
| 256 |
+
>>> indentcount_lines([' '])
|
| 257 |
+
0
|
| 258 |
+
"""
|
| 259 |
+
indentno = sys.maxsize
|
| 260 |
+
for line in lines:
|
| 261 |
+
stripped = line.lstrip()
|
| 262 |
+
if stripped:
|
| 263 |
+
indentno = min(indentno, len(line) - len(stripped))
|
| 264 |
+
if indentno == sys.maxsize:
|
| 265 |
+
return 0
|
| 266 |
+
return indentno
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator:
|
| 270 |
+
"""Return docstring decorator using docdict variable dictionary.
|
| 271 |
+
|
| 272 |
+
Parameters
|
| 273 |
+
----------
|
| 274 |
+
docdict : dict[str, str]
|
| 275 |
+
A dictionary containing name, docstring fragment pairs.
|
| 276 |
+
unindent_params : bool, optional
|
| 277 |
+
If True, strip common indentation from all parameters in docdict.
|
| 278 |
+
Default is False.
|
| 279 |
+
|
| 280 |
+
Returns
|
| 281 |
+
-------
|
| 282 |
+
decfunc : function
|
| 283 |
+
The decorator function that applies dictionary to its
|
| 284 |
+
argument's __doc__ attribute.
|
| 285 |
+
"""
|
| 286 |
+
if unindent_params:
|
| 287 |
+
docdict = unindent_dict(docdict)
|
| 288 |
+
|
| 289 |
+
def decorate(func: _F) -> _F:
|
| 290 |
+
# __doc__ may be None for optimized Python (-OO)
|
| 291 |
+
doc = func.__doc__ or ""
|
| 292 |
+
func.__doc__ = docformat(doc, docdict)
|
| 293 |
+
return func
|
| 294 |
+
|
| 295 |
+
return decorate
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]:
|
| 299 |
+
"""Unindent all strings in a docdict.
|
| 300 |
+
|
| 301 |
+
Parameters
|
| 302 |
+
----------
|
| 303 |
+
docdict : dict[str, str]
|
| 304 |
+
A dictionary with string values to unindent.
|
| 305 |
+
|
| 306 |
+
Returns
|
| 307 |
+
-------
|
| 308 |
+
docdict : dict[str, str]
|
| 309 |
+
The `docdict` dictionary but each of its string values are unindented.
|
| 310 |
+
"""
|
| 311 |
+
can_dict: dict[str, str] = {}
|
| 312 |
+
for name, dstr in docdict.items():
|
| 313 |
+
can_dict[name] = unindent_string(dstr)
|
| 314 |
+
return can_dict
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def unindent_string(docstring: str) -> str:
|
| 318 |
+
"""Set docstring to minimum indent for all lines, including first.
|
| 319 |
+
|
| 320 |
+
Parameters
|
| 321 |
+
----------
|
| 322 |
+
docstring : str
|
| 323 |
+
The input docstring to unindent.
|
| 324 |
+
|
| 325 |
+
Returns
|
| 326 |
+
-------
|
| 327 |
+
docstring : str
|
| 328 |
+
The unindented docstring.
|
| 329 |
+
|
| 330 |
+
Examples
|
| 331 |
+
--------
|
| 332 |
+
>>> unindent_string(' two')
|
| 333 |
+
'two'
|
| 334 |
+
>>> unindent_string(' two\\n three')
|
| 335 |
+
'two\\n three'
|
| 336 |
+
"""
|
| 337 |
+
lines = docstring.expandtabs().splitlines()
|
| 338 |
+
icount = indentcount_lines(lines)
|
| 339 |
+
if icount == 0:
|
| 340 |
+
return docstring
|
| 341 |
+
return "\n".join([line[icount:] for line in lines])
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def doc_replace(obj: object, oldval: str, newval: str) -> Decorator:
|
| 345 |
+
"""Decorator to take the docstring from obj, with oldval replaced by newval
|
| 346 |
+
|
| 347 |
+
Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)``
|
| 348 |
+
|
| 349 |
+
Parameters
|
| 350 |
+
----------
|
| 351 |
+
obj : object
|
| 352 |
+
A class or object whose docstring will be used as the basis for the
|
| 353 |
+
replacement operation.
|
| 354 |
+
oldval : str
|
| 355 |
+
The string to search for in the docstring.
|
| 356 |
+
newval : str
|
| 357 |
+
The string to replace `oldval` with in the docstring.
|
| 358 |
+
|
| 359 |
+
Returns
|
| 360 |
+
-------
|
| 361 |
+
decfunc : function
|
| 362 |
+
A decorator function that replaces occurrences of `oldval` with `newval`
|
| 363 |
+
in the docstring of the decorated function.
|
| 364 |
+
"""
|
| 365 |
+
# __doc__ may be None for optimized Python (-OO)
|
| 366 |
+
doc = (obj.__doc__ or "").replace(oldval, newval)
|
| 367 |
+
|
| 368 |
+
def inner(func: _F) -> _F:
|
| 369 |
+
func.__doc__ = doc
|
| 370 |
+
return func
|
| 371 |
+
|
| 372 |
+
return inner
|
python_embeded/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.62 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/_lib/uarray.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`uarray` provides functions for generating multimethods that dispatch to
|
| 2 |
+
multiple different backends
|
| 3 |
+
|
| 4 |
+
This should be imported, rather than `_uarray` so that an installed version could
|
| 5 |
+
be used instead, if available. This means that users can call
|
| 6 |
+
`uarray.set_backend` directly instead of going through SciPy.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Prefer an installed version of uarray, if available
|
| 12 |
+
try:
|
| 13 |
+
import uarray as _uarray
|
| 14 |
+
except ImportError:
|
| 15 |
+
_has_uarray = False
|
| 16 |
+
else:
|
| 17 |
+
from scipy._lib._pep440 import Version as _Version
|
| 18 |
+
|
| 19 |
+
_has_uarray = _Version(_uarray.__version__) >= _Version("0.8")
|
| 20 |
+
del _uarray
|
| 21 |
+
del _Version
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if _has_uarray:
|
| 25 |
+
from uarray import * # noqa: F403
|
| 26 |
+
from uarray import _Function
|
| 27 |
+
else:
|
| 28 |
+
from ._uarray import * # noqa: F403
|
| 29 |
+
from ._uarray import _Function # noqa: F401
|
| 30 |
+
|
| 31 |
+
del _has_uarray
|
python_embeded/Lib/site-packages/scipy/cluster/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
=========================================
|
| 3 |
+
Clustering package (:mod:`scipy.cluster`)
|
| 4 |
+
=========================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.cluster
|
| 7 |
+
|
| 8 |
+
Clustering algorithms are useful in information theory, target detection,
|
| 9 |
+
communications, compression, and other areas. The `vq` module only
|
| 10 |
+
supports vector quantization and the k-means algorithms.
|
| 11 |
+
|
| 12 |
+
The `hierarchy` module provides functions for hierarchical and
|
| 13 |
+
agglomerative clustering. Its features include generating hierarchical
|
| 14 |
+
clusters from distance matrices,
|
| 15 |
+
calculating statistics on clusters, cutting linkages
|
| 16 |
+
to generate flat clusters, and visualizing clusters with dendrograms.
|
| 17 |
+
|
| 18 |
+
.. toctree::
|
| 19 |
+
:maxdepth: 1
|
| 20 |
+
|
| 21 |
+
cluster.vq
|
| 22 |
+
cluster.hierarchy
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
__all__ = ['vq', 'hierarchy']
|
| 26 |
+
|
| 27 |
+
from . import vq, hierarchy
|
| 28 |
+
|
| 29 |
+
from scipy._lib._testutils import PytestTester
|
| 30 |
+
test = PytestTester(__name__)
|
| 31 |
+
del PytestTester
|
python_embeded/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.58 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.72 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a
ADDED
|
Binary file (1.5 kB). View file
|
|
|
python_embeded/Lib/site-packages/scipy/cluster/hierarchy.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
python_embeded/Lib/site-pack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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
K-means clustering and vector quantization (:mod:`scipy.cluster.vq`)
|
| 3 |
+
====================================================================
|
| 4 |
+
|
| 5 |
+
Provides routines for k-means clustering, generating code books
|
| 6 |
+
from k-means models and quantizing vectors by comparing them with
|
| 7 |
+
centroids in a code book.
|
| 8 |
+
|
| 9 |
+
.. autosummary::
|
| 10 |
+
:toctree: generated/
|
| 11 |
+
|
| 12 |
+
whiten -- Normalize a group of observations so each feature has unit variance
|
| 13 |
+
vq -- Calculate code book membership of a set of observation vectors
|
| 14 |
+
kmeans -- Perform k-means on a set of observation vectors forming k clusters
|
| 15 |
+
kmeans2 -- A different implementation of k-means with more methods
|
| 16 |
+
-- for initializing centroids
|
| 17 |
+
|
| 18 |
+
Background information
|
| 19 |
+
----------------------
|
| 20 |
+
The k-means algorithm takes as input the number of clusters to
|
| 21 |
+
generate, k, and a set of observation vectors to cluster. It
|
| 22 |
+
returns a set of centroids, one for each of the k clusters. An
|
| 23 |
+
observation vector is classified with the cluster number or
|
| 24 |
+
centroid index of the centroid closest to it.
|
| 25 |
+
|
| 26 |
+
A vector v belongs to cluster i if it is closer to centroid i than
|
| 27 |
+
any other centroid. If v belongs to i, we say centroid i is the
|
| 28 |
+
dominating centroid of v. The k-means algorithm tries to
|
| 29 |
+
minimize distortion, which is defined as the sum of the squared distances
|
| 30 |
+
between each observation vector and its dominating centroid.
|
| 31 |
+
The minimization is achieved by iteratively reclassifying
|
| 32 |
+
the observations into clusters and recalculating the centroids until
|
| 33 |
+
a configuration is reached in which the centroids are stable. One can
|
| 34 |
+
also define a maximum number of iterations.
|
| 35 |
+
|
| 36 |
+
Since vector quantization is a natural application for k-means,
|
| 37 |
+
information theory terminology is often used. The centroid index
|
| 38 |
+
or cluster index is also referred to as a "code" and the table
|
| 39 |
+
mapping codes to centroids and, vice versa, is often referred to as a
|
| 40 |
+
"code book". The result of k-means, a set of centroids, can be
|
| 41 |
+
used to quantize vectors. Quantization aims to find an encoding of
|
| 42 |
+
vectors that reduces the expected distortion.
|
| 43 |
+
|
| 44 |
+
All routines expect obs to be an M by N array, where the rows are
|
| 45 |
+
the observation vectors. The codebook is a k by N array, where the
|
| 46 |
+
ith row is the centroid of code word i. The observation vectors
|
| 47 |
+
and centroids have the same feature dimension.
|
| 48 |
+
|
| 49 |
+
As an example, suppose we wish to compress a 24-bit color image
|
| 50 |
+
(each pixel is represented by one byte for red, one for blue, and
|
| 51 |
+
one for green) before sending it over the web. By using a smaller
|
| 52 |
+
8-bit encoding, we can reduce the amount of data by two
|
| 53 |
+
thirds. Ideally, the colors for each of the 256 possible 8-bit
|
| 54 |
+
encoding values should be chosen to minimize distortion of the
|
| 55 |
+
color. Running k-means with k=256 generates a code book of 256
|
| 56 |
+
codes, which fills up all possible 8-bit sequences. Instead of
|
| 57 |
+
sending a 3-byte value for each pixel, the 8-bit centroid index
|
| 58 |
+
(or code word) of the dominating centroid is transmitted. The code
|
| 59 |
+
book is also sent over the wire so each 8-bit code can be
|
| 60 |
+
translated back to a 24-bit pixel value representation. If the
|
| 61 |
+
image of interest was of an ocean, we would expect many 24-bit
|
| 62 |
+
blues to be represented by 8-bit codes. If it was an image of a
|
| 63 |
+
human face, more flesh-tone colors would be represented in the
|
| 64 |
+
code book.
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
import warnings
|
| 68 |
+
import numpy as np
|
| 69 |
+
from collections import deque
|
| 70 |
+
from scipy._lib._array_api import (
|
| 71 |
+
_asarray, array_namespace, xp_size, xp_copy
|
| 72 |
+
)
|
| 73 |
+
from scipy._lib._util import (check_random_state, rng_integers,
|
| 74 |
+
_transition_to_rng)
|
| 75 |
+
from scipy._lib import array_api_extra as xpx
|
| 76 |
+
from scipy.spatial.distance import cdist
|
| 77 |
+
|
| 78 |
+
from . import _vq
|
| 79 |
+
|
| 80 |
+
__docformat__ = 'restructuredtext'
|
| 81 |
+
|
| 82 |
+
__all__ = ['whiten', 'vq', 'kmeans', 'kmeans2']
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ClusterError(Exception):
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def whiten(obs, check_finite=True):
|
| 90 |
+
"""
|
| 91 |
+
Normalize a group of observations on a per feature basis.
|
| 92 |
+
|
| 93 |
+
Before running k-means, it is beneficial to rescale each feature
|
| 94 |
+
dimension of the observation set by its standard deviation (i.e. "whiten"
|
| 95 |
+
it - as in "white noise" where each frequency has equal power).
|
| 96 |
+
Each feature is divided by its standard deviation across all observations
|
| 97 |
+
to give it unit variance.
|
| 98 |
+
|
| 99 |
+
Parameters
|
| 100 |
+
----------
|
| 101 |
+
obs : ndarray
|
| 102 |
+
Each row of the array is an observation. The
|
| 103 |
+
columns are the features seen during each observation.
|
| 104 |
+
|
| 105 |
+
>>> # f0 f1 f2
|
| 106 |
+
>>> obs = [[ 1., 1., 1.], #o0
|
| 107 |
+
... [ 2., 2., 2.], #o1
|
| 108 |
+
... [ 3., 3., 3.], #o2
|
| 109 |
+
... [ 4., 4., 4.]] #o3
|
| 110 |
+
|
| 111 |
+
check_finite : bool, optional
|
| 112 |
+
Whether to check that the input matrices contain only finite numbers.
|
| 113 |
+
Disabling may give a performance gain, but may result in problems
|
| 114 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 115 |
+
Default: True
|
| 116 |
+
|
| 117 |
+
Returns
|
| 118 |
+
-------
|
| 119 |
+
result : ndarray
|
| 120 |
+
Contains the values in `obs` scaled by the standard deviation
|
| 121 |
+
of each column.
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
--------
|
| 125 |
+
>>> import numpy as np
|
| 126 |
+
>>> from scipy.cluster.vq import whiten
|
| 127 |
+
>>> features = np.array([[1.9, 2.3, 1.7],
|
| 128 |
+
... [1.5, 2.5, 2.2],
|
| 129 |
+
... [0.8, 0.6, 1.7,]])
|
| 130 |
+
>>> whiten(features)
|
| 131 |
+
array([[ 4.17944278, 2.69811351, 7.21248917],
|
| 132 |
+
[ 3.29956009, 2.93273208, 9.33380951],
|
| 133 |
+
[ 1.75976538, 0.7038557 , 7.21248917]])
|
| 134 |
+
|
| 135 |
+
"""
|
| 136 |
+
xp = array_namespace(obs)
|
| 137 |
+
obs = _asarray(obs, check_finite=check_finite, xp=xp)
|
| 138 |
+
std_dev = xp.std(obs, axis=0)
|
| 139 |
+
zero_std_mask = std_dev == 0
|
| 140 |
+
if xp.any(zero_std_mask):
|
| 141 |
+
std_dev[zero_std_mask] = 1.0
|
| 142 |
+
warnings.warn("Some columns have standard deviation zero. "
|
| 143 |
+
"The values of these columns will not change.",
|
| 144 |
+
RuntimeWarning, stacklevel=2)
|
| 145 |
+
return obs / std_dev
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def vq(obs, code_book, check_finite=True):
|
| 149 |
+
"""
|
| 150 |
+
Assign codes from a code book to observations.
|
| 151 |
+
|
| 152 |
+
Assigns a code from a code book to each observation. Each
|
| 153 |
+
observation vector in the 'M' by 'N' `obs` array is compared with the
|
| 154 |
+
centroids in the code book and assigned the code of the closest
|
| 155 |
+
centroid.
|
| 156 |
+
|
| 157 |
+
The features in `obs` should have unit variance, which can be
|
| 158 |
+
achieved by passing them through the whiten function. The code
|
| 159 |
+
book can be created with the k-means algorithm or a different
|
| 160 |
+
encoding algorithm.
|
| 161 |
+
|
| 162 |
+
Parameters
|
| 163 |
+
----------
|
| 164 |
+
obs : ndarray
|
| 165 |
+
Each row of the 'M' x 'N' array is an observation. The columns are
|
| 166 |
+
the "features" seen during each observation. The features must be
|
| 167 |
+
whitened first using the whiten function or something equivalent.
|
| 168 |
+
code_book : ndarray
|
| 169 |
+
The code book is usually generated using the k-means algorithm.
|
| 170 |
+
Each row of the array holds a different code, and the columns are
|
| 171 |
+
the features of the code.
|
| 172 |
+
|
| 173 |
+
>>> # f0 f1 f2 f3
|
| 174 |
+
>>> code_book = [
|
| 175 |
+
... [ 1., 2., 3., 4.], #c0
|
| 176 |
+
... [ 1., 2., 3., 4.], #c1
|
| 177 |
+
... [ 1., 2., 3., 4.]] #c2
|
| 178 |
+
|
| 179 |
+
check_finite : bool, optional
|
| 180 |
+
Whether to check that the input matrices contain only finite numbers.
|
| 181 |
+
Disabling may give a performance gain, but may result in problems
|
| 182 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 183 |
+
Default: True
|
| 184 |
+
|
| 185 |
+
Returns
|
| 186 |
+
-------
|
| 187 |
+
code : ndarray
|
| 188 |
+
A length M array holding the code book index for each observation.
|
| 189 |
+
dist : ndarray
|
| 190 |
+
The distortion (distance) between the observation and its nearest
|
| 191 |
+
code.
|
| 192 |
+
|
| 193 |
+
Examples
|
| 194 |
+
--------
|
| 195 |
+
>>> import numpy as np
|
| 196 |
+
>>> from scipy.cluster.vq import vq
|
| 197 |
+
>>> code_book = np.array([[1., 1., 1.],
|
| 198 |
+
... [2., 2., 2.]])
|
| 199 |
+
>>> features = np.array([[1.9, 2.3, 1.7],
|
| 200 |
+
... [1.5, 2.5, 2.2],
|
| 201 |
+
... [0.8, 0.6, 1.7]])
|
| 202 |
+
>>> vq(features, code_book)
|
| 203 |
+
(array([1, 1, 0], dtype=int32), array([0.43588989, 0.73484692, 0.83066239]))
|
| 204 |
+
|
| 205 |
+
"""
|
| 206 |
+
xp = array_namespace(obs, code_book)
|
| 207 |
+
obs = _asarray(obs, xp=xp, check_finite=check_finite)
|
| 208 |
+
code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
|
| 209 |
+
ct = xp.result_type(obs, code_book)
|
| 210 |
+
|
| 211 |
+
c_obs = xp.astype(obs, ct, copy=False)
|
| 212 |
+
c_code_book = xp.astype(code_book, ct, copy=False)
|
| 213 |
+
|
| 214 |
+
if xp.isdtype(ct, kind='real floating'):
|
| 215 |
+
c_obs = np.asarray(c_obs)
|
| 216 |
+
c_code_book = np.asarray(c_code_book)
|
| 217 |
+
result = _vq.vq(c_obs, c_code_book)
|
| 218 |
+
return xp.asarray(result[0]), xp.asarray(result[1])
|
| 219 |
+
return py_vq(obs, code_book, check_finite=False)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def py_vq(obs, code_book, check_finite=True):
|
| 223 |
+
""" Python version of vq algorithm.
|
| 224 |
+
|
| 225 |
+
The algorithm computes the Euclidean distance between each
|
| 226 |
+
observation and every frame in the code_book.
|
| 227 |
+
|
| 228 |
+
Parameters
|
| 229 |
+
----------
|
| 230 |
+
obs : ndarray
|
| 231 |
+
Expects a rank 2 array. Each row is one observation.
|
| 232 |
+
code_book : ndarray
|
| 233 |
+
Code book to use. Same format than obs. Should have same number of
|
| 234 |
+
features (e.g., columns) than obs.
|
| 235 |
+
check_finite : bool, optional
|
| 236 |
+
Whether to check that the input matrices contain only finite numbers.
|
| 237 |
+
Disabling may give a performance gain, but may result in problems
|
| 238 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 239 |
+
Default: True
|
| 240 |
+
|
| 241 |
+
Returns
|
| 242 |
+
-------
|
| 243 |
+
code : ndarray
|
| 244 |
+
code[i] gives the label of the ith obversation; its code is
|
| 245 |
+
code_book[code[i]].
|
| 246 |
+
mind_dist : ndarray
|
| 247 |
+
min_dist[i] gives the distance between the ith observation and its
|
| 248 |
+
corresponding code.
|
| 249 |
+
|
| 250 |
+
Notes
|
| 251 |
+
-----
|
| 252 |
+
This function is slower than the C version but works for
|
| 253 |
+
all input types. If the inputs have the wrong types for the
|
| 254 |
+
C versions of the function, this one is called as a last resort.
|
| 255 |
+
|
| 256 |
+
It is about 20 times slower than the C version.
|
| 257 |
+
|
| 258 |
+
"""
|
| 259 |
+
xp = array_namespace(obs, code_book)
|
| 260 |
+
obs = _asarray(obs, xp=xp, check_finite=check_finite)
|
| 261 |
+
code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
|
| 262 |
+
|
| 263 |
+
if obs.ndim != code_book.ndim:
|
| 264 |
+
raise ValueError("Observation and code_book should have the same rank")
|
| 265 |
+
|
| 266 |
+
if obs.ndim == 1:
|
| 267 |
+
obs = obs[:, xp.newaxis]
|
| 268 |
+
code_book = code_book[:, xp.newaxis]
|
| 269 |
+
|
| 270 |
+
# Once `cdist` has array API support, this `xp.asarray` call can be removed
|
| 271 |
+
dist = xp.asarray(cdist(obs, code_book))
|
| 272 |
+
code = xp.argmin(dist, axis=1)
|
| 273 |
+
min_dist = xp.min(dist, axis=1)
|
| 274 |
+
return code, min_dist
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def _kmeans(obs, guess, thresh=1e-5, xp=None):
|
| 278 |
+
""" "raw" version of k-means.
|
| 279 |
+
|
| 280 |
+
Returns
|
| 281 |
+
-------
|
| 282 |
+
code_book
|
| 283 |
+
The lowest distortion codebook found.
|
| 284 |
+
avg_dist
|
| 285 |
+
The average distance a observation is from a code in the book.
|
| 286 |
+
Lower means the code_book matches the data better.
|
| 287 |
+
|
| 288 |
+
See Also
|
| 289 |
+
--------
|
| 290 |
+
kmeans : wrapper around k-means
|
| 291 |
+
|
| 292 |
+
Examples
|
| 293 |
+
--------
|
| 294 |
+
Note: not whitened in this example.
|
| 295 |
+
|
| 296 |
+
>>> import numpy as np
|
| 297 |
+
>>> from scipy.cluster.vq import _kmeans
|
| 298 |
+
>>> features = np.array([[ 1.9,2.3],
|
| 299 |
+
... [ 1.5,2.5],
|
| 300 |
+
... [ 0.8,0.6],
|
| 301 |
+
... [ 0.4,1.8],
|
| 302 |
+
... [ 1.0,1.0]])
|
| 303 |
+
>>> book = np.array((features[0],features[2]))
|
| 304 |
+
>>> _kmeans(features,book)
|
| 305 |
+
(array([[ 1.7 , 2.4 ],
|
| 306 |
+
[ 0.73333333, 1.13333333]]), 0.40563916697728591)
|
| 307 |
+
|
| 308 |
+
"""
|
| 309 |
+
xp = np if xp is None else xp
|
| 310 |
+
code_book = guess
|
| 311 |
+
diff = xp.inf
|
| 312 |
+
prev_avg_dists = deque([diff], maxlen=2)
|
| 313 |
+
while diff > thresh:
|
| 314 |
+
# compute membership and distances between obs and code_book
|
| 315 |
+
obs_code, distort = vq(obs, code_book, check_finite=False)
|
| 316 |
+
prev_avg_dists.append(xp.mean(distort, axis=-1))
|
| 317 |
+
# recalc code_book as centroids of associated obs
|
| 318 |
+
obs = np.asarray(obs)
|
| 319 |
+
obs_code = np.asarray(obs_code)
|
| 320 |
+
code_book, has_members = _vq.update_cluster_means(obs, obs_code,
|
| 321 |
+
code_book.shape[0])
|
| 322 |
+
obs = xp.asarray(obs)
|
| 323 |
+
obs_code = xp.asarray(obs_code)
|
| 324 |
+
code_book = xp.asarray(code_book)
|
| 325 |
+
has_members = xp.asarray(has_members)
|
| 326 |
+
code_book = code_book[has_members]
|
| 327 |
+
diff = xp.abs(prev_avg_dists[0] - prev_avg_dists[1])
|
| 328 |
+
|
| 329 |
+
return code_book, prev_avg_dists[1]
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
@_transition_to_rng("seed")
|
| 333 |
+
def kmeans(obs, k_or_guess, iter=20, thresh=1e-5, check_finite=True,
|
| 334 |
+
*, rng=None):
|
| 335 |
+
"""
|
| 336 |
+
Performs k-means on a set of observation vectors forming k clusters.
|
| 337 |
+
|
| 338 |
+
The k-means algorithm adjusts the classification of the observations
|
| 339 |
+
into clusters and updates the cluster centroids until the position of
|
| 340 |
+
the centroids is stable over successive iterations. In this
|
| 341 |
+
implementation of the algorithm, the stability of the centroids is
|
| 342 |
+
determined by comparing the absolute value of the change in the average
|
| 343 |
+
Euclidean distance between the observations and their corresponding
|
| 344 |
+
centroids against a threshold. This yields
|
| 345 |
+
a code book mapping centroids to codes and vice versa.
|
| 346 |
+
|
| 347 |
+
Parameters
|
| 348 |
+
----------
|
| 349 |
+
obs : ndarray
|
| 350 |
+
Each row of the M by N array is an observation vector. The
|
| 351 |
+
columns are the features seen during each observation.
|
| 352 |
+
The features must be whitened first with the `whiten` function.
|
| 353 |
+
|
| 354 |
+
k_or_guess : int or ndarray
|
| 355 |
+
The number of centroids to generate. A code is assigned to
|
| 356 |
+
each centroid, which is also the row index of the centroid
|
| 357 |
+
in the code_book matrix generated.
|
| 358 |
+
|
| 359 |
+
The initial k centroids are chosen by randomly selecting
|
| 360 |
+
observations from the observation matrix. Alternatively,
|
| 361 |
+
passing a k by N array specifies the initial k centroids.
|
| 362 |
+
|
| 363 |
+
iter : int, optional
|
| 364 |
+
The number of times to run k-means, returning the codebook
|
| 365 |
+
with the lowest distortion. This argument is ignored if
|
| 366 |
+
initial centroids are specified with an array for the
|
| 367 |
+
``k_or_guess`` parameter. This parameter does not represent the
|
| 368 |
+
number of iterations of the k-means algorithm.
|
| 369 |
+
|
| 370 |
+
thresh : float, optional
|
| 371 |
+
Terminates the k-means algorithm if the change in
|
| 372 |
+
distortion since the last k-means iteration is less than
|
| 373 |
+
or equal to threshold.
|
| 374 |
+
|
| 375 |
+
check_finite : bool, optional
|
| 376 |
+
Whether to check that the input matrices contain only finite numbers.
|
| 377 |
+
Disabling may give a performance gain, but may result in problems
|
| 378 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 379 |
+
Default: True
|
| 380 |
+
rng : `numpy.random.Generator`, optional
|
| 381 |
+
Pseudorandom number generator state. When `rng` is None, a new
|
| 382 |
+
`numpy.random.Generator` is created using entropy from the
|
| 383 |
+
operating system. Types other than `numpy.random.Generator` are
|
| 384 |
+
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
|
| 385 |
+
|
| 386 |
+
Returns
|
| 387 |
+
-------
|
| 388 |
+
codebook : ndarray
|
| 389 |
+
A k by N array of k centroids. The ith centroid
|
| 390 |
+
codebook[i] is represented with the code i. The centroids
|
| 391 |
+
and codes generated represent the lowest distortion seen,
|
| 392 |
+
not necessarily the globally minimal distortion.
|
| 393 |
+
Note that the number of centroids is not necessarily the same as the
|
| 394 |
+
``k_or_guess`` parameter, because centroids assigned to no observations
|
| 395 |
+
are removed during iterations.
|
| 396 |
+
|
| 397 |
+
distortion : float
|
| 398 |
+
The mean (non-squared) Euclidean distance between the observations
|
| 399 |
+
passed and the centroids generated. Note the difference to the standard
|
| 400 |
+
definition of distortion in the context of the k-means algorithm, which
|
| 401 |
+
is the sum of the squared distances.
|
| 402 |
+
|
| 403 |
+
See Also
|
| 404 |
+
--------
|
| 405 |
+
kmeans2 : a different implementation of k-means clustering
|
| 406 |
+
with more methods for generating initial centroids but without
|
| 407 |
+
using a distortion change threshold as a stopping criterion.
|
| 408 |
+
|
| 409 |
+
whiten : must be called prior to passing an observation matrix
|
| 410 |
+
to kmeans.
|
| 411 |
+
|
| 412 |
+
Notes
|
| 413 |
+
-----
|
| 414 |
+
For more functionalities or optimal performance, you can use
|
| 415 |
+
`sklearn.cluster.KMeans <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html>`_.
|
| 416 |
+
`This <https://hdbscan.readthedocs.io/en/latest/performance_and_scalability.html#comparison-of-high-performance-implementations>`_
|
| 417 |
+
is a benchmark result of several implementations.
|
| 418 |
+
|
| 419 |
+
Examples
|
| 420 |
+
--------
|
| 421 |
+
>>> import numpy as np
|
| 422 |
+
>>> from scipy.cluster.vq import vq, kmeans, whiten
|
| 423 |
+
>>> import matplotlib.pyplot as plt
|
| 424 |
+
>>> features = np.array([[ 1.9,2.3],
|
| 425 |
+
... [ 1.5,2.5],
|
| 426 |
+
... [ 0.8,0.6],
|
| 427 |
+
... [ 0.4,1.8],
|
| 428 |
+
... [ 0.1,0.1],
|
| 429 |
+
... [ 0.2,1.8],
|
| 430 |
+
... [ 2.0,0.5],
|
| 431 |
+
... [ 0.3,1.5],
|
| 432 |
+
... [ 1.0,1.0]])
|
| 433 |
+
>>> whitened = whiten(features)
|
| 434 |
+
>>> book = np.array((whitened[0],whitened[2]))
|
| 435 |
+
>>> kmeans(whitened,book)
|
| 436 |
+
(array([[ 2.3110306 , 2.86287398], # random
|
| 437 |
+
[ 0.93218041, 1.24398691]]), 0.85684700941625547)
|
| 438 |
+
|
| 439 |
+
>>> codes = 3
|
| 440 |
+
>>> kmeans(whitened,codes)
|
| 441 |
+
(array([[ 2.3110306 , 2.86287398], # random
|
| 442 |
+
[ 1.32544402, 0.65607529],
|
| 443 |
+
[ 0.40782893, 2.02786907]]), 0.5196582527686241)
|
| 444 |
+
|
| 445 |
+
>>> # Create 50 datapoints in two clusters a and b
|
| 446 |
+
>>> pts = 50
|
| 447 |
+
>>> rng = np.random.default_rng()
|
| 448 |
+
>>> a = rng.multivariate_normal([0, 0], [[4, 1], [1, 4]], size=pts)
|
| 449 |
+
>>> b = rng.multivariate_normal([30, 10],
|
| 450 |
+
... [[10, 2], [2, 1]],
|
| 451 |
+
... size=pts)
|
| 452 |
+
>>> features = np.concatenate((a, b))
|
| 453 |
+
>>> # Whiten data
|
| 454 |
+
>>> whitened = whiten(features)
|
| 455 |
+
>>> # Find 2 clusters in the data
|
| 456 |
+
>>> codebook, distortion = kmeans(whitened, 2)
|
| 457 |
+
>>> # Plot whitened data and cluster centers in red
|
| 458 |
+
>>> plt.scatter(whitened[:, 0], whitened[:, 1])
|
| 459 |
+
>>> plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
|
| 460 |
+
>>> plt.show()
|
| 461 |
+
|
| 462 |
+
"""
|
| 463 |
+
if isinstance(k_or_guess, int):
|
| 464 |
+
xp = array_namespace(obs)
|
| 465 |
+
else:
|
| 466 |
+
xp = array_namespace(obs, k_or_guess)
|
| 467 |
+
obs = _asarray(obs, xp=xp, check_finite=check_finite)
|
| 468 |
+
guess = _asarray(k_or_guess, xp=xp, check_finite=check_finite)
|
| 469 |
+
if iter < 1:
|
| 470 |
+
raise ValueError(f"iter must be at least 1, got {iter}")
|
| 471 |
+
|
| 472 |
+
# Determine whether a count (scalar) or an initial guess (array) was passed.
|
| 473 |
+
if xp_size(guess) != 1:
|
| 474 |
+
if xp_size(guess) < 1:
|
| 475 |
+
raise ValueError(f"Asked for 0 clusters. Initial book was {guess}")
|
| 476 |
+
return _kmeans(obs, guess, thresh=thresh, xp=xp)
|
| 477 |
+
|
| 478 |
+
# k_or_guess is a scalar, now verify that it's an integer
|
| 479 |
+
k = int(guess)
|
| 480 |
+
if k != guess:
|
| 481 |
+
raise ValueError("If k_or_guess is a scalar, it must be an integer.")
|
| 482 |
+
if k < 1:
|
| 483 |
+
raise ValueError("Asked for %d clusters." % k)
|
| 484 |
+
|
| 485 |
+
rng = check_random_state(rng)
|
| 486 |
+
|
| 487 |
+
# initialize best distance value to a large value
|
| 488 |
+
best_dist = xp.inf
|
| 489 |
+
for i in range(iter):
|
| 490 |
+
# the initial code book is randomly selected from observations
|
| 491 |
+
guess = _kpoints(obs, k, rng, xp)
|
| 492 |
+
book, dist = _kmeans(obs, guess, thresh=thresh, xp=xp)
|
| 493 |
+
if dist < best_dist:
|
| 494 |
+
best_book = book
|
| 495 |
+
best_dist = dist
|
| 496 |
+
return best_book, best_dist
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def _kpoints(data, k, rng, xp):
|
| 500 |
+
"""Pick k points at random in data (one row = one observation).
|
| 501 |
+
|
| 502 |
+
Parameters
|
| 503 |
+
----------
|
| 504 |
+
data : ndarray
|
| 505 |
+
Expect a rank 1 or 2 array. Rank 1 are assumed to describe one
|
| 506 |
+
dimensional data, rank 2 multidimensional data, in which case one
|
| 507 |
+
row is one observation.
|
| 508 |
+
k : int
|
| 509 |
+
Number of samples to generate.
|
| 510 |
+
rng : `numpy.random.Generator` or `numpy.random.RandomState`
|
| 511 |
+
Random number generator.
|
| 512 |
+
|
| 513 |
+
Returns
|
| 514 |
+
-------
|
| 515 |
+
x : ndarray
|
| 516 |
+
A 'k' by 'N' containing the initial centroids
|
| 517 |
+
|
| 518 |
+
"""
|
| 519 |
+
idx = rng.choice(data.shape[0], size=int(k), replace=False)
|
| 520 |
+
# convert to array with default integer dtype (avoids numpy#25607)
|
| 521 |
+
idx = xp.asarray(idx, dtype=xp.asarray([1]).dtype)
|
| 522 |
+
return xp.take(data, idx, axis=0)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def _krandinit(data, k, rng, xp):
|
| 526 |
+
"""Returns k samples of a random variable whose parameters depend on data.
|
| 527 |
+
|
| 528 |
+
More precisely, it returns k observations sampled from a Gaussian random
|
| 529 |
+
variable whose mean and covariances are the ones estimated from the data.
|
| 530 |
+
|
| 531 |
+
Parameters
|
| 532 |
+
----------
|
| 533 |
+
data : ndarray
|
| 534 |
+
Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
|
| 535 |
+
data, rank 2 multidimensional data, in which case one
|
| 536 |
+
row is one observation.
|
| 537 |
+
k : int
|
| 538 |
+
Number of samples to generate.
|
| 539 |
+
rng : `numpy.random.Generator` or `numpy.random.RandomState`
|
| 540 |
+
Random number generator.
|
| 541 |
+
|
| 542 |
+
Returns
|
| 543 |
+
-------
|
| 544 |
+
x : ndarray
|
| 545 |
+
A 'k' by 'N' containing the initial centroids
|
| 546 |
+
|
| 547 |
+
"""
|
| 548 |
+
mu = xp.mean(data, axis=0)
|
| 549 |
+
k = np.asarray(k)
|
| 550 |
+
|
| 551 |
+
if data.ndim == 1:
|
| 552 |
+
_cov = xpx.cov(data, xp=xp)
|
| 553 |
+
x = rng.standard_normal(size=k)
|
| 554 |
+
x = xp.asarray(x)
|
| 555 |
+
x *= xp.sqrt(_cov)
|
| 556 |
+
elif data.shape[1] > data.shape[0]:
|
| 557 |
+
# initialize when the covariance matrix is rank deficient
|
| 558 |
+
_, s, vh = xp.linalg.svd(data - mu, full_matrices=False)
|
| 559 |
+
x = rng.standard_normal(size=(k, xp_size(s)))
|
| 560 |
+
x = xp.asarray(x)
|
| 561 |
+
sVh = s[:, None] * vh / xp.sqrt(data.shape[0] - xp.asarray(1.))
|
| 562 |
+
x = x @ sVh
|
| 563 |
+
else:
|
| 564 |
+
_cov = xpx.atleast_nd(xpx.cov(data.T, xp=xp), ndim=2, xp=xp)
|
| 565 |
+
|
| 566 |
+
# k rows, d cols (one row = one obs)
|
| 567 |
+
# Generate k sample of a random variable ~ Gaussian(mu, cov)
|
| 568 |
+
x = rng.standard_normal(size=(k, xp_size(mu)))
|
| 569 |
+
x = xp.asarray(x)
|
| 570 |
+
x = x @ xp.linalg.cholesky(_cov).T
|
| 571 |
+
|
| 572 |
+
x += mu
|
| 573 |
+
return x
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def _kpp(data, k, rng, xp):
|
| 577 |
+
""" Picks k points in the data based on the kmeans++ method.
|
| 578 |
+
|
| 579 |
+
Parameters
|
| 580 |
+
----------
|
| 581 |
+
data : ndarray
|
| 582 |
+
Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
|
| 583 |
+
data, rank 2 multidimensional data, in which case one
|
| 584 |
+
row is one observation.
|
| 585 |
+
k : int
|
| 586 |
+
Number of samples to generate.
|
| 587 |
+
rng : `numpy.random.Generator` or `numpy.random.RandomState`
|
| 588 |
+
Random number generator.
|
| 589 |
+
|
| 590 |
+
Returns
|
| 591 |
+
-------
|
| 592 |
+
init : ndarray
|
| 593 |
+
A 'k' by 'N' containing the initial centroids.
|
| 594 |
+
|
| 595 |
+
References
|
| 596 |
+
----------
|
| 597 |
+
.. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
|
| 598 |
+
careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
|
| 599 |
+
on Discrete Algorithms, 2007.
|
| 600 |
+
"""
|
| 601 |
+
|
| 602 |
+
ndim = len(data.shape)
|
| 603 |
+
if ndim == 1:
|
| 604 |
+
data = data[:, None]
|
| 605 |
+
|
| 606 |
+
dims = data.shape[1]
|
| 607 |
+
|
| 608 |
+
init = xp.empty((int(k), dims))
|
| 609 |
+
|
| 610 |
+
for i in range(k):
|
| 611 |
+
if i == 0:
|
| 612 |
+
init[i, :] = data[rng_integers(rng, data.shape[0]), :]
|
| 613 |
+
|
| 614 |
+
else:
|
| 615 |
+
D2 = cdist(init[:i,:], data, metric='sqeuclidean').min(axis=0)
|
| 616 |
+
probs = D2/D2.sum()
|
| 617 |
+
cumprobs = probs.cumsum()
|
| 618 |
+
r = rng.uniform()
|
| 619 |
+
cumprobs = np.asarray(cumprobs)
|
| 620 |
+
init[i, :] = data[np.searchsorted(cumprobs, r), :]
|
| 621 |
+
|
| 622 |
+
if ndim == 1:
|
| 623 |
+
init = init[:, 0]
|
| 624 |
+
return init
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
_valid_init_meth = {'random': _krandinit, 'points': _kpoints, '++': _kpp}
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def _missing_warn():
|
| 631 |
+
"""Print a warning when called."""
|
| 632 |
+
warnings.warn("One of the clusters is empty. "
|
| 633 |
+
"Re-run kmeans with a different initialization.",
|
| 634 |
+
stacklevel=3)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def _missing_raise():
|
| 638 |
+
"""Raise a ClusterError when called."""
|
| 639 |
+
raise ClusterError("One of the clusters is empty. "
|
| 640 |
+
"Re-run kmeans with a different initialization.")
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
_valid_miss_meth = {'warn': _missing_warn, 'raise': _missing_raise}
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
@_transition_to_rng("seed")
|
| 647 |
+
def kmeans2(data, k, iter=10, thresh=1e-5, minit='random',
|
| 648 |
+
missing='warn', check_finite=True, *, rng=None):
|
| 649 |
+
"""
|
| 650 |
+
Classify a set of observations into k clusters using the k-means algorithm.
|
| 651 |
+
|
| 652 |
+
The algorithm attempts to minimize the Euclidean distance between
|
| 653 |
+
observations and centroids. Several initialization methods are
|
| 654 |
+
included.
|
| 655 |
+
|
| 656 |
+
Parameters
|
| 657 |
+
----------
|
| 658 |
+
data : ndarray
|
| 659 |
+
A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
|
| 660 |
+
'M' array of 'M' 1-D observations.
|
| 661 |
+
k : int or ndarray
|
| 662 |
+
The number of clusters to form as well as the number of
|
| 663 |
+
centroids to generate. If `minit` initialization string is
|
| 664 |
+
'matrix', or if a ndarray is given instead, it is
|
| 665 |
+
interpreted as initial cluster to use instead.
|
| 666 |
+
iter : int, optional
|
| 667 |
+
Number of iterations of the k-means algorithm to run. Note
|
| 668 |
+
that this differs in meaning from the iters parameter to
|
| 669 |
+
the kmeans function.
|
| 670 |
+
thresh : float, optional
|
| 671 |
+
(not used yet)
|
| 672 |
+
minit : str, optional
|
| 673 |
+
Method for initialization. Available methods are 'random',
|
| 674 |
+
'points', '++' and 'matrix':
|
| 675 |
+
|
| 676 |
+
'random': generate k centroids from a Gaussian with mean and
|
| 677 |
+
variance estimated from the data.
|
| 678 |
+
|
| 679 |
+
'points': choose k observations (rows) at random from data for
|
| 680 |
+
the initial centroids.
|
| 681 |
+
|
| 682 |
+
'++': choose k observations accordingly to the kmeans++ method
|
| 683 |
+
(careful seeding)
|
| 684 |
+
|
| 685 |
+
'matrix': interpret the k parameter as a k by M (or length k
|
| 686 |
+
array for 1-D data) array of initial centroids.
|
| 687 |
+
missing : str, optional
|
| 688 |
+
Method to deal with empty clusters. Available methods are
|
| 689 |
+
'warn' and 'raise':
|
| 690 |
+
|
| 691 |
+
'warn': give a warning and continue.
|
| 692 |
+
|
| 693 |
+
'raise': raise an ClusterError and terminate the algorithm.
|
| 694 |
+
check_finite : bool, optional
|
| 695 |
+
Whether to check that the input matrices contain only finite numbers.
|
| 696 |
+
Disabling may give a performance gain, but may result in problems
|
| 697 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 698 |
+
Default: True
|
| 699 |
+
rng : `numpy.random.Generator`, optional
|
| 700 |
+
Pseudorandom number generator state. When `rng` is None, a new
|
| 701 |
+
`numpy.random.Generator` is created using entropy from the
|
| 702 |
+
operating system. Types other than `numpy.random.Generator` are
|
| 703 |
+
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
|
| 704 |
+
|
| 705 |
+
Returns
|
| 706 |
+
-------
|
| 707 |
+
centroid : ndarray
|
| 708 |
+
A 'k' by 'N' array of centroids found at the last iteration of
|
| 709 |
+
k-means.
|
| 710 |
+
label : ndarray
|
| 711 |
+
label[i] is the code or index of the centroid the
|
| 712 |
+
ith observation is closest to.
|
| 713 |
+
|
| 714 |
+
See Also
|
| 715 |
+
--------
|
| 716 |
+
kmeans
|
| 717 |
+
|
| 718 |
+
References
|
| 719 |
+
----------
|
| 720 |
+
.. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
|
| 721 |
+
careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
|
| 722 |
+
on Discrete Algorithms, 2007.
|
| 723 |
+
|
| 724 |
+
Examples
|
| 725 |
+
--------
|
| 726 |
+
>>> from scipy.cluster.vq import kmeans2
|
| 727 |
+
>>> import matplotlib.pyplot as plt
|
| 728 |
+
>>> import numpy as np
|
| 729 |
+
|
| 730 |
+
Create z, an array with shape (100, 2) containing a mixture of samples
|
| 731 |
+
from three multivariate normal distributions.
|
| 732 |
+
|
| 733 |
+
>>> rng = np.random.default_rng()
|
| 734 |
+
>>> a = rng.multivariate_normal([0, 6], [[2, 1], [1, 1.5]], size=45)
|
| 735 |
+
>>> b = rng.multivariate_normal([2, 0], [[1, -1], [-1, 3]], size=30)
|
| 736 |
+
>>> c = rng.multivariate_normal([6, 4], [[5, 0], [0, 1.2]], size=25)
|
| 737 |
+
>>> z = np.concatenate((a, b, c))
|
| 738 |
+
>>> rng.shuffle(z)
|
| 739 |
+
|
| 740 |
+
Compute three clusters.
|
| 741 |
+
|
| 742 |
+
>>> centroid, label = kmeans2(z, 3, minit='points')
|
| 743 |
+
>>> centroid
|
| 744 |
+
array([[ 2.22274463, -0.61666946], # may vary
|
| 745 |
+
[ 0.54069047, 5.86541444],
|
| 746 |
+
[ 6.73846769, 4.01991898]])
|
| 747 |
+
|
| 748 |
+
How many points are in each cluster?
|
| 749 |
+
|
| 750 |
+
>>> counts = np.bincount(label)
|
| 751 |
+
>>> counts
|
| 752 |
+
array([29, 51, 20]) # may vary
|
| 753 |
+
|
| 754 |
+
Plot the clusters.
|
| 755 |
+
|
| 756 |
+
>>> w0 = z[label == 0]
|
| 757 |
+
>>> w1 = z[label == 1]
|
| 758 |
+
>>> w2 = z[label == 2]
|
| 759 |
+
>>> plt.plot(w0[:, 0], w0[:, 1], 'o', alpha=0.5, label='cluster 0')
|
| 760 |
+
>>> plt.plot(w1[:, 0], w1[:, 1], 'd', alpha=0.5, label='cluster 1')
|
| 761 |
+
>>> plt.plot(w2[:, 0], w2[:, 1], 's', alpha=0.5, label='cluster 2')
|
| 762 |
+
>>> plt.plot(centroid[:, 0], centroid[:, 1], 'k*', label='centroids')
|
| 763 |
+
>>> plt.axis('equal')
|
| 764 |
+
>>> plt.legend(shadow=True)
|
| 765 |
+
>>> plt.show()
|
| 766 |
+
|
| 767 |
+
"""
|
| 768 |
+
if int(iter) < 1:
|
| 769 |
+
raise ValueError(f"Invalid iter ({iter}), must be a positive integer.")
|
| 770 |
+
try:
|
| 771 |
+
miss_meth = _valid_miss_meth[missing]
|
| 772 |
+
except KeyError as e:
|
| 773 |
+
raise ValueError(f"Unknown missing method {missing!r}") from e
|
| 774 |
+
|
| 775 |
+
if isinstance(k, int):
|
| 776 |
+
xp = array_namespace(data)
|
| 777 |
+
else:
|
| 778 |
+
xp = array_namespace(data, k)
|
| 779 |
+
data = _asarray(data, xp=xp, check_finite=check_finite)
|
| 780 |
+
code_book = xp_copy(k, xp=xp)
|
| 781 |
+
if data.ndim == 1:
|
| 782 |
+
d = 1
|
| 783 |
+
elif data.ndim == 2:
|
| 784 |
+
d = data.shape[1]
|
| 785 |
+
else:
|
| 786 |
+
raise ValueError("Input of rank > 2 is not supported.")
|
| 787 |
+
|
| 788 |
+
if xp_size(data) < 1 or xp_size(code_book) < 1:
|
| 789 |
+
raise ValueError("Empty input is not supported.")
|
| 790 |
+
|
| 791 |
+
# If k is not a single value, it should be compatible with data's shape
|
| 792 |
+
if minit == 'matrix' or xp_size(code_book) > 1:
|
| 793 |
+
if data.ndim != code_book.ndim:
|
| 794 |
+
raise ValueError("k array doesn't match data rank")
|
| 795 |
+
nc = code_book.shape[0]
|
| 796 |
+
if data.ndim > 1 and code_book.shape[1] != d:
|
| 797 |
+
raise ValueError("k array doesn't match data dimension")
|
| 798 |
+
else:
|
| 799 |
+
nc = int(code_book)
|
| 800 |
+
|
| 801 |
+
if nc < 1:
|
| 802 |
+
raise ValueError("Cannot ask kmeans2 for %d clusters"
|
| 803 |
+
" (k was %s)" % (nc, code_book))
|
| 804 |
+
elif nc != code_book:
|
| 805 |
+
warnings.warn("k was not an integer, was converted.", stacklevel=2)
|
| 806 |
+
|
| 807 |
+
try:
|
| 808 |
+
init_meth = _valid_init_meth[minit]
|
| 809 |
+
except KeyError as e:
|
| 810 |
+
raise ValueError(f"Unknown init method {minit!r}") from e
|
| 811 |
+
else:
|
| 812 |
+
rng = check_random_state(rng)
|
| 813 |
+
code_book = init_meth(data, code_book, rng, xp)
|
| 814 |
+
|
| 815 |
+
data = np.asarray(data)
|
| 816 |
+
code_book = np.asarray(code_book)
|
| 817 |
+
for i in range(iter):
|
| 818 |
+
# Compute the nearest neighbor for each obs using the current code book
|
| 819 |
+
label = vq(data, code_book, check_finite=check_finite)[0]
|
| 820 |
+
# Update the code book by computing centroids
|
| 821 |
+
new_code_book, has_members = _vq.update_cluster_means(data, label, nc)
|
| 822 |
+
if not has_members.all():
|
| 823 |
+
miss_meth()
|
| 824 |
+
# Set the empty clusters to their previous positions
|
| 825 |
+
new_code_book[~has_members] = code_book[~has_members]
|
| 826 |
+
code_book = new_code_book
|
| 827 |
+
|
| 828 |
+
return xp.asarray(code_book), xp.asarray(label)
|
python_embeded/Lib/site-packages/scipy/constants/__init__.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
==================================
|
| 3 |
+
Constants (:mod:`scipy.constants`)
|
| 4 |
+
==================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.constants
|
| 7 |
+
|
| 8 |
+
Physical and mathematical constants and units.
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
Mathematical constants
|
| 12 |
+
======================
|
| 13 |
+
|
| 14 |
+
================ =================================================================
|
| 15 |
+
``pi`` Pi
|
| 16 |
+
``golden`` Golden ratio
|
| 17 |
+
``golden_ratio`` Golden ratio
|
| 18 |
+
================ =================================================================
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
Physical constants
|
| 22 |
+
==================
|
| 23 |
+
The following physical constants are available as attributes of `scipy.constants`.
|
| 24 |
+
All units are `SI <https://en.wikipedia.org/wiki/International_System_of_Units>`_.
|
| 25 |
+
|
| 26 |
+
=========================== ================================================================ ===============
|
| 27 |
+
Attribute Quantity Units
|
| 28 |
+
=========================== ================================================================ ===============
|
| 29 |
+
``c`` speed of light in vacuum m s^-1
|
| 30 |
+
``speed_of_light`` speed of light in vacuum m s^-1
|
| 31 |
+
``mu_0`` the magnetic constant :math:`\mu_0` N A^-2
|
| 32 |
+
``epsilon_0`` the electric constant (vacuum permittivity), :math:`\epsilon_0` F m^-1
|
| 33 |
+
``h`` the Planck constant :math:`h` J Hz^-1
|
| 34 |
+
``Planck`` the Planck constant :math:`h` J Hz^-1
|
| 35 |
+
``hbar`` the reduced Planck constant, :math:`\hbar = h/(2\pi)` J s
|
| 36 |
+
``G`` Newtonian constant of gravitation m^3 kg^-1 s^-2
|
| 37 |
+
``gravitational_constant`` Newtonian constant of gravitation m^3 kg^-1 s^-2
|
| 38 |
+
``g`` standard acceleration of gravity m s^-2
|
| 39 |
+
``e`` elementary charge C
|
| 40 |
+
``elementary_charge`` elementary charge C
|
| 41 |
+
``R`` molar gas constant J mol^-1 K^-1
|
| 42 |
+
``gas_constant`` molar gas constant J mol^-1 K^-1
|
| 43 |
+
``alpha`` fine-structure constant (unitless)
|
| 44 |
+
``fine_structure`` fine-structure constant (unitless)
|
| 45 |
+
``N_A`` Avogadro constant mol^-1
|
| 46 |
+
``Avogadro`` Avogadro constant mol^-1
|
| 47 |
+
``k`` Boltzmann constant J K^-1
|
| 48 |
+
``Boltzmann`` Boltzmann constant J K^-1
|
| 49 |
+
``sigma`` Stefan-Boltzmann constant :math:`\sigma` W m^-2 K^-4
|
| 50 |
+
``Stefan_Boltzmann`` Stefan-Boltzmann constant :math:`\sigma` W m^-2 K^-4
|
| 51 |
+
``Wien`` Wien wavelength displacement law constant m K
|
| 52 |
+
``Rydberg`` Rydberg constant m^-1
|
| 53 |
+
``m_e`` electron mass kg
|
| 54 |
+
``electron_mass`` electron mass kg
|
| 55 |
+
``m_p`` proton mass kg
|
| 56 |
+
``proton_mass`` proton mass kg
|
| 57 |
+
``m_n`` neutron mass kg
|
| 58 |
+
``neutron_mass`` neutron mass kg
|
| 59 |
+
=========================== ================================================================ ===============
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
Constants database
|
| 63 |
+
------------------
|
| 64 |
+
|
| 65 |
+
In addition to the above variables, :mod:`scipy.constants` also contains the
|
| 66 |
+
2022 CODATA recommended values [CODATA2022]_ database containing more physical
|
| 67 |
+
constants.
|
| 68 |
+
|
| 69 |
+
.. autosummary::
|
| 70 |
+
:toctree: generated/
|
| 71 |
+
|
| 72 |
+
value -- Value in physical_constants indexed by key
|
| 73 |
+
unit -- Unit in physical_constants indexed by key
|
| 74 |
+
precision -- Relative precision in physical_constants indexed by key
|
| 75 |
+
find -- Return list of physical_constant keys with a given string
|
| 76 |
+
ConstantWarning -- Constant sought not in newest CODATA data set
|
| 77 |
+
|
| 78 |
+
.. data:: physical_constants
|
| 79 |
+
|
| 80 |
+
Dictionary of physical constants, of the format
|
| 81 |
+
``physical_constants[name] = (value, unit, uncertainty)``.
|
| 82 |
+
The CODATA database uses ellipses to indicate that a value is defined
|
| 83 |
+
(exactly) in terms of others but cannot be represented exactly with the
|
| 84 |
+
allocated number of digits. In these cases, SciPy calculates the derived
|
| 85 |
+
value and reports it to the full precision of a Python ``float``. Although
|
| 86 |
+
``physical_constants`` lists the uncertainty as ``0.0`` to indicate that
|
| 87 |
+
the CODATA value is exact, the value in ``physical_constants`` is still
|
| 88 |
+
subject to the truncation error inherent in double-precision representation.
|
| 89 |
+
|
| 90 |
+
Available constants:
|
| 91 |
+
|
| 92 |
+
====================================================================== ====
|
| 93 |
+
%(constant_names)s
|
| 94 |
+
====================================================================== ====
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
Units
|
| 98 |
+
=====
|
| 99 |
+
|
| 100 |
+
SI prefixes
|
| 101 |
+
-----------
|
| 102 |
+
|
| 103 |
+
============ =================================================================
|
| 104 |
+
``quetta`` :math:`10^{30}`
|
| 105 |
+
``ronna`` :math:`10^{27}`
|
| 106 |
+
``yotta`` :math:`10^{24}`
|
| 107 |
+
``zetta`` :math:`10^{21}`
|
| 108 |
+
``exa`` :math:`10^{18}`
|
| 109 |
+
``peta`` :math:`10^{15}`
|
| 110 |
+
``tera`` :math:`10^{12}`
|
| 111 |
+
``giga`` :math:`10^{9}`
|
| 112 |
+
``mega`` :math:`10^{6}`
|
| 113 |
+
``kilo`` :math:`10^{3}`
|
| 114 |
+
``hecto`` :math:`10^{2}`
|
| 115 |
+
``deka`` :math:`10^{1}`
|
| 116 |
+
``deci`` :math:`10^{-1}`
|
| 117 |
+
``centi`` :math:`10^{-2}`
|
| 118 |
+
``milli`` :math:`10^{-3}`
|
| 119 |
+
``micro`` :math:`10^{-6}`
|
| 120 |
+
``nano`` :math:`10^{-9}`
|
| 121 |
+
``pico`` :math:`10^{-12}`
|
| 122 |
+
``femto`` :math:`10^{-15}`
|
| 123 |
+
``atto`` :math:`10^{-18}`
|
| 124 |
+
``zepto`` :math:`10^{-21}`
|
| 125 |
+
``yocto`` :math:`10^{-24}`
|
| 126 |
+
``ronto`` :math:`10^{-27}`
|
| 127 |
+
``quecto`` :math:`10^{-30}`
|
| 128 |
+
============ =================================================================
|
| 129 |
+
|
| 130 |
+
Binary prefixes
|
| 131 |
+
---------------
|
| 132 |
+
|
| 133 |
+
============ =================================================================
|
| 134 |
+
``kibi`` :math:`2^{10}`
|
| 135 |
+
``mebi`` :math:`2^{20}`
|
| 136 |
+
``gibi`` :math:`2^{30}`
|
| 137 |
+
``tebi`` :math:`2^{40}`
|
| 138 |
+
``pebi`` :math:`2^{50}`
|
| 139 |
+
``exbi`` :math:`2^{60}`
|
| 140 |
+
``zebi`` :math:`2^{70}`
|
| 141 |
+
``yobi`` :math:`2^{80}`
|
| 142 |
+
============ =================================================================
|
| 143 |
+
|
| 144 |
+
Mass
|
| 145 |
+
----
|
| 146 |
+
|
| 147 |
+
================= ============================================================
|
| 148 |
+
``gram`` :math:`10^{-3}` kg
|
| 149 |
+
``metric_ton`` :math:`10^{3}` kg
|
| 150 |
+
``grain`` one grain in kg
|
| 151 |
+
``lb`` one pound (avoirdupous) in kg
|
| 152 |
+
``pound`` one pound (avoirdupous) in kg
|
| 153 |
+
``blob`` one inch version of a slug in kg (added in 1.0.0)
|
| 154 |
+
``slinch`` one inch version of a slug in kg (added in 1.0.0)
|
| 155 |
+
``slug`` one slug in kg (added in 1.0.0)
|
| 156 |
+
``oz`` one ounce in kg
|
| 157 |
+
``ounce`` one ounce in kg
|
| 158 |
+
``stone`` one stone in kg
|
| 159 |
+
``grain`` one grain in kg
|
| 160 |
+
``long_ton`` one long ton in kg
|
| 161 |
+
``short_ton`` one short ton in kg
|
| 162 |
+
``troy_ounce`` one Troy ounce in kg
|
| 163 |
+
``troy_pound`` one Troy pound in kg
|
| 164 |
+
``carat`` one carat in kg
|
| 165 |
+
``m_u`` atomic mass constant (in kg)
|
| 166 |
+
``u`` atomic mass constant (in kg)
|
| 167 |
+
``atomic_mass`` atomic mass constant (in kg)
|
| 168 |
+
================= ============================================================
|
| 169 |
+
|
| 170 |
+
Angle
|
| 171 |
+
-----
|
| 172 |
+
|
| 173 |
+
================= ============================================================
|
| 174 |
+
``degree`` degree in radians
|
| 175 |
+
``arcmin`` arc minute in radians
|
| 176 |
+
``arcminute`` arc minute in radians
|
| 177 |
+
``arcsec`` arc second in radians
|
| 178 |
+
``arcsecond`` arc second in radians
|
| 179 |
+
================= ============================================================
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
Time
|
| 183 |
+
----
|
| 184 |
+
|
| 185 |
+
================= ============================================================
|
| 186 |
+
``minute`` one minute in seconds
|
| 187 |
+
``hour`` one hour in seconds
|
| 188 |
+
``day`` one day in seconds
|
| 189 |
+
``week`` one week in seconds
|
| 190 |
+
``year`` one year (365 days) in seconds
|
| 191 |
+
``Julian_year`` one Julian year (365.25 days) in seconds
|
| 192 |
+
================= ============================================================
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
Length
|
| 196 |
+
------
|
| 197 |
+
|
| 198 |
+
===================== ============================================================
|
| 199 |
+
``inch`` one inch in meters
|
| 200 |
+
``foot`` one foot in meters
|
| 201 |
+
``yard`` one yard in meters
|
| 202 |
+
``mile`` one mile in meters
|
| 203 |
+
``mil`` one mil in meters
|
| 204 |
+
``pt`` one point in meters
|
| 205 |
+
``point`` one point in meters
|
| 206 |
+
``survey_foot`` one survey foot in meters
|
| 207 |
+
``survey_mile`` one survey mile in meters
|
| 208 |
+
``nautical_mile`` one nautical mile in meters
|
| 209 |
+
``fermi`` one Fermi in meters
|
| 210 |
+
``angstrom`` one Angstrom in meters
|
| 211 |
+
``micron`` one micron in meters
|
| 212 |
+
``au`` one astronomical unit in meters
|
| 213 |
+
``astronomical_unit`` one astronomical unit in meters
|
| 214 |
+
``light_year`` one light year in meters
|
| 215 |
+
``parsec`` one parsec in meters
|
| 216 |
+
===================== ============================================================
|
| 217 |
+
|
| 218 |
+
Pressure
|
| 219 |
+
--------
|
| 220 |
+
|
| 221 |
+
================= ============================================================
|
| 222 |
+
``atm`` standard atmosphere in pascals
|
| 223 |
+
``atmosphere`` standard atmosphere in pascals
|
| 224 |
+
``bar`` one bar in pascals
|
| 225 |
+
``torr`` one torr (mmHg) in pascals
|
| 226 |
+
``mmHg`` one torr (mmHg) in pascals
|
| 227 |
+
``psi`` one psi in pascals
|
| 228 |
+
================= ============================================================
|
| 229 |
+
|
| 230 |
+
Area
|
| 231 |
+
----
|
| 232 |
+
|
| 233 |
+
================= ============================================================
|
| 234 |
+
``hectare`` one hectare in square meters
|
| 235 |
+
``acre`` one acre in square meters
|
| 236 |
+
================= ============================================================
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
Volume
|
| 240 |
+
------
|
| 241 |
+
|
| 242 |
+
=================== ========================================================
|
| 243 |
+
``liter`` one liter in cubic meters
|
| 244 |
+
``litre`` one liter in cubic meters
|
| 245 |
+
``gallon`` one gallon (US) in cubic meters
|
| 246 |
+
``gallon_US`` one gallon (US) in cubic meters
|
| 247 |
+
``gallon_imp`` one gallon (UK) in cubic meters
|
| 248 |
+
``fluid_ounce`` one fluid ounce (US) in cubic meters
|
| 249 |
+
``fluid_ounce_US`` one fluid ounce (US) in cubic meters
|
| 250 |
+
``fluid_ounce_imp`` one fluid ounce (UK) in cubic meters
|
| 251 |
+
``bbl`` one barrel in cubic meters
|
| 252 |
+
``barrel`` one barrel in cubic meters
|
| 253 |
+
=================== ========================================================
|
| 254 |
+
|
| 255 |
+
Speed
|
| 256 |
+
-----
|
| 257 |
+
|
| 258 |
+
================== ==========================================================
|
| 259 |
+
``kmh`` kilometers per hour in meters per second
|
| 260 |
+
``mph`` miles per hour in meters per second
|
| 261 |
+
``mach`` one Mach (approx., at 15 C, 1 atm) in meters per second
|
| 262 |
+
``speed_of_sound`` one Mach (approx., at 15 C, 1 atm) in meters per second
|
| 263 |
+
``knot`` one knot in meters per second
|
| 264 |
+
================== ==========================================================
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
Temperature
|
| 268 |
+
-----------
|
| 269 |
+
|
| 270 |
+
===================== =======================================================
|
| 271 |
+
``zero_Celsius`` zero of Celsius scale in Kelvin
|
| 272 |
+
``degree_Fahrenheit`` one Fahrenheit (only differences) in Kelvins
|
| 273 |
+
===================== =======================================================
|
| 274 |
+
|
| 275 |
+
.. autosummary::
|
| 276 |
+
:toctree: generated/
|
| 277 |
+
|
| 278 |
+
convert_temperature
|
| 279 |
+
|
| 280 |
+
Energy
|
| 281 |
+
------
|
| 282 |
+
|
| 283 |
+
==================== =======================================================
|
| 284 |
+
``eV`` one electron volt in Joules
|
| 285 |
+
``electron_volt`` one electron volt in Joules
|
| 286 |
+
``calorie`` one calorie (thermochemical) in Joules
|
| 287 |
+
``calorie_th`` one calorie (thermochemical) in Joules
|
| 288 |
+
``calorie_IT`` one calorie (International Steam Table calorie, 1956) in Joules
|
| 289 |
+
``erg`` one erg in Joules
|
| 290 |
+
``Btu`` one British thermal unit (International Steam Table) in Joules
|
| 291 |
+
``Btu_IT`` one British thermal unit (International Steam Table) in Joules
|
| 292 |
+
``Btu_th`` one British thermal unit (thermochemical) in Joules
|
| 293 |
+
``ton_TNT`` one ton of TNT in Joules
|
| 294 |
+
==================== =======================================================
|
| 295 |
+
|
| 296 |
+
Power
|
| 297 |
+
-----
|
| 298 |
+
|
| 299 |
+
==================== =======================================================
|
| 300 |
+
``hp`` one horsepower in watts
|
| 301 |
+
``horsepower`` one horsepower in watts
|
| 302 |
+
==================== =======================================================
|
| 303 |
+
|
| 304 |
+
Force
|
| 305 |
+
-----
|
| 306 |
+
|
| 307 |
+
==================== =======================================================
|
| 308 |
+
``dyn`` one dyne in newtons
|
| 309 |
+
``dyne`` one dyne in newtons
|
| 310 |
+
``lbf`` one pound force in newtons
|
| 311 |
+
``pound_force`` one pound force in newtons
|
| 312 |
+
``kgf`` one kilogram force in newtons
|
| 313 |
+
``kilogram_force`` one kilogram force in newtons
|
| 314 |
+
==================== =======================================================
|
| 315 |
+
|
| 316 |
+
Optics
|
| 317 |
+
------
|
| 318 |
+
|
| 319 |
+
.. autosummary::
|
| 320 |
+
:toctree: generated/
|
| 321 |
+
|
| 322 |
+
lambda2nu
|
| 323 |
+
nu2lambda
|
| 324 |
+
|
| 325 |
+
References
|
| 326 |
+
==========
|
| 327 |
+
|
| 328 |
+
.. [CODATA2022] CODATA Recommended Values of the Fundamental
|
| 329 |
+
Physical Constants 2022.
|
| 330 |
+
|
| 331 |
+
https://physics.nist.gov/cuu/Constants/
|
| 332 |
+
|
| 333 |
+
""" # noqa: E501
|
| 334 |
+
# Modules contributed by BasSw (wegwerp@gmail.com)
|
| 335 |
+
from ._codata import *
|
| 336 |
+
from ._constants import *
|
| 337 |
+
from ._codata import _obsolete_constants, physical_constants
|
| 338 |
+
|
| 339 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
| 340 |
+
from . import codata, constants
|
| 341 |
+
|
| 342 |
+
_constant_names_list = [(_k.lower(), _k, _v)
|
| 343 |
+
for _k, _v in physical_constants.items()
|
| 344 |
+
if _k not in _obsolete_constants]
|
| 345 |
+
_constant_names = "\n".join(["``{}``{} {} {}".format(_x[1], " "*(66-len(_x[1])),
|
| 346 |
+
_x[2][0], _x[2][1])
|
| 347 |
+
for _x in sorted(_constant_names_list)])
|
| 348 |
+
if __doc__:
|
| 349 |
+
__doc__ = __doc__ % dict(constant_names=_constant_names)
|
| 350 |
+
|
| 351 |
+
del _constant_names
|
| 352 |
+
del _constant_names_list
|
| 353 |
+
|
| 354 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
| 355 |
+
|
| 356 |
+
from scipy._lib._testutils import PytestTester
|
| 357 |
+
test = PytestTester(__name__)
|
| 358 |
+
del PytestTester
|
python_embeded/Lib/site-packages/scipy/constants/_codata.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
python_embeded/Lib/site-packages/scipy/constants/_constants.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Collection of physical constants and conversion factors.
|
| 3 |
+
|
| 4 |
+
Most constants are in SI units, so you can do
|
| 5 |
+
print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
|
| 6 |
+
|
| 7 |
+
The list is not meant to be comprehensive, but just convenient for everyday use.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import math as _math
|
| 11 |
+
from typing import TYPE_CHECKING, Any
|
| 12 |
+
|
| 13 |
+
from ._codata import value as _cd
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
import numpy.typing as npt
|
| 17 |
+
|
| 18 |
+
from scipy._lib._array_api import array_namespace, _asarray
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
BasSw 2006
|
| 23 |
+
physical constants: imported from CODATA
|
| 24 |
+
unit conversion: see e.g., NIST special publication 811
|
| 25 |
+
Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
|
| 26 |
+
Some constants exist in a few variants, which are marked with suffixes.
|
| 27 |
+
The ones without any suffix should be the most common ones.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
|
| 32 |
+
'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
|
| 33 |
+
'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
|
| 34 |
+
'angstrom', 'arcmin', 'arcminute', 'arcsec',
|
| 35 |
+
'arcsecond', 'astronomical_unit', 'atm',
|
| 36 |
+
'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
|
| 37 |
+
'barrel', 'bbl', 'blob', 'c', 'calorie',
|
| 38 |
+
'calorie_IT', 'calorie_th', 'carat', 'centi',
|
| 39 |
+
'convert_temperature', 'day', 'deci', 'degree',
|
| 40 |
+
'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
|
| 41 |
+
'eV', 'electron_mass', 'electron_volt',
|
| 42 |
+
'elementary_charge', 'epsilon_0', 'erg',
|
| 43 |
+
'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
|
| 44 |
+
'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
|
| 45 |
+
'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
|
| 46 |
+
'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
|
| 47 |
+
'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
|
| 48 |
+
'hectare', 'hecto', 'horsepower', 'hour', 'hp',
|
| 49 |
+
'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
|
| 50 |
+
'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
|
| 51 |
+
'light_year', 'liter', 'litre', 'long_ton', 'm_e',
|
| 52 |
+
'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
|
| 53 |
+
'metric_ton', 'micro', 'micron', 'mil', 'mile',
|
| 54 |
+
'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
|
| 55 |
+
'nautical_mile', 'neutron_mass', 'nu2lambda',
|
| 56 |
+
'ounce', 'oz', 'parsec', 'pebi', 'peta',
|
| 57 |
+
'pi', 'pico', 'point', 'pound', 'pound_force',
|
| 58 |
+
'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
|
| 59 |
+
'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
|
| 60 |
+
'speed_of_sound', 'stone', 'survey_foot',
|
| 61 |
+
'survey_mile', 'tebi', 'tera', 'ton_TNT',
|
| 62 |
+
'torr', 'troy_ounce', 'troy_pound', 'u',
|
| 63 |
+
'week', 'yard', 'year', 'yobi', 'yocto',
|
| 64 |
+
'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# mathematical constants
|
| 69 |
+
pi = _math.pi
|
| 70 |
+
golden = golden_ratio = (1 + _math.sqrt(5)) / 2
|
| 71 |
+
|
| 72 |
+
# SI prefixes
|
| 73 |
+
quetta = 1e30
|
| 74 |
+
ronna = 1e27
|
| 75 |
+
yotta = 1e24
|
| 76 |
+
zetta = 1e21
|
| 77 |
+
exa = 1e18
|
| 78 |
+
peta = 1e15
|
| 79 |
+
tera = 1e12
|
| 80 |
+
giga = 1e9
|
| 81 |
+
mega = 1e6
|
| 82 |
+
kilo = 1e3
|
| 83 |
+
hecto = 1e2
|
| 84 |
+
deka = 1e1
|
| 85 |
+
deci = 1e-1
|
| 86 |
+
centi = 1e-2
|
| 87 |
+
milli = 1e-3
|
| 88 |
+
micro = 1e-6
|
| 89 |
+
nano = 1e-9
|
| 90 |
+
pico = 1e-12
|
| 91 |
+
femto = 1e-15
|
| 92 |
+
atto = 1e-18
|
| 93 |
+
zepto = 1e-21
|
| 94 |
+
yocto = 1e-24
|
| 95 |
+
ronto = 1e-27
|
| 96 |
+
quecto = 1e-30
|
| 97 |
+
|
| 98 |
+
# binary prefixes
|
| 99 |
+
kibi = 2**10
|
| 100 |
+
mebi = 2**20
|
| 101 |
+
gibi = 2**30
|
| 102 |
+
tebi = 2**40
|
| 103 |
+
pebi = 2**50
|
| 104 |
+
exbi = 2**60
|
| 105 |
+
zebi = 2**70
|
| 106 |
+
yobi = 2**80
|
| 107 |
+
|
| 108 |
+
# physical constants
|
| 109 |
+
c = speed_of_light = _cd('speed of light in vacuum')
|
| 110 |
+
mu_0 = _cd('vacuum mag. permeability')
|
| 111 |
+
epsilon_0 = _cd('vacuum electric permittivity')
|
| 112 |
+
h = Planck = _cd('Planck constant')
|
| 113 |
+
hbar = _cd('reduced Planck constant')
|
| 114 |
+
G = gravitational_constant = _cd('Newtonian constant of gravitation')
|
| 115 |
+
g = _cd('standard acceleration of gravity')
|
| 116 |
+
e = elementary_charge = _cd('elementary charge')
|
| 117 |
+
R = gas_constant = _cd('molar gas constant')
|
| 118 |
+
alpha = fine_structure = _cd('fine-structure constant')
|
| 119 |
+
N_A = Avogadro = _cd('Avogadro constant')
|
| 120 |
+
k = Boltzmann = _cd('Boltzmann constant')
|
| 121 |
+
sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
|
| 122 |
+
Wien = _cd('Wien wavelength displacement law constant')
|
| 123 |
+
Rydberg = _cd('Rydberg constant')
|
| 124 |
+
|
| 125 |
+
# mass in kg
|
| 126 |
+
gram = 1e-3
|
| 127 |
+
metric_ton = 1e3
|
| 128 |
+
grain = 64.79891e-6
|
| 129 |
+
lb = pound = 7000 * grain # avoirdupois
|
| 130 |
+
blob = slinch = pound * g / 0.0254 # lbf*s**2/in (added in 1.0.0)
|
| 131 |
+
slug = blob / 12 # lbf*s**2/foot (added in 1.0.0)
|
| 132 |
+
oz = ounce = pound / 16
|
| 133 |
+
stone = 14 * pound
|
| 134 |
+
long_ton = 2240 * pound
|
| 135 |
+
short_ton = 2000 * pound
|
| 136 |
+
|
| 137 |
+
troy_ounce = 480 * grain # only for metals / gems
|
| 138 |
+
troy_pound = 12 * troy_ounce
|
| 139 |
+
carat = 200e-6
|
| 140 |
+
|
| 141 |
+
m_e = electron_mass = _cd('electron mass')
|
| 142 |
+
m_p = proton_mass = _cd('proton mass')
|
| 143 |
+
m_n = neutron_mass = _cd('neutron mass')
|
| 144 |
+
m_u = u = atomic_mass = _cd('atomic mass constant')
|
| 145 |
+
|
| 146 |
+
# angle in rad
|
| 147 |
+
degree = pi / 180
|
| 148 |
+
arcmin = arcminute = degree / 60
|
| 149 |
+
arcsec = arcsecond = arcmin / 60
|
| 150 |
+
|
| 151 |
+
# time in second
|
| 152 |
+
minute = 60.0
|
| 153 |
+
hour = 60 * minute
|
| 154 |
+
day = 24 * hour
|
| 155 |
+
week = 7 * day
|
| 156 |
+
year = 365 * day
|
| 157 |
+
Julian_year = 365.25 * day
|
| 158 |
+
|
| 159 |
+
# length in meter
|
| 160 |
+
inch = 0.0254
|
| 161 |
+
foot = 12 * inch
|
| 162 |
+
yard = 3 * foot
|
| 163 |
+
mile = 1760 * yard
|
| 164 |
+
mil = inch / 1000
|
| 165 |
+
pt = point = inch / 72 # typography
|
| 166 |
+
survey_foot = 1200.0 / 3937
|
| 167 |
+
survey_mile = 5280 * survey_foot
|
| 168 |
+
nautical_mile = 1852.0
|
| 169 |
+
fermi = 1e-15
|
| 170 |
+
angstrom = 1e-10
|
| 171 |
+
micron = 1e-6
|
| 172 |
+
au = astronomical_unit = 149597870700.0
|
| 173 |
+
light_year = Julian_year * c
|
| 174 |
+
parsec = au / arcsec
|
| 175 |
+
|
| 176 |
+
# pressure in pascal
|
| 177 |
+
atm = atmosphere = _cd('standard atmosphere')
|
| 178 |
+
bar = 1e5
|
| 179 |
+
torr = mmHg = atm / 760
|
| 180 |
+
psi = pound * g / (inch * inch)
|
| 181 |
+
|
| 182 |
+
# area in meter**2
|
| 183 |
+
hectare = 1e4
|
| 184 |
+
acre = 43560 * foot**2
|
| 185 |
+
|
| 186 |
+
# volume in meter**3
|
| 187 |
+
litre = liter = 1e-3
|
| 188 |
+
gallon = gallon_US = 231 * inch**3 # US
|
| 189 |
+
# pint = gallon_US / 8
|
| 190 |
+
fluid_ounce = fluid_ounce_US = gallon_US / 128
|
| 191 |
+
bbl = barrel = 42 * gallon_US # for oil
|
| 192 |
+
|
| 193 |
+
gallon_imp = 4.54609e-3 # UK
|
| 194 |
+
fluid_ounce_imp = gallon_imp / 160
|
| 195 |
+
|
| 196 |
+
# speed in meter per second
|
| 197 |
+
kmh = 1e3 / hour
|
| 198 |
+
mph = mile / hour
|
| 199 |
+
# approx value of mach at 15 degrees in 1 atm. Is this a common value?
|
| 200 |
+
mach = speed_of_sound = 340.5
|
| 201 |
+
knot = nautical_mile / hour
|
| 202 |
+
|
| 203 |
+
# temperature in kelvin
|
| 204 |
+
zero_Celsius = 273.15
|
| 205 |
+
degree_Fahrenheit = 1/1.8 # only for differences
|
| 206 |
+
|
| 207 |
+
# energy in joule
|
| 208 |
+
eV = electron_volt = elementary_charge # * 1 Volt
|
| 209 |
+
calorie = calorie_th = 4.184
|
| 210 |
+
calorie_IT = 4.1868
|
| 211 |
+
erg = 1e-7
|
| 212 |
+
Btu_th = pound * degree_Fahrenheit * calorie_th / gram
|
| 213 |
+
Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
|
| 214 |
+
ton_TNT = 1e9 * calorie_th
|
| 215 |
+
# Wh = watt_hour
|
| 216 |
+
|
| 217 |
+
# power in watt
|
| 218 |
+
hp = horsepower = 550 * foot * pound * g
|
| 219 |
+
|
| 220 |
+
# force in newton
|
| 221 |
+
dyn = dyne = 1e-5
|
| 222 |
+
lbf = pound_force = pound * g
|
| 223 |
+
kgf = kilogram_force = g # * 1 kg
|
| 224 |
+
|
| 225 |
+
# functions for conversions that are not linear
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def convert_temperature(
|
| 229 |
+
val: "npt.ArrayLike",
|
| 230 |
+
old_scale: str,
|
| 231 |
+
new_scale: str,
|
| 232 |
+
) -> Any:
|
| 233 |
+
"""
|
| 234 |
+
Convert from a temperature scale to another one among Celsius, Kelvin,
|
| 235 |
+
Fahrenheit, and Rankine scales.
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
----------
|
| 239 |
+
val : array_like
|
| 240 |
+
Value(s) of the temperature(s) to be converted expressed in the
|
| 241 |
+
original scale.
|
| 242 |
+
old_scale : str
|
| 243 |
+
Specifies as a string the original scale from which the temperature
|
| 244 |
+
value(s) will be converted. Supported scales are Celsius ('Celsius',
|
| 245 |
+
'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
|
| 246 |
+
Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
|
| 247 |
+
('Rankine', 'rankine', 'R', 'r').
|
| 248 |
+
new_scale : str
|
| 249 |
+
Specifies as a string the new scale to which the temperature
|
| 250 |
+
value(s) will be converted. Supported scales are Celsius ('Celsius',
|
| 251 |
+
'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
|
| 252 |
+
Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
|
| 253 |
+
('Rankine', 'rankine', 'R', 'r').
|
| 254 |
+
|
| 255 |
+
Returns
|
| 256 |
+
-------
|
| 257 |
+
res : float or array of floats
|
| 258 |
+
Value(s) of the converted temperature(s) expressed in the new scale.
|
| 259 |
+
|
| 260 |
+
Notes
|
| 261 |
+
-----
|
| 262 |
+
.. versionadded:: 0.18.0
|
| 263 |
+
|
| 264 |
+
Examples
|
| 265 |
+
--------
|
| 266 |
+
>>> from scipy.constants import convert_temperature
|
| 267 |
+
>>> import numpy as np
|
| 268 |
+
>>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
|
| 269 |
+
array([ 233.15, 313.15])
|
| 270 |
+
|
| 271 |
+
"""
|
| 272 |
+
xp = array_namespace(val)
|
| 273 |
+
_val = _asarray(val, xp=xp, subok=True)
|
| 274 |
+
# Convert from `old_scale` to Kelvin
|
| 275 |
+
if old_scale.lower() in ['celsius', 'c']:
|
| 276 |
+
tempo = _val + zero_Celsius
|
| 277 |
+
elif old_scale.lower() in ['kelvin', 'k']:
|
| 278 |
+
tempo = _val
|
| 279 |
+
elif old_scale.lower() in ['fahrenheit', 'f']:
|
| 280 |
+
tempo = (_val - 32) * 5 / 9 + zero_Celsius
|
| 281 |
+
elif old_scale.lower() in ['rankine', 'r']:
|
| 282 |
+
tempo = _val * 5 / 9
|
| 283 |
+
else:
|
| 284 |
+
raise NotImplementedError(f"{old_scale=} is unsupported: supported scales "
|
| 285 |
+
"are Celsius, Kelvin, Fahrenheit, and "
|
| 286 |
+
"Rankine")
|
| 287 |
+
# and from Kelvin to `new_scale`.
|
| 288 |
+
if new_scale.lower() in ['celsius', 'c']:
|
| 289 |
+
res = tempo - zero_Celsius
|
| 290 |
+
elif new_scale.lower() in ['kelvin', 'k']:
|
| 291 |
+
res = tempo
|
| 292 |
+
elif new_scale.lower() in ['fahrenheit', 'f']:
|
| 293 |
+
res = (tempo - zero_Celsius) * 9 / 5 + 32
|
| 294 |
+
elif new_scale.lower() in ['rankine', 'r']:
|
| 295 |
+
res = tempo * 9 / 5
|
| 296 |
+
else:
|
| 297 |
+
raise NotImplementedError(f"{new_scale=} is unsupported: supported "
|
| 298 |
+
"scales are 'Celsius', 'Kelvin', "
|
| 299 |
+
"'Fahrenheit', and 'Rankine'")
|
| 300 |
+
|
| 301 |
+
return res
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
# optics
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def lambda2nu(lambda_: "npt.ArrayLike") -> Any:
|
| 308 |
+
"""
|
| 309 |
+
Convert wavelength to optical frequency
|
| 310 |
+
|
| 311 |
+
Parameters
|
| 312 |
+
----------
|
| 313 |
+
lambda_ : array_like
|
| 314 |
+
Wavelength(s) to be converted.
|
| 315 |
+
|
| 316 |
+
Returns
|
| 317 |
+
-------
|
| 318 |
+
nu : float or array of floats
|
| 319 |
+
Equivalent optical frequency.
|
| 320 |
+
|
| 321 |
+
Notes
|
| 322 |
+
-----
|
| 323 |
+
Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
|
| 324 |
+
(vacuum) speed of light in meters/second.
|
| 325 |
+
|
| 326 |
+
Examples
|
| 327 |
+
--------
|
| 328 |
+
>>> from scipy.constants import lambda2nu, speed_of_light
|
| 329 |
+
>>> import numpy as np
|
| 330 |
+
>>> lambda2nu(np.array((1, speed_of_light)))
|
| 331 |
+
array([ 2.99792458e+08, 1.00000000e+00])
|
| 332 |
+
|
| 333 |
+
"""
|
| 334 |
+
xp = array_namespace(lambda_)
|
| 335 |
+
return c / _asarray(lambda_, xp=xp, subok=True)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def nu2lambda(nu: "npt.ArrayLike") -> Any:
|
| 339 |
+
"""
|
| 340 |
+
Convert optical frequency to wavelength.
|
| 341 |
+
|
| 342 |
+
Parameters
|
| 343 |
+
----------
|
| 344 |
+
nu : array_like
|
| 345 |
+
Optical frequency to be converted.
|
| 346 |
+
|
| 347 |
+
Returns
|
| 348 |
+
-------
|
| 349 |
+
lambda : float or array of floats
|
| 350 |
+
Equivalent wavelength(s).
|
| 351 |
+
|
| 352 |
+
Notes
|
| 353 |
+
-----
|
| 354 |
+
Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
|
| 355 |
+
(vacuum) speed of light in meters/second.
|
| 356 |
+
|
| 357 |
+
Examples
|
| 358 |
+
--------
|
| 359 |
+
>>> from scipy.constants import nu2lambda, speed_of_light
|
| 360 |
+
>>> import numpy as np
|
| 361 |
+
>>> nu2lambda(np.array((1, speed_of_light)))
|
| 362 |
+
array([ 2.99792458e+08, 1.00000000e+00])
|
| 363 |
+
|
| 364 |
+
"""
|
| 365 |
+
xp = array_namespace(nu)
|
| 366 |
+
return c / _asarray(nu, xp=xp, subok=True)
|
python_embeded/Lib/site-packages/scipy/constants/codata.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.constants` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = [ # noqa: F822
|
| 8 |
+
'physical_constants', 'value', 'unit', 'precision', 'find',
|
| 9 |
+
'ConstantWarning', 'k', 'c',
|
| 10 |
+
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __dir__():
|
| 15 |
+
return __all__
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name):
|
| 19 |
+
return _sub_module_deprecation(sub_package="constants", module="codata",
|
| 20 |
+
private_modules=["_codata"], all=__all__,
|
| 21 |
+
attribute=name)
|
python_embeded/Lib/site-packages/scipy/constants/constants.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.constants` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
|
| 10 |
+
'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
|
| 11 |
+
'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
|
| 12 |
+
'angstrom', 'arcmin', 'arcminute', 'arcsec',
|
| 13 |
+
'arcsecond', 'astronomical_unit', 'atm',
|
| 14 |
+
'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
|
| 15 |
+
'barrel', 'bbl', 'blob', 'c', 'calorie',
|
| 16 |
+
'calorie_IT', 'calorie_th', 'carat', 'centi',
|
| 17 |
+
'convert_temperature', 'day', 'deci', 'degree',
|
| 18 |
+
'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
|
| 19 |
+
'eV', 'electron_mass', 'electron_volt',
|
| 20 |
+
'elementary_charge', 'epsilon_0', 'erg',
|
| 21 |
+
'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
|
| 22 |
+
'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
|
| 23 |
+
'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
|
| 24 |
+
'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
|
| 25 |
+
'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
|
| 26 |
+
'hectare', 'hecto', 'horsepower', 'hour', 'hp',
|
| 27 |
+
'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
|
| 28 |
+
'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
|
| 29 |
+
'light_year', 'liter', 'litre', 'long_ton', 'm_e',
|
| 30 |
+
'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
|
| 31 |
+
'metric_ton', 'micro', 'micron', 'mil', 'mile',
|
| 32 |
+
'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
|
| 33 |
+
'nautical_mile', 'neutron_mass', 'nu2lambda',
|
| 34 |
+
'ounce', 'oz', 'parsec', 'pebi', 'peta',
|
| 35 |
+
'pi', 'pico', 'point', 'pound', 'pound_force',
|
| 36 |
+
'proton_mass', 'psi', 'pt', 'short_ton',
|
| 37 |
+
'sigma', 'slinch', 'slug', 'speed_of_light',
|
| 38 |
+
'speed_of_sound', 'stone', 'survey_foot',
|
| 39 |
+
'survey_mile', 'tebi', 'tera', 'ton_TNT',
|
| 40 |
+
'torr', 'troy_ounce', 'troy_pound', 'u',
|
| 41 |
+
'week', 'yard', 'year', 'yobi', 'yocto',
|
| 42 |
+
'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def __dir__():
|
| 47 |
+
return __all__
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def __getattr__(name):
|
| 51 |
+
return _sub_module_deprecation(sub_package="constants", module="constants",
|
| 52 |
+
private_modules=["_constants"], all=__all__,
|
| 53 |
+
attribute=name)
|
python_embeded/Lib/site-packages/scipy/datasets/__init__.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
================================
|
| 3 |
+
Datasets (:mod:`scipy.datasets`)
|
| 4 |
+
================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.datasets
|
| 7 |
+
|
| 8 |
+
Dataset Methods
|
| 9 |
+
===============
|
| 10 |
+
|
| 11 |
+
.. autosummary::
|
| 12 |
+
:toctree: generated/
|
| 13 |
+
|
| 14 |
+
ascent
|
| 15 |
+
face
|
| 16 |
+
electrocardiogram
|
| 17 |
+
|
| 18 |
+
Utility Methods
|
| 19 |
+
===============
|
| 20 |
+
|
| 21 |
+
.. autosummary::
|
| 22 |
+
:toctree: generated/
|
| 23 |
+
|
| 24 |
+
download_all -- Download all the dataset files to specified path.
|
| 25 |
+
clear_cache -- Clear cached dataset directory.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
Usage of Datasets
|
| 29 |
+
=================
|
| 30 |
+
|
| 31 |
+
SciPy dataset methods can be simply called as follows: ``'<dataset-name>()'``
|
| 32 |
+
This downloads the dataset files over the network once, and saves the cache,
|
| 33 |
+
before returning a `numpy.ndarray` object representing the dataset.
|
| 34 |
+
|
| 35 |
+
Note that the return data structure and data type might be different for
|
| 36 |
+
different dataset methods. For a more detailed example on usage, please look
|
| 37 |
+
into the particular dataset method documentation above.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
How dataset retrieval and storage works
|
| 41 |
+
=======================================
|
| 42 |
+
|
| 43 |
+
SciPy dataset files are stored within individual GitHub repositories under the
|
| 44 |
+
SciPy GitHub organization, following a naming convention as
|
| 45 |
+
``'dataset-<name>'``, for example `scipy.datasets.face` files live at
|
| 46 |
+
https://github.com/scipy/dataset-face. The `scipy.datasets` submodule utilizes
|
| 47 |
+
and depends on `Pooch <https://www.fatiando.org/pooch/latest/>`_, a Python
|
| 48 |
+
package built to simplify fetching data files. Pooch uses these repos to
|
| 49 |
+
retrieve the respective dataset files when calling the dataset function.
|
| 50 |
+
|
| 51 |
+
A registry of all the datasets, essentially a mapping of filenames with their
|
| 52 |
+
SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
|
| 53 |
+
the downloads on function call. After downloading the dataset once, the files
|
| 54 |
+
are saved in the system cache directory under ``'scipy-data'``.
|
| 55 |
+
|
| 56 |
+
Dataset cache locations may vary on different platforms.
|
| 57 |
+
|
| 58 |
+
For macOS::
|
| 59 |
+
|
| 60 |
+
'~/Library/Caches/scipy-data'
|
| 61 |
+
|
| 62 |
+
For Linux and other Unix-like platforms::
|
| 63 |
+
|
| 64 |
+
'~/.cache/scipy-data' # or the value of the XDG_CACHE_HOME env var, if defined
|
| 65 |
+
|
| 66 |
+
For Windows::
|
| 67 |
+
|
| 68 |
+
'C:\\Users\\<user>\\AppData\\Local\\<AppAuthor>\\scipy-data\\Cache'
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
In environments with constrained network connectivity for various security
|
| 72 |
+
reasons or on systems without continuous internet connections, one may manually
|
| 73 |
+
load the cache of the datasets by placing the contents of the dataset repo in
|
| 74 |
+
the above mentioned cache directory to avoid fetching dataset errors without
|
| 75 |
+
the internet connectivity.
|
| 76 |
+
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
from ._fetchers import face, ascent, electrocardiogram
|
| 81 |
+
from ._download_all import download_all
|
| 82 |
+
from ._utils import clear_cache
|
| 83 |
+
|
| 84 |
+
__all__ = ['ascent', 'electrocardiogram', 'face',
|
| 85 |
+
'download_all', 'clear_cache']
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
from scipy._lib._testutils import PytestTester
|
| 89 |
+
test = PytestTester(__name__)
|
| 90 |
+
del PytestTester
|
python_embeded/Lib/site-packages/scipy/datasets/_download_all.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Platform independent script to download all the
|
| 3 |
+
`scipy.datasets` module data files.
|
| 4 |
+
This doesn't require a full scipy build.
|
| 5 |
+
|
| 6 |
+
Run: python _download_all.py <download_dir>
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
try:
|
| 11 |
+
import pooch
|
| 12 |
+
except ImportError:
|
| 13 |
+
pooch = None
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if __package__ is None or __package__ == '':
|
| 17 |
+
# Running as python script, use absolute import
|
| 18 |
+
import _registry # type: ignore
|
| 19 |
+
else:
|
| 20 |
+
# Running as python module, use relative import
|
| 21 |
+
from . import _registry
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def download_all(path=None):
|
| 25 |
+
"""
|
| 26 |
+
Utility method to download all the dataset files
|
| 27 |
+
for `scipy.datasets` module.
|
| 28 |
+
|
| 29 |
+
Parameters
|
| 30 |
+
----------
|
| 31 |
+
path : str, optional
|
| 32 |
+
Directory path to download all the dataset files.
|
| 33 |
+
If None, default to the system cache_dir detected by pooch.
|
| 34 |
+
"""
|
| 35 |
+
if pooch is None:
|
| 36 |
+
raise ImportError("Missing optional dependency 'pooch' required "
|
| 37 |
+
"for scipy.datasets module. Please use pip or "
|
| 38 |
+
"conda to install 'pooch'.")
|
| 39 |
+
if path is None:
|
| 40 |
+
path = pooch.os_cache('scipy-data')
|
| 41 |
+
for dataset_name, dataset_hash in _registry.registry.items():
|
| 42 |
+
pooch.retrieve(url=_registry.registry_urls[dataset_name],
|
| 43 |
+
known_hash=dataset_hash,
|
| 44 |
+
fname=dataset_name, path=path)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
parser = argparse.ArgumentParser(description='Download SciPy data files.')
|
| 49 |
+
parser.add_argument("path", nargs='?', type=str,
|
| 50 |
+
default=pooch.os_cache('scipy-data'),
|
| 51 |
+
help="Directory path to download all the data files.")
|
| 52 |
+
args = parser.parse_args()
|
| 53 |
+
download_all(args.path)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
main()
|
python_embeded/Lib/site-packages/scipy/datasets/_fetchers.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy import array, frombuffer, load
|
| 2 |
+
from ._registry import registry, registry_urls
|
| 3 |
+
|
| 4 |
+
try:
|
| 5 |
+
import pooch
|
| 6 |
+
except ImportError:
|
| 7 |
+
pooch = None
|
| 8 |
+
data_fetcher = None
|
| 9 |
+
else:
|
| 10 |
+
data_fetcher = pooch.create(
|
| 11 |
+
# Use the default cache folder for the operating system
|
| 12 |
+
# Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
|
| 13 |
+
# select an appropriate directory for the cache on each platform.
|
| 14 |
+
path=pooch.os_cache("scipy-data"),
|
| 15 |
+
|
| 16 |
+
# The remote data is on Github
|
| 17 |
+
# base_url is a required param, even though we override this
|
| 18 |
+
# using individual urls in the registry.
|
| 19 |
+
base_url="https://github.com/scipy/",
|
| 20 |
+
registry=registry,
|
| 21 |
+
urls=registry_urls
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def fetch_data(dataset_name, data_fetcher=data_fetcher):
|
| 26 |
+
if data_fetcher is None:
|
| 27 |
+
raise ImportError("Missing optional dependency 'pooch' required "
|
| 28 |
+
"for scipy.datasets module. Please use pip or "
|
| 29 |
+
"conda to install 'pooch'.")
|
| 30 |
+
# The "fetch" method returns the full path to the downloaded data file.
|
| 31 |
+
return data_fetcher.fetch(dataset_name)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def ascent():
|
| 35 |
+
"""
|
| 36 |
+
Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
|
| 37 |
+
use in demos.
|
| 38 |
+
|
| 39 |
+
The image is derived from
|
| 40 |
+
https://pixnio.com/people/accent-to-the-top
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
None
|
| 45 |
+
|
| 46 |
+
Returns
|
| 47 |
+
-------
|
| 48 |
+
ascent : ndarray
|
| 49 |
+
convenient image to use for testing and demonstration
|
| 50 |
+
|
| 51 |
+
Examples
|
| 52 |
+
--------
|
| 53 |
+
>>> import scipy.datasets
|
| 54 |
+
>>> ascent = scipy.datasets.ascent()
|
| 55 |
+
>>> ascent.shape
|
| 56 |
+
(512, 512)
|
| 57 |
+
>>> ascent.max()
|
| 58 |
+
np.uint8(255)
|
| 59 |
+
|
| 60 |
+
>>> import matplotlib.pyplot as plt
|
| 61 |
+
>>> plt.gray()
|
| 62 |
+
>>> plt.imshow(ascent)
|
| 63 |
+
>>> plt.show()
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
import pickle
|
| 67 |
+
|
| 68 |
+
# The file will be downloaded automatically the first time this is run,
|
| 69 |
+
# returning the path to the downloaded file. Afterwards, Pooch finds
|
| 70 |
+
# it in the local cache and doesn't repeat the download.
|
| 71 |
+
fname = fetch_data("ascent.dat")
|
| 72 |
+
# Now we just need to load it with our standard Python tools.
|
| 73 |
+
with open(fname, 'rb') as f:
|
| 74 |
+
ascent = array(pickle.load(f))
|
| 75 |
+
return ascent
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def electrocardiogram():
|
| 79 |
+
"""
|
| 80 |
+
Load an electrocardiogram as an example for a 1-D signal.
|
| 81 |
+
|
| 82 |
+
The returned signal is a 5 minute long electrocardiogram (ECG), a medical
|
| 83 |
+
recording of the heart's electrical activity, sampled at 360 Hz.
|
| 84 |
+
|
| 85 |
+
Returns
|
| 86 |
+
-------
|
| 87 |
+
ecg : ndarray
|
| 88 |
+
The electrocardiogram in millivolt (mV) sampled at 360 Hz.
|
| 89 |
+
|
| 90 |
+
Notes
|
| 91 |
+
-----
|
| 92 |
+
The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
|
| 93 |
+
(lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
|
| 94 |
+
PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
|
| 95 |
+
heartbeats as well as pathological changes.
|
| 96 |
+
|
| 97 |
+
.. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
|
| 98 |
+
|
| 99 |
+
.. versionadded:: 1.1.0
|
| 100 |
+
|
| 101 |
+
References
|
| 102 |
+
----------
|
| 103 |
+
.. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
|
| 104 |
+
IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
|
| 105 |
+
(PMID: 11446209); :doi:`10.13026/C2F305`
|
| 106 |
+
.. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
|
| 107 |
+
Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
|
| 108 |
+
PhysioToolkit, and PhysioNet: Components of a New Research Resource
|
| 109 |
+
for Complex Physiologic Signals. Circulation 101(23):e215-e220;
|
| 110 |
+
:doi:`10.1161/01.CIR.101.23.e215`
|
| 111 |
+
|
| 112 |
+
Examples
|
| 113 |
+
--------
|
| 114 |
+
>>> from scipy.datasets import electrocardiogram
|
| 115 |
+
>>> ecg = electrocardiogram()
|
| 116 |
+
>>> ecg
|
| 117 |
+
array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
|
| 118 |
+
>>> ecg.shape, ecg.mean(), ecg.std()
|
| 119 |
+
((108000,), -0.16510875, 0.5992473991177294)
|
| 120 |
+
|
| 121 |
+
As stated the signal features several areas with a different morphology.
|
| 122 |
+
E.g., the first few seconds show the electrical activity of a heart in
|
| 123 |
+
normal sinus rhythm as seen below.
|
| 124 |
+
|
| 125 |
+
>>> import numpy as np
|
| 126 |
+
>>> import matplotlib.pyplot as plt
|
| 127 |
+
>>> fs = 360
|
| 128 |
+
>>> time = np.arange(ecg.size) / fs
|
| 129 |
+
>>> plt.plot(time, ecg)
|
| 130 |
+
>>> plt.xlabel("time in s")
|
| 131 |
+
>>> plt.ylabel("ECG in mV")
|
| 132 |
+
>>> plt.xlim(9, 10.2)
|
| 133 |
+
>>> plt.ylim(-1, 1.5)
|
| 134 |
+
>>> plt.show()
|
| 135 |
+
|
| 136 |
+
After second 16, however, the first premature ventricular contractions,
|
| 137 |
+
also called extrasystoles, appear. These have a different morphology
|
| 138 |
+
compared to typical heartbeats. The difference can easily be observed
|
| 139 |
+
in the following plot.
|
| 140 |
+
|
| 141 |
+
>>> plt.plot(time, ecg)
|
| 142 |
+
>>> plt.xlabel("time in s")
|
| 143 |
+
>>> plt.ylabel("ECG in mV")
|
| 144 |
+
>>> plt.xlim(46.5, 50)
|
| 145 |
+
>>> plt.ylim(-2, 1.5)
|
| 146 |
+
>>> plt.show()
|
| 147 |
+
|
| 148 |
+
At several points large artifacts disturb the recording, e.g.:
|
| 149 |
+
|
| 150 |
+
>>> plt.plot(time, ecg)
|
| 151 |
+
>>> plt.xlabel("time in s")
|
| 152 |
+
>>> plt.ylabel("ECG in mV")
|
| 153 |
+
>>> plt.xlim(207, 215)
|
| 154 |
+
>>> plt.ylim(-2, 3.5)
|
| 155 |
+
>>> plt.show()
|
| 156 |
+
|
| 157 |
+
Finally, examining the power spectrum reveals that most of the biosignal is
|
| 158 |
+
made up of lower frequencies. At 60 Hz the noise induced by the mains
|
| 159 |
+
electricity can be clearly observed.
|
| 160 |
+
|
| 161 |
+
>>> from scipy.signal import welch
|
| 162 |
+
>>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
|
| 163 |
+
>>> plt.semilogy(f, Pxx)
|
| 164 |
+
>>> plt.xlabel("Frequency in Hz")
|
| 165 |
+
>>> plt.ylabel("Power spectrum of the ECG in mV**2")
|
| 166 |
+
>>> plt.xlim(f[[0, -1]])
|
| 167 |
+
>>> plt.show()
|
| 168 |
+
"""
|
| 169 |
+
fname = fetch_data("ecg.dat")
|
| 170 |
+
with load(fname) as file:
|
| 171 |
+
ecg = file["ecg"].astype(int) # np.uint16 -> int
|
| 172 |
+
# Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
|
| 173 |
+
ecg = (ecg - 1024) / 200.0
|
| 174 |
+
return ecg
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def face(gray=False):
|
| 178 |
+
"""
|
| 179 |
+
Get a 1024 x 768, color image of a raccoon face.
|
| 180 |
+
|
| 181 |
+
The image is derived from
|
| 182 |
+
https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
|
| 183 |
+
|
| 184 |
+
Parameters
|
| 185 |
+
----------
|
| 186 |
+
gray : bool, optional
|
| 187 |
+
If True return 8-bit grey-scale image, otherwise return a color image
|
| 188 |
+
|
| 189 |
+
Returns
|
| 190 |
+
-------
|
| 191 |
+
face : ndarray
|
| 192 |
+
image of a raccoon face
|
| 193 |
+
|
| 194 |
+
Examples
|
| 195 |
+
--------
|
| 196 |
+
>>> import scipy.datasets
|
| 197 |
+
>>> face = scipy.datasets.face()
|
| 198 |
+
>>> face.shape
|
| 199 |
+
(768, 1024, 3)
|
| 200 |
+
>>> face.max()
|
| 201 |
+
np.uint8(255)
|
| 202 |
+
|
| 203 |
+
>>> import matplotlib.pyplot as plt
|
| 204 |
+
>>> plt.gray()
|
| 205 |
+
>>> plt.imshow(face)
|
| 206 |
+
>>> plt.show()
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
import bz2
|
| 210 |
+
fname = fetch_data("face.dat")
|
| 211 |
+
with open(fname, 'rb') as f:
|
| 212 |
+
rawdata = f.read()
|
| 213 |
+
face_data = bz2.decompress(rawdata)
|
| 214 |
+
face = frombuffer(face_data, dtype='uint8')
|
| 215 |
+
face.shape = (768, 1024, 3)
|
| 216 |
+
if gray is True:
|
| 217 |
+
face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
|
| 218 |
+
0.07 * face[:, :, 2]).astype('uint8')
|
| 219 |
+
return face
|