backup 04_physworld 2026-11-08 10:11:26 (part 17)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +50 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_delegation.py +1028 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__init__.py +1 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/__init__.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_at.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_backends.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_funcs.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_lazy.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_testing.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_at.py +463 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_backends.py +72 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_funcs.py +744 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_lazy.py +357 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_testing.py +304 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__init__.py +1 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.py +74 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.pyi +45 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_helpers.py +619 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.py +10 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.pyi +105 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/testing.py +415 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__init__.py +20 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/__init__.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/framework.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/main.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/models.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/problem.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/settings.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/framework.py +1240 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/main.py +1506 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/models.py +1531 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/problem.py +1296 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/settings.py +132 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py +14 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py +387 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py +1203 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__init__.py +18 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/math.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/versions.cpython-311.pyc +0 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/exceptions.py +22 -0
- physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/math.py +77 -0
.gitattributes
CHANGED
|
@@ -3623,3 +3623,53 @@ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/rtree/__pycache__/ind
|
|
| 3623 |
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/rtree.libs/libspatialindex-e5350069.so filter=lfs diff=lfs merge=lfs -text
|
| 3624 |
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_cyutility.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3625 |
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/_uarray/_uarray.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3623 |
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/rtree.libs/libspatialindex-e5350069.so filter=lfs diff=lfs merge=lfs -text
|
| 3624 |
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_cyutility.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3625 |
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/_uarray/_uarray.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3626 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3627 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/cluster/_hierarchy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3628 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3629 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/cluster/_vq.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3630 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/constants/__pycache__/_codata.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3631 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3632 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/fftpack/convolve.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3633 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3634 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/integrate/_odepack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3635 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/integrate/_quadpack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3636 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/integrate/_vode.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3637 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/__pycache__/_bsplines.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3638 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3639 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3640 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/_dfitpack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3641 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/_dierckx.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3642 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/_interpnd.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3643 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/_ppoly.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3644 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3645 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/_rgi_cython.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3646 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/tests/__pycache__/test_bsplines.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3647 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/tests/__pycache__/test_fitpack2.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3648 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/interpolate/tests/__pycache__/test_interpolate.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3649 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3650 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/io/matlab/_mio5_utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3651 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/io/matlab/_streams.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3652 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_batched_linalg.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3653 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_cythonized_array_utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3654 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_decomp_interpolative.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3655 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_decomp_lu_cython.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3656 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_decomp_update.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3657 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_fblas.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3658 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_flapack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3659 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_linalg_pythran.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3660 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_matfuncs_expm.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3661 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_matfuncs_schur_sqrtm.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3662 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/_solve_toeplitz.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3663 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/cython_blas.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3664 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/cython_lapack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3665 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3666 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3667 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3668 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3669 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3670 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/_nd_image.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3671 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/_ni_label.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3672 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3673 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3674 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_measurements.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 3675 |
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_delegation.py
ADDED
|
@@ -0,0 +1,1028 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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from collections.abc import Sequence
|
| 4 |
+
from types import ModuleType
|
| 5 |
+
from typing import Literal
|
| 6 |
+
|
| 7 |
+
from ._lib import _funcs
|
| 8 |
+
from ._lib._utils._compat import (
|
| 9 |
+
array_namespace,
|
| 10 |
+
is_cupy_namespace,
|
| 11 |
+
is_dask_namespace,
|
| 12 |
+
is_jax_namespace,
|
| 13 |
+
is_numpy_namespace,
|
| 14 |
+
is_pydata_sparse_namespace,
|
| 15 |
+
is_torch_namespace,
|
| 16 |
+
)
|
| 17 |
+
from ._lib._utils._compat import device as get_device
|
| 18 |
+
from ._lib._utils._helpers import asarrays, eager_shape
|
| 19 |
+
from ._lib._utils._typing import Array, DType
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"atleast_nd",
|
| 23 |
+
"cov",
|
| 24 |
+
"create_diagonal",
|
| 25 |
+
"expand_dims",
|
| 26 |
+
"isclose",
|
| 27 |
+
"nan_to_num",
|
| 28 |
+
"one_hot",
|
| 29 |
+
"pad",
|
| 30 |
+
"sinc",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType | None = None) -> Array:
|
| 35 |
+
"""
|
| 36 |
+
Recursively expand the dimension of an array to at least `ndim`.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
x : array
|
| 41 |
+
Input array.
|
| 42 |
+
ndim : int
|
| 43 |
+
The minimum number of dimensions for the result.
|
| 44 |
+
xp : array_namespace, optional
|
| 45 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 46 |
+
|
| 47 |
+
Returns
|
| 48 |
+
-------
|
| 49 |
+
array
|
| 50 |
+
An array with ``res.ndim`` >= `ndim`.
|
| 51 |
+
If ``x.ndim`` >= `ndim`, `x` is returned.
|
| 52 |
+
If ``x.ndim`` < `ndim`, `x` is expanded by prepending new axes
|
| 53 |
+
until ``res.ndim`` equals `ndim`.
|
| 54 |
+
|
| 55 |
+
Examples
|
| 56 |
+
--------
|
| 57 |
+
>>> import array_api_strict as xp
|
| 58 |
+
>>> import array_api_extra as xpx
|
| 59 |
+
>>> x = xp.asarray([1])
|
| 60 |
+
>>> xpx.atleast_nd(x, ndim=3, xp=xp)
|
| 61 |
+
Array([[[1]]], dtype=array_api_strict.int64)
|
| 62 |
+
|
| 63 |
+
>>> x = xp.asarray([[[1, 2],
|
| 64 |
+
... [3, 4]]])
|
| 65 |
+
>>> xpx.atleast_nd(x, ndim=1, xp=xp) is x
|
| 66 |
+
True
|
| 67 |
+
"""
|
| 68 |
+
if xp is None:
|
| 69 |
+
xp = array_namespace(x)
|
| 70 |
+
|
| 71 |
+
if 1 <= ndim <= 2 and (
|
| 72 |
+
is_numpy_namespace(xp)
|
| 73 |
+
or is_jax_namespace(xp)
|
| 74 |
+
or is_dask_namespace(xp)
|
| 75 |
+
or is_cupy_namespace(xp)
|
| 76 |
+
or is_torch_namespace(xp)
|
| 77 |
+
):
|
| 78 |
+
return getattr(xp, f"atleast_{ndim}d")(x)
|
| 79 |
+
|
| 80 |
+
return _funcs.atleast_nd(x, ndim=ndim, xp=xp)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def cov(m: Array, /, *, xp: ModuleType | None = None) -> Array:
|
| 84 |
+
"""
|
| 85 |
+
Estimate a covariance matrix (or a stack of covariance matrices).
|
| 86 |
+
|
| 87 |
+
Covariance indicates the level to which two variables vary together.
|
| 88 |
+
If we examine *N*-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
|
| 89 |
+
each with *M* observations, then element :math:`C_{ij}` of the
|
| 90 |
+
:math:`N \times N` covariance matrix is the covariance of
|
| 91 |
+
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
|
| 92 |
+
of :math:`x_i`.
|
| 93 |
+
|
| 94 |
+
With the exception of supporting batch input, this provides a subset of
|
| 95 |
+
the functionality of ``numpy.cov``.
|
| 96 |
+
|
| 97 |
+
Parameters
|
| 98 |
+
----------
|
| 99 |
+
m : array
|
| 100 |
+
An array of shape ``(..., N, M)`` whose innermost two dimensions
|
| 101 |
+
contain *M* observations of *N* variables. That is,
|
| 102 |
+
each row of `m` represents a variable, and each column a single
|
| 103 |
+
observation of all those variables.
|
| 104 |
+
xp : array_namespace, optional
|
| 105 |
+
The standard-compatible namespace for `m`. Default: infer.
|
| 106 |
+
|
| 107 |
+
Returns
|
| 108 |
+
-------
|
| 109 |
+
array
|
| 110 |
+
An array having shape (..., N, N) whose innermost two dimensions represent
|
| 111 |
+
the covariance matrix of the variables.
|
| 112 |
+
|
| 113 |
+
Examples
|
| 114 |
+
--------
|
| 115 |
+
>>> import array_api_strict as xp
|
| 116 |
+
>>> import array_api_extra as xpx
|
| 117 |
+
|
| 118 |
+
Consider two variables, :math:`x_0` and :math:`x_1`, which
|
| 119 |
+
correlate perfectly, but in opposite directions:
|
| 120 |
+
|
| 121 |
+
>>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T
|
| 122 |
+
>>> x
|
| 123 |
+
Array([[0, 1, 2],
|
| 124 |
+
[2, 1, 0]], dtype=array_api_strict.int64)
|
| 125 |
+
|
| 126 |
+
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
|
| 127 |
+
matrix shows this clearly:
|
| 128 |
+
|
| 129 |
+
>>> xpx.cov(x, xp=xp)
|
| 130 |
+
Array([[ 1., -1.],
|
| 131 |
+
[-1., 1.]], dtype=array_api_strict.float64)
|
| 132 |
+
|
| 133 |
+
Note that element :math:`C_{0,1}`, which shows the correlation between
|
| 134 |
+
:math:`x_0` and :math:`x_1`, is negative.
|
| 135 |
+
|
| 136 |
+
Further, note how `x` and `y` are combined:
|
| 137 |
+
|
| 138 |
+
>>> x = xp.asarray([-2.1, -1, 4.3])
|
| 139 |
+
>>> y = xp.asarray([3, 1.1, 0.12])
|
| 140 |
+
>>> X = xp.stack((x, y), axis=0)
|
| 141 |
+
>>> xpx.cov(X, xp=xp)
|
| 142 |
+
Array([[11.71 , -4.286 ],
|
| 143 |
+
[-4.286 , 2.14413333]], dtype=array_api_strict.float64)
|
| 144 |
+
|
| 145 |
+
>>> xpx.cov(x, xp=xp)
|
| 146 |
+
Array(11.71, dtype=array_api_strict.float64)
|
| 147 |
+
|
| 148 |
+
>>> xpx.cov(y, xp=xp)
|
| 149 |
+
Array(2.14413333, dtype=array_api_strict.float64)
|
| 150 |
+
|
| 151 |
+
Input with more than two dimensions is treated as a stack of
|
| 152 |
+
two-dimensional input.
|
| 153 |
+
|
| 154 |
+
>>> stack = xp.stack((X, 2*X))
|
| 155 |
+
>>> xpx.cov(stack)
|
| 156 |
+
Array([[[ 11.71 , -4.286 ],
|
| 157 |
+
[ -4.286 , 2.14413333]],
|
| 158 |
+
|
| 159 |
+
[[ 46.84 , -17.144 ],
|
| 160 |
+
[-17.144 , 8.57653333]]], dtype=array_api_strict.float64)
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
if xp is None:
|
| 164 |
+
xp = array_namespace(m)
|
| 165 |
+
|
| 166 |
+
if (
|
| 167 |
+
is_numpy_namespace(xp)
|
| 168 |
+
or is_cupy_namespace(xp)
|
| 169 |
+
or is_torch_namespace(xp)
|
| 170 |
+
or is_dask_namespace(xp)
|
| 171 |
+
or is_jax_namespace(xp)
|
| 172 |
+
) and m.ndim <= 2:
|
| 173 |
+
return xp.cov(m)
|
| 174 |
+
|
| 175 |
+
return _funcs.cov(m, xp=xp)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def create_diagonal(
|
| 179 |
+
x: Array, /, *, offset: int = 0, xp: ModuleType | None = None
|
| 180 |
+
) -> Array:
|
| 181 |
+
"""
|
| 182 |
+
Construct a diagonal array.
|
| 183 |
+
|
| 184 |
+
Parameters
|
| 185 |
+
----------
|
| 186 |
+
x : array
|
| 187 |
+
An array having shape ``(*batch_dims, k)``.
|
| 188 |
+
offset : int, optional
|
| 189 |
+
Offset from the leading diagonal (default is ``0``).
|
| 190 |
+
Use positive ints for diagonals above the leading diagonal,
|
| 191 |
+
and negative ints for diagonals below the leading diagonal.
|
| 192 |
+
xp : array_namespace, optional
|
| 193 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 194 |
+
|
| 195 |
+
Returns
|
| 196 |
+
-------
|
| 197 |
+
array
|
| 198 |
+
An array having shape ``(*batch_dims, k+abs(offset), k+abs(offset))`` with `x`
|
| 199 |
+
on the diagonal (offset by `offset`).
|
| 200 |
+
|
| 201 |
+
Examples
|
| 202 |
+
--------
|
| 203 |
+
>>> import array_api_strict as xp
|
| 204 |
+
>>> import array_api_extra as xpx
|
| 205 |
+
>>> x = xp.asarray([2, 4, 8])
|
| 206 |
+
|
| 207 |
+
>>> xpx.create_diagonal(x, xp=xp)
|
| 208 |
+
Array([[2, 0, 0],
|
| 209 |
+
[0, 4, 0],
|
| 210 |
+
[0, 0, 8]], dtype=array_api_strict.int64)
|
| 211 |
+
|
| 212 |
+
>>> xpx.create_diagonal(x, offset=-2, xp=xp)
|
| 213 |
+
Array([[0, 0, 0, 0, 0],
|
| 214 |
+
[0, 0, 0, 0, 0],
|
| 215 |
+
[2, 0, 0, 0, 0],
|
| 216 |
+
[0, 4, 0, 0, 0],
|
| 217 |
+
[0, 0, 8, 0, 0]], dtype=array_api_strict.int64)
|
| 218 |
+
"""
|
| 219 |
+
if xp is None:
|
| 220 |
+
xp = array_namespace(x)
|
| 221 |
+
|
| 222 |
+
if x.ndim == 0:
|
| 223 |
+
err_msg = "`x` must be at least 1-dimensional."
|
| 224 |
+
raise ValueError(err_msg)
|
| 225 |
+
|
| 226 |
+
if is_torch_namespace(xp):
|
| 227 |
+
return xp.diag_embed(x, offset=offset, dim1=-2, dim2=-1)
|
| 228 |
+
|
| 229 |
+
if (is_dask_namespace(xp) or is_cupy_namespace(xp)) and x.ndim < 2:
|
| 230 |
+
return xp.diag(x, k=offset)
|
| 231 |
+
|
| 232 |
+
if (is_jax_namespace(xp) or is_numpy_namespace(xp)) and x.ndim < 3:
|
| 233 |
+
batch_dim, n = eager_shape(x)[:-1], eager_shape(x, -1)[0] + abs(offset)
|
| 234 |
+
return xp.reshape(xp.diag(x, k=offset), (*batch_dim, n, n))
|
| 235 |
+
|
| 236 |
+
return _funcs.create_diagonal(x, offset=offset, xp=xp)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def expand_dims(
|
| 240 |
+
a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType | None = None
|
| 241 |
+
) -> Array:
|
| 242 |
+
"""
|
| 243 |
+
Expand the shape of an array.
|
| 244 |
+
|
| 245 |
+
Insert (a) new axis/axes that will appear at the position(s) specified by
|
| 246 |
+
`axis` in the expanded array shape.
|
| 247 |
+
|
| 248 |
+
This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*.
|
| 249 |
+
Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays.
|
| 250 |
+
|
| 251 |
+
Parameters
|
| 252 |
+
----------
|
| 253 |
+
a : array
|
| 254 |
+
Array to have its shape expanded.
|
| 255 |
+
axis : int or tuple of ints, optional
|
| 256 |
+
Position(s) in the expanded axes where the new axis (or axes) is/are placed.
|
| 257 |
+
If multiple positions are provided, they should be unique (note that a position
|
| 258 |
+
given by a positive index could also be referred to by a negative index -
|
| 259 |
+
that will also result in an error).
|
| 260 |
+
Default: ``(0,)``.
|
| 261 |
+
xp : array_namespace, optional
|
| 262 |
+
The standard-compatible namespace for `a`. Default: infer.
|
| 263 |
+
|
| 264 |
+
Returns
|
| 265 |
+
-------
|
| 266 |
+
array
|
| 267 |
+
`a` with an expanded shape.
|
| 268 |
+
|
| 269 |
+
Examples
|
| 270 |
+
--------
|
| 271 |
+
>>> import array_api_strict as xp
|
| 272 |
+
>>> import array_api_extra as xpx
|
| 273 |
+
>>> x = xp.asarray([1, 2])
|
| 274 |
+
>>> x.shape
|
| 275 |
+
(2,)
|
| 276 |
+
|
| 277 |
+
The following is equivalent to ``x[xp.newaxis, :]`` or ``x[xp.newaxis]``:
|
| 278 |
+
|
| 279 |
+
>>> y = xpx.expand_dims(x, axis=0, xp=xp)
|
| 280 |
+
>>> y
|
| 281 |
+
Array([[1, 2]], dtype=array_api_strict.int64)
|
| 282 |
+
>>> y.shape
|
| 283 |
+
(1, 2)
|
| 284 |
+
|
| 285 |
+
The following is equivalent to ``x[:, xp.newaxis]``:
|
| 286 |
+
|
| 287 |
+
>>> y = xpx.expand_dims(x, axis=1, xp=xp)
|
| 288 |
+
>>> y
|
| 289 |
+
Array([[1],
|
| 290 |
+
[2]], dtype=array_api_strict.int64)
|
| 291 |
+
>>> y.shape
|
| 292 |
+
(2, 1)
|
| 293 |
+
|
| 294 |
+
``axis`` may also be a tuple:
|
| 295 |
+
|
| 296 |
+
>>> y = xpx.expand_dims(x, axis=(0, 1), xp=xp)
|
| 297 |
+
>>> y
|
| 298 |
+
Array([[[1, 2]]], dtype=array_api_strict.int64)
|
| 299 |
+
|
| 300 |
+
>>> y = xpx.expand_dims(x, axis=(2, 0), xp=xp)
|
| 301 |
+
>>> y
|
| 302 |
+
Array([[[1],
|
| 303 |
+
[2]]], dtype=array_api_strict.int64)
|
| 304 |
+
"""
|
| 305 |
+
if xp is None:
|
| 306 |
+
xp = array_namespace(a)
|
| 307 |
+
|
| 308 |
+
if not isinstance(axis, tuple):
|
| 309 |
+
axis = (axis,)
|
| 310 |
+
ndim = a.ndim + len(axis)
|
| 311 |
+
if axis != () and (min(axis) < -ndim or max(axis) >= ndim):
|
| 312 |
+
err_msg = (
|
| 313 |
+
f"a provided axis position is out of bounds for array of dimension {a.ndim}"
|
| 314 |
+
)
|
| 315 |
+
raise IndexError(err_msg)
|
| 316 |
+
axis = tuple(dim % ndim for dim in axis)
|
| 317 |
+
if len(set(axis)) != len(axis):
|
| 318 |
+
err_msg = "Duplicate dimensions specified in `axis`."
|
| 319 |
+
raise ValueError(err_msg)
|
| 320 |
+
|
| 321 |
+
if is_numpy_namespace(xp) or is_dask_namespace(xp) or is_jax_namespace(xp):
|
| 322 |
+
return xp.expand_dims(a, axis=axis)
|
| 323 |
+
|
| 324 |
+
return _funcs.expand_dims(a, axis=axis, xp=xp)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def isclose(
|
| 328 |
+
a: Array | complex,
|
| 329 |
+
b: Array | complex,
|
| 330 |
+
*,
|
| 331 |
+
rtol: float = 1e-05,
|
| 332 |
+
atol: float = 1e-08,
|
| 333 |
+
equal_nan: bool = False,
|
| 334 |
+
xp: ModuleType | None = None,
|
| 335 |
+
) -> Array:
|
| 336 |
+
"""
|
| 337 |
+
Return a boolean array where two arrays are element-wise equal within a tolerance.
|
| 338 |
+
|
| 339 |
+
The tolerance values are positive, typically very small numbers. The relative
|
| 340 |
+
difference ``(rtol * abs(b))`` and the absolute difference `atol` are added together
|
| 341 |
+
to compare against the absolute difference between `a` and `b`.
|
| 342 |
+
|
| 343 |
+
NaNs are treated as equal if they are in the same place and if ``equal_nan=True``.
|
| 344 |
+
Infs are treated as equal if they are in the same place and of the same sign in both
|
| 345 |
+
arrays.
|
| 346 |
+
|
| 347 |
+
Parameters
|
| 348 |
+
----------
|
| 349 |
+
a, b : Array | int | float | complex | bool
|
| 350 |
+
Input objects to compare. At least one must be an array.
|
| 351 |
+
rtol : array_like, optional
|
| 352 |
+
The relative tolerance parameter (see Notes).
|
| 353 |
+
atol : array_like, optional
|
| 354 |
+
The absolute tolerance parameter (see Notes).
|
| 355 |
+
equal_nan : bool, optional
|
| 356 |
+
Whether to compare NaN's as equal. If True, NaN's in `a` will be considered
|
| 357 |
+
equal to NaN's in `b` in the output array.
|
| 358 |
+
xp : array_namespace, optional
|
| 359 |
+
The standard-compatible namespace for `a` and `b`. Default: infer.
|
| 360 |
+
|
| 361 |
+
Returns
|
| 362 |
+
-------
|
| 363 |
+
Array
|
| 364 |
+
A boolean array of shape broadcasted from `a` and `b`, containing ``True`` where
|
| 365 |
+
`a` is close to `b`, and ``False`` otherwise.
|
| 366 |
+
|
| 367 |
+
Warnings
|
| 368 |
+
--------
|
| 369 |
+
The default `atol` is not appropriate for comparing numbers with magnitudes much
|
| 370 |
+
smaller than one (see notes).
|
| 371 |
+
|
| 372 |
+
See Also
|
| 373 |
+
--------
|
| 374 |
+
math.isclose : Similar function in stdlib for Python scalars.
|
| 375 |
+
|
| 376 |
+
Notes
|
| 377 |
+
-----
|
| 378 |
+
For finite values, `isclose` uses the following equation to test whether two
|
| 379 |
+
floating point values are equivalent::
|
| 380 |
+
|
| 381 |
+
absolute(a - b) <= (atol + rtol * absolute(b))
|
| 382 |
+
|
| 383 |
+
Unlike the built-in `math.isclose`,
|
| 384 |
+
the above equation is not symmetric in `a` and `b`,
|
| 385 |
+
so that ``isclose(a, b)`` might be different from ``isclose(b, a)`` in some rare
|
| 386 |
+
cases.
|
| 387 |
+
|
| 388 |
+
The default value of `atol` is not appropriate when the reference value `b` has
|
| 389 |
+
magnitude smaller than one. For example, it is unlikely that ``a = 1e-9`` and
|
| 390 |
+
``b = 2e-9`` should be considered "close", yet ``isclose(1e-9, 2e-9)`` is ``True``
|
| 391 |
+
with default settings. Be sure to select `atol` for the use case at hand, especially
|
| 392 |
+
for defining the threshold below which a non-zero value in `a` will be considered
|
| 393 |
+
"close" to a very small or zero value in `b`.
|
| 394 |
+
|
| 395 |
+
The comparison of `a` and `b` uses standard broadcasting, which means that `a` and
|
| 396 |
+
`b` need not have the same shape in order for ``isclose(a, b)`` to evaluate to
|
| 397 |
+
``True``.
|
| 398 |
+
|
| 399 |
+
`isclose` is not defined for non-numeric data types.
|
| 400 |
+
``bool`` is considered a numeric data-type for this purpose.
|
| 401 |
+
"""
|
| 402 |
+
xp = array_namespace(a, b) if xp is None else xp
|
| 403 |
+
|
| 404 |
+
if (
|
| 405 |
+
is_numpy_namespace(xp)
|
| 406 |
+
or is_cupy_namespace(xp)
|
| 407 |
+
or is_dask_namespace(xp)
|
| 408 |
+
or is_jax_namespace(xp)
|
| 409 |
+
):
|
| 410 |
+
return xp.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
|
| 411 |
+
|
| 412 |
+
if is_torch_namespace(xp):
|
| 413 |
+
a, b = asarrays(a, b, xp=xp) # Array API 2024.12 support
|
| 414 |
+
return xp.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
|
| 415 |
+
|
| 416 |
+
return _funcs.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan, xp=xp)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def nan_to_num(
|
| 420 |
+
x: Array | float | complex,
|
| 421 |
+
/,
|
| 422 |
+
*,
|
| 423 |
+
fill_value: int | float = 0.0,
|
| 424 |
+
xp: ModuleType | None = None,
|
| 425 |
+
) -> Array:
|
| 426 |
+
"""
|
| 427 |
+
Replace NaN with zero and infinity with large finite numbers (default behaviour).
|
| 428 |
+
|
| 429 |
+
If `x` is inexact, NaN is replaced by zero or by the user defined value in the
|
| 430 |
+
`fill_value` keyword, infinity is replaced by the largest finite floating
|
| 431 |
+
point value representable by ``x.dtype``, and -infinity is replaced by the
|
| 432 |
+
most negative finite floating point value representable by ``x.dtype``.
|
| 433 |
+
|
| 434 |
+
For complex dtypes, the above is applied to each of the real and
|
| 435 |
+
imaginary components of `x` separately.
|
| 436 |
+
|
| 437 |
+
Parameters
|
| 438 |
+
----------
|
| 439 |
+
x : array | float | complex
|
| 440 |
+
Input data.
|
| 441 |
+
fill_value : int | float, optional
|
| 442 |
+
Value to be used to fill NaN values. If no value is passed
|
| 443 |
+
then NaN values will be replaced with 0.0.
|
| 444 |
+
xp : array_namespace, optional
|
| 445 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 446 |
+
|
| 447 |
+
Returns
|
| 448 |
+
-------
|
| 449 |
+
array
|
| 450 |
+
`x`, with the non-finite values replaced.
|
| 451 |
+
|
| 452 |
+
See Also
|
| 453 |
+
--------
|
| 454 |
+
array_api.isnan : Shows which elements are Not a Number (NaN).
|
| 455 |
+
|
| 456 |
+
Examples
|
| 457 |
+
--------
|
| 458 |
+
>>> import array_api_extra as xpx
|
| 459 |
+
>>> import array_api_strict as xp
|
| 460 |
+
>>> xpx.nan_to_num(xp.inf)
|
| 461 |
+
1.7976931348623157e+308
|
| 462 |
+
>>> xpx.nan_to_num(-xp.inf)
|
| 463 |
+
-1.7976931348623157e+308
|
| 464 |
+
>>> xpx.nan_to_num(xp.nan)
|
| 465 |
+
0.0
|
| 466 |
+
>>> x = xp.asarray([xp.inf, -xp.inf, xp.nan, -128, 128])
|
| 467 |
+
>>> xpx.nan_to_num(x)
|
| 468 |
+
array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary
|
| 469 |
+
-1.28000000e+002, 1.28000000e+002])
|
| 470 |
+
>>> y = xp.asarray([complex(xp.inf, xp.nan), xp.nan, complex(xp.nan, xp.inf)])
|
| 471 |
+
array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary
|
| 472 |
+
-1.28000000e+002, 1.28000000e+002])
|
| 473 |
+
>>> xpx.nan_to_num(y)
|
| 474 |
+
array([ 1.79769313e+308 +0.00000000e+000j, # may vary
|
| 475 |
+
0.00000000e+000 +0.00000000e+000j,
|
| 476 |
+
0.00000000e+000 +1.79769313e+308j])
|
| 477 |
+
"""
|
| 478 |
+
if isinstance(fill_value, complex):
|
| 479 |
+
msg = "Complex fill values are not supported."
|
| 480 |
+
raise TypeError(msg)
|
| 481 |
+
|
| 482 |
+
xp = array_namespace(x) if xp is None else xp
|
| 483 |
+
|
| 484 |
+
# for scalars we want to output an array
|
| 485 |
+
y = xp.asarray(x)
|
| 486 |
+
|
| 487 |
+
if (
|
| 488 |
+
is_cupy_namespace(xp)
|
| 489 |
+
or is_jax_namespace(xp)
|
| 490 |
+
or is_numpy_namespace(xp)
|
| 491 |
+
or is_torch_namespace(xp)
|
| 492 |
+
):
|
| 493 |
+
return xp.nan_to_num(y, nan=fill_value)
|
| 494 |
+
|
| 495 |
+
return _funcs.nan_to_num(y, fill_value=fill_value, xp=xp)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def one_hot(
|
| 499 |
+
x: Array,
|
| 500 |
+
/,
|
| 501 |
+
num_classes: int,
|
| 502 |
+
*,
|
| 503 |
+
dtype: DType | None = None,
|
| 504 |
+
axis: int = -1,
|
| 505 |
+
xp: ModuleType | None = None,
|
| 506 |
+
) -> Array:
|
| 507 |
+
"""
|
| 508 |
+
One-hot encode the given indices.
|
| 509 |
+
|
| 510 |
+
Each index in the input `x` is encoded as a vector of zeros of length `num_classes`
|
| 511 |
+
with the element at the given index set to one.
|
| 512 |
+
|
| 513 |
+
Parameters
|
| 514 |
+
----------
|
| 515 |
+
x : array
|
| 516 |
+
An array with integral dtype whose values are between `0` and `num_classes - 1`.
|
| 517 |
+
num_classes : int
|
| 518 |
+
Number of classes in the one-hot dimension.
|
| 519 |
+
dtype : DType, optional
|
| 520 |
+
The dtype of the return value. Defaults to the default float dtype (usually
|
| 521 |
+
float64).
|
| 522 |
+
axis : int, optional
|
| 523 |
+
Position in the expanded axes where the new axis is placed. Default: -1.
|
| 524 |
+
xp : array_namespace, optional
|
| 525 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 526 |
+
|
| 527 |
+
Returns
|
| 528 |
+
-------
|
| 529 |
+
array
|
| 530 |
+
An array having the same shape as `x` except for a new axis at the position
|
| 531 |
+
given by `axis` having size `num_classes`. If `axis` is unspecified, it
|
| 532 |
+
defaults to -1, which appends a new axis.
|
| 533 |
+
|
| 534 |
+
If ``x < 0`` or ``x >= num_classes``, then the result is undefined, may raise
|
| 535 |
+
an exception, or may even cause a bad state. `x` is not checked.
|
| 536 |
+
|
| 537 |
+
Examples
|
| 538 |
+
--------
|
| 539 |
+
>>> import array_api_extra as xpx
|
| 540 |
+
>>> import array_api_strict as xp
|
| 541 |
+
>>> xpx.one_hot(xp.asarray([1, 2, 0]), 3)
|
| 542 |
+
Array([[0., 1., 0.],
|
| 543 |
+
[0., 0., 1.],
|
| 544 |
+
[1., 0., 0.]], dtype=array_api_strict.float64)
|
| 545 |
+
"""
|
| 546 |
+
# Validate inputs.
|
| 547 |
+
if xp is None:
|
| 548 |
+
xp = array_namespace(x)
|
| 549 |
+
if not xp.isdtype(x.dtype, "integral"):
|
| 550 |
+
msg = "x must have an integral dtype."
|
| 551 |
+
raise TypeError(msg)
|
| 552 |
+
if dtype is None:
|
| 553 |
+
dtype = _funcs.default_dtype(xp, device=get_device(x))
|
| 554 |
+
# Delegate where possible.
|
| 555 |
+
if is_jax_namespace(xp):
|
| 556 |
+
from jax.nn import one_hot as jax_one_hot
|
| 557 |
+
|
| 558 |
+
return jax_one_hot(x, num_classes, dtype=dtype, axis=axis)
|
| 559 |
+
if is_torch_namespace(xp):
|
| 560 |
+
from torch.nn.functional import one_hot as torch_one_hot
|
| 561 |
+
|
| 562 |
+
x = xp.astype(x, xp.int64) # PyTorch only supports int64 here.
|
| 563 |
+
try:
|
| 564 |
+
out = torch_one_hot(x, num_classes)
|
| 565 |
+
except RuntimeError as e:
|
| 566 |
+
raise IndexError from e
|
| 567 |
+
else:
|
| 568 |
+
out = _funcs.one_hot(x, num_classes, xp=xp)
|
| 569 |
+
out = xp.astype(out, dtype, copy=False)
|
| 570 |
+
if axis != -1:
|
| 571 |
+
out = xp.moveaxis(out, -1, axis)
|
| 572 |
+
return out
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def pad(
|
| 576 |
+
x: Array,
|
| 577 |
+
pad_width: int | tuple[int, int] | Sequence[tuple[int, int]],
|
| 578 |
+
mode: Literal["constant"] = "constant",
|
| 579 |
+
*,
|
| 580 |
+
constant_values: complex = 0,
|
| 581 |
+
xp: ModuleType | None = None,
|
| 582 |
+
) -> Array:
|
| 583 |
+
"""
|
| 584 |
+
Pad the input array.
|
| 585 |
+
|
| 586 |
+
Parameters
|
| 587 |
+
----------
|
| 588 |
+
x : array
|
| 589 |
+
Input array.
|
| 590 |
+
pad_width : int or tuple of ints or sequence of pairs of ints
|
| 591 |
+
Pad the input array with this many elements from each side.
|
| 592 |
+
If a sequence of tuples, ``[(before_0, after_0), ... (before_N, after_N)]``,
|
| 593 |
+
each pair applies to the corresponding axis of ``x``.
|
| 594 |
+
A single tuple, ``(before, after)``, is equivalent to a list of ``x.ndim``
|
| 595 |
+
copies of this tuple.
|
| 596 |
+
mode : str, optional
|
| 597 |
+
Only "constant" mode is currently supported, which pads with
|
| 598 |
+
the value passed to `constant_values`.
|
| 599 |
+
constant_values : python scalar, optional
|
| 600 |
+
Use this value to pad the input. Default is zero.
|
| 601 |
+
xp : array_namespace, optional
|
| 602 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 603 |
+
|
| 604 |
+
Returns
|
| 605 |
+
-------
|
| 606 |
+
array
|
| 607 |
+
The input array,
|
| 608 |
+
padded with ``pad_width`` elements equal to ``constant_values``.
|
| 609 |
+
"""
|
| 610 |
+
xp = array_namespace(x) if xp is None else xp
|
| 611 |
+
|
| 612 |
+
if mode != "constant":
|
| 613 |
+
msg = "Only `'constant'` mode is currently supported"
|
| 614 |
+
raise NotImplementedError(msg)
|
| 615 |
+
|
| 616 |
+
if (
|
| 617 |
+
is_numpy_namespace(xp)
|
| 618 |
+
or is_cupy_namespace(xp)
|
| 619 |
+
or is_jax_namespace(xp)
|
| 620 |
+
or is_pydata_sparse_namespace(xp)
|
| 621 |
+
):
|
| 622 |
+
return xp.pad(x, pad_width, mode, constant_values=constant_values)
|
| 623 |
+
|
| 624 |
+
# https://github.com/pytorch/pytorch/blob/cf76c05b4dc629ac989d1fb8e789d4fac04a095a/torch/_numpy/_funcs_impl.py#L2045-L2056
|
| 625 |
+
if is_torch_namespace(xp):
|
| 626 |
+
pad_width = xp.asarray(pad_width)
|
| 627 |
+
pad_width = xp.broadcast_to(pad_width, (x.ndim, 2))
|
| 628 |
+
pad_width = xp.flip(pad_width, axis=(0,)).flatten()
|
| 629 |
+
return xp.nn.functional.pad(x, tuple(pad_width), value=constant_values) # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
| 630 |
+
|
| 631 |
+
return _funcs.pad(x, pad_width, constant_values=constant_values, xp=xp)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def setdiff1d(
|
| 635 |
+
x1: Array | complex,
|
| 636 |
+
x2: Array | complex,
|
| 637 |
+
/,
|
| 638 |
+
*,
|
| 639 |
+
assume_unique: bool = False,
|
| 640 |
+
xp: ModuleType | None = None,
|
| 641 |
+
) -> Array:
|
| 642 |
+
"""
|
| 643 |
+
Find the set difference of two arrays.
|
| 644 |
+
|
| 645 |
+
Return the unique values in `x1` that are not in `x2`.
|
| 646 |
+
|
| 647 |
+
Parameters
|
| 648 |
+
----------
|
| 649 |
+
x1 : array | int | float | complex | bool
|
| 650 |
+
Input array.
|
| 651 |
+
x2 : array
|
| 652 |
+
Input comparison array.
|
| 653 |
+
assume_unique : bool
|
| 654 |
+
If ``True``, the input arrays are both assumed to be unique, which
|
| 655 |
+
can speed up the calculation. Default is ``False``.
|
| 656 |
+
xp : array_namespace, optional
|
| 657 |
+
The standard-compatible namespace for `x1` and `x2`. Default: infer.
|
| 658 |
+
|
| 659 |
+
Returns
|
| 660 |
+
-------
|
| 661 |
+
array
|
| 662 |
+
1D array of values in `x1` that are not in `x2`. The result
|
| 663 |
+
is sorted when `assume_unique` is ``False``, but otherwise only sorted
|
| 664 |
+
if the input is sorted.
|
| 665 |
+
|
| 666 |
+
Examples
|
| 667 |
+
--------
|
| 668 |
+
>>> import array_api_strict as xp
|
| 669 |
+
>>> import array_api_extra as xpx
|
| 670 |
+
|
| 671 |
+
>>> x1 = xp.asarray([1, 2, 3, 2, 4, 1])
|
| 672 |
+
>>> x2 = xp.asarray([3, 4, 5, 6])
|
| 673 |
+
>>> xpx.setdiff1d(x1, x2, xp=xp)
|
| 674 |
+
Array([1, 2], dtype=array_api_strict.int64)
|
| 675 |
+
"""
|
| 676 |
+
|
| 677 |
+
if xp is None:
|
| 678 |
+
xp = array_namespace(x1, x2)
|
| 679 |
+
|
| 680 |
+
if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp):
|
| 681 |
+
x1, x2 = asarrays(x1, x2, xp=xp)
|
| 682 |
+
return xp.setdiff1d(x1, x2, assume_unique=assume_unique)
|
| 683 |
+
|
| 684 |
+
return _funcs.setdiff1d(x1, x2, assume_unique=assume_unique, xp=xp)
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def sinc(x: Array, /, *, xp: ModuleType | None = None) -> Array:
|
| 688 |
+
r"""
|
| 689 |
+
Return the normalized sinc function.
|
| 690 |
+
|
| 691 |
+
The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument
|
| 692 |
+
:math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not
|
| 693 |
+
only everywhere continuous but also infinitely differentiable.
|
| 694 |
+
|
| 695 |
+
.. note::
|
| 696 |
+
|
| 697 |
+
Note the normalization factor of ``pi`` used in the definition.
|
| 698 |
+
This is the most commonly used definition in signal processing.
|
| 699 |
+
Use ``sinc(x / xp.pi)`` to obtain the unnormalized sinc function
|
| 700 |
+
:math:`\sin(x)/x` that is more common in mathematics.
|
| 701 |
+
|
| 702 |
+
Parameters
|
| 703 |
+
----------
|
| 704 |
+
x : array
|
| 705 |
+
Array (possibly multi-dimensional) of values for which to calculate
|
| 706 |
+
``sinc(x)``. Must have a real floating point dtype.
|
| 707 |
+
xp : array_namespace, optional
|
| 708 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 709 |
+
|
| 710 |
+
Returns
|
| 711 |
+
-------
|
| 712 |
+
array
|
| 713 |
+
``sinc(x)`` calculated elementwise, which has the same shape as the input.
|
| 714 |
+
|
| 715 |
+
Notes
|
| 716 |
+
-----
|
| 717 |
+
The name sinc is short for "sine cardinal" or "sinus cardinalis".
|
| 718 |
+
|
| 719 |
+
The sinc function is used in various signal processing applications,
|
| 720 |
+
including in anti-aliasing, in the construction of a Lanczos resampling
|
| 721 |
+
filter, and in interpolation.
|
| 722 |
+
|
| 723 |
+
For bandlimited interpolation of discrete-time signals, the ideal
|
| 724 |
+
interpolation kernel is proportional to the sinc function.
|
| 725 |
+
|
| 726 |
+
References
|
| 727 |
+
----------
|
| 728 |
+
#. Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
|
| 729 |
+
Resource. https://mathworld.wolfram.com/SincFunction.html
|
| 730 |
+
#. Wikipedia, "Sinc function",
|
| 731 |
+
https://en.wikipedia.org/wiki/Sinc_function
|
| 732 |
+
|
| 733 |
+
Examples
|
| 734 |
+
--------
|
| 735 |
+
>>> import array_api_strict as xp
|
| 736 |
+
>>> import array_api_extra as xpx
|
| 737 |
+
>>> x = xp.linspace(-4, 4, 41)
|
| 738 |
+
>>> xpx.sinc(x, xp=xp)
|
| 739 |
+
Array([-3.89817183e-17, -4.92362781e-02,
|
| 740 |
+
-8.40918587e-02, -8.90384387e-02,
|
| 741 |
+
-5.84680802e-02, 3.89817183e-17,
|
| 742 |
+
6.68206631e-02, 1.16434881e-01,
|
| 743 |
+
1.26137788e-01, 8.50444803e-02,
|
| 744 |
+
-3.89817183e-17, -1.03943254e-01,
|
| 745 |
+
-1.89206682e-01, -2.16236208e-01,
|
| 746 |
+
-1.55914881e-01, 3.89817183e-17,
|
| 747 |
+
2.33872321e-01, 5.04551152e-01,
|
| 748 |
+
7.56826729e-01, 9.35489284e-01,
|
| 749 |
+
1.00000000e+00, 9.35489284e-01,
|
| 750 |
+
7.56826729e-01, 5.04551152e-01,
|
| 751 |
+
2.33872321e-01, 3.89817183e-17,
|
| 752 |
+
-1.55914881e-01, -2.16236208e-01,
|
| 753 |
+
-1.89206682e-01, -1.03943254e-01,
|
| 754 |
+
-3.89817183e-17, 8.50444803e-02,
|
| 755 |
+
1.26137788e-01, 1.16434881e-01,
|
| 756 |
+
6.68206631e-02, 3.89817183e-17,
|
| 757 |
+
-5.84680802e-02, -8.90384387e-02,
|
| 758 |
+
-8.40918587e-02, -4.92362781e-02,
|
| 759 |
+
-3.89817183e-17], dtype=array_api_strict.float64)
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
if xp is None:
|
| 763 |
+
xp = array_namespace(x)
|
| 764 |
+
|
| 765 |
+
if not xp.isdtype(x.dtype, "real floating"):
|
| 766 |
+
err_msg = "`x` must have a real floating data type."
|
| 767 |
+
raise ValueError(err_msg)
|
| 768 |
+
|
| 769 |
+
if (
|
| 770 |
+
is_numpy_namespace(xp)
|
| 771 |
+
or is_cupy_namespace(xp)
|
| 772 |
+
or is_jax_namespace(xp)
|
| 773 |
+
or is_torch_namespace(xp)
|
| 774 |
+
or is_dask_namespace(xp)
|
| 775 |
+
):
|
| 776 |
+
return xp.sinc(x)
|
| 777 |
+
|
| 778 |
+
return _funcs.sinc(x, xp=xp)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def partition(
|
| 782 |
+
a: Array,
|
| 783 |
+
kth: int,
|
| 784 |
+
/,
|
| 785 |
+
axis: int | None = -1,
|
| 786 |
+
*,
|
| 787 |
+
xp: ModuleType | None = None,
|
| 788 |
+
) -> Array:
|
| 789 |
+
"""
|
| 790 |
+
Return a partitioned copy of an array.
|
| 791 |
+
|
| 792 |
+
Creates a copy of the array and partially sorts it in such a way that the value
|
| 793 |
+
of the element in k-th position is in the position it would be in a sorted array.
|
| 794 |
+
In the output array, all elements smaller than the k-th element are located to
|
| 795 |
+
the left of this element and all equal or greater are located to its right.
|
| 796 |
+
The ordering of the elements in the two partitions on the either side of
|
| 797 |
+
the k-th element in the output array is undefined.
|
| 798 |
+
|
| 799 |
+
Parameters
|
| 800 |
+
----------
|
| 801 |
+
a : Array
|
| 802 |
+
Input array.
|
| 803 |
+
kth : int
|
| 804 |
+
Element index to partition by.
|
| 805 |
+
axis : int, optional
|
| 806 |
+
Axis along which to partition. The default is ``-1`` (the last axis).
|
| 807 |
+
If ``None``, the flattened array is used.
|
| 808 |
+
xp : array_namespace, optional
|
| 809 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 810 |
+
|
| 811 |
+
Returns
|
| 812 |
+
-------
|
| 813 |
+
partitioned_array
|
| 814 |
+
Array of the same type and shape as `a`.
|
| 815 |
+
|
| 816 |
+
Notes
|
| 817 |
+
-----
|
| 818 |
+
If `xp` implements ``partition`` or an equivalent function
|
| 819 |
+
(e.g. ``topk`` for torch), complexity will likely be O(n).
|
| 820 |
+
If not, this function simply calls ``xp.sort`` and complexity is O(n log n).
|
| 821 |
+
"""
|
| 822 |
+
# Validate inputs.
|
| 823 |
+
if xp is None:
|
| 824 |
+
xp = array_namespace(a)
|
| 825 |
+
if a.ndim < 1:
|
| 826 |
+
msg = "`a` must be at least 1-dimensional"
|
| 827 |
+
raise TypeError(msg)
|
| 828 |
+
if axis is None:
|
| 829 |
+
return partition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp)
|
| 830 |
+
(size,) = eager_shape(a, axis)
|
| 831 |
+
if not (0 <= kth < size):
|
| 832 |
+
msg = f"kth(={kth}) out of bounds [0 {size})"
|
| 833 |
+
raise ValueError(msg)
|
| 834 |
+
|
| 835 |
+
# Delegate where possible.
|
| 836 |
+
if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp):
|
| 837 |
+
return xp.partition(a, kth, axis=axis)
|
| 838 |
+
|
| 839 |
+
# Use top-k when possible:
|
| 840 |
+
if is_torch_namespace(xp):
|
| 841 |
+
if not (axis == -1 or axis == a.ndim - 1):
|
| 842 |
+
a = xp.transpose(a, axis, -1)
|
| 843 |
+
|
| 844 |
+
out = xp.empty_like(a)
|
| 845 |
+
ranks = xp.arange(a.shape[-1]).expand_as(a)
|
| 846 |
+
|
| 847 |
+
split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True)
|
| 848 |
+
del indices # indices won't be used => del ASAP to reduce peak memory usage
|
| 849 |
+
|
| 850 |
+
# fill the left-side of the partition
|
| 851 |
+
mask_src = a < split_value
|
| 852 |
+
n_left = mask_src.sum(dim=-1, keepdim=True)
|
| 853 |
+
mask_dest = ranks < n_left
|
| 854 |
+
out[mask_dest] = a[mask_src]
|
| 855 |
+
|
| 856 |
+
# fill the middle of the partition
|
| 857 |
+
mask_src = a == split_value
|
| 858 |
+
n_left += mask_src.sum(dim=-1, keepdim=True)
|
| 859 |
+
mask_dest ^= ranks < n_left
|
| 860 |
+
out[mask_dest] = a[mask_src]
|
| 861 |
+
|
| 862 |
+
# fill the right-side of the partition
|
| 863 |
+
mask_src = a > split_value
|
| 864 |
+
mask_dest = ranks >= n_left
|
| 865 |
+
out[mask_dest] = a[mask_src]
|
| 866 |
+
|
| 867 |
+
if not (axis == -1 or axis == a.ndim - 1):
|
| 868 |
+
out = xp.transpose(out, axis, -1)
|
| 869 |
+
return out
|
| 870 |
+
|
| 871 |
+
# Note: dask topk/argtopk sort the return values, so it's
|
| 872 |
+
# not much more efficient than sorting everything when
|
| 873 |
+
# kth is not small compared to x.size
|
| 874 |
+
|
| 875 |
+
return _funcs.partition(a, kth, axis=axis, xp=xp)
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def argpartition(
|
| 879 |
+
a: Array,
|
| 880 |
+
kth: int,
|
| 881 |
+
/,
|
| 882 |
+
axis: int | None = -1,
|
| 883 |
+
*,
|
| 884 |
+
xp: ModuleType | None = None,
|
| 885 |
+
) -> Array:
|
| 886 |
+
"""
|
| 887 |
+
Perform an indirect partition along the given axis.
|
| 888 |
+
|
| 889 |
+
It returns an array of indices of the same shape as `a` that
|
| 890 |
+
index data along the given axis in partitioned order.
|
| 891 |
+
|
| 892 |
+
Parameters
|
| 893 |
+
----------
|
| 894 |
+
a : Array
|
| 895 |
+
Input array.
|
| 896 |
+
kth : int
|
| 897 |
+
Element index to partition by.
|
| 898 |
+
axis : int, optional
|
| 899 |
+
Axis along which to partition. The default is ``-1`` (the last axis).
|
| 900 |
+
If ``None``, the flattened array is used.
|
| 901 |
+
xp : array_namespace, optional
|
| 902 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 903 |
+
|
| 904 |
+
Returns
|
| 905 |
+
-------
|
| 906 |
+
index_array
|
| 907 |
+
Array of indices that partition `a` along the specified axis.
|
| 908 |
+
|
| 909 |
+
Notes
|
| 910 |
+
-----
|
| 911 |
+
If `xp` implements ``argpartition`` or an equivalent function
|
| 912 |
+
e.g. ``topk`` for torch), complexity will likely be O(n).
|
| 913 |
+
If not, this function simply calls ``xp.argsort`` and complexity is O(n log n).
|
| 914 |
+
"""
|
| 915 |
+
# Validate inputs.
|
| 916 |
+
if xp is None:
|
| 917 |
+
xp = array_namespace(a)
|
| 918 |
+
if is_pydata_sparse_namespace(xp):
|
| 919 |
+
msg = "Not implemented for sparse backend: no argsort"
|
| 920 |
+
raise NotImplementedError(msg)
|
| 921 |
+
if a.ndim < 1:
|
| 922 |
+
msg = "`a` must be at least 1-dimensional"
|
| 923 |
+
raise TypeError(msg)
|
| 924 |
+
if axis is None:
|
| 925 |
+
return argpartition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp)
|
| 926 |
+
(size,) = eager_shape(a, axis)
|
| 927 |
+
if not (0 <= kth < size):
|
| 928 |
+
msg = f"kth(={kth}) out of bounds [0 {size})"
|
| 929 |
+
raise ValueError(msg)
|
| 930 |
+
|
| 931 |
+
# Delegate where possible.
|
| 932 |
+
if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp):
|
| 933 |
+
return xp.argpartition(a, kth, axis=axis)
|
| 934 |
+
|
| 935 |
+
# Use top-k when possible:
|
| 936 |
+
if is_torch_namespace(xp):
|
| 937 |
+
# see `partition` above for commented details of those steps:
|
| 938 |
+
if not (axis == -1 or axis == a.ndim - 1):
|
| 939 |
+
a = xp.transpose(a, axis, -1)
|
| 940 |
+
|
| 941 |
+
ranks = xp.arange(a.shape[-1]).expand_as(a)
|
| 942 |
+
out = xp.empty_like(ranks)
|
| 943 |
+
|
| 944 |
+
split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True)
|
| 945 |
+
del indices # indices won't be used => del ASAP to reduce peak memory usage
|
| 946 |
+
|
| 947 |
+
mask_src = a < split_value
|
| 948 |
+
n_left = mask_src.sum(dim=-1, keepdim=True)
|
| 949 |
+
mask_dest = ranks < n_left
|
| 950 |
+
out[mask_dest] = ranks[mask_src]
|
| 951 |
+
|
| 952 |
+
mask_src = a == split_value
|
| 953 |
+
n_left += mask_src.sum(dim=-1, keepdim=True)
|
| 954 |
+
mask_dest ^= ranks < n_left
|
| 955 |
+
out[mask_dest] = ranks[mask_src]
|
| 956 |
+
|
| 957 |
+
mask_src = a > split_value
|
| 958 |
+
mask_dest = ranks >= n_left
|
| 959 |
+
out[mask_dest] = ranks[mask_src]
|
| 960 |
+
|
| 961 |
+
if not (axis == -1 or axis == a.ndim - 1):
|
| 962 |
+
out = xp.transpose(out, axis, -1)
|
| 963 |
+
return out
|
| 964 |
+
|
| 965 |
+
# Note: dask topk/argtopk sort the return values, so it's
|
| 966 |
+
# not much more efficient than sorting everything when
|
| 967 |
+
# kth is not small compared to x.size
|
| 968 |
+
|
| 969 |
+
return _funcs.argpartition(a, kth, axis=axis, xp=xp)
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def isin(
|
| 973 |
+
a: Array,
|
| 974 |
+
b: Array,
|
| 975 |
+
/,
|
| 976 |
+
*,
|
| 977 |
+
assume_unique: bool = False,
|
| 978 |
+
invert: bool = False,
|
| 979 |
+
kind: str | None = None,
|
| 980 |
+
xp: ModuleType | None = None,
|
| 981 |
+
) -> Array:
|
| 982 |
+
"""
|
| 983 |
+
Determine whether each element in `a` is present in `b`.
|
| 984 |
+
|
| 985 |
+
Return a boolean array of the same shape as `a` that is True for elements
|
| 986 |
+
that are in `b` and False otherwise.
|
| 987 |
+
|
| 988 |
+
Parameters
|
| 989 |
+
----------
|
| 990 |
+
a : array
|
| 991 |
+
Input elements.
|
| 992 |
+
b : array
|
| 993 |
+
The elements against which to test each element of `a`.
|
| 994 |
+
assume_unique : bool, optional
|
| 995 |
+
If True, the input arrays are both assumed to be unique which can speed
|
| 996 |
+
up the calculation. Default: False.
|
| 997 |
+
invert : bool, optional
|
| 998 |
+
If True, the values in the returned array are inverted. Default: False.
|
| 999 |
+
kind : str | None, optional
|
| 1000 |
+
The algorithm or method to use. This will not affect the final result,
|
| 1001 |
+
but will affect the speed and memory use.
|
| 1002 |
+
For NumPy the options are {None, "sort", "table"}.
|
| 1003 |
+
For Jax the mapped parameter is instead `method` and the options are
|
| 1004 |
+
{"compare_all", "binary_search", "sort", and "auto" (default)}
|
| 1005 |
+
For CuPy, Dask, Torch and the default case this parameter is not present and
|
| 1006 |
+
thus ignored. Default: None.
|
| 1007 |
+
xp : array_namespace, optional
|
| 1008 |
+
The standard-compatible namespace for `a` and `b`. Default: infer.
|
| 1009 |
+
|
| 1010 |
+
Returns
|
| 1011 |
+
-------
|
| 1012 |
+
array
|
| 1013 |
+
An array having the same shape as that of `a` that is True for elements
|
| 1014 |
+
that are in `b` and False otherwise.
|
| 1015 |
+
"""
|
| 1016 |
+
if xp is None:
|
| 1017 |
+
xp = array_namespace(a, b)
|
| 1018 |
+
|
| 1019 |
+
if is_numpy_namespace(xp):
|
| 1020 |
+
return xp.isin(a, b, assume_unique=assume_unique, invert=invert, kind=kind)
|
| 1021 |
+
if is_jax_namespace(xp):
|
| 1022 |
+
if kind is None:
|
| 1023 |
+
kind = "auto"
|
| 1024 |
+
return xp.isin(a, b, assume_unique=assume_unique, invert=invert, method=kind)
|
| 1025 |
+
if is_cupy_namespace(xp) or is_torch_namespace(xp) or is_dask_namespace(xp):
|
| 1026 |
+
return xp.isin(a, b, assume_unique=assume_unique, invert=invert)
|
| 1027 |
+
|
| 1028 |
+
return _funcs.isin(a, b, assume_unique=assume_unique, invert=invert, xp=xp)
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Internals of array-api-extra."""
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (314 Bytes). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_at.cpython-311.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_backends.cpython-311.pyc
ADDED
|
Binary file (3.89 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_funcs.cpython-311.pyc
ADDED
|
Binary file (33.1 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_lazy.cpython-311.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/__pycache__/_testing.cpython-311.pyc
ADDED
|
Binary file (12.4 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_at.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Update operations for read-only arrays."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import operator
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from enum import Enum
|
| 8 |
+
from types import ModuleType
|
| 9 |
+
from typing import TYPE_CHECKING, ClassVar, cast
|
| 10 |
+
|
| 11 |
+
from ._utils import _compat
|
| 12 |
+
from ._utils._compat import (
|
| 13 |
+
array_namespace,
|
| 14 |
+
is_dask_array,
|
| 15 |
+
is_jax_array,
|
| 16 |
+
is_torch_array,
|
| 17 |
+
is_writeable_array,
|
| 18 |
+
)
|
| 19 |
+
from ._utils._helpers import meta_namespace
|
| 20 |
+
from ._utils._typing import Array, SetIndex
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 23 |
+
# TODO import from typing (requires Python >=3.11)
|
| 24 |
+
from typing_extensions import Self
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class _AtOp(Enum):
|
| 28 |
+
"""Operations for use in `xpx.at`."""
|
| 29 |
+
|
| 30 |
+
SET = "set"
|
| 31 |
+
ADD = "add"
|
| 32 |
+
SUBTRACT = "subtract"
|
| 33 |
+
MULTIPLY = "multiply"
|
| 34 |
+
DIVIDE = "divide"
|
| 35 |
+
POWER = "power"
|
| 36 |
+
MIN = "min"
|
| 37 |
+
MAX = "max"
|
| 38 |
+
|
| 39 |
+
# @override from Python 3.12
|
| 40 |
+
def __str__(self) -> str: # pyright: ignore[reportImplicitOverride]
|
| 41 |
+
"""
|
| 42 |
+
Return string representation (useful for pytest logs).
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
str
|
| 47 |
+
The operation's name.
|
| 48 |
+
"""
|
| 49 |
+
return self.value
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class Undef(Enum):
|
| 53 |
+
"""Sentinel for undefined values."""
|
| 54 |
+
|
| 55 |
+
UNDEF = 0
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
_undef = Undef.UNDEF
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class at: # pylint: disable=invalid-name # numpydoc ignore=PR02
|
| 62 |
+
"""
|
| 63 |
+
Update operations for read-only arrays.
|
| 64 |
+
|
| 65 |
+
This implements ``jax.numpy.ndarray.at`` for all writeable
|
| 66 |
+
backends (those that support ``__setitem__``) and routes
|
| 67 |
+
to the ``.at[]`` method for JAX arrays.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
x : array
|
| 72 |
+
Input array.
|
| 73 |
+
idx : index, optional
|
| 74 |
+
Only `array API standard compliant indices
|
| 75 |
+
<https://data-apis.org/array-api/latest/API_specification/indexing.html>`_
|
| 76 |
+
are supported.
|
| 77 |
+
|
| 78 |
+
You may use two alternate syntaxes::
|
| 79 |
+
|
| 80 |
+
>>> import array_api_extra as xpx
|
| 81 |
+
>>> xpx.at(x, idx).set(value) # or add(value), etc.
|
| 82 |
+
>>> xpx.at(x)[idx].set(value)
|
| 83 |
+
|
| 84 |
+
copy : bool, optional
|
| 85 |
+
None (default)
|
| 86 |
+
The array parameter *may* be modified in place if it is
|
| 87 |
+
possible and beneficial for performance.
|
| 88 |
+
You should not reuse it after calling this function.
|
| 89 |
+
True
|
| 90 |
+
Ensure that the inputs are not modified.
|
| 91 |
+
False
|
| 92 |
+
Ensure that the update operation writes back to the input.
|
| 93 |
+
Raise ``ValueError`` if a copy cannot be avoided.
|
| 94 |
+
|
| 95 |
+
xp : array_namespace, optional
|
| 96 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 97 |
+
|
| 98 |
+
Returns
|
| 99 |
+
-------
|
| 100 |
+
Updated input array.
|
| 101 |
+
|
| 102 |
+
Warnings
|
| 103 |
+
--------
|
| 104 |
+
(a) When you omit the ``copy`` parameter, you should never reuse the parameter
|
| 105 |
+
array later on; ideally, you should reassign it immediately::
|
| 106 |
+
|
| 107 |
+
>>> import array_api_extra as xpx
|
| 108 |
+
>>> x = xpx.at(x, 0).set(2)
|
| 109 |
+
|
| 110 |
+
The above best practice pattern ensures that the behaviour won't change depending
|
| 111 |
+
on whether ``x`` is writeable or not, as the original ``x`` object is dereferenced
|
| 112 |
+
as soon as ``xpx.at`` returns; this way there is no risk to accidentally update it
|
| 113 |
+
twice.
|
| 114 |
+
|
| 115 |
+
On the reverse, the anti-pattern below must be avoided, as it will result in
|
| 116 |
+
different behaviour on read-only versus writeable arrays::
|
| 117 |
+
|
| 118 |
+
>>> x = xp.asarray([0, 0, 0])
|
| 119 |
+
>>> y = xpx.at(x, 0).set(2)
|
| 120 |
+
>>> z = xpx.at(x, 1).set(3)
|
| 121 |
+
|
| 122 |
+
In the above example, both calls to ``xpx.at`` update ``x`` in place *if possible*.
|
| 123 |
+
This causes the behaviour to diverge depending on whether ``x`` is writeable or not:
|
| 124 |
+
|
| 125 |
+
- If ``x`` is writeable, then after the snippet above you'll have
|
| 126 |
+
``x == y == z == [2, 3, 0]``
|
| 127 |
+
- If ``x`` is read-only, then you'll end up with
|
| 128 |
+
``x == [0, 0, 0]``, ``y == [2, 0, 0]`` and ``z == [0, 3, 0]``.
|
| 129 |
+
|
| 130 |
+
The correct pattern to use if you want diverging outputs from the same input is
|
| 131 |
+
to enforce copies::
|
| 132 |
+
|
| 133 |
+
>>> x = xp.asarray([0, 0, 0])
|
| 134 |
+
>>> y = xpx.at(x, 0).set(2, copy=True) # Never updates x
|
| 135 |
+
>>> z = xpx.at(x, 1).set(3) # May or may not update x in place
|
| 136 |
+
>>> del x # avoid accidental reuse of x as we don't know its state anymore
|
| 137 |
+
|
| 138 |
+
(b) The array API standard does not support integer array indices.
|
| 139 |
+
The behaviour of update methods when the index is an array of integers is
|
| 140 |
+
undefined and will vary between backends; this is particularly true when the
|
| 141 |
+
index contains multiple occurrences of the same index, e.g.::
|
| 142 |
+
|
| 143 |
+
>>> import numpy as np
|
| 144 |
+
>>> import jax.numpy as jnp
|
| 145 |
+
>>> import array_api_extra as xpx
|
| 146 |
+
>>> xpx.at(np.asarray([123]), np.asarray([0, 0])).add(1)
|
| 147 |
+
array([124])
|
| 148 |
+
>>> xpx.at(jnp.asarray([123]), jnp.asarray([0, 0])).add(1)
|
| 149 |
+
Array([125], dtype=int32)
|
| 150 |
+
|
| 151 |
+
See Also
|
| 152 |
+
--------
|
| 153 |
+
jax.numpy.ndarray.at : Equivalent array method in JAX.
|
| 154 |
+
|
| 155 |
+
Notes
|
| 156 |
+
-----
|
| 157 |
+
`sparse <https://sparse.pydata.org/>`_, as well as read-only arrays from libraries
|
| 158 |
+
not explicitly covered by ``array-api-compat``, are not supported by update
|
| 159 |
+
methods.
|
| 160 |
+
|
| 161 |
+
Boolean masks are supported on Dask and jitted JAX arrays exclusively
|
| 162 |
+
when `idx` has the same shape as `x` and `y` is 0-dimensional.
|
| 163 |
+
Note that this support is not available in JAX's native
|
| 164 |
+
``x.at[mask].set(y)``.
|
| 165 |
+
|
| 166 |
+
This pattern::
|
| 167 |
+
|
| 168 |
+
>>> mask = m(x)
|
| 169 |
+
>>> x[mask] = f(x[mask])
|
| 170 |
+
|
| 171 |
+
Can't be replaced by `at`, as it won't work on Dask and JAX inside jax.jit::
|
| 172 |
+
|
| 173 |
+
>>> mask = m(x)
|
| 174 |
+
>>> x = xpx.at(x, mask).set(f(x[mask]) # Crash on Dask and jax.jit
|
| 175 |
+
|
| 176 |
+
You should instead use::
|
| 177 |
+
|
| 178 |
+
>>> x = xp.where(m(x), f(x), x)
|
| 179 |
+
|
| 180 |
+
Examples
|
| 181 |
+
--------
|
| 182 |
+
Given either of these equivalent expressions::
|
| 183 |
+
|
| 184 |
+
>>> import array_api_extra as xpx
|
| 185 |
+
>>> x = xpx.at(x)[1].add(2)
|
| 186 |
+
>>> x = xpx.at(x, 1).add(2)
|
| 187 |
+
|
| 188 |
+
If x is a JAX array, they are the same as::
|
| 189 |
+
|
| 190 |
+
>>> x = x.at[1].add(2)
|
| 191 |
+
|
| 192 |
+
If x is a read-only NumPy array, they are the same as::
|
| 193 |
+
|
| 194 |
+
>>> x = x.copy()
|
| 195 |
+
>>> x[1] += 2
|
| 196 |
+
|
| 197 |
+
For other known backends, they are the same as::
|
| 198 |
+
|
| 199 |
+
>>> x[1] += 2
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
_x: Array
|
| 203 |
+
_idx: SetIndex | Undef
|
| 204 |
+
__slots__: ClassVar[tuple[str, ...]] = ("_idx", "_x")
|
| 205 |
+
|
| 206 |
+
def __init__(
|
| 207 |
+
self, x: Array, idx: SetIndex | Undef = _undef, /
|
| 208 |
+
) -> None: # numpydoc ignore=GL08
|
| 209 |
+
self._x = x
|
| 210 |
+
self._idx = idx
|
| 211 |
+
|
| 212 |
+
def __getitem__(self, idx: SetIndex, /) -> Self: # numpydoc ignore=PR01,RT01
|
| 213 |
+
"""
|
| 214 |
+
Allow for the alternate syntax ``at(x)[start:stop:step]``.
|
| 215 |
+
|
| 216 |
+
It looks prettier than ``at(x, slice(start, stop, step))``
|
| 217 |
+
and feels more intuitive coming from the JAX documentation.
|
| 218 |
+
"""
|
| 219 |
+
if self._idx is not _undef:
|
| 220 |
+
msg = "Index has already been set"
|
| 221 |
+
raise ValueError(msg)
|
| 222 |
+
return type(self)(self._x, idx)
|
| 223 |
+
|
| 224 |
+
def _op(
|
| 225 |
+
self,
|
| 226 |
+
at_op: _AtOp,
|
| 227 |
+
in_place_op: Callable[[Array, Array | complex], Array] | None,
|
| 228 |
+
out_of_place_op: Callable[[Array, Array], Array] | None,
|
| 229 |
+
y: Array | complex,
|
| 230 |
+
/,
|
| 231 |
+
copy: bool | None,
|
| 232 |
+
xp: ModuleType | None,
|
| 233 |
+
) -> Array:
|
| 234 |
+
"""
|
| 235 |
+
Implement all update operations.
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
----------
|
| 239 |
+
at_op : _AtOp
|
| 240 |
+
Method of JAX's Array.at[].
|
| 241 |
+
in_place_op : Callable[[Array, Array | complex], Array] | None
|
| 242 |
+
In-place operation to apply on mutable backends::
|
| 243 |
+
|
| 244 |
+
x[idx] = in_place_op(x[idx], y)
|
| 245 |
+
|
| 246 |
+
If None::
|
| 247 |
+
|
| 248 |
+
x[idx] = y
|
| 249 |
+
|
| 250 |
+
out_of_place_op : Callable[[Array, Array], Array] | None
|
| 251 |
+
Out-of-place operation to apply when idx is a boolean mask and the backend
|
| 252 |
+
doesn't support in-place updates::
|
| 253 |
+
|
| 254 |
+
x = xp.where(idx, out_of_place_op(x, y), x)
|
| 255 |
+
|
| 256 |
+
If None::
|
| 257 |
+
|
| 258 |
+
x = xp.where(idx, y, x)
|
| 259 |
+
|
| 260 |
+
y : array or complex
|
| 261 |
+
Right-hand side of the operation.
|
| 262 |
+
copy : bool or None
|
| 263 |
+
Whether to copy the input array. See the class docstring for details.
|
| 264 |
+
xp : array_namespace, optional
|
| 265 |
+
The array namespace for the input array. Default: infer.
|
| 266 |
+
|
| 267 |
+
Returns
|
| 268 |
+
-------
|
| 269 |
+
Array
|
| 270 |
+
Updated `x`.
|
| 271 |
+
"""
|
| 272 |
+
from ._funcs import apply_where # pylint: disable=cyclic-import
|
| 273 |
+
|
| 274 |
+
x, idx = self._x, self._idx
|
| 275 |
+
xp = array_namespace(x, y) if xp is None else xp
|
| 276 |
+
|
| 277 |
+
if isinstance(idx, Undef):
|
| 278 |
+
msg = (
|
| 279 |
+
"Index has not been set.\n"
|
| 280 |
+
"Usage: either\n"
|
| 281 |
+
" at(x, idx).set(value)\n"
|
| 282 |
+
"or\n"
|
| 283 |
+
" at(x)[idx].set(value)\n"
|
| 284 |
+
"(same for all other methods)."
|
| 285 |
+
)
|
| 286 |
+
raise ValueError(msg)
|
| 287 |
+
|
| 288 |
+
if copy not in (True, False, None):
|
| 289 |
+
msg = f"copy must be True, False, or None; got {copy!r}"
|
| 290 |
+
raise ValueError(msg)
|
| 291 |
+
|
| 292 |
+
writeable = None if copy else is_writeable_array(x)
|
| 293 |
+
|
| 294 |
+
# JAX inside jax.jit doesn't support in-place updates with boolean
|
| 295 |
+
# masks; Dask exclusively supports __setitem__ but not iops.
|
| 296 |
+
# We can handle the common special case of 0-dimensional y
|
| 297 |
+
# with where(idx, y, x) instead.
|
| 298 |
+
if (
|
| 299 |
+
(is_dask_array(idx) or is_jax_array(idx))
|
| 300 |
+
and idx.dtype == xp.bool
|
| 301 |
+
and idx.shape == x.shape
|
| 302 |
+
):
|
| 303 |
+
y_xp = xp.asarray(y, dtype=x.dtype, device=_compat.device(x))
|
| 304 |
+
if y_xp.ndim == 0:
|
| 305 |
+
if out_of_place_op: # add(), subtract(), ...
|
| 306 |
+
# suppress inf warnings on Dask
|
| 307 |
+
out = apply_where(
|
| 308 |
+
idx, (x, y_xp), out_of_place_op, fill_value=x, xp=xp
|
| 309 |
+
)
|
| 310 |
+
# Undo int->float promotion on JAX after _AtOp.DIVIDE
|
| 311 |
+
out = xp.astype(out, x.dtype, copy=False)
|
| 312 |
+
else: # set()
|
| 313 |
+
out = xp.where(idx, y_xp, x)
|
| 314 |
+
|
| 315 |
+
if copy is False:
|
| 316 |
+
x[()] = out
|
| 317 |
+
return x
|
| 318 |
+
return out
|
| 319 |
+
|
| 320 |
+
# else: this will work on eager JAX and crash on jax.jit and Dask
|
| 321 |
+
|
| 322 |
+
if copy or (copy is None and not writeable):
|
| 323 |
+
if is_jax_array(x):
|
| 324 |
+
# Use JAX's at[]
|
| 325 |
+
func = cast(
|
| 326 |
+
Callable[[Array | complex], Array],
|
| 327 |
+
getattr(x.at[idx], at_op.value), # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue,reportUnknownArgumentType]
|
| 328 |
+
)
|
| 329 |
+
out = func(y)
|
| 330 |
+
# Undo int->float promotion on JAX after _AtOp.DIVIDE
|
| 331 |
+
return xp.astype(out, x.dtype, copy=False)
|
| 332 |
+
|
| 333 |
+
# Emulate at[] behaviour for non-JAX arrays
|
| 334 |
+
# with a copy followed by an update
|
| 335 |
+
|
| 336 |
+
x = xp.asarray(x, copy=True)
|
| 337 |
+
# A copy of a read-only numpy array is writeable
|
| 338 |
+
# Note: this assumes that a copy of a writeable array is writeable
|
| 339 |
+
assert not writeable
|
| 340 |
+
writeable = None
|
| 341 |
+
|
| 342 |
+
if writeable is None:
|
| 343 |
+
writeable = is_writeable_array(x)
|
| 344 |
+
if not writeable:
|
| 345 |
+
# sparse crashes here
|
| 346 |
+
msg = f"Can't update read-only array {x}"
|
| 347 |
+
raise ValueError(msg)
|
| 348 |
+
|
| 349 |
+
# Work around bug in PyTorch where __setitem__ doesn't
|
| 350 |
+
# always support mismatched dtypes
|
| 351 |
+
# https://github.com/pytorch/pytorch/issues/150017
|
| 352 |
+
if is_torch_array(y):
|
| 353 |
+
y = xp.astype(y, x.dtype, copy=False)
|
| 354 |
+
|
| 355 |
+
# Backends without boolean indexing (other than JAX) crash here
|
| 356 |
+
if in_place_op: # add(), subtract(), ...
|
| 357 |
+
x[idx] = in_place_op(x[idx], y)
|
| 358 |
+
else: # set()
|
| 359 |
+
x[idx] = y
|
| 360 |
+
return x
|
| 361 |
+
|
| 362 |
+
def set(
|
| 363 |
+
self,
|
| 364 |
+
y: Array | complex,
|
| 365 |
+
/,
|
| 366 |
+
copy: bool | None = None,
|
| 367 |
+
xp: ModuleType | None = None,
|
| 368 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 369 |
+
"""Apply ``x[idx] = y`` and return the update array."""
|
| 370 |
+
return self._op(_AtOp.SET, None, None, y, copy=copy, xp=xp)
|
| 371 |
+
|
| 372 |
+
def add(
|
| 373 |
+
self,
|
| 374 |
+
y: Array | complex,
|
| 375 |
+
/,
|
| 376 |
+
copy: bool | None = None,
|
| 377 |
+
xp: ModuleType | None = None,
|
| 378 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 379 |
+
"""Apply ``x[idx] += y`` and return the updated array."""
|
| 380 |
+
|
| 381 |
+
# Note for this and all other methods based on _iop:
|
| 382 |
+
# operator.iadd and operator.add subtly differ in behaviour, as
|
| 383 |
+
# only iadd will trigger exceptions when y has an incompatible dtype.
|
| 384 |
+
return self._op(_AtOp.ADD, operator.iadd, operator.add, y, copy=copy, xp=xp)
|
| 385 |
+
|
| 386 |
+
def subtract(
|
| 387 |
+
self,
|
| 388 |
+
y: Array | complex,
|
| 389 |
+
/,
|
| 390 |
+
copy: bool | None = None,
|
| 391 |
+
xp: ModuleType | None = None,
|
| 392 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 393 |
+
"""Apply ``x[idx] -= y`` and return the updated array."""
|
| 394 |
+
return self._op(
|
| 395 |
+
_AtOp.SUBTRACT, operator.isub, operator.sub, y, copy=copy, xp=xp
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
def multiply(
|
| 399 |
+
self,
|
| 400 |
+
y: Array | complex,
|
| 401 |
+
/,
|
| 402 |
+
copy: bool | None = None,
|
| 403 |
+
xp: ModuleType | None = None,
|
| 404 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 405 |
+
"""Apply ``x[idx] *= y`` and return the updated array."""
|
| 406 |
+
return self._op(
|
| 407 |
+
_AtOp.MULTIPLY, operator.imul, operator.mul, y, copy=copy, xp=xp
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
def divide(
|
| 411 |
+
self,
|
| 412 |
+
y: Array | complex,
|
| 413 |
+
/,
|
| 414 |
+
copy: bool | None = None,
|
| 415 |
+
xp: ModuleType | None = None,
|
| 416 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 417 |
+
"""Apply ``x[idx] /= y`` and return the updated array."""
|
| 418 |
+
return self._op(
|
| 419 |
+
_AtOp.DIVIDE, operator.itruediv, operator.truediv, y, copy=copy, xp=xp
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
def power(
|
| 423 |
+
self,
|
| 424 |
+
y: Array | complex,
|
| 425 |
+
/,
|
| 426 |
+
copy: bool | None = None,
|
| 427 |
+
xp: ModuleType | None = None,
|
| 428 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 429 |
+
"""Apply ``x[idx] **= y`` and return the updated array."""
|
| 430 |
+
return self._op(_AtOp.POWER, operator.ipow, operator.pow, y, copy=copy, xp=xp)
|
| 431 |
+
|
| 432 |
+
def min(
|
| 433 |
+
self,
|
| 434 |
+
y: Array | complex,
|
| 435 |
+
/,
|
| 436 |
+
copy: bool | None = None,
|
| 437 |
+
xp: ModuleType | None = None,
|
| 438 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 439 |
+
"""Apply ``x[idx] = minimum(x[idx], y)`` and return the updated array."""
|
| 440 |
+
# On Dask, this function runs on the chunks, so we need to determine the
|
| 441 |
+
# namespace that Dask is wrapping.
|
| 442 |
+
# Note that da.minimum _incidentally_ works on NumPy, CuPy, and sparse
|
| 443 |
+
# thanks to all these meta-namespaces implementing the __array_ufunc__
|
| 444 |
+
# interface, but there's no guarantee that it will work for other
|
| 445 |
+
# wrapped libraries in the future.
|
| 446 |
+
xp = array_namespace(self._x) if xp is None else xp
|
| 447 |
+
mxp = meta_namespace(self._x, xp=xp)
|
| 448 |
+
y = xp.asarray(y)
|
| 449 |
+
return self._op(_AtOp.MIN, mxp.minimum, mxp.minimum, y, copy=copy, xp=xp)
|
| 450 |
+
|
| 451 |
+
def max(
|
| 452 |
+
self,
|
| 453 |
+
y: Array | complex,
|
| 454 |
+
/,
|
| 455 |
+
copy: bool | None = None,
|
| 456 |
+
xp: ModuleType | None = None,
|
| 457 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 458 |
+
"""Apply ``x[idx] = maximum(x[idx], y)`` and return the updated array."""
|
| 459 |
+
# See note on min()
|
| 460 |
+
xp = array_namespace(self._x) if xp is None else xp
|
| 461 |
+
mxp = meta_namespace(self._x, xp=xp)
|
| 462 |
+
y = xp.asarray(y)
|
| 463 |
+
return self._op(_AtOp.MAX, mxp.maximum, mxp.maximum, y, copy=copy, xp=xp)
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_backends.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backends against which array-api-extra runs its tests."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
__all__ = ["NUMPY_VERSION", "Backend"]
|
| 12 |
+
|
| 13 |
+
NUMPY_VERSION = tuple(int(v) for v in np.__version__.split(".")[:3]) # pyright: ignore[reportUnknownArgumentType]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Backend(Enum): # numpydoc ignore=PR02
|
| 17 |
+
"""
|
| 18 |
+
All array library backends explicitly tested by array-api-extra.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
value : str
|
| 23 |
+
Tag of the backend's module, in the format ``<namespace>[:<extra tag>]``.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
# Use :<tag> to prevent Enum from deduplicating items with the same value
|
| 27 |
+
ARRAY_API_STRICT = "array_api_strict"
|
| 28 |
+
ARRAY_API_STRICTEST = "array_api_strict:strictest"
|
| 29 |
+
NUMPY = "numpy"
|
| 30 |
+
NUMPY_READONLY = "numpy:readonly"
|
| 31 |
+
CUPY = "cupy"
|
| 32 |
+
TORCH = "torch"
|
| 33 |
+
TORCH_GPU = "torch:gpu"
|
| 34 |
+
DASK = "dask.array"
|
| 35 |
+
SPARSE = "sparse"
|
| 36 |
+
JAX = "jax.numpy"
|
| 37 |
+
JAX_GPU = "jax.numpy:gpu"
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def modname(self) -> str: # numpydoc ignore=RT01
|
| 41 |
+
"""Module name to be imported."""
|
| 42 |
+
return self.value.split(":")[0]
|
| 43 |
+
|
| 44 |
+
def like(self, *others: Backend) -> bool: # numpydoc ignore=PR01,RT01
|
| 45 |
+
"""Check if this backend uses the same module as others."""
|
| 46 |
+
return any(self.modname == other.modname for other in others)
|
| 47 |
+
|
| 48 |
+
def pytest_param(self) -> Any:
|
| 49 |
+
"""
|
| 50 |
+
Backend as a pytest parameter
|
| 51 |
+
|
| 52 |
+
Returns
|
| 53 |
+
-------
|
| 54 |
+
pytest.mark.ParameterSet
|
| 55 |
+
"""
|
| 56 |
+
id_ = (
|
| 57 |
+
self.name.lower().replace("_gpu", ":gpu").replace("_readonly", ":readonly")
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
marks = []
|
| 61 |
+
if self.like(Backend.ARRAY_API_STRICT):
|
| 62 |
+
marks.append(
|
| 63 |
+
pytest.mark.skipif(
|
| 64 |
+
NUMPY_VERSION < (1, 26),
|
| 65 |
+
reason="array_api_strict is untested on NumPy <1.26",
|
| 66 |
+
)
|
| 67 |
+
)
|
| 68 |
+
if self.like(Backend.DASK, Backend.JAX):
|
| 69 |
+
# Monkey-patched by lazy_xp_function
|
| 70 |
+
marks.append(pytest.mark.thread_unsafe)
|
| 71 |
+
|
| 72 |
+
return pytest.param(self, id=id_, marks=marks) # pyright: ignore[reportUnknownArgumentType]
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_funcs.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Array-agnostic implementations for the public API."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import warnings
|
| 5 |
+
from collections.abc import Callable, Sequence
|
| 6 |
+
from types import ModuleType, NoneType
|
| 7 |
+
from typing import Literal, cast, overload
|
| 8 |
+
|
| 9 |
+
from ._at import at
|
| 10 |
+
from ._utils import _compat, _helpers
|
| 11 |
+
from ._utils._compat import array_namespace, is_dask_namespace, is_jax_array
|
| 12 |
+
from ._utils._helpers import (
|
| 13 |
+
asarrays,
|
| 14 |
+
capabilities,
|
| 15 |
+
eager_shape,
|
| 16 |
+
meta_namespace,
|
| 17 |
+
ndindex,
|
| 18 |
+
)
|
| 19 |
+
from ._utils._typing import Array, Device, DType
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"apply_where",
|
| 23 |
+
"atleast_nd",
|
| 24 |
+
"broadcast_shapes",
|
| 25 |
+
"cov",
|
| 26 |
+
"create_diagonal",
|
| 27 |
+
"expand_dims",
|
| 28 |
+
"kron",
|
| 29 |
+
"nunique",
|
| 30 |
+
"pad",
|
| 31 |
+
"setdiff1d",
|
| 32 |
+
"sinc",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@overload
|
| 37 |
+
def apply_where( # numpydoc ignore=GL08
|
| 38 |
+
cond: Array,
|
| 39 |
+
args: Array | tuple[Array, ...],
|
| 40 |
+
f1: Callable[..., Array],
|
| 41 |
+
f2: Callable[..., Array],
|
| 42 |
+
/,
|
| 43 |
+
*,
|
| 44 |
+
xp: ModuleType | None = None,
|
| 45 |
+
) -> Array: ...
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@overload
|
| 49 |
+
def apply_where( # numpydoc ignore=GL08
|
| 50 |
+
cond: Array,
|
| 51 |
+
args: Array | tuple[Array, ...],
|
| 52 |
+
f1: Callable[..., Array],
|
| 53 |
+
/,
|
| 54 |
+
*,
|
| 55 |
+
fill_value: Array | complex,
|
| 56 |
+
xp: ModuleType | None = None,
|
| 57 |
+
) -> Array: ...
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def apply_where( # numpydoc ignore=PR01,PR02
|
| 61 |
+
cond: Array,
|
| 62 |
+
args: Array | tuple[Array, ...],
|
| 63 |
+
f1: Callable[..., Array],
|
| 64 |
+
f2: Callable[..., Array] | None = None,
|
| 65 |
+
/,
|
| 66 |
+
*,
|
| 67 |
+
fill_value: Array | complex | None = None,
|
| 68 |
+
xp: ModuleType | None = None,
|
| 69 |
+
) -> Array:
|
| 70 |
+
"""
|
| 71 |
+
Run one of two elementwise functions depending on a condition.
|
| 72 |
+
|
| 73 |
+
Equivalent to ``f1(*args) if cond else fill_value`` performed elementwise
|
| 74 |
+
when `fill_value` is defined, otherwise to ``f1(*args) if cond else f2(*args)``.
|
| 75 |
+
|
| 76 |
+
Parameters
|
| 77 |
+
----------
|
| 78 |
+
cond : array
|
| 79 |
+
The condition, expressed as a boolean array.
|
| 80 |
+
args : Array or tuple of Arrays
|
| 81 |
+
Argument(s) to `f1` (and `f2`). Must be broadcastable with `cond`.
|
| 82 |
+
f1 : callable
|
| 83 |
+
Elementwise function of `args`, returning a single array.
|
| 84 |
+
Where `cond` is True, output will be ``f1(arg0[cond], arg1[cond], ...)``.
|
| 85 |
+
f2 : callable, optional
|
| 86 |
+
Elementwise function of `args`, returning a single array.
|
| 87 |
+
Where `cond` is False, output will be ``f2(arg0[cond], arg1[cond], ...)``.
|
| 88 |
+
Mutually exclusive with `fill_value`.
|
| 89 |
+
fill_value : Array or scalar, optional
|
| 90 |
+
If provided, value with which to fill output array where `cond` is False.
|
| 91 |
+
It does not need to be scalar; it needs however to be broadcastable with
|
| 92 |
+
`cond` and `args`.
|
| 93 |
+
Mutually exclusive with `f2`. You must provide one or the other.
|
| 94 |
+
xp : array_namespace, optional
|
| 95 |
+
The standard-compatible namespace for `cond` and `args`. Default: infer.
|
| 96 |
+
|
| 97 |
+
Returns
|
| 98 |
+
-------
|
| 99 |
+
Array
|
| 100 |
+
An array with elements from the output of `f1` where `cond` is True and either
|
| 101 |
+
the output of `f2` or `fill_value` where `cond` is False. The returned array has
|
| 102 |
+
data type determined by type promotion rules between the output of `f1` and
|
| 103 |
+
either `fill_value` or the output of `f2`.
|
| 104 |
+
|
| 105 |
+
Notes
|
| 106 |
+
-----
|
| 107 |
+
``xp.where(cond, f1(*args), f2(*args))`` requires explicitly evaluating `f1` even
|
| 108 |
+
when `cond` is False, and `f2` when cond is True. This function evaluates each
|
| 109 |
+
function only for their matching condition, if the backend allows for it.
|
| 110 |
+
|
| 111 |
+
On Dask, `f1` and `f2` are applied to the individual chunks and should use functions
|
| 112 |
+
from the namespace of the chunks.
|
| 113 |
+
|
| 114 |
+
Examples
|
| 115 |
+
--------
|
| 116 |
+
>>> import array_api_strict as xp
|
| 117 |
+
>>> import array_api_extra as xpx
|
| 118 |
+
>>> a = xp.asarray([5, 4, 3])
|
| 119 |
+
>>> b = xp.asarray([0, 2, 2])
|
| 120 |
+
>>> def f(a, b):
|
| 121 |
+
... return a // b
|
| 122 |
+
>>> xpx.apply_where(b != 0, (a, b), f, fill_value=xp.nan)
|
| 123 |
+
array([ nan, 2., 1.])
|
| 124 |
+
"""
|
| 125 |
+
# Parse and normalize arguments
|
| 126 |
+
if (f2 is None) == (fill_value is None):
|
| 127 |
+
msg = "Exactly one of `fill_value` or `f2` must be given."
|
| 128 |
+
raise TypeError(msg)
|
| 129 |
+
args_ = list(args) if isinstance(args, tuple) else [args]
|
| 130 |
+
del args
|
| 131 |
+
|
| 132 |
+
xp = array_namespace(cond, fill_value, *args_) if xp is None else xp
|
| 133 |
+
|
| 134 |
+
if isinstance(fill_value, int | float | complex | NoneType):
|
| 135 |
+
cond, *args_ = xp.broadcast_arrays(cond, *args_)
|
| 136 |
+
else:
|
| 137 |
+
cond, fill_value, *args_ = xp.broadcast_arrays(cond, fill_value, *args_)
|
| 138 |
+
|
| 139 |
+
if is_dask_namespace(xp):
|
| 140 |
+
meta_xp = meta_namespace(cond, fill_value, *args_, xp=xp)
|
| 141 |
+
# map_blocks doesn't descend into tuples of Arrays
|
| 142 |
+
return xp.map_blocks(_apply_where, cond, f1, f2, fill_value, *args_, xp=meta_xp)
|
| 143 |
+
return _apply_where(cond, f1, f2, fill_value, *args_, xp=xp)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _apply_where( # numpydoc ignore=PR01,RT01
|
| 147 |
+
cond: Array,
|
| 148 |
+
f1: Callable[..., Array],
|
| 149 |
+
f2: Callable[..., Array] | None,
|
| 150 |
+
fill_value: Array | int | float | complex | bool | None,
|
| 151 |
+
*args: Array,
|
| 152 |
+
xp: ModuleType,
|
| 153 |
+
) -> Array:
|
| 154 |
+
"""Helper of `apply_where`. On Dask, this runs on a single chunk."""
|
| 155 |
+
|
| 156 |
+
if not capabilities(xp, device=_compat.device(cond))["boolean indexing"]:
|
| 157 |
+
# jax.jit does not support assignment by boolean mask
|
| 158 |
+
return xp.where(cond, f1(*args), f2(*args) if f2 is not None else fill_value)
|
| 159 |
+
|
| 160 |
+
temp1 = f1(*(arr[cond] for arr in args))
|
| 161 |
+
|
| 162 |
+
if f2 is None:
|
| 163 |
+
dtype = xp.result_type(temp1, fill_value)
|
| 164 |
+
if isinstance(fill_value, int | float | complex):
|
| 165 |
+
out = xp.full_like(cond, dtype=dtype, fill_value=fill_value)
|
| 166 |
+
else:
|
| 167 |
+
out = xp.astype(fill_value, dtype, copy=True)
|
| 168 |
+
else:
|
| 169 |
+
ncond = ~cond
|
| 170 |
+
temp2 = f2(*(arr[ncond] for arr in args))
|
| 171 |
+
dtype = xp.result_type(temp1, temp2)
|
| 172 |
+
out = xp.empty_like(cond, dtype=dtype)
|
| 173 |
+
out = at(out, ncond).set(temp2)
|
| 174 |
+
|
| 175 |
+
return at(out, cond).set(temp1)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array:
|
| 179 |
+
# numpydoc ignore=PR01,RT01
|
| 180 |
+
"""See docstring in array_api_extra._delegation."""
|
| 181 |
+
|
| 182 |
+
if x.ndim < ndim:
|
| 183 |
+
x = xp.expand_dims(x, axis=0)
|
| 184 |
+
x = atleast_nd(x, ndim=ndim, xp=xp)
|
| 185 |
+
return x
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# `float` in signature to accept `math.nan` for Dask.
|
| 189 |
+
# `int`s are still accepted as `float` is a superclass of `int` in typing
|
| 190 |
+
def broadcast_shapes(*shapes: tuple[float | None, ...]) -> tuple[int | None, ...]:
|
| 191 |
+
"""
|
| 192 |
+
Compute the shape of the broadcasted arrays.
|
| 193 |
+
|
| 194 |
+
Duplicates :func:`numpy.broadcast_shapes`, with additional support for
|
| 195 |
+
None and NaN sizes.
|
| 196 |
+
|
| 197 |
+
This is equivalent to ``xp.broadcast_arrays(arr1, arr2, ...)[0].shape``
|
| 198 |
+
without needing to worry about the backend potentially deep copying
|
| 199 |
+
the arrays.
|
| 200 |
+
|
| 201 |
+
Parameters
|
| 202 |
+
----------
|
| 203 |
+
*shapes : tuple[int | None, ...]
|
| 204 |
+
Shapes of the arrays to broadcast.
|
| 205 |
+
|
| 206 |
+
Returns
|
| 207 |
+
-------
|
| 208 |
+
tuple[int | None, ...]
|
| 209 |
+
The shape of the broadcasted arrays.
|
| 210 |
+
|
| 211 |
+
See Also
|
| 212 |
+
--------
|
| 213 |
+
numpy.broadcast_shapes : Equivalent NumPy function.
|
| 214 |
+
array_api.broadcast_arrays : Function to broadcast actual arrays.
|
| 215 |
+
|
| 216 |
+
Notes
|
| 217 |
+
-----
|
| 218 |
+
This function accepts the Array API's ``None`` for unknown sizes,
|
| 219 |
+
as well as Dask's non-standard ``math.nan``.
|
| 220 |
+
Regardless of input, the output always contains ``None`` for unknown sizes.
|
| 221 |
+
|
| 222 |
+
Examples
|
| 223 |
+
--------
|
| 224 |
+
>>> import array_api_extra as xpx
|
| 225 |
+
>>> xpx.broadcast_shapes((2, 3), (2, 1))
|
| 226 |
+
(2, 3)
|
| 227 |
+
>>> xpx.broadcast_shapes((4, 2, 3), (2, 1), (1, 3))
|
| 228 |
+
(4, 2, 3)
|
| 229 |
+
"""
|
| 230 |
+
if not shapes:
|
| 231 |
+
return () # Match NumPy output
|
| 232 |
+
|
| 233 |
+
ndim = max(len(shape) for shape in shapes)
|
| 234 |
+
out: list[int | None] = []
|
| 235 |
+
for axis in range(-ndim, 0):
|
| 236 |
+
sizes = {shape[axis] for shape in shapes if axis >= -len(shape)}
|
| 237 |
+
# Dask uses NaN for unknown shape, which predates the Array API spec for None
|
| 238 |
+
none_size = None in sizes or math.nan in sizes # noqa: PLW0177
|
| 239 |
+
sizes -= {1, None, math.nan}
|
| 240 |
+
if len(sizes) > 1:
|
| 241 |
+
msg = (
|
| 242 |
+
"shape mismatch: objects cannot be broadcast to a single shape: "
|
| 243 |
+
f"{shapes}."
|
| 244 |
+
)
|
| 245 |
+
raise ValueError(msg)
|
| 246 |
+
out.append(None if none_size else cast(int, sizes.pop()) if sizes else 1)
|
| 247 |
+
|
| 248 |
+
return tuple(out)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def cov(m: Array, /, *, xp: ModuleType) -> Array: # numpydoc ignore=PR01,RT01
|
| 252 |
+
"""See docstring in array_api_extra._delegation."""
|
| 253 |
+
m = xp.asarray(m, copy=True)
|
| 254 |
+
dtype = (
|
| 255 |
+
xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64)
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
m = atleast_nd(m, ndim=2, xp=xp)
|
| 259 |
+
m = xp.astype(m, dtype)
|
| 260 |
+
|
| 261 |
+
avg = _helpers.mean(m, axis=-1, keepdims=True, xp=xp)
|
| 262 |
+
|
| 263 |
+
m_shape = eager_shape(m)
|
| 264 |
+
fact = m_shape[-1] - 1
|
| 265 |
+
|
| 266 |
+
if fact <= 0:
|
| 267 |
+
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2)
|
| 268 |
+
fact = 0
|
| 269 |
+
|
| 270 |
+
m -= avg
|
| 271 |
+
m_transpose = xp.matrix_transpose(m)
|
| 272 |
+
if xp.isdtype(m_transpose.dtype, "complex floating"):
|
| 273 |
+
m_transpose = xp.conj(m_transpose)
|
| 274 |
+
c = xp.matmul(m, m_transpose)
|
| 275 |
+
c /= fact
|
| 276 |
+
axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1)
|
| 277 |
+
return xp.squeeze(c, axis=axes)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def one_hot(
|
| 281 |
+
x: Array,
|
| 282 |
+
/,
|
| 283 |
+
num_classes: int,
|
| 284 |
+
*,
|
| 285 |
+
xp: ModuleType,
|
| 286 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 287 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 288 |
+
# TODO: Benchmark whether this is faster on the NumPy backend:
|
| 289 |
+
# if is_numpy_array(x):
|
| 290 |
+
# out = xp.zeros((x.size, num_classes), dtype=dtype)
|
| 291 |
+
# out[xp.arange(x.size), xp.reshape(x, (-1,))] = 1
|
| 292 |
+
# return xp.reshape(out, (*x.shape, num_classes))
|
| 293 |
+
range_num_classes = xp.arange(num_classes, dtype=x.dtype, device=_compat.device(x))
|
| 294 |
+
return x[..., xp.newaxis] == range_num_classes
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def create_diagonal(
|
| 298 |
+
x: Array, /, *, offset: int = 0, xp: ModuleType
|
| 299 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 300 |
+
"""See docstring in array_api_extra._delegation."""
|
| 301 |
+
x_shape = eager_shape(x)
|
| 302 |
+
batch_dims = x_shape[:-1]
|
| 303 |
+
n = x_shape[-1] + abs(offset)
|
| 304 |
+
diag = xp.zeros((*batch_dims, n**2), dtype=x.dtype, device=_compat.device(x))
|
| 305 |
+
|
| 306 |
+
target_slice = slice(
|
| 307 |
+
offset if offset >= 0 else abs(offset) * n,
|
| 308 |
+
min(n * (n - offset), diag.shape[-1]),
|
| 309 |
+
n + 1,
|
| 310 |
+
)
|
| 311 |
+
for index in ndindex(*batch_dims):
|
| 312 |
+
diag = at(diag)[(*index, target_slice)].set(x[(*index, slice(None))])
|
| 313 |
+
return xp.reshape(diag, (*batch_dims, n, n))
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def default_dtype(
|
| 317 |
+
xp: ModuleType,
|
| 318 |
+
kind: Literal[
|
| 319 |
+
"real floating", "complex floating", "integral", "indexing"
|
| 320 |
+
] = "real floating",
|
| 321 |
+
*,
|
| 322 |
+
device: Device | None = None,
|
| 323 |
+
) -> DType:
|
| 324 |
+
"""
|
| 325 |
+
Return the default dtype for the given namespace and device.
|
| 326 |
+
|
| 327 |
+
This is a convenience shorthand for
|
| 328 |
+
``xp.__array_namespace_info__().default_dtypes(device=device)[kind]``.
|
| 329 |
+
|
| 330 |
+
Parameters
|
| 331 |
+
----------
|
| 332 |
+
xp : array_namespace
|
| 333 |
+
The standard-compatible namespace for which to get the default dtype.
|
| 334 |
+
kind : {'real floating', 'complex floating', 'integral', 'indexing'}, optional
|
| 335 |
+
The kind of dtype to return. Default is 'real floating'.
|
| 336 |
+
device : Device, optional
|
| 337 |
+
The device for which to get the default dtype. Default: current device.
|
| 338 |
+
|
| 339 |
+
Returns
|
| 340 |
+
-------
|
| 341 |
+
dtype
|
| 342 |
+
The default dtype for the given namespace, kind, and device.
|
| 343 |
+
"""
|
| 344 |
+
dtypes = xp.__array_namespace_info__().default_dtypes(device=device)
|
| 345 |
+
try:
|
| 346 |
+
return dtypes[kind]
|
| 347 |
+
except KeyError as e:
|
| 348 |
+
domain = ("real floating", "complex floating", "integral", "indexing")
|
| 349 |
+
assert set(dtypes) == set(domain), f"Non-compliant namespace: {dtypes}"
|
| 350 |
+
msg = f"Unknown kind '{kind}'. Expected one of {domain}."
|
| 351 |
+
raise ValueError(msg) from e
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def expand_dims(a: Array, /, *, axis: tuple[int, ...] = (0,), xp: ModuleType) -> Array:
|
| 355 |
+
# numpydoc ignore=PR01,RT01
|
| 356 |
+
"""See docstring in array_api_extra._delegation."""
|
| 357 |
+
for i in sorted(axis):
|
| 358 |
+
a = xp.expand_dims(a, axis=i)
|
| 359 |
+
return a
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def isclose(
|
| 363 |
+
a: Array | complex,
|
| 364 |
+
b: Array | complex,
|
| 365 |
+
*,
|
| 366 |
+
rtol: float = 1e-05,
|
| 367 |
+
atol: float = 1e-08,
|
| 368 |
+
equal_nan: bool = False,
|
| 369 |
+
xp: ModuleType,
|
| 370 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 371 |
+
"""See docstring in array_api_extra._delegation."""
|
| 372 |
+
a, b = asarrays(a, b, xp=xp)
|
| 373 |
+
|
| 374 |
+
a_inexact = xp.isdtype(a.dtype, ("real floating", "complex floating"))
|
| 375 |
+
b_inexact = xp.isdtype(b.dtype, ("real floating", "complex floating"))
|
| 376 |
+
if a_inexact or b_inexact:
|
| 377 |
+
# prevent warnings on NumPy and Dask on inf - inf
|
| 378 |
+
mxp = meta_namespace(a, b, xp=xp)
|
| 379 |
+
out = apply_where(
|
| 380 |
+
xp.isinf(a) | xp.isinf(b),
|
| 381 |
+
(a, b),
|
| 382 |
+
lambda a, b: mxp.isinf(a) & mxp.isinf(b) & (mxp.sign(a) == mxp.sign(b)), # pyright: ignore[reportUnknownArgumentType]
|
| 383 |
+
# Note: inf <= inf is True!
|
| 384 |
+
lambda a, b: mxp.abs(a - b) <= (atol + rtol * mxp.abs(b)), # pyright: ignore[reportUnknownArgumentType]
|
| 385 |
+
xp=xp,
|
| 386 |
+
)
|
| 387 |
+
if equal_nan:
|
| 388 |
+
out = xp.where(xp.isnan(a) & xp.isnan(b), True, out)
|
| 389 |
+
return out
|
| 390 |
+
|
| 391 |
+
if xp.isdtype(a.dtype, "bool") or xp.isdtype(b.dtype, "bool"):
|
| 392 |
+
if atol >= 1 or rtol >= 1:
|
| 393 |
+
return xp.ones_like(a == b)
|
| 394 |
+
return a == b
|
| 395 |
+
|
| 396 |
+
# integer types
|
| 397 |
+
atol = int(atol)
|
| 398 |
+
if rtol == 0:
|
| 399 |
+
return xp.abs(a - b) <= atol
|
| 400 |
+
|
| 401 |
+
# Don't rely on OverflowError, as it is not guaranteed by the Array API.
|
| 402 |
+
nrtol = int(1.0 / rtol)
|
| 403 |
+
if nrtol > xp.iinfo(b.dtype).max:
|
| 404 |
+
# rtol * max_int < 1, so it's inconsequential
|
| 405 |
+
return xp.abs(a - b) <= atol
|
| 406 |
+
return xp.abs(a - b) <= (atol + xp.abs(b) // nrtol)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def kron(
|
| 410 |
+
a: Array | complex,
|
| 411 |
+
b: Array | complex,
|
| 412 |
+
/,
|
| 413 |
+
*,
|
| 414 |
+
xp: ModuleType | None = None,
|
| 415 |
+
) -> Array:
|
| 416 |
+
"""
|
| 417 |
+
Kronecker product of two arrays.
|
| 418 |
+
|
| 419 |
+
Computes the Kronecker product, a composite array made of blocks of the
|
| 420 |
+
second array scaled by the first.
|
| 421 |
+
|
| 422 |
+
Equivalent to ``numpy.kron`` for NumPy arrays.
|
| 423 |
+
|
| 424 |
+
Parameters
|
| 425 |
+
----------
|
| 426 |
+
a, b : Array | int | float | complex
|
| 427 |
+
Input arrays or scalars. At least one must be an array.
|
| 428 |
+
xp : array_namespace, optional
|
| 429 |
+
The standard-compatible namespace for `a` and `b`. Default: infer.
|
| 430 |
+
|
| 431 |
+
Returns
|
| 432 |
+
-------
|
| 433 |
+
array
|
| 434 |
+
The Kronecker product of `a` and `b`.
|
| 435 |
+
|
| 436 |
+
Notes
|
| 437 |
+
-----
|
| 438 |
+
The function assumes that the number of dimensions of `a` and `b`
|
| 439 |
+
are the same, if necessary prepending the smallest with ones.
|
| 440 |
+
If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
|
| 441 |
+
the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
|
| 442 |
+
The elements are products of elements from `a` and `b`, organized
|
| 443 |
+
explicitly by::
|
| 444 |
+
|
| 445 |
+
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
|
| 446 |
+
|
| 447 |
+
where::
|
| 448 |
+
|
| 449 |
+
kt = it * st + jt, t = 0,...,N
|
| 450 |
+
|
| 451 |
+
In the common 2-D case (N=1), the block structure can be visualized::
|
| 452 |
+
|
| 453 |
+
[[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
|
| 454 |
+
[ ... ... ],
|
| 455 |
+
[ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
|
| 456 |
+
|
| 457 |
+
Examples
|
| 458 |
+
--------
|
| 459 |
+
>>> import array_api_strict as xp
|
| 460 |
+
>>> import array_api_extra as xpx
|
| 461 |
+
>>> xpx.kron(xp.asarray([1, 10, 100]), xp.asarray([5, 6, 7]), xp=xp)
|
| 462 |
+
Array([ 5, 6, 7, 50, 60, 70, 500,
|
| 463 |
+
600, 700], dtype=array_api_strict.int64)
|
| 464 |
+
|
| 465 |
+
>>> xpx.kron(xp.asarray([5, 6, 7]), xp.asarray([1, 10, 100]), xp=xp)
|
| 466 |
+
Array([ 5, 50, 500, 6, 60, 600, 7,
|
| 467 |
+
70, 700], dtype=array_api_strict.int64)
|
| 468 |
+
|
| 469 |
+
>>> xpx.kron(xp.eye(2), xp.ones((2, 2)), xp=xp)
|
| 470 |
+
Array([[1., 1., 0., 0.],
|
| 471 |
+
[1., 1., 0., 0.],
|
| 472 |
+
[0., 0., 1., 1.],
|
| 473 |
+
[0., 0., 1., 1.]], dtype=array_api_strict.float64)
|
| 474 |
+
|
| 475 |
+
>>> a = xp.reshape(xp.arange(100), (2, 5, 2, 5))
|
| 476 |
+
>>> b = xp.reshape(xp.arange(24), (2, 3, 4))
|
| 477 |
+
>>> c = xpx.kron(a, b, xp=xp)
|
| 478 |
+
>>> c.shape
|
| 479 |
+
(2, 10, 6, 20)
|
| 480 |
+
>>> I = (1, 3, 0, 2)
|
| 481 |
+
>>> J = (0, 2, 1)
|
| 482 |
+
>>> J1 = (0,) + J # extend to ndim=4
|
| 483 |
+
>>> S1 = (1,) + b.shape
|
| 484 |
+
>>> K = tuple(xp.asarray(I) * xp.asarray(S1) + xp.asarray(J1))
|
| 485 |
+
>>> c[K] == a[I]*b[J]
|
| 486 |
+
Array(True, dtype=array_api_strict.bool)
|
| 487 |
+
"""
|
| 488 |
+
if xp is None:
|
| 489 |
+
xp = array_namespace(a, b)
|
| 490 |
+
a, b = asarrays(a, b, xp=xp)
|
| 491 |
+
|
| 492 |
+
singletons = (1,) * (b.ndim - a.ndim)
|
| 493 |
+
a = cast(Array, xp.broadcast_to(a, singletons + a.shape))
|
| 494 |
+
|
| 495 |
+
nd_b, nd_a = b.ndim, a.ndim
|
| 496 |
+
nd_max = max(nd_b, nd_a)
|
| 497 |
+
if nd_a == 0 or nd_b == 0:
|
| 498 |
+
return xp.multiply(a, b)
|
| 499 |
+
|
| 500 |
+
a_shape = eager_shape(a)
|
| 501 |
+
b_shape = eager_shape(b)
|
| 502 |
+
|
| 503 |
+
# Equalise the shapes by prepending smaller one with 1s
|
| 504 |
+
a_shape = (1,) * max(0, nd_b - nd_a) + a_shape
|
| 505 |
+
b_shape = (1,) * max(0, nd_a - nd_b) + b_shape
|
| 506 |
+
|
| 507 |
+
# Insert empty dimensions
|
| 508 |
+
a_arr = expand_dims(a, axis=tuple(range(nd_b - nd_a)), xp=xp)
|
| 509 |
+
b_arr = expand_dims(b, axis=tuple(range(nd_a - nd_b)), xp=xp)
|
| 510 |
+
|
| 511 |
+
# Compute the product
|
| 512 |
+
a_arr = expand_dims(a_arr, axis=tuple(range(1, nd_max * 2, 2)), xp=xp)
|
| 513 |
+
b_arr = expand_dims(b_arr, axis=tuple(range(0, nd_max * 2, 2)), xp=xp)
|
| 514 |
+
result = xp.multiply(a_arr, b_arr)
|
| 515 |
+
|
| 516 |
+
# Reshape back and return
|
| 517 |
+
res_shape = tuple(a_s * b_s for a_s, b_s in zip(a_shape, b_shape, strict=True))
|
| 518 |
+
return xp.reshape(result, res_shape)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def nan_to_num( # numpydoc ignore=PR01,RT01
|
| 522 |
+
x: Array,
|
| 523 |
+
/,
|
| 524 |
+
fill_value: int | float = 0.0,
|
| 525 |
+
*,
|
| 526 |
+
xp: ModuleType,
|
| 527 |
+
) -> Array:
|
| 528 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 529 |
+
|
| 530 |
+
def perform_replacements( # numpydoc ignore=PR01,RT01
|
| 531 |
+
x: Array,
|
| 532 |
+
fill_value: int | float,
|
| 533 |
+
xp: ModuleType,
|
| 534 |
+
) -> Array:
|
| 535 |
+
"""Internal function to perform the replacements."""
|
| 536 |
+
x = xp.where(xp.isnan(x), fill_value, x)
|
| 537 |
+
|
| 538 |
+
# convert infinities to finite values
|
| 539 |
+
finfo = xp.finfo(x.dtype)
|
| 540 |
+
idx_posinf = xp.isinf(x) & ~xp.signbit(x)
|
| 541 |
+
idx_neginf = xp.isinf(x) & xp.signbit(x)
|
| 542 |
+
x = xp.where(idx_posinf, finfo.max, x)
|
| 543 |
+
return xp.where(idx_neginf, finfo.min, x)
|
| 544 |
+
|
| 545 |
+
if xp.isdtype(x.dtype, "complex floating"):
|
| 546 |
+
return perform_replacements(
|
| 547 |
+
xp.real(x),
|
| 548 |
+
fill_value,
|
| 549 |
+
xp,
|
| 550 |
+
) + 1j * perform_replacements(
|
| 551 |
+
xp.imag(x),
|
| 552 |
+
fill_value,
|
| 553 |
+
xp,
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
if xp.isdtype(x.dtype, "numeric"):
|
| 557 |
+
return perform_replacements(x, fill_value, xp)
|
| 558 |
+
|
| 559 |
+
return x
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def nunique(x: Array, /, *, xp: ModuleType | None = None) -> Array:
|
| 563 |
+
"""
|
| 564 |
+
Count the number of unique elements in an array.
|
| 565 |
+
|
| 566 |
+
Compatible with JAX and Dask, whose laziness would be otherwise
|
| 567 |
+
problematic.
|
| 568 |
+
|
| 569 |
+
Parameters
|
| 570 |
+
----------
|
| 571 |
+
x : Array
|
| 572 |
+
Input array.
|
| 573 |
+
xp : array_namespace, optional
|
| 574 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 575 |
+
|
| 576 |
+
Returns
|
| 577 |
+
-------
|
| 578 |
+
array: 0-dimensional integer array
|
| 579 |
+
The number of unique elements in `x`. It can be lazy.
|
| 580 |
+
"""
|
| 581 |
+
if xp is None:
|
| 582 |
+
xp = array_namespace(x)
|
| 583 |
+
|
| 584 |
+
if is_jax_array(x):
|
| 585 |
+
# size= is JAX-specific
|
| 586 |
+
# https://github.com/data-apis/array-api/issues/883
|
| 587 |
+
_, counts = xp.unique_counts(x, size=_compat.size(x))
|
| 588 |
+
return (counts > 0).sum()
|
| 589 |
+
|
| 590 |
+
# There are 3 general use cases:
|
| 591 |
+
# 1. backend has unique_counts and it returns an array with known shape
|
| 592 |
+
# 2. backend has unique_counts and it returns a None-sized array;
|
| 593 |
+
# e.g. Dask, ndonnx
|
| 594 |
+
# 3. backend does not have unique_counts; e.g. wrapped JAX
|
| 595 |
+
if capabilities(xp, device=_compat.device(x))["data-dependent shapes"]:
|
| 596 |
+
# xp has unique_counts; O(n) complexity
|
| 597 |
+
_, counts = xp.unique_counts(x)
|
| 598 |
+
n = _compat.size(counts)
|
| 599 |
+
if n is None:
|
| 600 |
+
return xp.sum(xp.ones_like(counts))
|
| 601 |
+
return xp.asarray(n, device=_compat.device(x))
|
| 602 |
+
|
| 603 |
+
# xp does not have unique_counts; O(n*logn) complexity
|
| 604 |
+
x = xp.reshape(x, (-1,))
|
| 605 |
+
x = xp.sort(x, stable=False)
|
| 606 |
+
mask = x != xp.roll(x, -1)
|
| 607 |
+
default_int = default_dtype(xp, "integral", device=_compat.device(x))
|
| 608 |
+
return xp.maximum(
|
| 609 |
+
# Special cases:
|
| 610 |
+
# - array is size 0
|
| 611 |
+
# - array has all elements equal to each other
|
| 612 |
+
xp.astype(xp.any(~mask), default_int),
|
| 613 |
+
xp.sum(xp.astype(mask, default_int)),
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def pad(
|
| 618 |
+
x: Array,
|
| 619 |
+
pad_width: int | tuple[int, int] | Sequence[tuple[int, int]],
|
| 620 |
+
*,
|
| 621 |
+
constant_values: complex = 0,
|
| 622 |
+
xp: ModuleType,
|
| 623 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 624 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 625 |
+
# make pad_width a list of length-2 tuples of ints
|
| 626 |
+
if isinstance(pad_width, int):
|
| 627 |
+
pad_width_seq = [(pad_width, pad_width)] * x.ndim
|
| 628 |
+
elif (
|
| 629 |
+
isinstance(pad_width, tuple)
|
| 630 |
+
and len(pad_width) == 2
|
| 631 |
+
and all(isinstance(i, int) for i in pad_width)
|
| 632 |
+
):
|
| 633 |
+
pad_width_seq = [cast(tuple[int, int], pad_width)] * x.ndim
|
| 634 |
+
else:
|
| 635 |
+
pad_width_seq = cast(list[tuple[int, int]], list(pad_width))
|
| 636 |
+
|
| 637 |
+
slices: list[slice] = []
|
| 638 |
+
newshape: list[int] = []
|
| 639 |
+
for ax, w_tpl in enumerate(pad_width_seq):
|
| 640 |
+
if len(w_tpl) != 2:
|
| 641 |
+
msg = f"expect a 2-tuple (before, after), got {w_tpl}."
|
| 642 |
+
raise ValueError(msg)
|
| 643 |
+
|
| 644 |
+
sh = eager_shape(x)[ax]
|
| 645 |
+
|
| 646 |
+
if w_tpl[0] == 0 and w_tpl[1] == 0:
|
| 647 |
+
sl = slice(None, None, None)
|
| 648 |
+
else:
|
| 649 |
+
stop: int | None
|
| 650 |
+
start, stop = w_tpl
|
| 651 |
+
stop = None if stop == 0 else -stop
|
| 652 |
+
|
| 653 |
+
sl = slice(start, stop, None)
|
| 654 |
+
sh += w_tpl[0] + w_tpl[1]
|
| 655 |
+
|
| 656 |
+
newshape.append(sh)
|
| 657 |
+
slices.append(sl)
|
| 658 |
+
|
| 659 |
+
padded = xp.full(
|
| 660 |
+
tuple(newshape),
|
| 661 |
+
fill_value=constant_values,
|
| 662 |
+
dtype=x.dtype,
|
| 663 |
+
device=_compat.device(x),
|
| 664 |
+
)
|
| 665 |
+
return at(padded, tuple(slices)).set(x)
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def setdiff1d(
|
| 669 |
+
x1: Array | complex,
|
| 670 |
+
x2: Array | complex,
|
| 671 |
+
/,
|
| 672 |
+
*,
|
| 673 |
+
assume_unique: bool = False,
|
| 674 |
+
xp: ModuleType,
|
| 675 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 676 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 677 |
+
|
| 678 |
+
# https://github.com/microsoft/pyright/issues/10103
|
| 679 |
+
x1_, x2_ = asarrays(x1, x2, xp=xp)
|
| 680 |
+
|
| 681 |
+
if assume_unique:
|
| 682 |
+
x1_ = xp.reshape(x1_, (-1,))
|
| 683 |
+
x2_ = xp.reshape(x2_, (-1,))
|
| 684 |
+
else:
|
| 685 |
+
x1_ = xp.unique_values(x1_)
|
| 686 |
+
x2_ = xp.unique_values(x2_)
|
| 687 |
+
|
| 688 |
+
return x1_[_helpers.in1d(x1_, x2_, assume_unique=True, invert=True, xp=xp)]
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def sinc(x: Array, /, *, xp: ModuleType) -> Array:
|
| 692 |
+
# numpydoc ignore=PR01,RT01
|
| 693 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 694 |
+
|
| 695 |
+
# no scalars in `where` - array-api#807
|
| 696 |
+
y = xp.pi * xp.where(
|
| 697 |
+
xp.astype(x, xp.bool),
|
| 698 |
+
x,
|
| 699 |
+
xp.asarray(xp.finfo(x.dtype).eps, dtype=x.dtype, device=_compat.device(x)),
|
| 700 |
+
)
|
| 701 |
+
return xp.sin(y) / y
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
def partition( # numpydoc ignore=PR01,RT01
|
| 705 |
+
x: Array,
|
| 706 |
+
kth: int, # noqa: ARG001
|
| 707 |
+
/,
|
| 708 |
+
axis: int = -1,
|
| 709 |
+
*,
|
| 710 |
+
xp: ModuleType,
|
| 711 |
+
) -> Array:
|
| 712 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 713 |
+
return xp.sort(x, axis=axis, stable=False)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def argpartition( # numpydoc ignore=PR01,RT01
|
| 717 |
+
x: Array,
|
| 718 |
+
kth: int, # noqa: ARG001
|
| 719 |
+
/,
|
| 720 |
+
axis: int = -1,
|
| 721 |
+
*,
|
| 722 |
+
xp: ModuleType,
|
| 723 |
+
) -> Array:
|
| 724 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 725 |
+
return xp.argsort(x, axis=axis, stable=False)
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def isin( # numpydoc ignore=PR01,RT01
|
| 729 |
+
a: Array,
|
| 730 |
+
b: Array,
|
| 731 |
+
/,
|
| 732 |
+
*,
|
| 733 |
+
assume_unique: bool = False,
|
| 734 |
+
invert: bool = False,
|
| 735 |
+
xp: ModuleType,
|
| 736 |
+
) -> Array:
|
| 737 |
+
"""See docstring in `array_api_extra._delegation.py`."""
|
| 738 |
+
original_a_shape = a.shape
|
| 739 |
+
a = xp.reshape(a, (-1,))
|
| 740 |
+
b = xp.reshape(b, (-1,))
|
| 741 |
+
return xp.reshape(
|
| 742 |
+
_helpers.in1d(a, b, assume_unique=assume_unique, invert=invert, xp=xp),
|
| 743 |
+
original_a_shape,
|
| 744 |
+
)
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_lazy.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public API Functions."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from collections.abc import Callable, Sequence
|
| 7 |
+
from functools import partial, wraps
|
| 8 |
+
from types import ModuleType
|
| 9 |
+
from typing import TYPE_CHECKING, Any, ParamSpec, TypeAlias, cast, overload
|
| 10 |
+
|
| 11 |
+
from ._funcs import broadcast_shapes
|
| 12 |
+
from ._utils import _compat
|
| 13 |
+
from ._utils._compat import (
|
| 14 |
+
array_namespace,
|
| 15 |
+
is_dask_namespace,
|
| 16 |
+
is_jax_namespace,
|
| 17 |
+
)
|
| 18 |
+
from ._utils._helpers import is_python_scalar
|
| 19 |
+
from ._utils._typing import Array, DType
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 22 |
+
import numpy as np
|
| 23 |
+
from numpy.typing import ArrayLike
|
| 24 |
+
|
| 25 |
+
NumPyObject: TypeAlias = np.ndarray[Any, Any] | np.generic
|
| 26 |
+
else:
|
| 27 |
+
# Sphinx hack
|
| 28 |
+
NumPyObject = Any
|
| 29 |
+
|
| 30 |
+
P = ParamSpec("P")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@overload
|
| 34 |
+
def lazy_apply( # type: ignore[valid-type]
|
| 35 |
+
func: Callable[P, Array | ArrayLike],
|
| 36 |
+
*args: Array | complex | None,
|
| 37 |
+
shape: tuple[int | None, ...] | None = None,
|
| 38 |
+
dtype: DType | None = None,
|
| 39 |
+
as_numpy: bool = False,
|
| 40 |
+
xp: ModuleType | None = None,
|
| 41 |
+
**kwargs: P.kwargs, # pyright: ignore[reportGeneralTypeIssues]
|
| 42 |
+
) -> Array: ... # numpydoc ignore=GL08
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@overload
|
| 46 |
+
def lazy_apply( # type: ignore[valid-type]
|
| 47 |
+
func: Callable[P, Sequence[Array | ArrayLike]],
|
| 48 |
+
*args: Array | complex | None,
|
| 49 |
+
shape: Sequence[tuple[int | None, ...]],
|
| 50 |
+
dtype: Sequence[DType] | None = None,
|
| 51 |
+
as_numpy: bool = False,
|
| 52 |
+
xp: ModuleType | None = None,
|
| 53 |
+
**kwargs: P.kwargs, # pyright: ignore[reportGeneralTypeIssues]
|
| 54 |
+
) -> tuple[Array, ...]: ... # numpydoc ignore=GL08
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def lazy_apply( # type: ignore[valid-type] # numpydoc ignore=GL07,SA04
|
| 58 |
+
func: Callable[P, Array | ArrayLike | Sequence[Array | ArrayLike]],
|
| 59 |
+
*args: Array | complex | None,
|
| 60 |
+
shape: tuple[int | None, ...] | Sequence[tuple[int | None, ...]] | None = None,
|
| 61 |
+
dtype: DType | Sequence[DType] | None = None,
|
| 62 |
+
as_numpy: bool = False,
|
| 63 |
+
xp: ModuleType | None = None,
|
| 64 |
+
**kwargs: P.kwargs, # pyright: ignore[reportGeneralTypeIssues]
|
| 65 |
+
) -> Array | tuple[Array, ...]:
|
| 66 |
+
"""
|
| 67 |
+
Lazily apply an eager function.
|
| 68 |
+
|
| 69 |
+
If the backend of the input arrays is lazy, e.g. Dask or jitted JAX, the execution
|
| 70 |
+
of the function is delayed until the graph is materialized; if it's eager, the
|
| 71 |
+
function is executed immediately.
|
| 72 |
+
|
| 73 |
+
Parameters
|
| 74 |
+
----------
|
| 75 |
+
func : callable
|
| 76 |
+
The function to apply.
|
| 77 |
+
|
| 78 |
+
It must accept one or more array API compliant arrays as positional arguments.
|
| 79 |
+
If `as_numpy=True`, inputs are converted to NumPy before they are passed to
|
| 80 |
+
`func`.
|
| 81 |
+
It must return either a single array-like or a sequence of array-likes.
|
| 82 |
+
|
| 83 |
+
`func` must be a pure function, i.e. without side effects, as depending on the
|
| 84 |
+
backend it may be executed more than once or never.
|
| 85 |
+
*args : Array | int | float | complex | bool | None
|
| 86 |
+
One or more Array API compliant arrays, Python scalars, or None's.
|
| 87 |
+
|
| 88 |
+
If `as_numpy=True`, you need to be able to apply :func:`numpy.asarray` to
|
| 89 |
+
non-None args to convert them to NumPy; read notes below about specific
|
| 90 |
+
backends.
|
| 91 |
+
shape : tuple[int | None, ...] | Sequence[tuple[int | None, ...]], optional
|
| 92 |
+
Output shape or sequence of output shapes, one for each output of `func`.
|
| 93 |
+
Default: assume single output and broadcast shapes of the input arrays.
|
| 94 |
+
dtype : DType | Sequence[DType], optional
|
| 95 |
+
Output dtype or sequence of output dtypes, one for each output of `func`.
|
| 96 |
+
dtype(s) must belong to the same array namespace as the input arrays.
|
| 97 |
+
Default: infer the result type(s) from the input arrays.
|
| 98 |
+
as_numpy : bool, optional
|
| 99 |
+
If True, convert the input arrays to NumPy before passing them to `func`.
|
| 100 |
+
This is particularly useful to make NumPy-only functions, e.g. written in Cython
|
| 101 |
+
or Numba, work transparently with array API-compliant arrays.
|
| 102 |
+
Default: False.
|
| 103 |
+
xp : array_namespace, optional
|
| 104 |
+
The standard-compatible namespace for `args`. Default: infer.
|
| 105 |
+
**kwargs : Any, optional
|
| 106 |
+
Additional keyword arguments to pass verbatim to `func`.
|
| 107 |
+
They cannot contain Array objects.
|
| 108 |
+
|
| 109 |
+
Returns
|
| 110 |
+
-------
|
| 111 |
+
Array | tuple[Array, ...]
|
| 112 |
+
The result(s) of `func` applied to the input arrays, wrapped in the same
|
| 113 |
+
array namespace as the inputs.
|
| 114 |
+
If shape is omitted or a single `tuple[int | None, ...]`, return a single array.
|
| 115 |
+
Otherwise, return a tuple of arrays.
|
| 116 |
+
|
| 117 |
+
Notes
|
| 118 |
+
-----
|
| 119 |
+
JAX
|
| 120 |
+
This allows applying eager functions to jitted JAX arrays, which are lazy.
|
| 121 |
+
The function won't be applied until the JAX array is materialized.
|
| 122 |
+
When running inside ``jax.jit``, `shape` must be fully known, i.e. it cannot
|
| 123 |
+
contain any `None` elements.
|
| 124 |
+
|
| 125 |
+
.. warning::
|
| 126 |
+
|
| 127 |
+
`func` must never raise inside ``jax.jit``, as the resulting behavior is
|
| 128 |
+
undefined.
|
| 129 |
+
|
| 130 |
+
Using this with `as_numpy=False` is particularly useful to apply non-jittable
|
| 131 |
+
JAX functions to arrays on GPU devices.
|
| 132 |
+
If ``as_numpy=True``, the :doc:`jax:transfer_guard` may prevent arrays on a GPU
|
| 133 |
+
device from being transferred back to CPU. This is treated as an implicit
|
| 134 |
+
transfer.
|
| 135 |
+
|
| 136 |
+
PyTorch, CuPy
|
| 137 |
+
If ``as_numpy=True``, these backends raise by default if you attempt to convert
|
| 138 |
+
arrays on a GPU device to NumPy.
|
| 139 |
+
|
| 140 |
+
Sparse
|
| 141 |
+
If ``as_numpy=True``, by default sparse prevents implicit densification through
|
| 142 |
+
:func:`numpy.asarray`. `This safety mechanism can be disabled
|
| 143 |
+
<https://sparse.pydata.org/en/stable/operations.html#package-configuration>`_.
|
| 144 |
+
|
| 145 |
+
Dask
|
| 146 |
+
This allows applying eager functions to Dask arrays.
|
| 147 |
+
The Dask graph won't be computed until the user calls ``compute()`` or
|
| 148 |
+
``persist()`` down the line.
|
| 149 |
+
|
| 150 |
+
The function name will be prominently visible on the user-facing Dask
|
| 151 |
+
dashboard and on Prometheus metrics, so it is recommended for it to be
|
| 152 |
+
meaningful.
|
| 153 |
+
|
| 154 |
+
`lazy_apply` doesn't know if `func` reduces along any axes; also, shape
|
| 155 |
+
changes are non-trivial in chunked Dask arrays. For these reasons, all inputs
|
| 156 |
+
will be rechunked into a single chunk.
|
| 157 |
+
|
| 158 |
+
.. warning::
|
| 159 |
+
|
| 160 |
+
The whole operation needs to fit in memory all at once on a single worker.
|
| 161 |
+
|
| 162 |
+
The outputs will also be returned as a single chunk and you should consider
|
| 163 |
+
rechunking them into smaller chunks afterwards.
|
| 164 |
+
|
| 165 |
+
If you want to distribute the calculation across multiple workers, you
|
| 166 |
+
should use :func:`dask.array.map_blocks`, :func:`dask.array.map_overlap`,
|
| 167 |
+
:func:`dask.array.blockwise`, or a native Dask wrapper instead of
|
| 168 |
+
`lazy_apply`.
|
| 169 |
+
|
| 170 |
+
Dask wrapping around other backends
|
| 171 |
+
If ``as_numpy=False``, `func` will receive in input eager arrays of the meta
|
| 172 |
+
namespace, as defined by the ``._meta`` attribute of the input Dask arrays.
|
| 173 |
+
The outputs of `func` will be wrapped by the meta namespace, and then wrapped
|
| 174 |
+
again by Dask.
|
| 175 |
+
|
| 176 |
+
Raises
|
| 177 |
+
------
|
| 178 |
+
ValueError
|
| 179 |
+
When ``xp=jax.numpy``, the output `shape` is unknown (it contains ``None`` on
|
| 180 |
+
one or more axes) and this function was called inside ``jax.jit``.
|
| 181 |
+
RuntimeError
|
| 182 |
+
When ``xp=sparse`` and auto-densification is disabled.
|
| 183 |
+
Exception (backend-specific)
|
| 184 |
+
When the backend disallows implicit device to host transfers and the input
|
| 185 |
+
arrays are on a non-CPU device, e.g. on GPU.
|
| 186 |
+
|
| 187 |
+
See Also
|
| 188 |
+
--------
|
| 189 |
+
jax.transfer_guard
|
| 190 |
+
jax.pure_callback
|
| 191 |
+
dask.array.map_blocks
|
| 192 |
+
dask.array.map_overlap
|
| 193 |
+
dask.array.blockwise
|
| 194 |
+
"""
|
| 195 |
+
args_not_none = [arg for arg in args if arg is not None]
|
| 196 |
+
array_args = [arg for arg in args_not_none if not is_python_scalar(arg)]
|
| 197 |
+
if not array_args:
|
| 198 |
+
msg = "Must have at least one argument array"
|
| 199 |
+
raise ValueError(msg)
|
| 200 |
+
if xp is None:
|
| 201 |
+
xp = array_namespace(*args)
|
| 202 |
+
|
| 203 |
+
# Normalize and validate shape and dtype
|
| 204 |
+
shapes: list[tuple[int | None, ...]]
|
| 205 |
+
dtypes: list[DType]
|
| 206 |
+
multi_output = False
|
| 207 |
+
|
| 208 |
+
if shape is None:
|
| 209 |
+
shapes = [broadcast_shapes(*(arg.shape for arg in array_args))]
|
| 210 |
+
elif all(isinstance(s, int | None) for s in shape):
|
| 211 |
+
# Do not test for shape to be a tuple
|
| 212 |
+
# https://github.com/data-apis/array-api/issues/891#issuecomment-2637430522
|
| 213 |
+
shapes = [cast(tuple[int | None, ...], shape)]
|
| 214 |
+
else:
|
| 215 |
+
shapes = list(shape) # type: ignore[arg-type] # pyright: ignore[reportAssignmentType]
|
| 216 |
+
multi_output = True
|
| 217 |
+
|
| 218 |
+
if dtype is None:
|
| 219 |
+
dtypes = [xp.result_type(*args_not_none)] * len(shapes)
|
| 220 |
+
elif multi_output:
|
| 221 |
+
if not isinstance(dtype, Sequence):
|
| 222 |
+
msg = "Got multiple shapes but only one dtype"
|
| 223 |
+
raise ValueError(msg)
|
| 224 |
+
dtypes = list(dtype) # pyright: ignore[reportUnknownArgumentType]
|
| 225 |
+
else:
|
| 226 |
+
if isinstance(dtype, Sequence):
|
| 227 |
+
msg = "Got single shape but multiple dtypes"
|
| 228 |
+
raise ValueError(msg)
|
| 229 |
+
|
| 230 |
+
dtypes = [dtype]
|
| 231 |
+
|
| 232 |
+
if len(shapes) != len(dtypes):
|
| 233 |
+
msg = f"Got {len(shapes)} shapes and {len(dtypes)} dtypes"
|
| 234 |
+
raise ValueError(msg)
|
| 235 |
+
del shape
|
| 236 |
+
del dtype
|
| 237 |
+
# End of shape and dtype parsing
|
| 238 |
+
|
| 239 |
+
# Backend-specific branches
|
| 240 |
+
if is_dask_namespace(xp):
|
| 241 |
+
import dask
|
| 242 |
+
|
| 243 |
+
metas: list[Array] = [arg._meta for arg in array_args] # pylint: disable=protected-access # pyright: ignore[reportAttributeAccessIssue]
|
| 244 |
+
meta_xp = array_namespace(*metas)
|
| 245 |
+
|
| 246 |
+
wrapped = dask.delayed( # type: ignore[attr-defined] # pyright: ignore[reportPrivateImportUsage]
|
| 247 |
+
_lazy_apply_wrapper(func, as_numpy, multi_output, meta_xp),
|
| 248 |
+
pure=True,
|
| 249 |
+
)
|
| 250 |
+
# This finalizes each arg, which is the same as arg.rechunk(-1).
|
| 251 |
+
# Please read docstring above for why we're not using
|
| 252 |
+
# dask.array.map_blocks or dask.array.blockwise!
|
| 253 |
+
delayed_out = wrapped(*args, **kwargs)
|
| 254 |
+
|
| 255 |
+
out = tuple(
|
| 256 |
+
xp.from_delayed(
|
| 257 |
+
delayed_out[i], # pyright: ignore[reportIndexIssue]
|
| 258 |
+
# Dask's unknown shapes diverge from the Array API specification
|
| 259 |
+
shape=tuple(math.nan if s is None else s for s in shape),
|
| 260 |
+
dtype=dtype,
|
| 261 |
+
meta=metas[0],
|
| 262 |
+
)
|
| 263 |
+
for i, (shape, dtype) in enumerate(zip(shapes, dtypes, strict=True))
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
elif is_jax_namespace(xp) and _is_jax_jit_enabled(xp):
|
| 267 |
+
# Delay calling func with jax.pure_callback, which will forward to func eager
|
| 268 |
+
# JAX arrays. Do not use jax.pure_callback when running outside of the JIT,
|
| 269 |
+
# as it does not support raising exceptions:
|
| 270 |
+
# https://github.com/jax-ml/jax/issues/26102
|
| 271 |
+
import jax
|
| 272 |
+
|
| 273 |
+
if any(None in shape for shape in shapes):
|
| 274 |
+
msg = "Output shape must be fully known when running inside jax.jit"
|
| 275 |
+
raise ValueError(msg)
|
| 276 |
+
|
| 277 |
+
# Shield kwargs from being coerced into JAX arrays.
|
| 278 |
+
# jax.pure_callback calls jax.jit under the hood, but without the chance of
|
| 279 |
+
# passing static_argnames / static_argnums.
|
| 280 |
+
wrapped = _lazy_apply_wrapper(
|
| 281 |
+
partial(func, **kwargs), as_numpy, multi_output, xp
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
# suppress unused-ignore to run mypy in -e lint as well as -e dev
|
| 285 |
+
out = cast( # type: ignore[bad-cast,unused-ignore]
|
| 286 |
+
tuple[Array, ...],
|
| 287 |
+
jax.pure_callback(
|
| 288 |
+
wrapped,
|
| 289 |
+
tuple(
|
| 290 |
+
jax.ShapeDtypeStruct(shape, dtype) # pyright: ignore[reportUnknownArgumentType]
|
| 291 |
+
for shape, dtype in zip(shapes, dtypes, strict=True)
|
| 292 |
+
),
|
| 293 |
+
*args,
|
| 294 |
+
),
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
else:
|
| 298 |
+
# Eager backends, including non-jitted JAX
|
| 299 |
+
wrapped = _lazy_apply_wrapper(func, as_numpy, multi_output, xp)
|
| 300 |
+
out = wrapped(*args, **kwargs)
|
| 301 |
+
|
| 302 |
+
return out if multi_output else out[0]
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _is_jax_jit_enabled(xp: ModuleType) -> bool: # numpydoc ignore=PR01,RT01
|
| 306 |
+
"""Return True if this function is being called inside ``jax.jit``."""
|
| 307 |
+
import jax # pylint: disable=import-outside-toplevel
|
| 308 |
+
|
| 309 |
+
x = xp.asarray(False)
|
| 310 |
+
try:
|
| 311 |
+
return bool(x)
|
| 312 |
+
except jax.errors.TracerBoolConversionError:
|
| 313 |
+
return True
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _lazy_apply_wrapper( # numpydoc ignore=PR01,RT01
|
| 317 |
+
func: Callable[..., Array | ArrayLike | Sequence[Array | ArrayLike]],
|
| 318 |
+
as_numpy: bool,
|
| 319 |
+
multi_output: bool,
|
| 320 |
+
xp: ModuleType,
|
| 321 |
+
) -> Callable[..., tuple[Array, ...]]:
|
| 322 |
+
"""
|
| 323 |
+
Helper of `lazy_apply`.
|
| 324 |
+
|
| 325 |
+
Given a function that accepts one or more arrays as positional arguments and returns
|
| 326 |
+
a single array-like or a sequence of array-likes, return a function that accepts the
|
| 327 |
+
same number of Array API arrays and always returns a tuple of Array API array.
|
| 328 |
+
|
| 329 |
+
Any keyword arguments are passed through verbatim to the wrapped function.
|
| 330 |
+
"""
|
| 331 |
+
|
| 332 |
+
# On Dask, @wraps causes the graph key to contain the wrapped function's name
|
| 333 |
+
@wraps(func)
|
| 334 |
+
def wrapper(
|
| 335 |
+
*args: Array | complex | None, **kwargs: Any
|
| 336 |
+
) -> tuple[Array, ...]: # numpydoc ignore=GL08
|
| 337 |
+
args_list = []
|
| 338 |
+
device = None
|
| 339 |
+
for arg in args:
|
| 340 |
+
if arg is not None and not is_python_scalar(arg):
|
| 341 |
+
if device is None:
|
| 342 |
+
device = _compat.device(arg)
|
| 343 |
+
if as_numpy:
|
| 344 |
+
import numpy as np
|
| 345 |
+
|
| 346 |
+
arg = cast(Array, np.asarray(arg)) # pyright: ignore[reportInvalidCast] # noqa: PLW2901
|
| 347 |
+
args_list.append(arg)
|
| 348 |
+
assert device is not None
|
| 349 |
+
|
| 350 |
+
out = func(*args_list, **kwargs)
|
| 351 |
+
|
| 352 |
+
if multi_output:
|
| 353 |
+
assert isinstance(out, Sequence)
|
| 354 |
+
return tuple(xp.asarray(o, device=device) for o in out)
|
| 355 |
+
return (xp.asarray(out, device=device),)
|
| 356 |
+
|
| 357 |
+
return wrapper
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_testing.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
Testing utilities.
|
| 3 |
+
|
| 4 |
+
Note that this is private API; don't expect it to be stable.
|
| 5 |
+
See also ..testing for public testing utilities.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import math
|
| 11 |
+
from types import ModuleType
|
| 12 |
+
from typing import Any, cast
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pytest
|
| 16 |
+
|
| 17 |
+
from ._utils._compat import (
|
| 18 |
+
array_namespace,
|
| 19 |
+
is_array_api_strict_namespace,
|
| 20 |
+
is_cupy_namespace,
|
| 21 |
+
is_dask_namespace,
|
| 22 |
+
is_jax_namespace,
|
| 23 |
+
is_numpy_namespace,
|
| 24 |
+
is_pydata_sparse_namespace,
|
| 25 |
+
is_torch_array,
|
| 26 |
+
is_torch_namespace,
|
| 27 |
+
to_device,
|
| 28 |
+
)
|
| 29 |
+
from ._utils._typing import Array, Device
|
| 30 |
+
|
| 31 |
+
__all__ = ["as_numpy_array", "xp_assert_close", "xp_assert_equal", "xp_assert_less"]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _check_ns_shape_dtype(
|
| 35 |
+
actual: Array,
|
| 36 |
+
desired: Array,
|
| 37 |
+
check_dtype: bool,
|
| 38 |
+
check_shape: bool,
|
| 39 |
+
check_scalar: bool,
|
| 40 |
+
) -> ModuleType: # numpydoc ignore=RT03
|
| 41 |
+
"""
|
| 42 |
+
Assert that namespace, shape and dtype of the two arrays match.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
actual : Array
|
| 47 |
+
The array produced by the tested function.
|
| 48 |
+
desired : Array
|
| 49 |
+
The expected array (typically hardcoded).
|
| 50 |
+
check_dtype, check_shape : bool, default: True
|
| 51 |
+
Whether to check agreement between actual and desired dtypes and shapes
|
| 52 |
+
check_scalar : bool, default: False
|
| 53 |
+
NumPy only: whether to check agreement between actual and desired types -
|
| 54 |
+
0d array vs scalar.
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
Arrays namespace.
|
| 59 |
+
"""
|
| 60 |
+
actual_xp = array_namespace(actual) # Raises on scalars and lists
|
| 61 |
+
desired_xp = array_namespace(desired)
|
| 62 |
+
|
| 63 |
+
msg = f"namespaces do not match: {actual_xp} != f{desired_xp}"
|
| 64 |
+
assert actual_xp == desired_xp, msg
|
| 65 |
+
|
| 66 |
+
# Dask uses nan instead of None for unknown shapes
|
| 67 |
+
actual_shape = cast(tuple[float, ...], actual.shape)
|
| 68 |
+
desired_shape = cast(tuple[float, ...], desired.shape)
|
| 69 |
+
assert None not in actual_shape # Requires explicit support
|
| 70 |
+
assert None not in desired_shape
|
| 71 |
+
if is_dask_namespace(desired_xp):
|
| 72 |
+
if any(math.isnan(i) for i in actual_shape):
|
| 73 |
+
actual_shape = actual.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]
|
| 74 |
+
if any(math.isnan(i) for i in desired_shape):
|
| 75 |
+
desired_shape = desired.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]
|
| 76 |
+
|
| 77 |
+
if check_shape:
|
| 78 |
+
msg = f"shapes do not match: {actual_shape} != f{desired_shape}"
|
| 79 |
+
assert actual_shape == desired_shape, msg
|
| 80 |
+
else:
|
| 81 |
+
# Ignore shape, but check flattened size. This is normally done by
|
| 82 |
+
# np.testing.assert_array_equal etc even when strict=False, but not for
|
| 83 |
+
# non-materializable arrays.
|
| 84 |
+
actual_size = math.prod(actual_shape) # pyright: ignore[reportUnknownArgumentType]
|
| 85 |
+
desired_size = math.prod(desired_shape) # pyright: ignore[reportUnknownArgumentType]
|
| 86 |
+
msg = f"sizes do not match: {actual_size} != f{desired_size}"
|
| 87 |
+
assert actual_size == desired_size, msg
|
| 88 |
+
|
| 89 |
+
if check_dtype:
|
| 90 |
+
msg = f"dtypes do not match: {actual.dtype} != {desired.dtype}"
|
| 91 |
+
assert actual.dtype == desired.dtype, msg
|
| 92 |
+
|
| 93 |
+
if is_numpy_namespace(actual_xp) and check_scalar:
|
| 94 |
+
# only NumPy distinguishes between scalars and arrays; we do if check_scalar.
|
| 95 |
+
_msg = (
|
| 96 |
+
"array-ness does not match:\n Actual: "
|
| 97 |
+
f"{type(actual)}\n Desired: {type(desired)}"
|
| 98 |
+
)
|
| 99 |
+
assert np.isscalar(actual) == np.isscalar(desired), _msg
|
| 100 |
+
|
| 101 |
+
return desired_xp
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _is_materializable(x: Array) -> bool:
|
| 105 |
+
"""
|
| 106 |
+
Return True if you can call `as_numpy_array(x)`; False otherwise.
|
| 107 |
+
"""
|
| 108 |
+
# Important: here we assume that we're not tracing -
|
| 109 |
+
# e.g. we're not inside `jax.jit`` nor `cupy.cuda.Stream.begin_capture`.
|
| 110 |
+
return not is_torch_array(x) or x.device.type != "meta" # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def as_numpy_array(array: Array, *, xp: ModuleType) -> np.typing.NDArray[Any]:
|
| 114 |
+
"""
|
| 115 |
+
Convert array to NumPy, bypassing GPU-CPU transfer guards and densification guards.
|
| 116 |
+
"""
|
| 117 |
+
if is_cupy_namespace(xp):
|
| 118 |
+
return xp.asnumpy(array)
|
| 119 |
+
if is_pydata_sparse_namespace(xp):
|
| 120 |
+
return array.todense() # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]
|
| 121 |
+
|
| 122 |
+
if is_torch_namespace(xp):
|
| 123 |
+
array = to_device(array, "cpu")
|
| 124 |
+
if is_array_api_strict_namespace(xp):
|
| 125 |
+
cpu: Device = xp.Device("CPU_DEVICE")
|
| 126 |
+
array = to_device(array, cpu)
|
| 127 |
+
if is_jax_namespace(xp):
|
| 128 |
+
import jax
|
| 129 |
+
|
| 130 |
+
# Note: only needed if the transfer guard is enabled
|
| 131 |
+
cpu = cast(Device, jax.devices("cpu")[0])
|
| 132 |
+
array = to_device(array, cpu)
|
| 133 |
+
|
| 134 |
+
return np.asarray(array)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def xp_assert_equal(
|
| 138 |
+
actual: Array,
|
| 139 |
+
desired: Array,
|
| 140 |
+
*,
|
| 141 |
+
err_msg: str = "",
|
| 142 |
+
check_dtype: bool = True,
|
| 143 |
+
check_shape: bool = True,
|
| 144 |
+
check_scalar: bool = False,
|
| 145 |
+
) -> None:
|
| 146 |
+
"""
|
| 147 |
+
Array-API compatible version of `np.testing.assert_array_equal`.
|
| 148 |
+
|
| 149 |
+
Parameters
|
| 150 |
+
----------
|
| 151 |
+
actual : Array
|
| 152 |
+
The array produced by the tested function.
|
| 153 |
+
desired : Array
|
| 154 |
+
The expected array (typically hardcoded).
|
| 155 |
+
err_msg : str, optional
|
| 156 |
+
Error message to display on failure.
|
| 157 |
+
check_dtype, check_shape : bool, default: True
|
| 158 |
+
Whether to check agreement between actual and desired dtypes and shapes
|
| 159 |
+
check_scalar : bool, default: False
|
| 160 |
+
NumPy only: whether to check agreement between actual and desired types -
|
| 161 |
+
0d array vs scalar.
|
| 162 |
+
|
| 163 |
+
See Also
|
| 164 |
+
--------
|
| 165 |
+
xp_assert_close : Similar function for inexact equality checks.
|
| 166 |
+
numpy.testing.assert_array_equal : Similar function for NumPy arrays.
|
| 167 |
+
"""
|
| 168 |
+
xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar)
|
| 169 |
+
if not _is_materializable(actual):
|
| 170 |
+
return
|
| 171 |
+
actual_np = as_numpy_array(actual, xp=xp)
|
| 172 |
+
desired_np = as_numpy_array(desired, xp=xp)
|
| 173 |
+
np.testing.assert_array_equal(actual_np, desired_np, err_msg=err_msg)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def xp_assert_less(
|
| 177 |
+
x: Array,
|
| 178 |
+
y: Array,
|
| 179 |
+
*,
|
| 180 |
+
err_msg: str = "",
|
| 181 |
+
check_dtype: bool = True,
|
| 182 |
+
check_shape: bool = True,
|
| 183 |
+
check_scalar: bool = False,
|
| 184 |
+
) -> None:
|
| 185 |
+
"""
|
| 186 |
+
Array-API compatible version of `np.testing.assert_array_less`.
|
| 187 |
+
|
| 188 |
+
Parameters
|
| 189 |
+
----------
|
| 190 |
+
x, y : Array
|
| 191 |
+
The arrays to compare according to ``x < y`` (elementwise).
|
| 192 |
+
err_msg : str, optional
|
| 193 |
+
Error message to display on failure.
|
| 194 |
+
check_dtype, check_shape : bool, default: True
|
| 195 |
+
Whether to check agreement between actual and desired dtypes and shapes
|
| 196 |
+
check_scalar : bool, default: False
|
| 197 |
+
NumPy only: whether to check agreement between actual and desired types -
|
| 198 |
+
0d array vs scalar.
|
| 199 |
+
|
| 200 |
+
See Also
|
| 201 |
+
--------
|
| 202 |
+
xp_assert_close : Similar function for inexact equality checks.
|
| 203 |
+
numpy.testing.assert_array_equal : Similar function for NumPy arrays.
|
| 204 |
+
"""
|
| 205 |
+
xp = _check_ns_shape_dtype(x, y, check_dtype, check_shape, check_scalar)
|
| 206 |
+
if not _is_materializable(x):
|
| 207 |
+
return
|
| 208 |
+
x_np = as_numpy_array(x, xp=xp)
|
| 209 |
+
y_np = as_numpy_array(y, xp=xp)
|
| 210 |
+
np.testing.assert_array_less(x_np, y_np, err_msg=err_msg)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def xp_assert_close(
|
| 214 |
+
actual: Array,
|
| 215 |
+
desired: Array,
|
| 216 |
+
*,
|
| 217 |
+
rtol: float | None = None,
|
| 218 |
+
atol: float = 0,
|
| 219 |
+
err_msg: str = "",
|
| 220 |
+
check_dtype: bool = True,
|
| 221 |
+
check_shape: bool = True,
|
| 222 |
+
check_scalar: bool = False,
|
| 223 |
+
) -> None:
|
| 224 |
+
"""
|
| 225 |
+
Array-API compatible version of `np.testing.assert_allclose`.
|
| 226 |
+
|
| 227 |
+
Parameters
|
| 228 |
+
----------
|
| 229 |
+
actual : Array
|
| 230 |
+
The array produced by the tested function.
|
| 231 |
+
desired : Array
|
| 232 |
+
The expected array (typically hardcoded).
|
| 233 |
+
rtol : float, optional
|
| 234 |
+
Relative tolerance. Default: dtype-dependent.
|
| 235 |
+
atol : float, optional
|
| 236 |
+
Absolute tolerance. Default: 0.
|
| 237 |
+
err_msg : str, optional
|
| 238 |
+
Error message to display on failure.
|
| 239 |
+
check_dtype, check_shape : bool, default: True
|
| 240 |
+
Whether to check agreement between actual and desired dtypes and shapes
|
| 241 |
+
check_scalar : bool, default: False
|
| 242 |
+
NumPy only: whether to check agreement between actual and desired types -
|
| 243 |
+
0d array vs scalar.
|
| 244 |
+
|
| 245 |
+
See Also
|
| 246 |
+
--------
|
| 247 |
+
xp_assert_equal : Similar function for exact equality checks.
|
| 248 |
+
isclose : Public function for checking closeness.
|
| 249 |
+
numpy.testing.assert_allclose : Similar function for NumPy arrays.
|
| 250 |
+
|
| 251 |
+
Notes
|
| 252 |
+
-----
|
| 253 |
+
The default `atol` and `rtol` differ from `xp.all(xpx.isclose(a, b))`.
|
| 254 |
+
"""
|
| 255 |
+
xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar)
|
| 256 |
+
if not _is_materializable(actual):
|
| 257 |
+
return
|
| 258 |
+
|
| 259 |
+
if rtol is None:
|
| 260 |
+
if xp.isdtype(actual.dtype, ("real floating", "complex floating")):
|
| 261 |
+
# multiplier of 4 is used as for `np.float64` this puts the default `rtol`
|
| 262 |
+
# roughly half way between sqrt(eps) and the default for
|
| 263 |
+
# `numpy.testing.assert_allclose`, 1e-7
|
| 264 |
+
rtol = xp.finfo(actual.dtype).eps ** 0.5 * 4
|
| 265 |
+
else:
|
| 266 |
+
rtol = 1e-7
|
| 267 |
+
|
| 268 |
+
actual_np = as_numpy_array(actual, xp=xp)
|
| 269 |
+
desired_np = as_numpy_array(desired, xp=xp)
|
| 270 |
+
np.testing.assert_allclose( # pyright: ignore[reportCallIssue]
|
| 271 |
+
actual_np,
|
| 272 |
+
desired_np,
|
| 273 |
+
rtol=rtol, # pyright: ignore[reportArgumentType]
|
| 274 |
+
atol=atol,
|
| 275 |
+
err_msg=err_msg,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def xfail(
|
| 280 |
+
request: pytest.FixtureRequest, *, reason: str, strict: bool | None = None
|
| 281 |
+
) -> None:
|
| 282 |
+
"""
|
| 283 |
+
XFAIL the currently running test.
|
| 284 |
+
|
| 285 |
+
Unlike ``pytest.xfail``, allow rest of test to execute instead of immediately
|
| 286 |
+
halting it, so that it may result in a XPASS.
|
| 287 |
+
xref https://github.com/pandas-dev/pandas/issues/38902
|
| 288 |
+
|
| 289 |
+
Parameters
|
| 290 |
+
----------
|
| 291 |
+
request : pytest.FixtureRequest
|
| 292 |
+
``request`` argument of the test function.
|
| 293 |
+
reason : str
|
| 294 |
+
Reason for the expected failure.
|
| 295 |
+
strict: bool, optional
|
| 296 |
+
If True, the test will be marked as failed if it passes.
|
| 297 |
+
If False, the test will be marked as passed if it fails.
|
| 298 |
+
Default: ``xfail_strict`` value in ``pyproject.toml``, or False if absent.
|
| 299 |
+
"""
|
| 300 |
+
if strict is not None:
|
| 301 |
+
marker = pytest.mark.xfail(reason=reason, strict=strict)
|
| 302 |
+
else:
|
| 303 |
+
marker = pytest.mark.xfail(reason=reason)
|
| 304 |
+
request.node.add_marker(marker)
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Modules housing private utility functions."""
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (334 Bytes). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-311.pyc
ADDED
|
Binary file (1.59 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-311.pyc
ADDED
|
Binary file (25.5 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-311.pyc
ADDED
|
Binary file (420 Bytes). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Acquire helpers from array-api-compat."""
|
| 2 |
+
# Allow packages that vendor both `array-api-extra` and
|
| 3 |
+
# `array-api-compat` to override the import location
|
| 4 |
+
|
| 5 |
+
# pylint: disable=duplicate-code
|
| 6 |
+
try:
|
| 7 |
+
from ...._array_api_compat_vendor import (
|
| 8 |
+
array_namespace,
|
| 9 |
+
device,
|
| 10 |
+
is_array_api_obj,
|
| 11 |
+
is_array_api_strict_namespace,
|
| 12 |
+
is_cupy_array,
|
| 13 |
+
is_cupy_namespace,
|
| 14 |
+
is_dask_array,
|
| 15 |
+
is_dask_namespace,
|
| 16 |
+
is_jax_array,
|
| 17 |
+
is_jax_namespace,
|
| 18 |
+
is_lazy_array,
|
| 19 |
+
is_numpy_array,
|
| 20 |
+
is_numpy_namespace,
|
| 21 |
+
is_pydata_sparse_array,
|
| 22 |
+
is_pydata_sparse_namespace,
|
| 23 |
+
is_torch_array,
|
| 24 |
+
is_torch_namespace,
|
| 25 |
+
is_writeable_array,
|
| 26 |
+
size,
|
| 27 |
+
to_device,
|
| 28 |
+
)
|
| 29 |
+
except ImportError:
|
| 30 |
+
from array_api_compat import (
|
| 31 |
+
array_namespace,
|
| 32 |
+
device,
|
| 33 |
+
is_array_api_obj,
|
| 34 |
+
is_array_api_strict_namespace,
|
| 35 |
+
is_cupy_array,
|
| 36 |
+
is_cupy_namespace,
|
| 37 |
+
is_dask_array,
|
| 38 |
+
is_dask_namespace,
|
| 39 |
+
is_jax_array,
|
| 40 |
+
is_jax_namespace,
|
| 41 |
+
is_lazy_array,
|
| 42 |
+
is_numpy_array,
|
| 43 |
+
is_numpy_namespace,
|
| 44 |
+
is_pydata_sparse_array,
|
| 45 |
+
is_pydata_sparse_namespace,
|
| 46 |
+
is_torch_array,
|
| 47 |
+
is_torch_namespace,
|
| 48 |
+
is_writeable_array,
|
| 49 |
+
size,
|
| 50 |
+
to_device,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
__all__ = [
|
| 54 |
+
"array_namespace",
|
| 55 |
+
"device",
|
| 56 |
+
"is_array_api_obj",
|
| 57 |
+
"is_array_api_strict_namespace",
|
| 58 |
+
"is_cupy_array",
|
| 59 |
+
"is_cupy_namespace",
|
| 60 |
+
"is_dask_array",
|
| 61 |
+
"is_dask_namespace",
|
| 62 |
+
"is_jax_array",
|
| 63 |
+
"is_jax_namespace",
|
| 64 |
+
"is_lazy_array",
|
| 65 |
+
"is_numpy_array",
|
| 66 |
+
"is_numpy_namespace",
|
| 67 |
+
"is_pydata_sparse_array",
|
| 68 |
+
"is_pydata_sparse_namespace",
|
| 69 |
+
"is_torch_array",
|
| 70 |
+
"is_torch_namespace",
|
| 71 |
+
"is_writeable_array",
|
| 72 |
+
"size",
|
| 73 |
+
"to_device",
|
| 74 |
+
]
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_compat.pyi
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Static type stubs for `_compat.py`."""
|
| 2 |
+
|
| 3 |
+
# https://github.com/scikit-learn/scikit-learn/pull/27910#issuecomment-2568023972
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from types import ModuleType
|
| 7 |
+
from typing import Any, TypeGuard
|
| 8 |
+
|
| 9 |
+
# TODO import from typing (requires Python >=3.13)
|
| 10 |
+
from typing_extensions import TypeIs
|
| 11 |
+
|
| 12 |
+
from ._typing import Array, Device
|
| 13 |
+
|
| 14 |
+
# pylint: disable=missing-class-docstring,unused-argument
|
| 15 |
+
|
| 16 |
+
def array_namespace(
|
| 17 |
+
*xs: Array | complex | None,
|
| 18 |
+
api_version: str | None = None,
|
| 19 |
+
use_compat: bool | None = None,
|
| 20 |
+
) -> ModuleType: ...
|
| 21 |
+
def device(x: Array, /) -> Device: ...
|
| 22 |
+
def is_array_api_obj(x: object, /) -> TypeIs[Array]: ...
|
| 23 |
+
def is_array_api_strict_namespace(xp: ModuleType, /) -> bool: ...
|
| 24 |
+
def is_cupy_namespace(xp: ModuleType, /) -> bool: ...
|
| 25 |
+
def is_dask_namespace(xp: ModuleType, /) -> bool: ...
|
| 26 |
+
def is_jax_namespace(xp: ModuleType, /) -> bool: ...
|
| 27 |
+
def is_numpy_namespace(xp: ModuleType, /) -> bool: ...
|
| 28 |
+
def is_pydata_sparse_namespace(xp: ModuleType, /) -> bool: ...
|
| 29 |
+
def is_torch_namespace(xp: ModuleType, /) -> bool: ...
|
| 30 |
+
def is_cupy_array(x: object, /) -> TypeGuard[Array]: ...
|
| 31 |
+
def is_dask_array(x: object, /) -> TypeGuard[Array]: ...
|
| 32 |
+
def is_jax_array(x: object, /) -> TypeGuard[Array]: ...
|
| 33 |
+
def is_numpy_array(x: object, /) -> TypeGuard[Array]: ...
|
| 34 |
+
def is_pydata_sparse_array(x: object, /) -> TypeGuard[Array]: ...
|
| 35 |
+
def is_torch_array(x: object, /) -> TypeGuard[Array]: ...
|
| 36 |
+
def is_lazy_array(x: object, /) -> TypeGuard[Array]: ...
|
| 37 |
+
def is_writeable_array(x: object, /) -> TypeGuard[Array]: ...
|
| 38 |
+
def size(x: Array, /) -> int | None: ...
|
| 39 |
+
def to_device(
|
| 40 |
+
x: Array,
|
| 41 |
+
device: Device, # pylint: disable=redefined-outer-name
|
| 42 |
+
/,
|
| 43 |
+
*,
|
| 44 |
+
stream: int | Any | None = None,
|
| 45 |
+
) -> Array: ...
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_helpers.py
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper functions used by `array_api_extra/_funcs.py`."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import io
|
| 6 |
+
import math
|
| 7 |
+
import pickle
|
| 8 |
+
import types
|
| 9 |
+
from collections.abc import Callable, Generator, Iterable, Iterator
|
| 10 |
+
from functools import wraps
|
| 11 |
+
from types import ModuleType
|
| 12 |
+
from typing import (
|
| 13 |
+
TYPE_CHECKING,
|
| 14 |
+
Any,
|
| 15 |
+
ClassVar,
|
| 16 |
+
Generic,
|
| 17 |
+
Literal,
|
| 18 |
+
ParamSpec,
|
| 19 |
+
TypeAlias,
|
| 20 |
+
TypeVar,
|
| 21 |
+
cast,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
from . import _compat
|
| 25 |
+
from ._compat import (
|
| 26 |
+
array_namespace,
|
| 27 |
+
is_array_api_obj,
|
| 28 |
+
is_dask_namespace,
|
| 29 |
+
is_jax_namespace,
|
| 30 |
+
is_numpy_array,
|
| 31 |
+
is_pydata_sparse_namespace,
|
| 32 |
+
is_torch_namespace,
|
| 33 |
+
)
|
| 34 |
+
from ._typing import Array, Device
|
| 35 |
+
|
| 36 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 37 |
+
# TODO import from typing (requires Python >=3.12 and >=3.13)
|
| 38 |
+
from typing_extensions import TypeIs, override
|
| 39 |
+
else:
|
| 40 |
+
|
| 41 |
+
def override(func):
|
| 42 |
+
return func
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
P = ParamSpec("P")
|
| 46 |
+
T = TypeVar("T")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
__all__ = [
|
| 50 |
+
"asarrays",
|
| 51 |
+
"capabilities",
|
| 52 |
+
"eager_shape",
|
| 53 |
+
"in1d",
|
| 54 |
+
"is_python_scalar",
|
| 55 |
+
"jax_autojit",
|
| 56 |
+
"mean",
|
| 57 |
+
"meta_namespace",
|
| 58 |
+
"pickle_flatten",
|
| 59 |
+
"pickle_unflatten",
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def in1d(
|
| 64 |
+
x1: Array,
|
| 65 |
+
x2: Array,
|
| 66 |
+
/,
|
| 67 |
+
*,
|
| 68 |
+
assume_unique: bool = False,
|
| 69 |
+
invert: bool = False,
|
| 70 |
+
xp: ModuleType | None = None,
|
| 71 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 72 |
+
"""
|
| 73 |
+
Check whether each element of an array is also present in a second array.
|
| 74 |
+
|
| 75 |
+
Returns a boolean array the same length as `x1` that is True
|
| 76 |
+
where an element of `x1` is in `x2` and False otherwise.
|
| 77 |
+
|
| 78 |
+
This function has been adapted using the original implementation
|
| 79 |
+
present in numpy:
|
| 80 |
+
https://github.com/numpy/numpy/blob/v1.26.0/numpy/lib/arraysetops.py#L524-L758
|
| 81 |
+
"""
|
| 82 |
+
if xp is None:
|
| 83 |
+
xp = array_namespace(x1, x2)
|
| 84 |
+
|
| 85 |
+
x1_shape = eager_shape(x1)
|
| 86 |
+
x2_shape = eager_shape(x2)
|
| 87 |
+
|
| 88 |
+
# This code is run to make the code significantly faster
|
| 89 |
+
if x2_shape[0] < 10 * x1_shape[0] ** 0.145 and isinstance(x2, Iterable):
|
| 90 |
+
if invert:
|
| 91 |
+
mask = xp.ones(x1_shape[0], dtype=xp.bool, device=_compat.device(x1))
|
| 92 |
+
for a in x2:
|
| 93 |
+
mask &= x1 != a
|
| 94 |
+
else:
|
| 95 |
+
mask = xp.zeros(x1_shape[0], dtype=xp.bool, device=_compat.device(x1))
|
| 96 |
+
for a in x2:
|
| 97 |
+
mask |= x1 == a
|
| 98 |
+
return mask
|
| 99 |
+
|
| 100 |
+
rev_idx = xp.empty(0) # placeholder
|
| 101 |
+
if not assume_unique:
|
| 102 |
+
x1, rev_idx = xp.unique_inverse(x1)
|
| 103 |
+
x2 = xp.unique_values(x2)
|
| 104 |
+
|
| 105 |
+
ar = xp.concat((x1, x2))
|
| 106 |
+
device_ = _compat.device(ar)
|
| 107 |
+
# We need this to be a stable sort.
|
| 108 |
+
order = xp.argsort(ar, stable=True)
|
| 109 |
+
reverse_order = xp.argsort(order, stable=True)
|
| 110 |
+
sar = xp.take(ar, order, axis=0)
|
| 111 |
+
ar_size = _compat.size(sar)
|
| 112 |
+
assert ar_size is not None, "xp.unique*() on lazy backends raises"
|
| 113 |
+
if ar_size >= 1:
|
| 114 |
+
bool_ar = sar[1:] != sar[:-1] if invert else sar[1:] == sar[:-1]
|
| 115 |
+
else:
|
| 116 |
+
bool_ar = xp.asarray([False]) if invert else xp.asarray([True])
|
| 117 |
+
flag = xp.concat((bool_ar, xp.asarray([invert], device=device_)))
|
| 118 |
+
ret = xp.take(flag, reverse_order, axis=0)
|
| 119 |
+
|
| 120 |
+
if assume_unique:
|
| 121 |
+
return ret[: x1.shape[0]]
|
| 122 |
+
return xp.take(ret, rev_idx, axis=0)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def mean(
|
| 126 |
+
x: Array,
|
| 127 |
+
/,
|
| 128 |
+
*,
|
| 129 |
+
axis: int | tuple[int, ...] | None = None,
|
| 130 |
+
keepdims: bool = False,
|
| 131 |
+
xp: ModuleType | None = None,
|
| 132 |
+
) -> Array: # numpydoc ignore=PR01,RT01
|
| 133 |
+
"""
|
| 134 |
+
Complex mean, https://github.com/data-apis/array-api/issues/846.
|
| 135 |
+
"""
|
| 136 |
+
if xp is None:
|
| 137 |
+
xp = array_namespace(x)
|
| 138 |
+
|
| 139 |
+
if xp.isdtype(x.dtype, "complex floating"):
|
| 140 |
+
x_real = xp.real(x)
|
| 141 |
+
x_imag = xp.imag(x)
|
| 142 |
+
mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims)
|
| 143 |
+
mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims)
|
| 144 |
+
return mean_real + (mean_imag * xp.asarray(1j))
|
| 145 |
+
return xp.mean(x, axis=axis, keepdims=keepdims)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def is_python_scalar(x: object) -> TypeIs[complex]: # numpydoc ignore=PR01,RT01
|
| 149 |
+
"""Return True if `x` is a Python scalar, False otherwise."""
|
| 150 |
+
# isinstance(x, float) returns True for np.float64
|
| 151 |
+
# isinstance(x, complex) returns True for np.complex128
|
| 152 |
+
# bool is a subclass of int
|
| 153 |
+
return isinstance(x, int | float | complex) and not is_numpy_array(x)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def asarrays(
|
| 157 |
+
a: Array | complex,
|
| 158 |
+
b: Array | complex,
|
| 159 |
+
xp: ModuleType,
|
| 160 |
+
) -> tuple[Array, Array]:
|
| 161 |
+
"""
|
| 162 |
+
Ensure both `a` and `b` are arrays.
|
| 163 |
+
|
| 164 |
+
If `b` is a python scalar, it is converted to the same dtype as `a`, and vice versa.
|
| 165 |
+
|
| 166 |
+
Behavior is not specified when mixing a Python ``float`` and an array with an
|
| 167 |
+
integer data type; this may give ``float32``, ``float64``, or raise an exception.
|
| 168 |
+
Behavior is implementation-specific.
|
| 169 |
+
|
| 170 |
+
Similarly, behavior is not specified when mixing a Python ``complex`` and an array
|
| 171 |
+
with a real-valued data type; this may give ``complex64``, ``complex128``, or raise
|
| 172 |
+
an exception. Behavior is implementation-specific.
|
| 173 |
+
|
| 174 |
+
Parameters
|
| 175 |
+
----------
|
| 176 |
+
a, b : Array | int | float | complex | bool
|
| 177 |
+
Input arrays or scalars. At least one must be an array.
|
| 178 |
+
xp : array_namespace, optional
|
| 179 |
+
The standard-compatible namespace for `x`. Default: infer.
|
| 180 |
+
|
| 181 |
+
Returns
|
| 182 |
+
-------
|
| 183 |
+
Array, Array
|
| 184 |
+
The input arrays, possibly converted to arrays if they were scalars.
|
| 185 |
+
|
| 186 |
+
See Also
|
| 187 |
+
--------
|
| 188 |
+
mixing-arrays-with-python-scalars : Array API specification for the behavior.
|
| 189 |
+
"""
|
| 190 |
+
a_scalar = is_python_scalar(a)
|
| 191 |
+
b_scalar = is_python_scalar(b)
|
| 192 |
+
if not a_scalar and not b_scalar:
|
| 193 |
+
# This includes misc. malformed input e.g. str
|
| 194 |
+
return a, b # type: ignore[return-value]
|
| 195 |
+
|
| 196 |
+
swap = False
|
| 197 |
+
if a_scalar:
|
| 198 |
+
swap = True
|
| 199 |
+
b, a = a, b
|
| 200 |
+
|
| 201 |
+
if is_array_api_obj(a):
|
| 202 |
+
# a is an Array API object
|
| 203 |
+
# b is a int | float | complex | bool
|
| 204 |
+
xa = a
|
| 205 |
+
|
| 206 |
+
# https://data-apis.org/array-api/draft/API_specification/type_promotion.html#mixing-arrays-with-python-scalars
|
| 207 |
+
same_dtype = {
|
| 208 |
+
bool: "bool",
|
| 209 |
+
int: ("integral", "real floating", "complex floating"),
|
| 210 |
+
float: ("real floating", "complex floating"),
|
| 211 |
+
complex: "complex floating",
|
| 212 |
+
}
|
| 213 |
+
kind = same_dtype[type(cast(complex, b))]
|
| 214 |
+
if xp.isdtype(a.dtype, kind):
|
| 215 |
+
xb = xp.asarray(b, dtype=a.dtype, device=_compat.device(a))
|
| 216 |
+
else:
|
| 217 |
+
# Undefined behaviour. Let the function deal with it, if it can.
|
| 218 |
+
xb = xp.asarray(b, device=_compat.device(a))
|
| 219 |
+
|
| 220 |
+
else:
|
| 221 |
+
# Neither a nor b are Array API objects.
|
| 222 |
+
# Note: we can only reach this point when one explicitly passes
|
| 223 |
+
# xp=xp to the calling function; otherwise we fail earlier on
|
| 224 |
+
# array_namespace(a, b).
|
| 225 |
+
xa, xb = xp.asarray(a), xp.asarray(b)
|
| 226 |
+
|
| 227 |
+
return (xb, xa) if swap else (xa, xb)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def ndindex(*x: int) -> Generator[tuple[int, ...]]:
|
| 231 |
+
"""
|
| 232 |
+
Generate all N-dimensional indices for a given array shape.
|
| 233 |
+
|
| 234 |
+
Given the shape of an array, an ndindex instance iterates over the N-dimensional
|
| 235 |
+
index of the array. At each iteration a tuple of indices is returned, the last
|
| 236 |
+
dimension is iterated over first.
|
| 237 |
+
|
| 238 |
+
This has an identical API to numpy.ndindex.
|
| 239 |
+
|
| 240 |
+
Parameters
|
| 241 |
+
----------
|
| 242 |
+
*x : int
|
| 243 |
+
The shape of the array.
|
| 244 |
+
"""
|
| 245 |
+
if not x:
|
| 246 |
+
yield ()
|
| 247 |
+
return
|
| 248 |
+
for i in ndindex(*x[:-1]):
|
| 249 |
+
for j in range(x[-1]):
|
| 250 |
+
yield *i, j
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def eager_shape(x: Array, /, axis: int | None = None) -> tuple[int, ...]:
|
| 254 |
+
"""
|
| 255 |
+
Return shape of an array. Raise if shape is not fully defined.
|
| 256 |
+
|
| 257 |
+
Parameters
|
| 258 |
+
----------
|
| 259 |
+
x : Array
|
| 260 |
+
Input array.
|
| 261 |
+
axis : int, optional
|
| 262 |
+
If provided, only returns the tuple (shape[axis],).
|
| 263 |
+
|
| 264 |
+
Returns
|
| 265 |
+
-------
|
| 266 |
+
tuple[int, ...]
|
| 267 |
+
Shape of the array.
|
| 268 |
+
"""
|
| 269 |
+
shape = x.shape
|
| 270 |
+
if axis is not None:
|
| 271 |
+
s = shape[axis]
|
| 272 |
+
# Dask arrays uses non-standard NaN instead of None
|
| 273 |
+
if s is None or math.isnan(s):
|
| 274 |
+
msg = f"Unsupported lazy shape for axis {axis}"
|
| 275 |
+
raise TypeError(msg)
|
| 276 |
+
return (s,)
|
| 277 |
+
|
| 278 |
+
if any(s is None or math.isnan(s) for s in shape):
|
| 279 |
+
msg = "Unsupported lazy shape"
|
| 280 |
+
raise TypeError(msg)
|
| 281 |
+
return cast(tuple[int, ...], shape)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def meta_namespace(
|
| 285 |
+
*arrays: Array | complex | None, xp: ModuleType | None = None
|
| 286 |
+
) -> ModuleType:
|
| 287 |
+
"""
|
| 288 |
+
Get the namespace of Dask chunks.
|
| 289 |
+
|
| 290 |
+
On all other backends, just return the namespace of the arrays.
|
| 291 |
+
|
| 292 |
+
Parameters
|
| 293 |
+
----------
|
| 294 |
+
*arrays : Array | int | float | complex | bool | None
|
| 295 |
+
Input arrays.
|
| 296 |
+
xp : array_namespace, optional
|
| 297 |
+
The standard-compatible namespace for the input arrays. Default: infer.
|
| 298 |
+
|
| 299 |
+
Returns
|
| 300 |
+
-------
|
| 301 |
+
array_namespace
|
| 302 |
+
If xp is Dask, the namespace of the Dask chunks;
|
| 303 |
+
otherwise, the namespace of the arrays.
|
| 304 |
+
"""
|
| 305 |
+
xp = array_namespace(*arrays) if xp is None else xp
|
| 306 |
+
if not is_dask_namespace(xp):
|
| 307 |
+
return xp
|
| 308 |
+
# Quietly skip scalars and None's
|
| 309 |
+
metas = [cast(Array | None, getattr(a, "_meta", None)) for a in arrays]
|
| 310 |
+
return array_namespace(*metas)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def capabilities(
|
| 314 |
+
xp: ModuleType, *, device: Device | None = None
|
| 315 |
+
) -> dict[str, int | None]:
|
| 316 |
+
"""
|
| 317 |
+
Return patched ``xp.__array_namespace_info__().capabilities()``.
|
| 318 |
+
|
| 319 |
+
TODO this helper should be eventually removed once all the special cases
|
| 320 |
+
it handles are fixed in the respective backends.
|
| 321 |
+
|
| 322 |
+
Parameters
|
| 323 |
+
----------
|
| 324 |
+
xp : array_namespace
|
| 325 |
+
The standard-compatible namespace.
|
| 326 |
+
device : Device, optional
|
| 327 |
+
The device to use.
|
| 328 |
+
|
| 329 |
+
Returns
|
| 330 |
+
-------
|
| 331 |
+
dict
|
| 332 |
+
Capabilities of the namespace.
|
| 333 |
+
"""
|
| 334 |
+
out = xp.__array_namespace_info__().capabilities()
|
| 335 |
+
if is_pydata_sparse_namespace(xp):
|
| 336 |
+
if out["boolean indexing"]:
|
| 337 |
+
# FIXME https://github.com/pydata/sparse/issues/876
|
| 338 |
+
# boolean indexing is supported, but not when the index is a sparse array.
|
| 339 |
+
# boolean indexing by list or numpy array is not part of the Array API.
|
| 340 |
+
out = out.copy()
|
| 341 |
+
out["boolean indexing"] = False
|
| 342 |
+
elif is_jax_namespace(xp):
|
| 343 |
+
if out["boolean indexing"]: # pragma: no cover
|
| 344 |
+
# Backwards compatibility with jax <0.6.0
|
| 345 |
+
# https://github.com/jax-ml/jax/issues/27418
|
| 346 |
+
out = out.copy()
|
| 347 |
+
out["boolean indexing"] = False
|
| 348 |
+
elif is_torch_namespace(xp):
|
| 349 |
+
# FIXME https://github.com/data-apis/array-api/issues/945
|
| 350 |
+
device = xp.get_default_device() if device is None else xp.device(device)
|
| 351 |
+
if device.type == "meta": # type: ignore[union-attr] # pyright: ignore[reportAttributeAccessIssue,reportOptionalMemberAccess]
|
| 352 |
+
out = out.copy()
|
| 353 |
+
out["boolean indexing"] = False
|
| 354 |
+
out["data-dependent shapes"] = False
|
| 355 |
+
|
| 356 |
+
return out
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
_BASIC_PICKLED_TYPES = frozenset((
|
| 360 |
+
bool, int, float, complex, str, bytes, bytearray,
|
| 361 |
+
list, tuple, dict, set, frozenset, range, slice,
|
| 362 |
+
types.NoneType, types.EllipsisType,
|
| 363 |
+
)) # fmt: skip
|
| 364 |
+
_BASIC_REST_TYPES = frozenset((
|
| 365 |
+
type, types.BuiltinFunctionType, types.FunctionType, types.ModuleType
|
| 366 |
+
)) # fmt: skip
|
| 367 |
+
|
| 368 |
+
FlattenRest: TypeAlias = tuple[object, ...]
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def pickle_flatten(
|
| 372 |
+
obj: object, cls: type[T] | tuple[type[T], ...]
|
| 373 |
+
) -> tuple[list[T], FlattenRest]:
|
| 374 |
+
"""
|
| 375 |
+
Use the pickle machinery to extract objects out of an arbitrary container.
|
| 376 |
+
|
| 377 |
+
Unlike regular ``pickle.dumps``, this function always succeeds.
|
| 378 |
+
|
| 379 |
+
Parameters
|
| 380 |
+
----------
|
| 381 |
+
obj : object
|
| 382 |
+
The object to pickle.
|
| 383 |
+
cls : type | tuple[type, ...]
|
| 384 |
+
One or multiple classes to extract from the object.
|
| 385 |
+
The instances of these classes inside ``obj`` will not be pickled.
|
| 386 |
+
|
| 387 |
+
Returns
|
| 388 |
+
-------
|
| 389 |
+
instances : list[cls]
|
| 390 |
+
All instances of ``cls`` found inside ``obj`` (not pickled).
|
| 391 |
+
rest
|
| 392 |
+
Opaque object containing the pickled bytes plus all other objects where
|
| 393 |
+
``__reduce__`` / ``__reduce_ex__`` is either not implemented or raised.
|
| 394 |
+
These are unpickleable objects, types, modules, and functions.
|
| 395 |
+
|
| 396 |
+
This object is *typically* hashable save for fairly exotic objects
|
| 397 |
+
that are neither pickleable nor hashable.
|
| 398 |
+
|
| 399 |
+
This object is pickleable if everything except ``instances`` was pickleable
|
| 400 |
+
in the input object.
|
| 401 |
+
|
| 402 |
+
See Also
|
| 403 |
+
--------
|
| 404 |
+
pickle_unflatten : Reverse function.
|
| 405 |
+
|
| 406 |
+
Examples
|
| 407 |
+
--------
|
| 408 |
+
>>> class A:
|
| 409 |
+
... def __repr__(self):
|
| 410 |
+
... return "<A>"
|
| 411 |
+
>>> class NS:
|
| 412 |
+
... def __repr__(self):
|
| 413 |
+
... return "<NS>"
|
| 414 |
+
... def __reduce__(self):
|
| 415 |
+
... assert False, "not serializable"
|
| 416 |
+
>>> obj = {1: A(), 2: [A(), NS(), A()]}
|
| 417 |
+
>>> instances, rest = pickle_flatten(obj, A)
|
| 418 |
+
>>> instances
|
| 419 |
+
[<A>, <A>, <A>]
|
| 420 |
+
>>> pickle_unflatten(instances, rest)
|
| 421 |
+
{1: <A>, 2: [<A>, <NS>, <A>]}
|
| 422 |
+
|
| 423 |
+
This can be also used to swap inner objects; the only constraint is that
|
| 424 |
+
the number of objects in and out must be the same:
|
| 425 |
+
|
| 426 |
+
>>> pickle_unflatten(["foo", "bar", "baz"], rest)
|
| 427 |
+
{1: "foo", 2: ["bar", <NS>, "baz"]}
|
| 428 |
+
"""
|
| 429 |
+
instances: list[T] = []
|
| 430 |
+
rest: list[object] = []
|
| 431 |
+
|
| 432 |
+
class Pickler(pickle.Pickler): # numpydoc ignore=GL08
|
| 433 |
+
"""
|
| 434 |
+
Use the `pickle.Pickler.persistent_id` hook to extract objects.
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
@override
|
| 438 |
+
def persistent_id(
|
| 439 |
+
self, obj: object
|
| 440 |
+
) -> Literal[0, 1, None]: # numpydoc ignore=GL08
|
| 441 |
+
if isinstance(obj, cls):
|
| 442 |
+
instances.append(obj) # type: ignore[arg-type]
|
| 443 |
+
return 0
|
| 444 |
+
|
| 445 |
+
typ_ = type(obj)
|
| 446 |
+
if typ_ in _BASIC_PICKLED_TYPES: # No subclasses!
|
| 447 |
+
# If obj is a collection, recursively descend inside it
|
| 448 |
+
return None
|
| 449 |
+
if typ_ in _BASIC_REST_TYPES:
|
| 450 |
+
rest.append(obj)
|
| 451 |
+
return 1
|
| 452 |
+
|
| 453 |
+
try:
|
| 454 |
+
# Note: a class that defines __slots__ without defining __getstate__
|
| 455 |
+
# cannot be pickled with __reduce__(), but can with __reduce_ex__(5)
|
| 456 |
+
_ = obj.__reduce_ex__(pickle.HIGHEST_PROTOCOL)
|
| 457 |
+
except Exception: # pylint: disable=broad-exception-caught
|
| 458 |
+
rest.append(obj)
|
| 459 |
+
return 1
|
| 460 |
+
|
| 461 |
+
# Object can be pickled. Let the Pickler recursively descend inside it.
|
| 462 |
+
return None
|
| 463 |
+
|
| 464 |
+
f = io.BytesIO()
|
| 465 |
+
p = Pickler(f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 466 |
+
p.dump(obj)
|
| 467 |
+
return instances, (f.getvalue(), *rest)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def pickle_unflatten(instances: Iterable[object], rest: FlattenRest) -> Any:
|
| 471 |
+
"""
|
| 472 |
+
Reverse of ``pickle_flatten``.
|
| 473 |
+
|
| 474 |
+
Parameters
|
| 475 |
+
----------
|
| 476 |
+
instances : Iterable
|
| 477 |
+
Inner objects to be reinserted into the flattened container.
|
| 478 |
+
rest : FlattenRest
|
| 479 |
+
Extra bits, as returned by ``pickle_flatten``.
|
| 480 |
+
|
| 481 |
+
Returns
|
| 482 |
+
-------
|
| 483 |
+
object
|
| 484 |
+
The outer object originally passed to ``pickle_flatten`` after a
|
| 485 |
+
pickle->unpickle round-trip.
|
| 486 |
+
|
| 487 |
+
See Also
|
| 488 |
+
--------
|
| 489 |
+
pickle_flatten : Serializing function.
|
| 490 |
+
pickle.loads : Standard unpickle function.
|
| 491 |
+
|
| 492 |
+
Notes
|
| 493 |
+
-----
|
| 494 |
+
The `instances` iterable must yield at least the same number of elements as the ones
|
| 495 |
+
returned by ``pickle_flatten``, but the elements do not need to be the same objects
|
| 496 |
+
or even the same types of objects. Excess elements, if any, will be left untouched.
|
| 497 |
+
"""
|
| 498 |
+
iters = iter(instances), iter(rest)
|
| 499 |
+
pik = cast(bytes, next(iters[1]))
|
| 500 |
+
|
| 501 |
+
class Unpickler(pickle.Unpickler): # numpydoc ignore=GL08
|
| 502 |
+
"""Mirror of the overridden Pickler in pickle_flatten."""
|
| 503 |
+
|
| 504 |
+
@override
|
| 505 |
+
def persistent_load(self, pid: Literal[0, 1]) -> object: # numpydoc ignore=GL08
|
| 506 |
+
try:
|
| 507 |
+
return next(iters[pid])
|
| 508 |
+
except StopIteration as e:
|
| 509 |
+
msg = "Not enough objects to unpickle"
|
| 510 |
+
raise ValueError(msg) from e
|
| 511 |
+
|
| 512 |
+
f = io.BytesIO(pik)
|
| 513 |
+
return Unpickler(f).load()
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class _AutoJITWrapper(Generic[T]): # numpydoc ignore=PR01
|
| 517 |
+
"""
|
| 518 |
+
Helper of :func:`jax_autojit`.
|
| 519 |
+
|
| 520 |
+
Wrap arbitrary inputs and outputs of the jitted function and
|
| 521 |
+
convert them to/from PyTrees.
|
| 522 |
+
"""
|
| 523 |
+
|
| 524 |
+
_obj: Any
|
| 525 |
+
_is_iter: bool
|
| 526 |
+
_registered: ClassVar[bool] = False
|
| 527 |
+
__slots__: tuple[str, ...] = ("_is_iter", "_obj")
|
| 528 |
+
|
| 529 |
+
def __init__(self, obj: T) -> None: # numpydoc ignore=GL08
|
| 530 |
+
self._register()
|
| 531 |
+
if isinstance(obj, Iterator):
|
| 532 |
+
self._obj = list(obj)
|
| 533 |
+
self._is_iter = True
|
| 534 |
+
else:
|
| 535 |
+
self._obj = obj
|
| 536 |
+
self._is_iter = False
|
| 537 |
+
|
| 538 |
+
@property
|
| 539 |
+
def obj(self) -> T: # numpydoc ignore=RT01
|
| 540 |
+
"""Return wrapped object."""
|
| 541 |
+
return iter(self._obj) if self._is_iter else self._obj
|
| 542 |
+
|
| 543 |
+
@classmethod
|
| 544 |
+
def _register(cls) -> None: # numpydoc ignore=SS06
|
| 545 |
+
"""
|
| 546 |
+
Register upon first use instead of at import time, to avoid
|
| 547 |
+
globally importing JAX.
|
| 548 |
+
"""
|
| 549 |
+
if not cls._registered:
|
| 550 |
+
import jax
|
| 551 |
+
|
| 552 |
+
jax.tree_util.register_pytree_node(
|
| 553 |
+
cls,
|
| 554 |
+
lambda instance: pickle_flatten(instance, jax.Array), # pyright: ignore[reportUnknownArgumentType]
|
| 555 |
+
lambda aux_data, children: pickle_unflatten(children, aux_data), # pyright: ignore[reportUnknownArgumentType]
|
| 556 |
+
)
|
| 557 |
+
cls._registered = True
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def jax_autojit(
|
| 561 |
+
func: Callable[P, T],
|
| 562 |
+
) -> Callable[P, T]: # numpydoc ignore=PR01,RT01,SS03
|
| 563 |
+
"""
|
| 564 |
+
Wrap `func` with ``jax.jit``, with the following differences:
|
| 565 |
+
|
| 566 |
+
- Python scalar arguments and return values are not automatically converted to
|
| 567 |
+
``jax.Array`` objects.
|
| 568 |
+
- All non-array arguments are automatically treated as static.
|
| 569 |
+
Unlike ``jax.jit``, static arguments must be either hashable or serializable with
|
| 570 |
+
``pickle``.
|
| 571 |
+
- Unlike ``jax.jit``, non-array arguments and return values are not limited to
|
| 572 |
+
tuple/list/dict, but can be any object serializable with ``pickle``.
|
| 573 |
+
- Automatically descend into non-array arguments and find ``jax.Array`` objects
|
| 574 |
+
inside them, then rebuild the arguments when entering `func`, swapping the JAX
|
| 575 |
+
concrete arrays with tracer objects.
|
| 576 |
+
- Automatically descend into non-array return values and find ``jax.Array`` objects
|
| 577 |
+
inside them, then rebuild them downstream of exiting the JIT, swapping the JAX
|
| 578 |
+
tracer objects with concrete arrays.
|
| 579 |
+
- Returned iterators are immediately completely consumed.
|
| 580 |
+
|
| 581 |
+
See Also
|
| 582 |
+
--------
|
| 583 |
+
jax.jit : JAX JIT compilation function.
|
| 584 |
+
|
| 585 |
+
Notes
|
| 586 |
+
-----
|
| 587 |
+
These are useful choices *for testing purposes only*, which is how this function is
|
| 588 |
+
intended to be used. The output of ``jax.jit`` is a C++ level callable, that
|
| 589 |
+
directly dispatches to the compiled kernel after the initial call. In comparison,
|
| 590 |
+
``jax_autojit`` incurs a much higher dispatch time.
|
| 591 |
+
|
| 592 |
+
Additionally, consider::
|
| 593 |
+
|
| 594 |
+
def f(x: Array, y: float, plus: bool) -> Array:
|
| 595 |
+
return x + y if plus else x - y
|
| 596 |
+
|
| 597 |
+
j1 = jax.jit(f, static_argnames="plus")
|
| 598 |
+
j2 = jax_autojit(f)
|
| 599 |
+
|
| 600 |
+
In the above example, ``j2`` requires a lot less setup to be tested effectively than
|
| 601 |
+
``j1``, but on the flip side it means that it will be re-traced for every different
|
| 602 |
+
value of ``y``, which likely makes it not fit for purpose in production.
|
| 603 |
+
"""
|
| 604 |
+
import jax
|
| 605 |
+
|
| 606 |
+
@jax.jit # type: ignore[misc] # pyright: ignore[reportUntypedFunctionDecorator]
|
| 607 |
+
def inner( # numpydoc ignore=GL08
|
| 608 |
+
wargs: _AutoJITWrapper[Any],
|
| 609 |
+
) -> _AutoJITWrapper[T]:
|
| 610 |
+
args, kwargs = wargs.obj
|
| 611 |
+
res = func(*args, **kwargs) # pyright: ignore[reportCallIssue]
|
| 612 |
+
return _AutoJITWrapper(res)
|
| 613 |
+
|
| 614 |
+
@wraps(func)
|
| 615 |
+
def outer(*args: P.args, **kwargs: P.kwargs) -> T: # numpydoc ignore=GL08
|
| 616 |
+
wargs = _AutoJITWrapper((args, kwargs))
|
| 617 |
+
return inner(wargs).obj
|
| 618 |
+
|
| 619 |
+
return outer
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# numpydoc ignore=GL08
|
| 2 |
+
# pylint: disable=missing-module-docstring,duplicate-code
|
| 3 |
+
|
| 4 |
+
Array = object
|
| 5 |
+
DType = object
|
| 6 |
+
Device = object
|
| 7 |
+
GetIndex = object
|
| 8 |
+
SetIndex = object
|
| 9 |
+
|
| 10 |
+
__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"]
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/_lib/_utils/_typing.pyi
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Static typing helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from types import EllipsisType
|
| 6 |
+
from typing import Protocol, TypeAlias
|
| 7 |
+
|
| 8 |
+
# TODO import from typing (requires Python >=3.12)
|
| 9 |
+
from typing_extensions import override
|
| 10 |
+
|
| 11 |
+
# TODO: use array-api-typing once it is available
|
| 12 |
+
|
| 13 |
+
class Array(Protocol): # pylint: disable=missing-class-docstring
|
| 14 |
+
# Unary operations
|
| 15 |
+
def __abs__(self) -> Array: ...
|
| 16 |
+
def __pos__(self) -> Array: ...
|
| 17 |
+
def __neg__(self) -> Array: ...
|
| 18 |
+
def __invert__(self) -> Array: ...
|
| 19 |
+
# Binary operations
|
| 20 |
+
def __add__(self, other: Array | complex, /) -> Array: ...
|
| 21 |
+
def __sub__(self, other: Array | complex, /) -> Array: ...
|
| 22 |
+
def __mul__(self, other: Array | complex, /) -> Array: ...
|
| 23 |
+
def __truediv__(self, other: Array | complex, /) -> Array: ...
|
| 24 |
+
def __floordiv__(self, other: Array | complex, /) -> Array: ...
|
| 25 |
+
def __mod__(self, other: Array | complex, /) -> Array: ...
|
| 26 |
+
def __pow__(self, other: Array | complex, /) -> Array: ...
|
| 27 |
+
def __matmul__(self, other: Array, /) -> Array: ...
|
| 28 |
+
def __and__(self, other: Array | int, /) -> Array: ...
|
| 29 |
+
def __or__(self, other: Array | int, /) -> Array: ...
|
| 30 |
+
def __xor__(self, other: Array | int, /) -> Array: ...
|
| 31 |
+
def __lshift__(self, other: Array | int, /) -> Array: ...
|
| 32 |
+
def __rshift__(self, other: Array | int, /) -> Array: ...
|
| 33 |
+
def __lt__(self, other: Array | complex, /) -> Array: ...
|
| 34 |
+
def __le__(self, other: Array | complex, /) -> Array: ...
|
| 35 |
+
def __gt__(self, other: Array | complex, /) -> Array: ...
|
| 36 |
+
def __ge__(self, other: Array | complex, /) -> Array: ...
|
| 37 |
+
@override
|
| 38 |
+
def __eq__(self, other: Array | complex, /) -> Array: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
|
| 39 |
+
@override
|
| 40 |
+
def __ne__(self, other: Array | complex, /) -> Array: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
|
| 41 |
+
# Reflected operations
|
| 42 |
+
def __radd__(self, other: Array | complex, /) -> Array: ...
|
| 43 |
+
def __rsub__(self, other: Array | complex, /) -> Array: ...
|
| 44 |
+
def __rmul__(self, other: Array | complex, /) -> Array: ...
|
| 45 |
+
def __rtruediv__(self, other: Array | complex, /) -> Array: ...
|
| 46 |
+
def __rfloordiv__(self, other: Array | complex, /) -> Array: ...
|
| 47 |
+
def __rmod__(self, other: Array | complex, /) -> Array: ...
|
| 48 |
+
def __rpow__(self, other: Array | complex, /) -> Array: ...
|
| 49 |
+
def __rmatmul__(self, other: Array, /) -> Array: ...
|
| 50 |
+
def __rand__(self, other: Array | int, /) -> Array: ...
|
| 51 |
+
def __ror__(self, other: Array | int, /) -> Array: ...
|
| 52 |
+
def __rxor__(self, other: Array | int, /) -> Array: ...
|
| 53 |
+
def __rlshift__(self, other: Array | int, /) -> Array: ...
|
| 54 |
+
def __rrshift__(self, other: Array | int, /) -> Array: ...
|
| 55 |
+
# Attributes
|
| 56 |
+
@property
|
| 57 |
+
def dtype(self) -> DType: ...
|
| 58 |
+
@property
|
| 59 |
+
def device(self) -> Device: ...
|
| 60 |
+
@property
|
| 61 |
+
def mT(self) -> Array: ... # pylint: disable=invalid-name
|
| 62 |
+
@property
|
| 63 |
+
def ndim(self) -> int: ...
|
| 64 |
+
@property
|
| 65 |
+
def shape(self) -> tuple[int | None, ...]: ...
|
| 66 |
+
@property
|
| 67 |
+
def size(self) -> int | None: ...
|
| 68 |
+
@property
|
| 69 |
+
def T(self) -> Array: ... # pylint: disable=invalid-name
|
| 70 |
+
# Collection operations (note: an Array does not have to be Sized or Iterable)
|
| 71 |
+
def __getitem__(self, key: GetIndex, /) -> Array: ...
|
| 72 |
+
def __setitem__(self, key: SetIndex, value: Array | complex, /) -> None: ...
|
| 73 |
+
# Materialization methods (may raise on lazy arrays)
|
| 74 |
+
def __bool__(self) -> bool: ...
|
| 75 |
+
def __complex__(self) -> complex: ...
|
| 76 |
+
def __float__(self) -> float: ...
|
| 77 |
+
def __index__(self) -> int: ...
|
| 78 |
+
def __int__(self) -> int: ...
|
| 79 |
+
|
| 80 |
+
# Misc methods (frequently not implemented in Arrays wrapped by array-api-compat)
|
| 81 |
+
# def __array_namespace__(*, api_version: str | None) -> ModuleType: ...
|
| 82 |
+
# def __dlpack__(
|
| 83 |
+
# *,
|
| 84 |
+
# stream: int | Any | None = None,
|
| 85 |
+
# max_version: tuple[int, int] | None = None,
|
| 86 |
+
# dl_device: tuple[int, int] | None = None, # tuple[Enum, int]
|
| 87 |
+
# copy: bool | None = None,
|
| 88 |
+
# ) -> Any: ...
|
| 89 |
+
# def __dlpack_device__() -> tuple[int, int]: ... # tuple[Enum, int]
|
| 90 |
+
# def to_device(device: Device, /, *, stream: int | Any | None = None) -> Array: ...
|
| 91 |
+
|
| 92 |
+
class DType(Protocol): # pylint: disable=missing-class-docstring
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
class Device(Protocol): # pylint: disable=missing-class-docstring
|
| 96 |
+
pass
|
| 97 |
+
|
| 98 |
+
SetIndex: TypeAlias = (
|
| 99 |
+
int | slice | EllipsisType | Array | tuple[int | slice | EllipsisType | Array, ...]
|
| 100 |
+
)
|
| 101 |
+
GetIndex: TypeAlias = (
|
| 102 |
+
SetIndex | None | tuple[int | slice | EllipsisType | None | Array, ...]
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"]
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/array_api_extra/testing.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Public testing utilities.
|
| 3 |
+
|
| 4 |
+
See also _lib._testing for additional private testing utilities.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import contextlib
|
| 10 |
+
import enum
|
| 11 |
+
import warnings
|
| 12 |
+
from collections.abc import Callable, Generator, Iterator, Sequence
|
| 13 |
+
from functools import wraps
|
| 14 |
+
from types import ModuleType
|
| 15 |
+
from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, cast
|
| 16 |
+
|
| 17 |
+
from ._lib._utils._compat import is_dask_namespace, is_jax_namespace
|
| 18 |
+
from ._lib._utils._helpers import jax_autojit, pickle_flatten, pickle_unflatten
|
| 19 |
+
|
| 20 |
+
__all__ = ["lazy_xp_function", "patch_lazy_xp_functions"]
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 23 |
+
# TODO import override from typing (requires Python >=3.12)
|
| 24 |
+
import pytest
|
| 25 |
+
from dask.typing import Graph, Key, SchedulerGetCallable
|
| 26 |
+
from typing_extensions import override
|
| 27 |
+
|
| 28 |
+
else:
|
| 29 |
+
# Sphinx hacks
|
| 30 |
+
SchedulerGetCallable = object
|
| 31 |
+
|
| 32 |
+
def override(func):
|
| 33 |
+
return func
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
P = ParamSpec("P")
|
| 37 |
+
T = TypeVar("T")
|
| 38 |
+
|
| 39 |
+
_ufuncs_tags: dict[object, dict[str, Any]] = {}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Deprecated(enum.Enum):
|
| 43 |
+
"""Unique type for deprecated parameters."""
|
| 44 |
+
|
| 45 |
+
DEPRECATED = 1
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
DEPRECATED = Deprecated.DEPRECATED
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def lazy_xp_function(
|
| 52 |
+
func: Callable[..., Any],
|
| 53 |
+
*,
|
| 54 |
+
allow_dask_compute: bool | int = False,
|
| 55 |
+
jax_jit: bool = True,
|
| 56 |
+
static_argnums: Deprecated = DEPRECATED,
|
| 57 |
+
static_argnames: Deprecated = DEPRECATED,
|
| 58 |
+
) -> None: # numpydoc ignore=GL07
|
| 59 |
+
"""
|
| 60 |
+
Tag a function to be tested on lazy backends.
|
| 61 |
+
|
| 62 |
+
Tag a function so that when any tests are executed with ``xp=jax.numpy`` the
|
| 63 |
+
function is replaced with a jitted version of itself, and when it is executed with
|
| 64 |
+
``xp=dask.array`` the function will raise if it attempts to materialize the graph.
|
| 65 |
+
This will be later expanded to provide test coverage for other lazy backends.
|
| 66 |
+
|
| 67 |
+
In order for the tag to be effective, the test or a fixture must call
|
| 68 |
+
:func:`patch_lazy_xp_functions`.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
func : callable
|
| 73 |
+
Function to be tested.
|
| 74 |
+
allow_dask_compute : bool | int, optional
|
| 75 |
+
Whether `func` is allowed to internally materialize the Dask graph, or maximum
|
| 76 |
+
number of times it is allowed to do so. This is typically triggered by
|
| 77 |
+
``bool()``, ``float()``, or ``np.asarray()``.
|
| 78 |
+
|
| 79 |
+
Set to 1 if you are aware that `func` converts the input parameters to NumPy and
|
| 80 |
+
want to let it do so at least for the time being, knowing that it is going to be
|
| 81 |
+
extremely detrimental for performance.
|
| 82 |
+
|
| 83 |
+
If a test needs values higher than 1 to pass, it is a canary that the conversion
|
| 84 |
+
to NumPy/bool/float is happening multiple times, which translates to multiple
|
| 85 |
+
computations of the whole graph. Short of making the function fully lazy, you
|
| 86 |
+
should at least add explicit calls to ``np.asarray()`` early in the function.
|
| 87 |
+
*Note:* the counter of `allow_dask_compute` resets after each call to `func`, so
|
| 88 |
+
a test function that invokes `func` multiple times should still work with this
|
| 89 |
+
parameter set to 1.
|
| 90 |
+
|
| 91 |
+
Set to True to allow `func` to materialize the graph an unlimited number
|
| 92 |
+
of times.
|
| 93 |
+
|
| 94 |
+
Default: False, meaning that `func` must be fully lazy and never materialize the
|
| 95 |
+
graph.
|
| 96 |
+
jax_jit : bool, optional
|
| 97 |
+
Set to True to replace `func` with a smart variant of ``jax.jit(func)`` after
|
| 98 |
+
calling the :func:`patch_lazy_xp_functions` test helper with ``xp=jax.numpy``.
|
| 99 |
+
This is the default behaviour.
|
| 100 |
+
Set to False if `func` is only compatible with eager (non-jitted) JAX.
|
| 101 |
+
|
| 102 |
+
Unlike with vanilla ``jax.jit``, all arguments and return types that are not JAX
|
| 103 |
+
arrays are treated as static; the function can accept and return arbitrary
|
| 104 |
+
wrappers around JAX arrays. This difference is because, in real life, most users
|
| 105 |
+
won't wrap the function directly with ``jax.jit`` but rather they will use it
|
| 106 |
+
within their own code, which is itself then wrapped by ``jax.jit``, and
|
| 107 |
+
internally consume the function's outputs.
|
| 108 |
+
|
| 109 |
+
In other words, the pattern that is being tested is::
|
| 110 |
+
|
| 111 |
+
>>> @jax.jit
|
| 112 |
+
... def user_func(x):
|
| 113 |
+
... y = user_prepares_inputs(x)
|
| 114 |
+
... z = func(y, some_static_arg=True)
|
| 115 |
+
... return user_consumes(z)
|
| 116 |
+
|
| 117 |
+
Default: True.
|
| 118 |
+
static_argnums :
|
| 119 |
+
Deprecated; ignored
|
| 120 |
+
static_argnames :
|
| 121 |
+
Deprecated; ignored
|
| 122 |
+
|
| 123 |
+
See Also
|
| 124 |
+
--------
|
| 125 |
+
patch_lazy_xp_functions : Companion function to call from the test or fixture.
|
| 126 |
+
jax.jit : JAX function to compile a function for performance.
|
| 127 |
+
|
| 128 |
+
Examples
|
| 129 |
+
--------
|
| 130 |
+
In ``test_mymodule.py``::
|
| 131 |
+
|
| 132 |
+
from array_api_extra.testing import lazy_xp_function from mymodule import myfunc
|
| 133 |
+
|
| 134 |
+
lazy_xp_function(myfunc)
|
| 135 |
+
|
| 136 |
+
def test_myfunc(xp):
|
| 137 |
+
a = xp.asarray([1, 2])
|
| 138 |
+
# When xp=jax.numpy, this is similar to `b = jax.jit(myfunc)(a)`
|
| 139 |
+
# When xp=dask.array, crash on compute() or persist()
|
| 140 |
+
b = myfunc(a)
|
| 141 |
+
|
| 142 |
+
Notes
|
| 143 |
+
-----
|
| 144 |
+
In order for this tag to be effective, the test function must be imported into the
|
| 145 |
+
test module globals without its namespace; alternatively its namespace must be
|
| 146 |
+
declared in a ``lazy_xp_modules`` list in the test module globals.
|
| 147 |
+
|
| 148 |
+
Example 1::
|
| 149 |
+
|
| 150 |
+
from mymodule import myfunc
|
| 151 |
+
|
| 152 |
+
lazy_xp_function(myfunc)
|
| 153 |
+
|
| 154 |
+
def test_myfunc(xp):
|
| 155 |
+
x = myfunc(xp.asarray([1, 2]))
|
| 156 |
+
|
| 157 |
+
Example 2::
|
| 158 |
+
|
| 159 |
+
import mymodule
|
| 160 |
+
|
| 161 |
+
lazy_xp_modules = [mymodule]
|
| 162 |
+
lazy_xp_function(mymodule.myfunc)
|
| 163 |
+
|
| 164 |
+
def test_myfunc(xp):
|
| 165 |
+
x = mymodule.myfunc(xp.asarray([1, 2]))
|
| 166 |
+
|
| 167 |
+
A test function can circumvent this monkey-patching system by using a namespace
|
| 168 |
+
outside of the two above patterns. You need to sanitize your code to make sure this
|
| 169 |
+
only happens intentionally.
|
| 170 |
+
|
| 171 |
+
Example 1::
|
| 172 |
+
|
| 173 |
+
import mymodule
|
| 174 |
+
from mymodule import myfunc
|
| 175 |
+
|
| 176 |
+
lazy_xp_function(myfunc)
|
| 177 |
+
|
| 178 |
+
def test_myfunc(xp):
|
| 179 |
+
a = xp.asarray([1, 2])
|
| 180 |
+
b = myfunc(a) # This is wrapped when xp=jax.numpy or xp=dask.array
|
| 181 |
+
c = mymodule.myfunc(a) # This is not
|
| 182 |
+
|
| 183 |
+
Example 2::
|
| 184 |
+
|
| 185 |
+
import mymodule
|
| 186 |
+
|
| 187 |
+
class naked:
|
| 188 |
+
myfunc = mymodule.myfunc
|
| 189 |
+
|
| 190 |
+
lazy_xp_modules = [mymodule]
|
| 191 |
+
lazy_xp_function(mymodule.myfunc)
|
| 192 |
+
|
| 193 |
+
def test_myfunc(xp):
|
| 194 |
+
a = xp.asarray([1, 2])
|
| 195 |
+
b = mymodule.myfunc(a) # This is wrapped when xp=jax.numpy or xp=dask.array
|
| 196 |
+
c = naked.myfunc(a) # This is not
|
| 197 |
+
"""
|
| 198 |
+
if static_argnums is not DEPRECATED or static_argnames is not DEPRECATED:
|
| 199 |
+
warnings.warn(
|
| 200 |
+
(
|
| 201 |
+
"The `static_argnums` and `static_argnames` parameters are deprecated "
|
| 202 |
+
"and ignored. They will be removed in a future version."
|
| 203 |
+
),
|
| 204 |
+
DeprecationWarning,
|
| 205 |
+
stacklevel=2,
|
| 206 |
+
)
|
| 207 |
+
tags = {
|
| 208 |
+
"allow_dask_compute": allow_dask_compute,
|
| 209 |
+
"jax_jit": jax_jit,
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
try:
|
| 213 |
+
func._lazy_xp_function = tags # type: ignore[attr-defined] # pylint: disable=protected-access # pyright: ignore[reportFunctionMemberAccess]
|
| 214 |
+
except AttributeError: # @cython.vectorize
|
| 215 |
+
_ufuncs_tags[func] = tags
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def patch_lazy_xp_functions(
|
| 219 |
+
request: pytest.FixtureRequest,
|
| 220 |
+
monkeypatch: pytest.MonkeyPatch | None = None,
|
| 221 |
+
*,
|
| 222 |
+
xp: ModuleType,
|
| 223 |
+
) -> contextlib.AbstractContextManager[None]:
|
| 224 |
+
"""
|
| 225 |
+
Test lazy execution of functions tagged with :func:`lazy_xp_function`.
|
| 226 |
+
|
| 227 |
+
If ``xp==jax.numpy``, search for all functions which have been tagged with
|
| 228 |
+
:func:`lazy_xp_function` in the globals of the module that defines the current test,
|
| 229 |
+
as well as in the ``lazy_xp_modules`` list in the globals of the same module,
|
| 230 |
+
and wrap them with :func:`jax.jit`. Unwrap them at the end of the test.
|
| 231 |
+
|
| 232 |
+
If ``xp==dask.array``, wrap the functions with a decorator that disables
|
| 233 |
+
``compute()`` and ``persist()`` and ensures that exceptions and warnings are raised
|
| 234 |
+
eagerly.
|
| 235 |
+
|
| 236 |
+
This function should be typically called by your library's `xp` fixture that runs
|
| 237 |
+
tests on multiple backends::
|
| 238 |
+
|
| 239 |
+
@pytest.fixture(params=[
|
| 240 |
+
numpy,
|
| 241 |
+
array_api_strict,
|
| 242 |
+
pytest.param(jax.numpy, marks=pytest.mark.thread_unsafe),
|
| 243 |
+
pytest.param(dask.array, marks=pytest.mark.thread_unsafe),
|
| 244 |
+
])
|
| 245 |
+
def xp(request):
|
| 246 |
+
with patch_lazy_xp_functions(request, xp=request.param):
|
| 247 |
+
yield request.param
|
| 248 |
+
|
| 249 |
+
but it can be otherwise be called by the test itself too.
|
| 250 |
+
|
| 251 |
+
Parameters
|
| 252 |
+
----------
|
| 253 |
+
request : pytest.FixtureRequest
|
| 254 |
+
Pytest fixture, as acquired by the test itself or by one of its fixtures.
|
| 255 |
+
monkeypatch : pytest.MonkeyPatch
|
| 256 |
+
Deprecated
|
| 257 |
+
xp : array_namespace
|
| 258 |
+
Array namespace to be tested.
|
| 259 |
+
|
| 260 |
+
See Also
|
| 261 |
+
--------
|
| 262 |
+
lazy_xp_function : Tag a function to be tested on lazy backends.
|
| 263 |
+
pytest.FixtureRequest : `request` test function parameter.
|
| 264 |
+
|
| 265 |
+
Notes
|
| 266 |
+
-----
|
| 267 |
+
This context manager monkey-patches modules and as such is thread unsafe
|
| 268 |
+
on Dask and JAX. If you run your test suite with
|
| 269 |
+
`pytest-run-parallel <https://github.com/Quansight-Labs/pytest-run-parallel/>`_,
|
| 270 |
+
you should mark these backends with ``@pytest.mark.thread_unsafe``, as shown in
|
| 271 |
+
the example above.
|
| 272 |
+
"""
|
| 273 |
+
mod = cast(ModuleType, request.module)
|
| 274 |
+
mods = [mod, *cast(list[ModuleType], getattr(mod, "lazy_xp_modules", []))]
|
| 275 |
+
|
| 276 |
+
to_revert: list[tuple[ModuleType, str, object]] = []
|
| 277 |
+
|
| 278 |
+
def temp_setattr(mod: ModuleType, name: str, func: object) -> None:
|
| 279 |
+
"""
|
| 280 |
+
Variant of monkeypatch.setattr, which allows monkey-patching only selected
|
| 281 |
+
parameters of a test so that pytest-run-parallel can run on the remainder.
|
| 282 |
+
"""
|
| 283 |
+
assert hasattr(mod, name)
|
| 284 |
+
to_revert.append((mod, name, getattr(mod, name)))
|
| 285 |
+
setattr(mod, name, func)
|
| 286 |
+
|
| 287 |
+
if monkeypatch is not None:
|
| 288 |
+
warnings.warn(
|
| 289 |
+
(
|
| 290 |
+
"The `monkeypatch` parameter is deprecated and will be removed in a "
|
| 291 |
+
"future version. "
|
| 292 |
+
"Use `patch_lazy_xp_function` as a context manager instead."
|
| 293 |
+
),
|
| 294 |
+
DeprecationWarning,
|
| 295 |
+
stacklevel=2,
|
| 296 |
+
)
|
| 297 |
+
# Enable using patch_lazy_xp_function not as a context manager
|
| 298 |
+
temp_setattr = monkeypatch.setattr # type: ignore[assignment] # pyright: ignore[reportAssignmentType]
|
| 299 |
+
|
| 300 |
+
def iter_tagged() -> Iterator[
|
| 301 |
+
tuple[ModuleType, str, Callable[..., Any], dict[str, Any]]
|
| 302 |
+
]:
|
| 303 |
+
for mod in mods:
|
| 304 |
+
for name, func in mod.__dict__.items():
|
| 305 |
+
tags: dict[str, Any] | None = None
|
| 306 |
+
with contextlib.suppress(AttributeError):
|
| 307 |
+
tags = func._lazy_xp_function # pylint: disable=protected-access
|
| 308 |
+
if tags is None:
|
| 309 |
+
with contextlib.suppress(KeyError, TypeError):
|
| 310 |
+
tags = _ufuncs_tags[func]
|
| 311 |
+
if tags is not None:
|
| 312 |
+
yield mod, name, func, tags
|
| 313 |
+
|
| 314 |
+
if is_dask_namespace(xp):
|
| 315 |
+
for mod, name, func, tags in iter_tagged():
|
| 316 |
+
n = tags["allow_dask_compute"]
|
| 317 |
+
if n is True:
|
| 318 |
+
n = 1_000_000
|
| 319 |
+
elif n is False:
|
| 320 |
+
n = 0
|
| 321 |
+
wrapped = _dask_wrap(func, n)
|
| 322 |
+
temp_setattr(mod, name, wrapped)
|
| 323 |
+
|
| 324 |
+
elif is_jax_namespace(xp):
|
| 325 |
+
for mod, name, func, tags in iter_tagged():
|
| 326 |
+
if tags["jax_jit"]:
|
| 327 |
+
wrapped = jax_autojit(func)
|
| 328 |
+
temp_setattr(mod, name, wrapped)
|
| 329 |
+
|
| 330 |
+
# We can't just decorate patch_lazy_xp_functions with
|
| 331 |
+
# @contextlib.contextmanager because it would not work with the
|
| 332 |
+
# deprecated monkeypatch when not used as a context manager.
|
| 333 |
+
@contextlib.contextmanager
|
| 334 |
+
def revert_on_exit() -> Generator[None]:
|
| 335 |
+
try:
|
| 336 |
+
yield
|
| 337 |
+
finally:
|
| 338 |
+
for mod, name, orig_func in to_revert:
|
| 339 |
+
setattr(mod, name, orig_func)
|
| 340 |
+
|
| 341 |
+
return revert_on_exit()
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class CountingDaskScheduler(SchedulerGetCallable):
|
| 345 |
+
"""
|
| 346 |
+
Dask scheduler that counts how many times `dask.compute` is called.
|
| 347 |
+
|
| 348 |
+
If the number of times exceeds 'max_count', it raises an error.
|
| 349 |
+
This is a wrapper around Dask's own 'synchronous' scheduler.
|
| 350 |
+
|
| 351 |
+
Parameters
|
| 352 |
+
----------
|
| 353 |
+
max_count : int
|
| 354 |
+
Maximum number of allowed calls to `dask.compute`.
|
| 355 |
+
msg : str
|
| 356 |
+
Assertion to raise when the count exceeds `max_count`.
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
count: int
|
| 360 |
+
max_count: int
|
| 361 |
+
msg: str
|
| 362 |
+
|
| 363 |
+
def __init__(self, max_count: int, msg: str): # numpydoc ignore=GL08
|
| 364 |
+
self.count = 0
|
| 365 |
+
self.max_count = max_count
|
| 366 |
+
self.msg = msg
|
| 367 |
+
|
| 368 |
+
@override
|
| 369 |
+
def __call__(
|
| 370 |
+
self, dsk: Graph, keys: Sequence[Key] | Key, **kwargs: Any
|
| 371 |
+
) -> Any: # numpydoc ignore=GL08
|
| 372 |
+
import dask
|
| 373 |
+
|
| 374 |
+
self.count += 1
|
| 375 |
+
# This should yield a nice traceback to the
|
| 376 |
+
# offending line in the user's code
|
| 377 |
+
assert self.count <= self.max_count, self.msg
|
| 378 |
+
|
| 379 |
+
return dask.get(dsk, keys, **kwargs) # type: ignore[attr-defined] # pyright: ignore[reportPrivateImportUsage]
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _dask_wrap(
|
| 383 |
+
func: Callable[P, T], n: int
|
| 384 |
+
) -> Callable[P, T]: # numpydoc ignore=PR01,RT01
|
| 385 |
+
"""
|
| 386 |
+
Wrap `func` to raise if it attempts to call `dask.compute` more than `n` times.
|
| 387 |
+
|
| 388 |
+
After the function returns, materialize the graph in order to re-raise exceptions.
|
| 389 |
+
"""
|
| 390 |
+
import dask
|
| 391 |
+
import dask.array as da
|
| 392 |
+
|
| 393 |
+
func_name = getattr(func, "__name__", str(func))
|
| 394 |
+
n_str = f"only up to {n}" if n else "no"
|
| 395 |
+
msg = (
|
| 396 |
+
f"Called `dask.compute()` or `dask.persist()` {n + 1} times, "
|
| 397 |
+
f"but {n_str} calls are allowed. Set "
|
| 398 |
+
f"`lazy_xp_function({func_name}, allow_dask_compute={n + 1})` "
|
| 399 |
+
"to allow for more (but note that this will harm performance). "
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
@wraps(func)
|
| 403 |
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: # numpydoc ignore=GL08
|
| 404 |
+
scheduler = CountingDaskScheduler(n, msg)
|
| 405 |
+
with dask.config.set({"scheduler": scheduler}): # pyright: ignore[reportPrivateImportUsage]
|
| 406 |
+
out = func(*args, **kwargs)
|
| 407 |
+
|
| 408 |
+
# Block until the graph materializes and reraise exceptions. This allows
|
| 409 |
+
# `pytest.raises` and `pytest.warns` to work as expected. Note that this would
|
| 410 |
+
# not work on scheduler='distributed', as it would not block.
|
| 411 |
+
arrays, rest = pickle_flatten(out, da.Array)
|
| 412 |
+
arrays = dask.persist(arrays, scheduler="threads")[0] # type: ignore[attr-defined,no-untyped-call] # pyright: ignore[reportPrivateImportUsage]
|
| 413 |
+
return pickle_unflatten(arrays, rest) # pyright: ignore[reportUnknownArgumentType]
|
| 414 |
+
|
| 415 |
+
return wrapper
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .main import minimize
|
| 2 |
+
from .utils import show_versions
|
| 3 |
+
|
| 4 |
+
# PEP0440 compatible formatted version, see:
|
| 5 |
+
# https://www.python.org/dev/peps/pep-0440/
|
| 6 |
+
#
|
| 7 |
+
# Final release markers:
|
| 8 |
+
# X.Y.0 # For first release after an increment in Y
|
| 9 |
+
# X.Y.Z # For bugfix releases
|
| 10 |
+
#
|
| 11 |
+
# Admissible pre-release markers:
|
| 12 |
+
# X.YaN # Alpha release
|
| 13 |
+
# X.YbN # Beta release
|
| 14 |
+
# X.YrcN # Release Candidate
|
| 15 |
+
#
|
| 16 |
+
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
|
| 17 |
+
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'.
|
| 18 |
+
__version__ = "1.1.3"
|
| 19 |
+
|
| 20 |
+
__all__ = ["minimize", "show_versions"]
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (433 Bytes). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/framework.cpython-311.pyc
ADDED
|
Binary file (48.7 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/main.cpython-311.pyc
ADDED
|
Binary file (58.8 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/models.cpython-311.pyc
ADDED
|
Binary file (62.6 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/problem.cpython-311.pyc
ADDED
|
Binary file (49 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/__pycache__/settings.cpython-311.pyc
ADDED
|
Binary file (5.73 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/framework.py
ADDED
|
@@ -0,0 +1,1240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.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
|
physworld_p1_20261018/envs/p1/lib/python3.11/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}.")
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/models.py
ADDED
|
@@ -0,0 +1,1531 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
self._lhs_cache = None
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def n(self):
|
| 95 |
+
"""
|
| 96 |
+
Number of variables.
|
| 97 |
+
|
| 98 |
+
Returns
|
| 99 |
+
-------
|
| 100 |
+
int
|
| 101 |
+
Number of variables.
|
| 102 |
+
"""
|
| 103 |
+
return self.xpt.shape[0]
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def npt(self):
|
| 107 |
+
"""
|
| 108 |
+
Number of interpolation points.
|
| 109 |
+
|
| 110 |
+
Returns
|
| 111 |
+
-------
|
| 112 |
+
int
|
| 113 |
+
Number of interpolation points.
|
| 114 |
+
"""
|
| 115 |
+
return self.xpt.shape[1]
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def xpt(self):
|
| 119 |
+
"""
|
| 120 |
+
Interpolation points.
|
| 121 |
+
|
| 122 |
+
Returns
|
| 123 |
+
-------
|
| 124 |
+
`numpy.ndarray`, shape (n, npt)
|
| 125 |
+
Interpolation points.
|
| 126 |
+
"""
|
| 127 |
+
return self._xpt
|
| 128 |
+
|
| 129 |
+
@xpt.setter
|
| 130 |
+
def xpt(self, xpt):
|
| 131 |
+
"""
|
| 132 |
+
Set the interpolation points.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
xpt : `numpy.ndarray`, shape (n, npt)
|
| 137 |
+
New interpolation points.
|
| 138 |
+
"""
|
| 139 |
+
if self._debug:
|
| 140 |
+
assert xpt.shape == (
|
| 141 |
+
self.n,
|
| 142 |
+
self.npt,
|
| 143 |
+
), "The shape of `xpt` is not valid."
|
| 144 |
+
self._xpt = xpt
|
| 145 |
+
|
| 146 |
+
@property
|
| 147 |
+
def x_base(self):
|
| 148 |
+
"""
|
| 149 |
+
Base point around which the models are expanded.
|
| 150 |
+
|
| 151 |
+
Returns
|
| 152 |
+
-------
|
| 153 |
+
`numpy.ndarray`, shape (n,)
|
| 154 |
+
Base point around which the models are expanded.
|
| 155 |
+
"""
|
| 156 |
+
return self._x_base
|
| 157 |
+
|
| 158 |
+
@x_base.setter
|
| 159 |
+
def x_base(self, x_base):
|
| 160 |
+
"""
|
| 161 |
+
Set the base point around which the models are expanded.
|
| 162 |
+
|
| 163 |
+
Parameters
|
| 164 |
+
----------
|
| 165 |
+
x_base : `numpy.ndarray`, shape (n,)
|
| 166 |
+
New base point around which the models are expanded.
|
| 167 |
+
"""
|
| 168 |
+
if self._debug:
|
| 169 |
+
assert x_base.shape == (
|
| 170 |
+
self.n,
|
| 171 |
+
), "The shape of `x_base` is not valid."
|
| 172 |
+
self._x_base = x_base
|
| 173 |
+
|
| 174 |
+
def point(self, k):
|
| 175 |
+
"""
|
| 176 |
+
Get the `k`-th interpolation point.
|
| 177 |
+
|
| 178 |
+
The return point is relative to the origin.
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
k : int
|
| 183 |
+
Index of the interpolation point.
|
| 184 |
+
|
| 185 |
+
Returns
|
| 186 |
+
-------
|
| 187 |
+
`numpy.ndarray`, shape (n,)
|
| 188 |
+
`k`-th interpolation point.
|
| 189 |
+
"""
|
| 190 |
+
if self._debug:
|
| 191 |
+
assert 0 <= k < self.npt, "The index `k` is not valid."
|
| 192 |
+
return self.x_base + self.xpt[:, k]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def build_system(interpolation):
|
| 196 |
+
"""
|
| 197 |
+
Build the left-hand side matrix of the interpolation system. The
|
| 198 |
+
matrix below stores W * diag(right_scaling),
|
| 199 |
+
where W is the theoretical matrix of the interpolation system. The
|
| 200 |
+
right scaling matrices is chosen to keep the elements in
|
| 201 |
+
the matrix well-balanced.
|
| 202 |
+
|
| 203 |
+
Parameters
|
| 204 |
+
----------
|
| 205 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 206 |
+
Interpolation set.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
_cache = interpolation._lhs_cache
|
| 210 |
+
# Compute the scaled directions from the base point to the
|
| 211 |
+
# interpolation points. We scale the directions to avoid numerical
|
| 212 |
+
# difficulties.
|
| 213 |
+
if _cache is not None and np.array_equal(
|
| 214 |
+
interpolation.xpt, _cache["xpt"]
|
| 215 |
+
):
|
| 216 |
+
return _cache["a"], _cache["right_scaling"], _cache["eigh"]
|
| 217 |
+
|
| 218 |
+
scale = np.max(np.linalg.norm(interpolation.xpt, axis=0), initial=EPS)
|
| 219 |
+
xpt_scale = interpolation.xpt / scale
|
| 220 |
+
|
| 221 |
+
n, npt = xpt_scale.shape
|
| 222 |
+
a = np.zeros((npt + n + 1, npt + n + 1))
|
| 223 |
+
a[:npt, :npt] = 0.5 * (xpt_scale.T @ xpt_scale) ** 2.0
|
| 224 |
+
a[:npt, npt] = 1.0
|
| 225 |
+
a[:npt, npt + 1:] = xpt_scale.T
|
| 226 |
+
a[npt, :npt] = 1.0
|
| 227 |
+
a[npt + 1:, :npt] = xpt_scale
|
| 228 |
+
|
| 229 |
+
# Build the left and right scaling diagonal matrices.
|
| 230 |
+
right_scaling = np.empty(npt + n + 1)
|
| 231 |
+
right_scaling[:npt] = 1.0 / scale**2.0
|
| 232 |
+
right_scaling[npt] = scale**2.0
|
| 233 |
+
right_scaling[npt + 1:] = scale
|
| 234 |
+
|
| 235 |
+
eig_values, eig_vectors = eigh(a, check_finite=False)
|
| 236 |
+
|
| 237 |
+
new_cache = {
|
| 238 |
+
"xpt": np.copy(interpolation.xpt),
|
| 239 |
+
"a": np.copy(a),
|
| 240 |
+
"right_scaling": np.copy(right_scaling),
|
| 241 |
+
"eigh": (eig_values, eig_vectors),
|
| 242 |
+
}
|
| 243 |
+
interpolation._lhs_cache = new_cache
|
| 244 |
+
|
| 245 |
+
return a, right_scaling, (eig_values, eig_vectors)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class Quadratic:
|
| 249 |
+
"""
|
| 250 |
+
Quadratic model.
|
| 251 |
+
|
| 252 |
+
This class stores the Hessian matrix of the quadratic model using the
|
| 253 |
+
implicit/explicit representation designed by Powell for NEWUOA [1]_.
|
| 254 |
+
|
| 255 |
+
References
|
| 256 |
+
----------
|
| 257 |
+
.. [1] M. J. D. Powell. The NEWUOA software for unconstrained optimization
|
| 258 |
+
without derivatives. In G. Di Pillo and M. Roma, editors, *Large-Scale
|
| 259 |
+
Nonlinear Optimization*, volume 83 of Nonconvex Optim. Appl., pages
|
| 260 |
+
255--297. Springer, Boston, MA, USA, 2006. `doi:10.1007/0-387-30065-1_16
|
| 261 |
+
<https://doi.org/10.1007/0-387-30065-1_16>`_.
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
def __init__(self, interpolation, values, debug):
|
| 265 |
+
"""
|
| 266 |
+
Initialize the quadratic model.
|
| 267 |
+
|
| 268 |
+
Parameters
|
| 269 |
+
----------
|
| 270 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 271 |
+
Interpolation set.
|
| 272 |
+
values : `numpy.ndarray`, shape (npt,)
|
| 273 |
+
Values of the interpolated function at the interpolation points.
|
| 274 |
+
debug : bool
|
| 275 |
+
Whether to make debugging tests during the execution.
|
| 276 |
+
|
| 277 |
+
Raises
|
| 278 |
+
------
|
| 279 |
+
`numpy.linalg.LinAlgError`
|
| 280 |
+
If the interpolation system is ill-defined.
|
| 281 |
+
"""
|
| 282 |
+
self._debug = debug
|
| 283 |
+
if self._debug:
|
| 284 |
+
assert values.shape == (
|
| 285 |
+
interpolation.npt,
|
| 286 |
+
), "The shape of `values` is not valid."
|
| 287 |
+
if interpolation.npt < interpolation.n + 1:
|
| 288 |
+
raise ValueError(
|
| 289 |
+
f"The number of interpolation points must be at least "
|
| 290 |
+
f"{interpolation.n + 1}."
|
| 291 |
+
)
|
| 292 |
+
self._const, self._grad, self._i_hess, _ = self._get_model(
|
| 293 |
+
interpolation,
|
| 294 |
+
values,
|
| 295 |
+
)
|
| 296 |
+
self._e_hess = np.zeros((self.n, self.n))
|
| 297 |
+
|
| 298 |
+
def __call__(self, x, interpolation):
|
| 299 |
+
"""
|
| 300 |
+
Evaluate the quadratic model at a given point.
|
| 301 |
+
|
| 302 |
+
Parameters
|
| 303 |
+
----------
|
| 304 |
+
x : `numpy.ndarray`, shape (n,)
|
| 305 |
+
Point at which the quadratic model is evaluated.
|
| 306 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 307 |
+
Interpolation set.
|
| 308 |
+
|
| 309 |
+
Returns
|
| 310 |
+
-------
|
| 311 |
+
float
|
| 312 |
+
Value of the quadratic model at `x`.
|
| 313 |
+
"""
|
| 314 |
+
if self._debug:
|
| 315 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 316 |
+
x_diff = x - interpolation.x_base
|
| 317 |
+
return (
|
| 318 |
+
self._const
|
| 319 |
+
+ self._grad @ x_diff
|
| 320 |
+
+ 0.5
|
| 321 |
+
* (
|
| 322 |
+
self._i_hess @ (interpolation.xpt.T @ x_diff) ** 2.0
|
| 323 |
+
+ x_diff @ self._e_hess @ x_diff
|
| 324 |
+
)
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
@property
|
| 328 |
+
def n(self):
|
| 329 |
+
"""
|
| 330 |
+
Number of variables.
|
| 331 |
+
|
| 332 |
+
Returns
|
| 333 |
+
-------
|
| 334 |
+
int
|
| 335 |
+
Number of variables.
|
| 336 |
+
"""
|
| 337 |
+
return self._grad.size
|
| 338 |
+
|
| 339 |
+
@property
|
| 340 |
+
def npt(self):
|
| 341 |
+
"""
|
| 342 |
+
Number of interpolation points used to define the quadratic model.
|
| 343 |
+
|
| 344 |
+
Returns
|
| 345 |
+
-------
|
| 346 |
+
int
|
| 347 |
+
Number of interpolation points used to define the quadratic model.
|
| 348 |
+
"""
|
| 349 |
+
return self._i_hess.size
|
| 350 |
+
|
| 351 |
+
def grad(self, x, interpolation):
|
| 352 |
+
"""
|
| 353 |
+
Evaluate the gradient of the quadratic model at a given point.
|
| 354 |
+
|
| 355 |
+
Parameters
|
| 356 |
+
----------
|
| 357 |
+
x : `numpy.ndarray`, shape (n,)
|
| 358 |
+
Point at which the gradient of the quadratic model is evaluated.
|
| 359 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 360 |
+
Interpolation set.
|
| 361 |
+
|
| 362 |
+
Returns
|
| 363 |
+
-------
|
| 364 |
+
`numpy.ndarray`, shape (n,)
|
| 365 |
+
Gradient of the quadratic model at `x`.
|
| 366 |
+
"""
|
| 367 |
+
if self._debug:
|
| 368 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 369 |
+
x_diff = x - interpolation.x_base
|
| 370 |
+
return self._grad + self.hess_prod(x_diff, interpolation)
|
| 371 |
+
|
| 372 |
+
def hess(self, interpolation):
|
| 373 |
+
"""
|
| 374 |
+
Evaluate the Hessian matrix of the quadratic model.
|
| 375 |
+
|
| 376 |
+
Parameters
|
| 377 |
+
----------
|
| 378 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 379 |
+
Interpolation set.
|
| 380 |
+
|
| 381 |
+
Returns
|
| 382 |
+
-------
|
| 383 |
+
`numpy.ndarray`, shape (n, n)
|
| 384 |
+
Hessian matrix of the quadratic model.
|
| 385 |
+
"""
|
| 386 |
+
return self._e_hess + interpolation.xpt @ (
|
| 387 |
+
self._i_hess[:, np.newaxis] * interpolation.xpt.T
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
def hess_prod(self, v, interpolation):
|
| 391 |
+
"""
|
| 392 |
+
Evaluate the right product of the Hessian matrix of the quadratic model
|
| 393 |
+
with a given vector.
|
| 394 |
+
|
| 395 |
+
Parameters
|
| 396 |
+
----------
|
| 397 |
+
v : `numpy.ndarray`, shape (n,)
|
| 398 |
+
Vector with which the Hessian matrix of the quadratic model is
|
| 399 |
+
multiplied from the right.
|
| 400 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 401 |
+
Interpolation set.
|
| 402 |
+
|
| 403 |
+
Returns
|
| 404 |
+
-------
|
| 405 |
+
`numpy.ndarray`, shape (n,)
|
| 406 |
+
Right product of the Hessian matrix of the quadratic model with
|
| 407 |
+
`v`.
|
| 408 |
+
"""
|
| 409 |
+
if self._debug:
|
| 410 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 411 |
+
return self._e_hess @ v + interpolation.xpt @ (
|
| 412 |
+
self._i_hess * (interpolation.xpt.T @ v)
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
def curv(self, v, interpolation):
|
| 416 |
+
"""
|
| 417 |
+
Evaluate the curvature of the quadratic model along a given direction.
|
| 418 |
+
|
| 419 |
+
Parameters
|
| 420 |
+
----------
|
| 421 |
+
v : `numpy.ndarray`, shape (n,)
|
| 422 |
+
Direction along which the curvature of the quadratic model is
|
| 423 |
+
evaluated.
|
| 424 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 425 |
+
Interpolation set.
|
| 426 |
+
|
| 427 |
+
Returns
|
| 428 |
+
-------
|
| 429 |
+
float
|
| 430 |
+
Curvature of the quadratic model along `v`.
|
| 431 |
+
"""
|
| 432 |
+
if self._debug:
|
| 433 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 434 |
+
return (
|
| 435 |
+
v @ self._e_hess @ v
|
| 436 |
+
+ self._i_hess @ (interpolation.xpt.T @ v) ** 2.0
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
def update(self, interpolation, k_new, dir_old, values_diff):
|
| 440 |
+
"""
|
| 441 |
+
Update the quadratic model.
|
| 442 |
+
|
| 443 |
+
This method applies the derivative-free symmetric Broyden update to the
|
| 444 |
+
quadratic model. The `knew`-th interpolation point must be updated
|
| 445 |
+
before calling this method.
|
| 446 |
+
|
| 447 |
+
Parameters
|
| 448 |
+
----------
|
| 449 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 450 |
+
Updated interpolation set.
|
| 451 |
+
k_new : int
|
| 452 |
+
Index of the updated interpolation point.
|
| 453 |
+
dir_old : `numpy.ndarray`, shape (n,)
|
| 454 |
+
Value of ``interpolation.xpt[:, k_new]`` before the update.
|
| 455 |
+
values_diff : `numpy.ndarray`, shape (npt,)
|
| 456 |
+
Differences between the values of the interpolated nonlinear
|
| 457 |
+
function and the previous quadratic model at the updated
|
| 458 |
+
interpolation points.
|
| 459 |
+
|
| 460 |
+
Raises
|
| 461 |
+
------
|
| 462 |
+
`numpy.linalg.LinAlgError`
|
| 463 |
+
If the interpolation system is ill-defined.
|
| 464 |
+
"""
|
| 465 |
+
if self._debug:
|
| 466 |
+
assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
|
| 467 |
+
assert dir_old.shape == (
|
| 468 |
+
self.n,
|
| 469 |
+
), "The shape of `dir_old` is not valid."
|
| 470 |
+
assert values_diff.shape == (
|
| 471 |
+
self.npt,
|
| 472 |
+
), "The shape of `values_diff` is not valid."
|
| 473 |
+
|
| 474 |
+
# Forward the k_new-th element of the implicit Hessian matrix to the
|
| 475 |
+
# explicit Hessian matrix. This must be done because the implicit
|
| 476 |
+
# Hessian matrix is related to the interpolation points, and the
|
| 477 |
+
# k_new-th interpolation point is modified.
|
| 478 |
+
self._e_hess += self._i_hess[k_new] * np.outer(dir_old, dir_old)
|
| 479 |
+
self._i_hess[k_new] = 0.0
|
| 480 |
+
|
| 481 |
+
# Update the quadratic model.
|
| 482 |
+
const, grad, i_hess, ill_conditioned = self._get_model(
|
| 483 |
+
interpolation,
|
| 484 |
+
values_diff,
|
| 485 |
+
)
|
| 486 |
+
self._const += const
|
| 487 |
+
self._grad += grad
|
| 488 |
+
self._i_hess += i_hess
|
| 489 |
+
return ill_conditioned
|
| 490 |
+
|
| 491 |
+
def shift_x_base(self, interpolation, new_x_base):
|
| 492 |
+
"""
|
| 493 |
+
Shift the point around which the quadratic model is defined.
|
| 494 |
+
|
| 495 |
+
Parameters
|
| 496 |
+
----------
|
| 497 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 498 |
+
Previous interpolation set.
|
| 499 |
+
new_x_base : `numpy.ndarray`, shape (n,)
|
| 500 |
+
Point that will replace ``interpolation.x_base``.
|
| 501 |
+
"""
|
| 502 |
+
if self._debug:
|
| 503 |
+
assert new_x_base.shape == (
|
| 504 |
+
self.n,
|
| 505 |
+
), "The shape of `new_x_base` is not valid."
|
| 506 |
+
self._const = self(new_x_base, interpolation)
|
| 507 |
+
self._grad = self.grad(new_x_base, interpolation)
|
| 508 |
+
shift = new_x_base - interpolation.x_base
|
| 509 |
+
update = np.outer(
|
| 510 |
+
shift,
|
| 511 |
+
(interpolation.xpt - 0.5 * shift[:, np.newaxis]) @ self._i_hess,
|
| 512 |
+
)
|
| 513 |
+
self._e_hess += update + update.T
|
| 514 |
+
|
| 515 |
+
@staticmethod
|
| 516 |
+
def solve_systems(interpolation, rhs):
|
| 517 |
+
"""
|
| 518 |
+
Solve the interpolation systems.
|
| 519 |
+
|
| 520 |
+
Parameters
|
| 521 |
+
----------
|
| 522 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 523 |
+
Interpolation set.
|
| 524 |
+
rhs : `numpy.ndarray`, shape (npt + n + 1, m)
|
| 525 |
+
Right-hand side vectors of the ``m`` interpolation systems.
|
| 526 |
+
|
| 527 |
+
Returns
|
| 528 |
+
-------
|
| 529 |
+
`numpy.ndarray`, shape (npt + n + 1, m)
|
| 530 |
+
Solutions of the interpolation systems.
|
| 531 |
+
`numpy.ndarray`, shape (m, )
|
| 532 |
+
Whether the interpolation systems are ill-conditioned.
|
| 533 |
+
|
| 534 |
+
Raises
|
| 535 |
+
------
|
| 536 |
+
`numpy.linalg.LinAlgError`
|
| 537 |
+
If the interpolation systems are ill-defined.
|
| 538 |
+
"""
|
| 539 |
+
n, npt = interpolation.xpt.shape
|
| 540 |
+
assert (
|
| 541 |
+
rhs.ndim == 2 and rhs.shape[0] == npt + n + 1
|
| 542 |
+
), "The shape of `rhs` is not valid."
|
| 543 |
+
|
| 544 |
+
# Build the left-hand side matrix of the interpolation system. The
|
| 545 |
+
# matrix below stores diag(left_scaling) * W * diag(right_scaling),
|
| 546 |
+
# where W is the theoretical matrix of the interpolation system. The
|
| 547 |
+
# left and right scaling matrices are chosen to keep the elements in
|
| 548 |
+
# the matrix well-balanced.
|
| 549 |
+
a, right_scaling, eig = build_system(interpolation)
|
| 550 |
+
|
| 551 |
+
# Build the solution. After a discussion with Mike Saunders and Alexis
|
| 552 |
+
# Montoison during their visit to the Hong Kong Polytechnic University
|
| 553 |
+
# in 2024, we decided to use the eigendecomposition of the symmetric
|
| 554 |
+
# matrix a. This is more stable than the previously employed LBL
|
| 555 |
+
# decomposition, and allows us to directly detect ill-conditioning of
|
| 556 |
+
# the system and to build the least-squares solution if necessary.
|
| 557 |
+
# Numerical experiments have shown that this strategy improves the
|
| 558 |
+
# performance of the solver.
|
| 559 |
+
rhs_scaled = rhs * right_scaling[:, np.newaxis]
|
| 560 |
+
if not (np.all(np.isfinite(a)) and np.all(np.isfinite(rhs_scaled))):
|
| 561 |
+
raise np.linalg.LinAlgError(
|
| 562 |
+
"The interpolation system is ill-defined."
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
# calculated in build_system
|
| 566 |
+
eig_values, eig_vectors = eig
|
| 567 |
+
|
| 568 |
+
large_eig_values = np.abs(eig_values) > EPS
|
| 569 |
+
eig_vectors = eig_vectors[:, large_eig_values]
|
| 570 |
+
inv_eig_values = 1.0 / eig_values[large_eig_values]
|
| 571 |
+
ill_conditioned = ~np.all(large_eig_values, 0)
|
| 572 |
+
left_scaled_solutions = eig_vectors @ (
|
| 573 |
+
(eig_vectors.T @ rhs_scaled) * inv_eig_values[:, np.newaxis]
|
| 574 |
+
)
|
| 575 |
+
return (
|
| 576 |
+
left_scaled_solutions * right_scaling[:, np.newaxis],
|
| 577 |
+
ill_conditioned,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
@staticmethod
|
| 581 |
+
def _get_model(interpolation, values):
|
| 582 |
+
"""
|
| 583 |
+
Solve the interpolation system.
|
| 584 |
+
|
| 585 |
+
Parameters
|
| 586 |
+
----------
|
| 587 |
+
interpolation : `cobyqa.models.Interpolation`
|
| 588 |
+
Interpolation set.
|
| 589 |
+
values : `numpy.ndarray`, shape (npt,)
|
| 590 |
+
Values of the interpolated function at the interpolation points.
|
| 591 |
+
|
| 592 |
+
Returns
|
| 593 |
+
-------
|
| 594 |
+
float
|
| 595 |
+
Constant term of the quadratic model.
|
| 596 |
+
`numpy.ndarray`, shape (n,)
|
| 597 |
+
Gradient of the quadratic model at ``interpolation.x_base``.
|
| 598 |
+
`numpy.ndarray`, shape (npt,)
|
| 599 |
+
Implicit Hessian matrix of the quadratic model.
|
| 600 |
+
|
| 601 |
+
Raises
|
| 602 |
+
------
|
| 603 |
+
`numpy.linalg.LinAlgError`
|
| 604 |
+
If the interpolation system is ill-defined.
|
| 605 |
+
"""
|
| 606 |
+
assert values.shape == (
|
| 607 |
+
interpolation.npt,
|
| 608 |
+
), "The shape of `values` is not valid."
|
| 609 |
+
n, npt = interpolation.xpt.shape
|
| 610 |
+
x, ill_conditioned = Quadratic.solve_systems(
|
| 611 |
+
interpolation,
|
| 612 |
+
np.block(
|
| 613 |
+
[
|
| 614 |
+
[
|
| 615 |
+
values,
|
| 616 |
+
np.zeros(n + 1),
|
| 617 |
+
]
|
| 618 |
+
]
|
| 619 |
+
).T,
|
| 620 |
+
)
|
| 621 |
+
return x[npt, 0], x[npt + 1:, 0], x[:npt, 0], ill_conditioned
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
class Models:
|
| 625 |
+
"""
|
| 626 |
+
Models for a nonlinear optimization problem.
|
| 627 |
+
"""
|
| 628 |
+
|
| 629 |
+
def __init__(self, pb, options, penalty):
|
| 630 |
+
"""
|
| 631 |
+
Initialize the models.
|
| 632 |
+
|
| 633 |
+
Parameters
|
| 634 |
+
----------
|
| 635 |
+
pb : `cobyqa.problem.Problem`
|
| 636 |
+
Problem to be solved.
|
| 637 |
+
options : dict
|
| 638 |
+
Options of the solver.
|
| 639 |
+
penalty : float
|
| 640 |
+
Penalty parameter used to select the point in the filter to forward
|
| 641 |
+
to the callback function.
|
| 642 |
+
|
| 643 |
+
Raises
|
| 644 |
+
------
|
| 645 |
+
`cobyqa.utils.MaxEvalError`
|
| 646 |
+
If the maximum number of evaluations is reached.
|
| 647 |
+
`cobyqa.utils.TargetSuccess`
|
| 648 |
+
If a nearly feasible point has been found with an objective
|
| 649 |
+
function value below the target.
|
| 650 |
+
`cobyqa.utils.FeasibleSuccess`
|
| 651 |
+
If a feasible point has been found for a feasibility problem.
|
| 652 |
+
`numpy.linalg.LinAlgError`
|
| 653 |
+
If the interpolation system is ill-defined.
|
| 654 |
+
"""
|
| 655 |
+
# Set the initial interpolation set.
|
| 656 |
+
self._debug = options[Options.DEBUG]
|
| 657 |
+
self._interpolation = Interpolation(pb, options)
|
| 658 |
+
|
| 659 |
+
# Evaluate the nonlinear functions at the initial interpolation points.
|
| 660 |
+
x_eval = self.interpolation.point(0)
|
| 661 |
+
fun_init, cub_init, ceq_init = pb(x_eval, penalty)
|
| 662 |
+
self._fun_val = np.full(options[Options.NPT], np.nan)
|
| 663 |
+
self._cub_val = np.full((options[Options.NPT], cub_init.size), np.nan)
|
| 664 |
+
self._ceq_val = np.full((options[Options.NPT], ceq_init.size), np.nan)
|
| 665 |
+
for k in range(options[Options.NPT]):
|
| 666 |
+
if k >= options[Options.MAX_EVAL]:
|
| 667 |
+
raise MaxEvalError
|
| 668 |
+
if k == 0:
|
| 669 |
+
self.fun_val[k] = fun_init
|
| 670 |
+
self.cub_val[k, :] = cub_init
|
| 671 |
+
self.ceq_val[k, :] = ceq_init
|
| 672 |
+
else:
|
| 673 |
+
x_eval = self.interpolation.point(k)
|
| 674 |
+
self.fun_val[k], self.cub_val[k, :], self.ceq_val[k, :] = pb(
|
| 675 |
+
x_eval,
|
| 676 |
+
penalty,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
# Stop the iterations if the problem is a feasibility problem and
|
| 680 |
+
# the current interpolation point is feasible.
|
| 681 |
+
if (
|
| 682 |
+
pb.is_feasibility
|
| 683 |
+
and pb.maxcv(
|
| 684 |
+
self.interpolation.point(k),
|
| 685 |
+
self.cub_val[k, :],
|
| 686 |
+
self.ceq_val[k, :],
|
| 687 |
+
)
|
| 688 |
+
<= options[Options.FEASIBILITY_TOL]
|
| 689 |
+
):
|
| 690 |
+
raise FeasibleSuccess
|
| 691 |
+
|
| 692 |
+
# Stop the iterations if the current interpolation point is nearly
|
| 693 |
+
# feasible and has an objective function value below the target.
|
| 694 |
+
if (
|
| 695 |
+
self._fun_val[k] <= options[Options.TARGET]
|
| 696 |
+
and pb.maxcv(
|
| 697 |
+
self.interpolation.point(k),
|
| 698 |
+
self.cub_val[k, :],
|
| 699 |
+
self.ceq_val[k, :],
|
| 700 |
+
)
|
| 701 |
+
<= options[Options.FEASIBILITY_TOL]
|
| 702 |
+
):
|
| 703 |
+
raise TargetSuccess
|
| 704 |
+
|
| 705 |
+
# Build the initial quadratic models.
|
| 706 |
+
self._fun = Quadratic(
|
| 707 |
+
self.interpolation,
|
| 708 |
+
self._fun_val,
|
| 709 |
+
options[Options.DEBUG],
|
| 710 |
+
)
|
| 711 |
+
self._cub = np.empty(self.m_nonlinear_ub, dtype=Quadratic)
|
| 712 |
+
self._ceq = np.empty(self.m_nonlinear_eq, dtype=Quadratic)
|
| 713 |
+
for i in range(self.m_nonlinear_ub):
|
| 714 |
+
self._cub[i] = Quadratic(
|
| 715 |
+
self.interpolation,
|
| 716 |
+
self.cub_val[:, i],
|
| 717 |
+
options[Options.DEBUG],
|
| 718 |
+
)
|
| 719 |
+
for i in range(self.m_nonlinear_eq):
|
| 720 |
+
self._ceq[i] = Quadratic(
|
| 721 |
+
self.interpolation,
|
| 722 |
+
self.ceq_val[:, i],
|
| 723 |
+
options[Options.DEBUG],
|
| 724 |
+
)
|
| 725 |
+
if self._debug:
|
| 726 |
+
self._check_interpolation_conditions()
|
| 727 |
+
|
| 728 |
+
@property
|
| 729 |
+
def n(self):
|
| 730 |
+
"""
|
| 731 |
+
Dimension of the problem.
|
| 732 |
+
|
| 733 |
+
Returns
|
| 734 |
+
-------
|
| 735 |
+
int
|
| 736 |
+
Dimension of the problem.
|
| 737 |
+
"""
|
| 738 |
+
return self.interpolation.n
|
| 739 |
+
|
| 740 |
+
@property
|
| 741 |
+
def npt(self):
|
| 742 |
+
"""
|
| 743 |
+
Number of interpolation points.
|
| 744 |
+
|
| 745 |
+
Returns
|
| 746 |
+
-------
|
| 747 |
+
int
|
| 748 |
+
Number of interpolation points.
|
| 749 |
+
"""
|
| 750 |
+
return self.interpolation.npt
|
| 751 |
+
|
| 752 |
+
@property
|
| 753 |
+
def m_nonlinear_ub(self):
|
| 754 |
+
"""
|
| 755 |
+
Number of nonlinear inequality constraints.
|
| 756 |
+
|
| 757 |
+
Returns
|
| 758 |
+
-------
|
| 759 |
+
int
|
| 760 |
+
Number of nonlinear inequality constraints.
|
| 761 |
+
"""
|
| 762 |
+
return self.cub_val.shape[1]
|
| 763 |
+
|
| 764 |
+
@property
|
| 765 |
+
def m_nonlinear_eq(self):
|
| 766 |
+
"""
|
| 767 |
+
Number of nonlinear equality constraints.
|
| 768 |
+
|
| 769 |
+
Returns
|
| 770 |
+
-------
|
| 771 |
+
int
|
| 772 |
+
Number of nonlinear equality constraints.
|
| 773 |
+
"""
|
| 774 |
+
return self.ceq_val.shape[1]
|
| 775 |
+
|
| 776 |
+
@property
|
| 777 |
+
def interpolation(self):
|
| 778 |
+
"""
|
| 779 |
+
Interpolation set.
|
| 780 |
+
|
| 781 |
+
Returns
|
| 782 |
+
-------
|
| 783 |
+
`cobyqa.models.Interpolation`
|
| 784 |
+
Interpolation set.
|
| 785 |
+
"""
|
| 786 |
+
return self._interpolation
|
| 787 |
+
|
| 788 |
+
@property
|
| 789 |
+
def fun_val(self):
|
| 790 |
+
"""
|
| 791 |
+
Values of the objective function at the interpolation points.
|
| 792 |
+
|
| 793 |
+
Returns
|
| 794 |
+
-------
|
| 795 |
+
`numpy.ndarray`, shape (npt,)
|
| 796 |
+
Values of the objective function at the interpolation points.
|
| 797 |
+
"""
|
| 798 |
+
return self._fun_val
|
| 799 |
+
|
| 800 |
+
@property
|
| 801 |
+
def cub_val(self):
|
| 802 |
+
"""
|
| 803 |
+
Values of the nonlinear inequality constraint functions at the
|
| 804 |
+
interpolation points.
|
| 805 |
+
|
| 806 |
+
Returns
|
| 807 |
+
-------
|
| 808 |
+
`numpy.ndarray`, shape (npt, m_nonlinear_ub)
|
| 809 |
+
Values of the nonlinear inequality constraint functions at the
|
| 810 |
+
interpolation points.
|
| 811 |
+
"""
|
| 812 |
+
return self._cub_val
|
| 813 |
+
|
| 814 |
+
@property
|
| 815 |
+
def ceq_val(self):
|
| 816 |
+
"""
|
| 817 |
+
Values of the nonlinear equality constraint functions at the
|
| 818 |
+
interpolation points.
|
| 819 |
+
|
| 820 |
+
Returns
|
| 821 |
+
-------
|
| 822 |
+
`numpy.ndarray`, shape (npt, m_nonlinear_eq)
|
| 823 |
+
Values of the nonlinear equality constraint functions at the
|
| 824 |
+
interpolation points.
|
| 825 |
+
"""
|
| 826 |
+
return self._ceq_val
|
| 827 |
+
|
| 828 |
+
def fun(self, x):
|
| 829 |
+
"""
|
| 830 |
+
Evaluate the quadratic model of the objective function at a given
|
| 831 |
+
point.
|
| 832 |
+
|
| 833 |
+
Parameters
|
| 834 |
+
----------
|
| 835 |
+
x : `numpy.ndarray`, shape (n,)
|
| 836 |
+
Point at which to evaluate the quadratic model of the objective
|
| 837 |
+
function.
|
| 838 |
+
|
| 839 |
+
Returns
|
| 840 |
+
-------
|
| 841 |
+
float
|
| 842 |
+
Value of the quadratic model of the objective function at `x`.
|
| 843 |
+
"""
|
| 844 |
+
if self._debug:
|
| 845 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 846 |
+
return self._fun(x, self.interpolation)
|
| 847 |
+
|
| 848 |
+
def fun_grad(self, x):
|
| 849 |
+
"""
|
| 850 |
+
Evaluate the gradient of the quadratic model of the objective function
|
| 851 |
+
at a given point.
|
| 852 |
+
|
| 853 |
+
Parameters
|
| 854 |
+
----------
|
| 855 |
+
x : `numpy.ndarray`, shape (n,)
|
| 856 |
+
Point at which to evaluate the gradient of the quadratic model of
|
| 857 |
+
the objective function.
|
| 858 |
+
|
| 859 |
+
Returns
|
| 860 |
+
-------
|
| 861 |
+
`numpy.ndarray`, shape (n,)
|
| 862 |
+
Gradient of the quadratic model of the objective function at `x`.
|
| 863 |
+
"""
|
| 864 |
+
if self._debug:
|
| 865 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 866 |
+
return self._fun.grad(x, self.interpolation)
|
| 867 |
+
|
| 868 |
+
def fun_hess(self):
|
| 869 |
+
"""
|
| 870 |
+
Evaluate the Hessian matrix of the quadratic model of the objective
|
| 871 |
+
function.
|
| 872 |
+
|
| 873 |
+
Returns
|
| 874 |
+
-------
|
| 875 |
+
`numpy.ndarray`, shape (n, n)
|
| 876 |
+
Hessian matrix of the quadratic model of the objective function.
|
| 877 |
+
"""
|
| 878 |
+
return self._fun.hess(self.interpolation)
|
| 879 |
+
|
| 880 |
+
def fun_hess_prod(self, v):
|
| 881 |
+
"""
|
| 882 |
+
Evaluate the right product of the Hessian matrix of the quadratic model
|
| 883 |
+
of the objective function with a given vector.
|
| 884 |
+
|
| 885 |
+
Parameters
|
| 886 |
+
----------
|
| 887 |
+
v : `numpy.ndarray`, shape (n,)
|
| 888 |
+
Vector with which the Hessian matrix of the quadratic model of the
|
| 889 |
+
objective function is multiplied from the right.
|
| 890 |
+
|
| 891 |
+
Returns
|
| 892 |
+
-------
|
| 893 |
+
`numpy.ndarray`, shape (n,)
|
| 894 |
+
Right product of the Hessian matrix of the quadratic model of the
|
| 895 |
+
objective function with `v`.
|
| 896 |
+
"""
|
| 897 |
+
if self._debug:
|
| 898 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 899 |
+
return self._fun.hess_prod(v, self.interpolation)
|
| 900 |
+
|
| 901 |
+
def fun_curv(self, v):
|
| 902 |
+
"""
|
| 903 |
+
Evaluate the curvature of the quadratic model of the objective function
|
| 904 |
+
along a given direction.
|
| 905 |
+
|
| 906 |
+
Parameters
|
| 907 |
+
----------
|
| 908 |
+
v : `numpy.ndarray`, shape (n,)
|
| 909 |
+
Direction along which the curvature of the quadratic model of the
|
| 910 |
+
objective function is evaluated.
|
| 911 |
+
|
| 912 |
+
Returns
|
| 913 |
+
-------
|
| 914 |
+
float
|
| 915 |
+
Curvature of the quadratic model of the objective function along
|
| 916 |
+
`v`.
|
| 917 |
+
"""
|
| 918 |
+
if self._debug:
|
| 919 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 920 |
+
return self._fun.curv(v, self.interpolation)
|
| 921 |
+
|
| 922 |
+
def fun_alt_grad(self, x):
|
| 923 |
+
"""
|
| 924 |
+
Evaluate the gradient of the alternative quadratic model of the
|
| 925 |
+
objective function at a given point.
|
| 926 |
+
|
| 927 |
+
Parameters
|
| 928 |
+
----------
|
| 929 |
+
x : `numpy.ndarray`, shape (n,)
|
| 930 |
+
Point at which to evaluate the gradient of the alternative
|
| 931 |
+
quadratic model of the objective function.
|
| 932 |
+
|
| 933 |
+
Returns
|
| 934 |
+
-------
|
| 935 |
+
`numpy.ndarray`, shape (n,)
|
| 936 |
+
Gradient of the alternative quadratic model of the objective
|
| 937 |
+
function at `x`.
|
| 938 |
+
|
| 939 |
+
Raises
|
| 940 |
+
------
|
| 941 |
+
`numpy.linalg.LinAlgError`
|
| 942 |
+
If the interpolation system is ill-defined.
|
| 943 |
+
"""
|
| 944 |
+
if self._debug:
|
| 945 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 946 |
+
model = Quadratic(self.interpolation, self.fun_val, self._debug)
|
| 947 |
+
return model.grad(x, self.interpolation)
|
| 948 |
+
|
| 949 |
+
def cub(self, x, mask=None):
|
| 950 |
+
"""
|
| 951 |
+
Evaluate the quadratic models of the nonlinear inequality functions at
|
| 952 |
+
a given point.
|
| 953 |
+
|
| 954 |
+
Parameters
|
| 955 |
+
----------
|
| 956 |
+
x : `numpy.ndarray`, shape (n,)
|
| 957 |
+
Point at which to evaluate the quadratic models of the nonlinear
|
| 958 |
+
inequality functions.
|
| 959 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 960 |
+
Mask of the quadratic models to consider.
|
| 961 |
+
|
| 962 |
+
Returns
|
| 963 |
+
-------
|
| 964 |
+
`numpy.ndarray`
|
| 965 |
+
Values of the quadratic model of the nonlinear inequality
|
| 966 |
+
functions.
|
| 967 |
+
"""
|
| 968 |
+
if self._debug:
|
| 969 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 970 |
+
assert mask is None or mask.shape == (
|
| 971 |
+
self.m_nonlinear_ub,
|
| 972 |
+
), "The shape of `mask` is not valid."
|
| 973 |
+
return np.array(
|
| 974 |
+
[model(x, self.interpolation) for model in self._get_cub(mask)]
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
def cub_grad(self, x, mask=None):
|
| 978 |
+
"""
|
| 979 |
+
Evaluate the gradients of the quadratic models of the nonlinear
|
| 980 |
+
inequality functions at a given point.
|
| 981 |
+
|
| 982 |
+
Parameters
|
| 983 |
+
----------
|
| 984 |
+
x : `numpy.ndarray`, shape (n,)
|
| 985 |
+
Point at which to evaluate the gradients of the quadratic models of
|
| 986 |
+
the nonlinear inequality functions.
|
| 987 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 988 |
+
Mask of the quadratic models to consider.
|
| 989 |
+
|
| 990 |
+
Returns
|
| 991 |
+
-------
|
| 992 |
+
`numpy.ndarray`
|
| 993 |
+
Gradients of the quadratic model of the nonlinear inequality
|
| 994 |
+
functions.
|
| 995 |
+
"""
|
| 996 |
+
if self._debug:
|
| 997 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 998 |
+
assert mask is None or mask.shape == (
|
| 999 |
+
self.m_nonlinear_ub,
|
| 1000 |
+
), "The shape of `mask` is not valid."
|
| 1001 |
+
return np.reshape(
|
| 1002 |
+
[model.grad(x, self.interpolation)
|
| 1003 |
+
for model in self._get_cub(mask)],
|
| 1004 |
+
(-1, self.n),
|
| 1005 |
+
)
|
| 1006 |
+
|
| 1007 |
+
def cub_hess(self, mask=None):
|
| 1008 |
+
"""
|
| 1009 |
+
Evaluate the Hessian matrices of the quadratic models of the nonlinear
|
| 1010 |
+
inequality functions.
|
| 1011 |
+
|
| 1012 |
+
Parameters
|
| 1013 |
+
----------
|
| 1014 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1015 |
+
Mask of the quadratic models to consider.
|
| 1016 |
+
|
| 1017 |
+
Returns
|
| 1018 |
+
-------
|
| 1019 |
+
`numpy.ndarray`
|
| 1020 |
+
Hessian matrices of the quadratic models of the nonlinear
|
| 1021 |
+
inequality functions.
|
| 1022 |
+
"""
|
| 1023 |
+
if self._debug:
|
| 1024 |
+
assert mask is None or mask.shape == (
|
| 1025 |
+
self.m_nonlinear_ub,
|
| 1026 |
+
), "The shape of `mask` is not valid."
|
| 1027 |
+
return np.reshape(
|
| 1028 |
+
[model.hess(self.interpolation) for model in self._get_cub(mask)],
|
| 1029 |
+
(-1, self.n, self.n),
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
def cub_hess_prod(self, v, mask=None):
|
| 1033 |
+
"""
|
| 1034 |
+
Evaluate the right product of the Hessian matrices of the quadratic
|
| 1035 |
+
models of the nonlinear inequality functions with a given vector.
|
| 1036 |
+
|
| 1037 |
+
Parameters
|
| 1038 |
+
----------
|
| 1039 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1040 |
+
Vector with which the Hessian matrices of the quadratic models of
|
| 1041 |
+
the nonlinear inequality functions are multiplied from the right.
|
| 1042 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1043 |
+
Mask of the quadratic models to consider.
|
| 1044 |
+
|
| 1045 |
+
Returns
|
| 1046 |
+
-------
|
| 1047 |
+
`numpy.ndarray`
|
| 1048 |
+
Right products of the Hessian matrices of the quadratic models of
|
| 1049 |
+
the nonlinear inequality functions with `v`.
|
| 1050 |
+
"""
|
| 1051 |
+
if self._debug:
|
| 1052 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1053 |
+
assert mask is None or mask.shape == (
|
| 1054 |
+
self.m_nonlinear_ub,
|
| 1055 |
+
), "The shape of `mask` is not valid."
|
| 1056 |
+
return np.reshape(
|
| 1057 |
+
[
|
| 1058 |
+
model.hess_prod(v, self.interpolation)
|
| 1059 |
+
for model in self._get_cub(mask)
|
| 1060 |
+
],
|
| 1061 |
+
(-1, self.n),
|
| 1062 |
+
)
|
| 1063 |
+
|
| 1064 |
+
def cub_curv(self, v, mask=None):
|
| 1065 |
+
"""
|
| 1066 |
+
Evaluate the curvature of the quadratic models of the nonlinear
|
| 1067 |
+
inequality functions along a given direction.
|
| 1068 |
+
|
| 1069 |
+
Parameters
|
| 1070 |
+
----------
|
| 1071 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1072 |
+
Direction along which the curvature of the quadratic models of the
|
| 1073 |
+
nonlinear inequality functions is evaluated.
|
| 1074 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1075 |
+
Mask of the quadratic models to consider.
|
| 1076 |
+
|
| 1077 |
+
Returns
|
| 1078 |
+
-------
|
| 1079 |
+
`numpy.ndarray`
|
| 1080 |
+
Curvature of the quadratic models of the nonlinear inequality
|
| 1081 |
+
functions along `v`.
|
| 1082 |
+
"""
|
| 1083 |
+
if self._debug:
|
| 1084 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1085 |
+
assert mask is None or mask.shape == (
|
| 1086 |
+
self.m_nonlinear_ub,
|
| 1087 |
+
), "The shape of `mask` is not valid."
|
| 1088 |
+
return np.array(
|
| 1089 |
+
[model.curv(v, self.interpolation)
|
| 1090 |
+
for model in self._get_cub(mask)]
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
def ceq(self, x, mask=None):
|
| 1094 |
+
"""
|
| 1095 |
+
Evaluate the quadratic models of the nonlinear equality functions at a
|
| 1096 |
+
given point.
|
| 1097 |
+
|
| 1098 |
+
Parameters
|
| 1099 |
+
----------
|
| 1100 |
+
x : `numpy.ndarray`, shape (n,)
|
| 1101 |
+
Point at which to evaluate the quadratic models of the nonlinear
|
| 1102 |
+
equality functions.
|
| 1103 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1104 |
+
Mask of the quadratic models to consider.
|
| 1105 |
+
|
| 1106 |
+
Returns
|
| 1107 |
+
-------
|
| 1108 |
+
`numpy.ndarray`
|
| 1109 |
+
Values of the quadratic model of the nonlinear equality functions.
|
| 1110 |
+
"""
|
| 1111 |
+
if self._debug:
|
| 1112 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 1113 |
+
assert mask is None or mask.shape == (
|
| 1114 |
+
self.m_nonlinear_eq,
|
| 1115 |
+
), "The shape of `mask` is not valid."
|
| 1116 |
+
return np.array(
|
| 1117 |
+
[model(x, self.interpolation) for model in self._get_ceq(mask)]
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
def ceq_grad(self, x, mask=None):
|
| 1121 |
+
"""
|
| 1122 |
+
Evaluate the gradients of the quadratic models of the nonlinear
|
| 1123 |
+
equality functions at a given point.
|
| 1124 |
+
|
| 1125 |
+
Parameters
|
| 1126 |
+
----------
|
| 1127 |
+
x : `numpy.ndarray`, shape (n,)
|
| 1128 |
+
Point at which to evaluate the gradients of the quadratic models of
|
| 1129 |
+
the nonlinear equality functions.
|
| 1130 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1131 |
+
Mask of the quadratic models to consider.
|
| 1132 |
+
|
| 1133 |
+
Returns
|
| 1134 |
+
-------
|
| 1135 |
+
`numpy.ndarray`
|
| 1136 |
+
Gradients of the quadratic model of the nonlinear equality
|
| 1137 |
+
functions.
|
| 1138 |
+
"""
|
| 1139 |
+
if self._debug:
|
| 1140 |
+
assert x.shape == (self.n,), "The shape of `x` is not valid."
|
| 1141 |
+
assert mask is None or mask.shape == (
|
| 1142 |
+
self.m_nonlinear_eq,
|
| 1143 |
+
), "The shape of `mask` is not valid."
|
| 1144 |
+
return np.reshape(
|
| 1145 |
+
[model.grad(x, self.interpolation)
|
| 1146 |
+
for model in self._get_ceq(mask)],
|
| 1147 |
+
(-1, self.n),
|
| 1148 |
+
)
|
| 1149 |
+
|
| 1150 |
+
def ceq_hess(self, mask=None):
|
| 1151 |
+
"""
|
| 1152 |
+
Evaluate the Hessian matrices of the quadratic models of the nonlinear
|
| 1153 |
+
equality functions.
|
| 1154 |
+
|
| 1155 |
+
Parameters
|
| 1156 |
+
----------
|
| 1157 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1158 |
+
Mask of the quadratic models to consider.
|
| 1159 |
+
|
| 1160 |
+
Returns
|
| 1161 |
+
-------
|
| 1162 |
+
`numpy.ndarray`
|
| 1163 |
+
Hessian matrices of the quadratic models of the nonlinear equality
|
| 1164 |
+
functions.
|
| 1165 |
+
"""
|
| 1166 |
+
if self._debug:
|
| 1167 |
+
assert mask is None or mask.shape == (
|
| 1168 |
+
self.m_nonlinear_eq,
|
| 1169 |
+
), "The shape of `mask` is not valid."
|
| 1170 |
+
return np.reshape(
|
| 1171 |
+
[model.hess(self.interpolation) for model in self._get_ceq(mask)],
|
| 1172 |
+
(-1, self.n, self.n),
|
| 1173 |
+
)
|
| 1174 |
+
|
| 1175 |
+
def ceq_hess_prod(self, v, mask=None):
|
| 1176 |
+
"""
|
| 1177 |
+
Evaluate the right product of the Hessian matrices of the quadratic
|
| 1178 |
+
models of the nonlinear equality functions with a given vector.
|
| 1179 |
+
|
| 1180 |
+
Parameters
|
| 1181 |
+
----------
|
| 1182 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1183 |
+
Vector with which the Hessian matrices of the quadratic models of
|
| 1184 |
+
the nonlinear equality functions are multiplied from the right.
|
| 1185 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1186 |
+
Mask of the quadratic models to consider.
|
| 1187 |
+
|
| 1188 |
+
Returns
|
| 1189 |
+
-------
|
| 1190 |
+
`numpy.ndarray`
|
| 1191 |
+
Right products of the Hessian matrices of the quadratic models of
|
| 1192 |
+
the nonlinear equality functions with `v`.
|
| 1193 |
+
"""
|
| 1194 |
+
if self._debug:
|
| 1195 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1196 |
+
assert mask is None or mask.shape == (
|
| 1197 |
+
self.m_nonlinear_eq,
|
| 1198 |
+
), "The shape of `mask` is not valid."
|
| 1199 |
+
return np.reshape(
|
| 1200 |
+
[
|
| 1201 |
+
model.hess_prod(v, self.interpolation)
|
| 1202 |
+
for model in self._get_ceq(mask)
|
| 1203 |
+
],
|
| 1204 |
+
(-1, self.n),
|
| 1205 |
+
)
|
| 1206 |
+
|
| 1207 |
+
def ceq_curv(self, v, mask=None):
|
| 1208 |
+
"""
|
| 1209 |
+
Evaluate the curvature of the quadratic models of the nonlinear
|
| 1210 |
+
equality functions along a given direction.
|
| 1211 |
+
|
| 1212 |
+
Parameters
|
| 1213 |
+
----------
|
| 1214 |
+
v : `numpy.ndarray`, shape (n,)
|
| 1215 |
+
Direction along which the curvature of the quadratic models of the
|
| 1216 |
+
nonlinear equality functions is evaluated.
|
| 1217 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1218 |
+
Mask of the quadratic models to consider.
|
| 1219 |
+
|
| 1220 |
+
Returns
|
| 1221 |
+
-------
|
| 1222 |
+
`numpy.ndarray`
|
| 1223 |
+
Curvature of the quadratic models of the nonlinear equality
|
| 1224 |
+
functions along `v`.
|
| 1225 |
+
"""
|
| 1226 |
+
if self._debug:
|
| 1227 |
+
assert v.shape == (self.n,), "The shape of `v` is not valid."
|
| 1228 |
+
assert mask is None or mask.shape == (
|
| 1229 |
+
self.m_nonlinear_eq,
|
| 1230 |
+
), "The shape of `mask` is not valid."
|
| 1231 |
+
return np.array(
|
| 1232 |
+
[model.curv(v, self.interpolation)
|
| 1233 |
+
for model in self._get_ceq(mask)]
|
| 1234 |
+
)
|
| 1235 |
+
|
| 1236 |
+
def reset_models(self):
|
| 1237 |
+
"""
|
| 1238 |
+
Set the quadratic models of the objective function, nonlinear
|
| 1239 |
+
inequality constraints, and nonlinear equality constraints to the
|
| 1240 |
+
alternative quadratic models.
|
| 1241 |
+
|
| 1242 |
+
Raises
|
| 1243 |
+
------
|
| 1244 |
+
`numpy.linalg.LinAlgError`
|
| 1245 |
+
If the interpolation system is ill-defined.
|
| 1246 |
+
"""
|
| 1247 |
+
self._fun = Quadratic(self.interpolation, self.fun_val, self._debug)
|
| 1248 |
+
for i in range(self.m_nonlinear_ub):
|
| 1249 |
+
self._cub[i] = Quadratic(
|
| 1250 |
+
self.interpolation,
|
| 1251 |
+
self.cub_val[:, i],
|
| 1252 |
+
self._debug,
|
| 1253 |
+
)
|
| 1254 |
+
for i in range(self.m_nonlinear_eq):
|
| 1255 |
+
self._ceq[i] = Quadratic(
|
| 1256 |
+
self.interpolation,
|
| 1257 |
+
self.ceq_val[:, i],
|
| 1258 |
+
self._debug,
|
| 1259 |
+
)
|
| 1260 |
+
if self._debug:
|
| 1261 |
+
self._check_interpolation_conditions()
|
| 1262 |
+
|
| 1263 |
+
def update_interpolation(self, k_new, x_new, fun_val, cub_val, ceq_val):
|
| 1264 |
+
"""
|
| 1265 |
+
Update the interpolation set.
|
| 1266 |
+
|
| 1267 |
+
This method updates the interpolation set by replacing the `knew`-th
|
| 1268 |
+
interpolation point with `xnew`. It also updates the function values
|
| 1269 |
+
and the quadratic models.
|
| 1270 |
+
|
| 1271 |
+
Parameters
|
| 1272 |
+
----------
|
| 1273 |
+
k_new : int
|
| 1274 |
+
Index of the updated interpolation point.
|
| 1275 |
+
x_new : `numpy.ndarray`, shape (n,)
|
| 1276 |
+
New interpolation point. Its value is interpreted as relative to
|
| 1277 |
+
the origin, not the base point.
|
| 1278 |
+
fun_val : float
|
| 1279 |
+
Value of the objective function at `x_new`.
|
| 1280 |
+
Objective function value at `x_new`.
|
| 1281 |
+
cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
|
| 1282 |
+
Values of the nonlinear inequality constraints at `x_new`.
|
| 1283 |
+
ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
|
| 1284 |
+
Values of the nonlinear equality constraints at `x_new`.
|
| 1285 |
+
|
| 1286 |
+
Raises
|
| 1287 |
+
------
|
| 1288 |
+
`numpy.linalg.LinAlgError`
|
| 1289 |
+
If the interpolation system is ill-defined.
|
| 1290 |
+
"""
|
| 1291 |
+
if self._debug:
|
| 1292 |
+
assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
|
| 1293 |
+
assert x_new.shape == (self.n,), \
|
| 1294 |
+
"The shape of `x_new` is not valid."
|
| 1295 |
+
assert isinstance(fun_val, float), \
|
| 1296 |
+
"The function value is not valid."
|
| 1297 |
+
assert cub_val.shape == (
|
| 1298 |
+
self.m_nonlinear_ub,
|
| 1299 |
+
), "The shape of `cub_val` is not valid."
|
| 1300 |
+
assert ceq_val.shape == (
|
| 1301 |
+
self.m_nonlinear_eq,
|
| 1302 |
+
), "The shape of `ceq_val` is not valid."
|
| 1303 |
+
|
| 1304 |
+
# Compute the updates in the interpolation conditions.
|
| 1305 |
+
fun_diff = np.zeros(self.npt)
|
| 1306 |
+
cub_diff = np.zeros(self.cub_val.shape)
|
| 1307 |
+
ceq_diff = np.zeros(self.ceq_val.shape)
|
| 1308 |
+
fun_diff[k_new] = fun_val - self.fun(x_new)
|
| 1309 |
+
cub_diff[k_new, :] = cub_val - self.cub(x_new)
|
| 1310 |
+
ceq_diff[k_new, :] = ceq_val - self.ceq(x_new)
|
| 1311 |
+
|
| 1312 |
+
# Update the function values.
|
| 1313 |
+
self.fun_val[k_new] = fun_val
|
| 1314 |
+
self.cub_val[k_new, :] = cub_val
|
| 1315 |
+
self.ceq_val[k_new, :] = ceq_val
|
| 1316 |
+
|
| 1317 |
+
# Update the interpolation set.
|
| 1318 |
+
dir_old = np.copy(self.interpolation.xpt[:, k_new])
|
| 1319 |
+
self.interpolation.xpt[:, k_new] = x_new - self.interpolation.x_base
|
| 1320 |
+
|
| 1321 |
+
# Update the quadratic models.
|
| 1322 |
+
ill_conditioned = self._fun.update(
|
| 1323 |
+
self.interpolation,
|
| 1324 |
+
k_new,
|
| 1325 |
+
dir_old,
|
| 1326 |
+
fun_diff,
|
| 1327 |
+
)
|
| 1328 |
+
for i in range(self.m_nonlinear_ub):
|
| 1329 |
+
ill_conditioned = ill_conditioned or self._cub[i].update(
|
| 1330 |
+
self.interpolation,
|
| 1331 |
+
k_new,
|
| 1332 |
+
dir_old,
|
| 1333 |
+
cub_diff[:, i],
|
| 1334 |
+
)
|
| 1335 |
+
for i in range(self.m_nonlinear_eq):
|
| 1336 |
+
ill_conditioned = ill_conditioned or self._ceq[i].update(
|
| 1337 |
+
self.interpolation,
|
| 1338 |
+
k_new,
|
| 1339 |
+
dir_old,
|
| 1340 |
+
ceq_diff[:, i],
|
| 1341 |
+
)
|
| 1342 |
+
if self._debug:
|
| 1343 |
+
self._check_interpolation_conditions()
|
| 1344 |
+
return ill_conditioned
|
| 1345 |
+
|
| 1346 |
+
def determinants(self, x_new, k_new=None):
|
| 1347 |
+
"""
|
| 1348 |
+
Compute the normalized determinants of the new interpolation systems.
|
| 1349 |
+
|
| 1350 |
+
Parameters
|
| 1351 |
+
----------
|
| 1352 |
+
x_new : `numpy.ndarray`, shape (n,)
|
| 1353 |
+
New interpolation point. Its value is interpreted as relative to
|
| 1354 |
+
the origin, not the base point.
|
| 1355 |
+
k_new : int, optional
|
| 1356 |
+
Index of the updated interpolation point. If `k_new` is not
|
| 1357 |
+
specified, all the possible determinants are computed.
|
| 1358 |
+
|
| 1359 |
+
Returns
|
| 1360 |
+
-------
|
| 1361 |
+
{float, `numpy.ndarray`, shape (npt,)}
|
| 1362 |
+
Determinant(s) of the new interpolation system.
|
| 1363 |
+
|
| 1364 |
+
Raises
|
| 1365 |
+
------
|
| 1366 |
+
`numpy.linalg.LinAlgError`
|
| 1367 |
+
If the interpolation system is ill-defined.
|
| 1368 |
+
|
| 1369 |
+
Notes
|
| 1370 |
+
-----
|
| 1371 |
+
The determinants are normalized by the determinant of the current
|
| 1372 |
+
interpolation system. For stability reasons, the calculations are done
|
| 1373 |
+
using the formula (2.12) in [1]_.
|
| 1374 |
+
|
| 1375 |
+
References
|
| 1376 |
+
----------
|
| 1377 |
+
.. [1] M. J. D. Powell. On updating the inverse of a KKT matrix.
|
| 1378 |
+
Technical Report DAMTP 2004/NA01, Department of Applied Mathematics
|
| 1379 |
+
and Theoretical Physics, University of Cambridge, Cambridge, UK,
|
| 1380 |
+
2004.
|
| 1381 |
+
"""
|
| 1382 |
+
if self._debug:
|
| 1383 |
+
assert x_new.shape == (self.n,), \
|
| 1384 |
+
"The shape of `x_new` is not valid."
|
| 1385 |
+
assert (
|
| 1386 |
+
k_new is None or 0 <= k_new < self.npt
|
| 1387 |
+
), "The index `k_new` is not valid."
|
| 1388 |
+
|
| 1389 |
+
# Compute the values independent of k_new.
|
| 1390 |
+
shift = x_new - self.interpolation.x_base
|
| 1391 |
+
new_col = np.empty((self.npt + self.n + 1, 1))
|
| 1392 |
+
new_col[: self.npt, 0] = (
|
| 1393 |
+
0.5 * (self.interpolation.xpt.T @ shift) ** 2.0)
|
| 1394 |
+
new_col[self.npt, 0] = 1.0
|
| 1395 |
+
new_col[self.npt + 1:, 0] = shift
|
| 1396 |
+
inv_new_col = Quadratic.solve_systems(self.interpolation, new_col)[0]
|
| 1397 |
+
beta = 0.5 * (shift @ shift) ** 2.0 - new_col[:, 0] @ inv_new_col[:, 0]
|
| 1398 |
+
|
| 1399 |
+
# Compute the values that depend on k.
|
| 1400 |
+
if k_new is None:
|
| 1401 |
+
coord_vec = np.eye(self.npt + self.n + 1, self.npt)
|
| 1402 |
+
alpha = np.diag(
|
| 1403 |
+
Quadratic.solve_systems(
|
| 1404 |
+
self.interpolation,
|
| 1405 |
+
coord_vec,
|
| 1406 |
+
)[0]
|
| 1407 |
+
)
|
| 1408 |
+
tau = inv_new_col[: self.npt, 0]
|
| 1409 |
+
else:
|
| 1410 |
+
coord_vec = np.eye(self.npt + self.n + 1, 1, -k_new)
|
| 1411 |
+
alpha = Quadratic.solve_systems(
|
| 1412 |
+
self.interpolation,
|
| 1413 |
+
coord_vec,
|
| 1414 |
+
)[
|
| 1415 |
+
0
|
| 1416 |
+
][k_new, 0]
|
| 1417 |
+
tau = inv_new_col[k_new, 0]
|
| 1418 |
+
return alpha * beta + tau**2.0
|
| 1419 |
+
|
| 1420 |
+
def shift_x_base(self, new_x_base, options):
|
| 1421 |
+
"""
|
| 1422 |
+
Shift the base point without changing the interpolation set.
|
| 1423 |
+
|
| 1424 |
+
Parameters
|
| 1425 |
+
----------
|
| 1426 |
+
new_x_base : `numpy.ndarray`, shape (n,)
|
| 1427 |
+
New base point.
|
| 1428 |
+
options : dict
|
| 1429 |
+
Options of the solver.
|
| 1430 |
+
"""
|
| 1431 |
+
if self._debug:
|
| 1432 |
+
assert new_x_base.shape == (
|
| 1433 |
+
self.n,
|
| 1434 |
+
), "The shape of `new_x_base` is not valid."
|
| 1435 |
+
|
| 1436 |
+
# Update the models.
|
| 1437 |
+
self._fun.shift_x_base(self.interpolation, new_x_base)
|
| 1438 |
+
for model in self._cub:
|
| 1439 |
+
model.shift_x_base(self.interpolation, new_x_base)
|
| 1440 |
+
for model in self._ceq:
|
| 1441 |
+
model.shift_x_base(self.interpolation, new_x_base)
|
| 1442 |
+
|
| 1443 |
+
# Update the base point and the interpolation points.
|
| 1444 |
+
shift = new_x_base - self.interpolation.x_base
|
| 1445 |
+
self.interpolation.x_base += shift
|
| 1446 |
+
self.interpolation.xpt -= shift[:, np.newaxis]
|
| 1447 |
+
if options[Options.DEBUG]:
|
| 1448 |
+
self._check_interpolation_conditions()
|
| 1449 |
+
|
| 1450 |
+
def _get_cub(self, mask=None):
|
| 1451 |
+
"""
|
| 1452 |
+
Get the quadratic models of the nonlinear inequality constraints.
|
| 1453 |
+
|
| 1454 |
+
Parameters
|
| 1455 |
+
----------
|
| 1456 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
|
| 1457 |
+
Mask of the quadratic models to return.
|
| 1458 |
+
|
| 1459 |
+
Returns
|
| 1460 |
+
-------
|
| 1461 |
+
`numpy.ndarray`
|
| 1462 |
+
Quadratic models of the nonlinear inequality constraints.
|
| 1463 |
+
"""
|
| 1464 |
+
return self._cub if mask is None else self._cub[mask]
|
| 1465 |
+
|
| 1466 |
+
def _get_ceq(self, mask=None):
|
| 1467 |
+
"""
|
| 1468 |
+
Get the quadratic models of the nonlinear equality constraints.
|
| 1469 |
+
|
| 1470 |
+
Parameters
|
| 1471 |
+
----------
|
| 1472 |
+
mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
|
| 1473 |
+
Mask of the quadratic models to return.
|
| 1474 |
+
|
| 1475 |
+
Returns
|
| 1476 |
+
-------
|
| 1477 |
+
`numpy.ndarray`
|
| 1478 |
+
Quadratic models of the nonlinear equality constraints.
|
| 1479 |
+
"""
|
| 1480 |
+
return self._ceq if mask is None else self._ceq[mask]
|
| 1481 |
+
|
| 1482 |
+
def _check_interpolation_conditions(self):
|
| 1483 |
+
"""
|
| 1484 |
+
Check the interpolation conditions of all quadratic models.
|
| 1485 |
+
"""
|
| 1486 |
+
error_fun = 0.0
|
| 1487 |
+
error_cub = 0.0
|
| 1488 |
+
error_ceq = 0.0
|
| 1489 |
+
for k in range(self.npt):
|
| 1490 |
+
error_fun = np.max(
|
| 1491 |
+
[
|
| 1492 |
+
error_fun,
|
| 1493 |
+
np.abs(
|
| 1494 |
+
self.fun(self.interpolation.point(k)) - self.fun_val[k]
|
| 1495 |
+
),
|
| 1496 |
+
]
|
| 1497 |
+
)
|
| 1498 |
+
error_cub = np.max(
|
| 1499 |
+
np.abs(
|
| 1500 |
+
self.cub(self.interpolation.point(k)) - self.cub_val[k, :]
|
| 1501 |
+
),
|
| 1502 |
+
initial=error_cub,
|
| 1503 |
+
)
|
| 1504 |
+
error_ceq = np.max(
|
| 1505 |
+
np.abs(
|
| 1506 |
+
self.ceq(self.interpolation.point(k)) - self.ceq_val[k, :]
|
| 1507 |
+
),
|
| 1508 |
+
initial=error_ceq,
|
| 1509 |
+
)
|
| 1510 |
+
tol = 10.0 * np.sqrt(EPS) * max(self.n, self.npt)
|
| 1511 |
+
if error_fun > tol * np.max(np.abs(self.fun_val), initial=1.0):
|
| 1512 |
+
warnings.warn(
|
| 1513 |
+
"The interpolation conditions for the objective function are "
|
| 1514 |
+
"not satisfied.",
|
| 1515 |
+
RuntimeWarning,
|
| 1516 |
+
2,
|
| 1517 |
+
)
|
| 1518 |
+
if error_cub > tol * np.max(np.abs(self.cub_val), initial=1.0):
|
| 1519 |
+
warnings.warn(
|
| 1520 |
+
"The interpolation conditions for the inequality constraint "
|
| 1521 |
+
"function are not satisfied.",
|
| 1522 |
+
RuntimeWarning,
|
| 1523 |
+
2,
|
| 1524 |
+
)
|
| 1525 |
+
if error_ceq > tol * np.max(np.abs(self.ceq_val), initial=1.0):
|
| 1526 |
+
warnings.warn(
|
| 1527 |
+
"The interpolation conditions for the equality constraint "
|
| 1528 |
+
"function are not satisfied.",
|
| 1529 |
+
RuntimeWarning,
|
| 1530 |
+
2,
|
| 1531 |
+
)
|
physworld_p1_20261018/envs/p1/lib/python3.11/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 |
+
)
|
physworld_p1_20261018/envs/p1/lib/python3.11/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 |
+
)
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .geometry import cauchy_geometry, spider_geometry
|
| 2 |
+
from .optim import (
|
| 3 |
+
tangential_byrd_omojokun,
|
| 4 |
+
constrained_tangential_byrd_omojokun,
|
| 5 |
+
normal_byrd_omojokun,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"cauchy_geometry",
|
| 10 |
+
"spider_geometry",
|
| 11 |
+
"tangential_byrd_omojokun",
|
| 12 |
+
"constrained_tangential_byrd_omojokun",
|
| 13 |
+
"normal_byrd_omojokun",
|
| 14 |
+
]
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (601 Bytes). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-311.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-311.pyc
ADDED
|
Binary file (47.4 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from ..utils import get_arrays_tol
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
TINY = np.finfo(float).tiny
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def cauchy_geometry(const, grad, curv, xl, xu, delta, debug):
|
| 12 |
+
r"""
|
| 13 |
+
Maximize approximately the absolute value of a quadratic function subject
|
| 14 |
+
to bound constraints in a trust region.
|
| 15 |
+
|
| 16 |
+
This function solves approximately
|
| 17 |
+
|
| 18 |
+
.. math::
|
| 19 |
+
|
| 20 |
+
\max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s +
|
| 21 |
+
\frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad
|
| 22 |
+
\left\{ \begin{array}{l}
|
| 23 |
+
l \le s \le u,\\
|
| 24 |
+
\lVert s \rVert \le \Delta,
|
| 25 |
+
\end{array} \right.
|
| 26 |
+
|
| 27 |
+
by maximizing the objective function along the constrained Cauchy
|
| 28 |
+
direction.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
----------
|
| 32 |
+
const : float
|
| 33 |
+
Constant :math:`c` as shown above.
|
| 34 |
+
grad : `numpy.ndarray`, shape (n,)
|
| 35 |
+
Gradient :math:`g` as shown above.
|
| 36 |
+
curv : callable
|
| 37 |
+
Curvature of :math:`H` along any vector.
|
| 38 |
+
|
| 39 |
+
``curv(s) -> float``
|
| 40 |
+
|
| 41 |
+
returns :math:`s^{\mathsf{T}} H s`.
|
| 42 |
+
xl : `numpy.ndarray`, shape (n,)
|
| 43 |
+
Lower bounds :math:`l` as shown above.
|
| 44 |
+
xu : `numpy.ndarray`, shape (n,)
|
| 45 |
+
Upper bounds :math:`u` as shown above.
|
| 46 |
+
delta : float
|
| 47 |
+
Trust-region radius :math:`\Delta` as shown above.
|
| 48 |
+
debug : bool
|
| 49 |
+
Whether to make debugging tests during the execution.
|
| 50 |
+
|
| 51 |
+
Returns
|
| 52 |
+
-------
|
| 53 |
+
`numpy.ndarray`, shape (n,)
|
| 54 |
+
Approximate solution :math:`s`.
|
| 55 |
+
|
| 56 |
+
Notes
|
| 57 |
+
-----
|
| 58 |
+
This function is described as the first alternative in Section 6.5 of [1]_.
|
| 59 |
+
It is assumed that the origin is feasible with respect to the bound
|
| 60 |
+
constraints and that `delta` is finite and positive.
|
| 61 |
+
|
| 62 |
+
References
|
| 63 |
+
----------
|
| 64 |
+
.. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
|
| 65 |
+
and Software*. PhD thesis, Department of Applied Mathematics, The Hong
|
| 66 |
+
Kong Polytechnic University, Hong Kong, China, 2022. URL:
|
| 67 |
+
https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 68 |
+
"""
|
| 69 |
+
if debug:
|
| 70 |
+
assert isinstance(const, float)
|
| 71 |
+
assert isinstance(grad, np.ndarray) and grad.ndim == 1
|
| 72 |
+
assert inspect.signature(curv).bind(grad)
|
| 73 |
+
assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
|
| 74 |
+
assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
|
| 75 |
+
assert isinstance(delta, float)
|
| 76 |
+
assert isinstance(debug, bool)
|
| 77 |
+
tol = get_arrays_tol(xl, xu)
|
| 78 |
+
assert np.all(xl <= tol)
|
| 79 |
+
assert np.all(xu >= -tol)
|
| 80 |
+
assert np.isfinite(delta) and delta > 0.0
|
| 81 |
+
xl = np.minimum(xl, 0.0)
|
| 82 |
+
xu = np.maximum(xu, 0.0)
|
| 83 |
+
|
| 84 |
+
# To maximize the absolute value of a quadratic function, we maximize the
|
| 85 |
+
# function itself or its negative, and we choose the solution that provides
|
| 86 |
+
# the largest function value.
|
| 87 |
+
step1, q_val1 = _cauchy_geom(const, grad, curv, xl, xu, delta, debug)
|
| 88 |
+
step2, q_val2 = _cauchy_geom(
|
| 89 |
+
-const,
|
| 90 |
+
-grad,
|
| 91 |
+
lambda x: -curv(x),
|
| 92 |
+
xl,
|
| 93 |
+
xu,
|
| 94 |
+
delta,
|
| 95 |
+
debug,
|
| 96 |
+
)
|
| 97 |
+
step = step1 if abs(q_val1) >= abs(q_val2) else step2
|
| 98 |
+
|
| 99 |
+
if debug:
|
| 100 |
+
assert np.all(xl <= step)
|
| 101 |
+
assert np.all(step <= xu)
|
| 102 |
+
assert np.linalg.norm(step) < 1.1 * delta
|
| 103 |
+
return step
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def spider_geometry(const, grad, curv, xpt, xl, xu, delta, debug):
|
| 107 |
+
r"""
|
| 108 |
+
Maximize approximately the absolute value of a quadratic function subject
|
| 109 |
+
to bound constraints in a trust region.
|
| 110 |
+
|
| 111 |
+
This function solves approximately
|
| 112 |
+
|
| 113 |
+
.. math::
|
| 114 |
+
|
| 115 |
+
\max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s +
|
| 116 |
+
\frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad
|
| 117 |
+
\left\{ \begin{array}{l}
|
| 118 |
+
l \le s \le u,\\
|
| 119 |
+
\lVert s \rVert \le \Delta,
|
| 120 |
+
\end{array} \right.
|
| 121 |
+
|
| 122 |
+
by maximizing the objective function along given straight lines.
|
| 123 |
+
|
| 124 |
+
Parameters
|
| 125 |
+
----------
|
| 126 |
+
const : float
|
| 127 |
+
Constant :math:`c` as shown above.
|
| 128 |
+
grad : `numpy.ndarray`, shape (n,)
|
| 129 |
+
Gradient :math:`g` as shown above.
|
| 130 |
+
curv : callable
|
| 131 |
+
Curvature of :math:`H` along any vector.
|
| 132 |
+
|
| 133 |
+
``curv(s) -> float``
|
| 134 |
+
|
| 135 |
+
returns :math:`s^{\mathsf{T}} H s`.
|
| 136 |
+
xpt : `numpy.ndarray`, shape (n, npt)
|
| 137 |
+
Points defining the straight lines. The straight lines considered are
|
| 138 |
+
the ones passing through the origin and the points in `xpt`.
|
| 139 |
+
xl : `numpy.ndarray`, shape (n,)
|
| 140 |
+
Lower bounds :math:`l` as shown above.
|
| 141 |
+
xu : `numpy.ndarray`, shape (n,)
|
| 142 |
+
Upper bounds :math:`u` as shown above.
|
| 143 |
+
delta : float
|
| 144 |
+
Trust-region radius :math:`\Delta` as shown above.
|
| 145 |
+
debug : bool
|
| 146 |
+
Whether to make debugging tests during the execution.
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
`numpy.ndarray`, shape (n,)
|
| 151 |
+
Approximate solution :math:`s`.
|
| 152 |
+
|
| 153 |
+
Notes
|
| 154 |
+
-----
|
| 155 |
+
This function is described as the second alternative in Section 6.5 of
|
| 156 |
+
[1]_. It is assumed that the origin is feasible with respect to the bound
|
| 157 |
+
constraints and that `delta` is finite and positive.
|
| 158 |
+
|
| 159 |
+
References
|
| 160 |
+
----------
|
| 161 |
+
.. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
|
| 162 |
+
and Software*. PhD thesis, Department of Applied Mathematics, The Hong
|
| 163 |
+
Kong Polytechnic University, Hong Kong, China, 2022. URL:
|
| 164 |
+
https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 165 |
+
"""
|
| 166 |
+
if debug:
|
| 167 |
+
assert isinstance(const, float)
|
| 168 |
+
assert isinstance(grad, np.ndarray) and grad.ndim == 1
|
| 169 |
+
assert inspect.signature(curv).bind(grad)
|
| 170 |
+
assert (
|
| 171 |
+
isinstance(xpt, np.ndarray)
|
| 172 |
+
and xpt.ndim == 2
|
| 173 |
+
and xpt.shape[0] == grad.size
|
| 174 |
+
)
|
| 175 |
+
assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
|
| 176 |
+
assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
|
| 177 |
+
assert isinstance(delta, float)
|
| 178 |
+
assert isinstance(debug, bool)
|
| 179 |
+
tol = get_arrays_tol(xl, xu)
|
| 180 |
+
assert np.all(xl <= tol)
|
| 181 |
+
assert np.all(xu >= -tol)
|
| 182 |
+
assert np.isfinite(delta) and delta > 0.0
|
| 183 |
+
xl = np.minimum(xl, 0.0)
|
| 184 |
+
xu = np.maximum(xu, 0.0)
|
| 185 |
+
|
| 186 |
+
# Iterate through the straight lines.
|
| 187 |
+
step = np.zeros_like(grad)
|
| 188 |
+
q_val = const
|
| 189 |
+
s_norm = np.linalg.norm(xpt, axis=0)
|
| 190 |
+
|
| 191 |
+
# Set alpha_xl to the step size for the lower-bound constraint and
|
| 192 |
+
# alpha_xu to the step size for the upper-bound constraint.
|
| 193 |
+
|
| 194 |
+
# xl.shape = (N,)
|
| 195 |
+
# xpt.shape = (N, M)
|
| 196 |
+
# i_xl_pos.shape = (M, N)
|
| 197 |
+
i_xl_pos = (xl > -np.inf) & (xpt.T > -TINY * xl)
|
| 198 |
+
i_xl_neg = (xl > -np.inf) & (xpt.T < TINY * xl)
|
| 199 |
+
i_xu_pos = (xu < np.inf) & (xpt.T > TINY * xu)
|
| 200 |
+
i_xu_neg = (xu < np.inf) & (xpt.T < -TINY * xu)
|
| 201 |
+
|
| 202 |
+
# (M, N)
|
| 203 |
+
alpha_xl_pos = np.atleast_2d(
|
| 204 |
+
np.broadcast_to(xl, i_xl_pos.shape)[i_xl_pos] / xpt.T[i_xl_pos]
|
| 205 |
+
)
|
| 206 |
+
# (M,)
|
| 207 |
+
alpha_xl_pos = np.max(alpha_xl_pos, axis=1, initial=-np.inf)
|
| 208 |
+
# make sure it's (M,)
|
| 209 |
+
alpha_xl_pos = np.broadcast_to(np.atleast_1d(alpha_xl_pos), xpt.shape[1])
|
| 210 |
+
|
| 211 |
+
alpha_xl_neg = np.atleast_2d(
|
| 212 |
+
np.broadcast_to(xl, i_xl_neg.shape)[i_xl_neg] / xpt.T[i_xl_neg]
|
| 213 |
+
)
|
| 214 |
+
alpha_xl_neg = np.max(alpha_xl_neg, axis=1, initial=np.inf)
|
| 215 |
+
alpha_xl_neg = np.broadcast_to(np.atleast_1d(alpha_xl_neg), xpt.shape[1])
|
| 216 |
+
|
| 217 |
+
alpha_xu_neg = np.atleast_2d(
|
| 218 |
+
np.broadcast_to(xu, i_xu_neg.shape)[i_xu_neg] / xpt.T[i_xu_neg]
|
| 219 |
+
)
|
| 220 |
+
alpha_xu_neg = np.max(alpha_xu_neg, axis=1, initial=-np.inf)
|
| 221 |
+
alpha_xu_neg = np.broadcast_to(np.atleast_1d(alpha_xu_neg), xpt.shape[1])
|
| 222 |
+
|
| 223 |
+
alpha_xu_pos = np.atleast_2d(
|
| 224 |
+
np.broadcast_to(xu, i_xu_pos.shape)[i_xu_pos] / xpt.T[i_xu_pos]
|
| 225 |
+
)
|
| 226 |
+
alpha_xu_pos = np.max(alpha_xu_pos, axis=1, initial=np.inf)
|
| 227 |
+
alpha_xu_pos = np.broadcast_to(np.atleast_1d(alpha_xu_pos), xpt.shape[1])
|
| 228 |
+
|
| 229 |
+
for k in range(xpt.shape[1]):
|
| 230 |
+
# Set alpha_tr to the step size for the trust-region constraint.
|
| 231 |
+
if s_norm[k] > TINY * delta:
|
| 232 |
+
alpha_tr = max(delta / s_norm[k], 0.0)
|
| 233 |
+
else:
|
| 234 |
+
# The current straight line is basically zero.
|
| 235 |
+
continue
|
| 236 |
+
|
| 237 |
+
alpha_bd_pos = max(min(alpha_xu_pos[k], alpha_xl_neg[k]), 0.0)
|
| 238 |
+
alpha_bd_neg = min(max(alpha_xl_pos[k], alpha_xu_neg[k]), 0.0)
|
| 239 |
+
|
| 240 |
+
# Set alpha_quad_pos and alpha_quad_neg to the step size to the extrema
|
| 241 |
+
# of the quadratic function along the positive and negative directions.
|
| 242 |
+
grad_step = grad @ xpt[:, k]
|
| 243 |
+
curv_step = curv(xpt[:, k])
|
| 244 |
+
if (
|
| 245 |
+
grad_step >= 0.0
|
| 246 |
+
and curv_step < -TINY * grad_step
|
| 247 |
+
or grad_step <= 0.0
|
| 248 |
+
and curv_step > -TINY * grad_step
|
| 249 |
+
):
|
| 250 |
+
alpha_quad_pos = max(-grad_step / curv_step, 0.0)
|
| 251 |
+
else:
|
| 252 |
+
alpha_quad_pos = np.inf
|
| 253 |
+
if (
|
| 254 |
+
grad_step >= 0.0
|
| 255 |
+
and curv_step > TINY * grad_step
|
| 256 |
+
or grad_step <= 0.0
|
| 257 |
+
and curv_step < TINY * grad_step
|
| 258 |
+
):
|
| 259 |
+
alpha_quad_neg = min(-grad_step / curv_step, 0.0)
|
| 260 |
+
else:
|
| 261 |
+
alpha_quad_neg = -np.inf
|
| 262 |
+
|
| 263 |
+
# Select the step that provides the largest value of the objective
|
| 264 |
+
# function if it improves the current best. The best positive step is
|
| 265 |
+
# either the one that reaches the constraints or the one that reaches
|
| 266 |
+
# the extremum of the objective function along the current direction
|
| 267 |
+
# (only possible if the resulting step is feasible). We test both, and
|
| 268 |
+
# we perform similar calculations along the negative step.
|
| 269 |
+
# N.B.: we select the largest possible step among all the ones that
|
| 270 |
+
# maximize the objective function. This is to avoid returning the zero
|
| 271 |
+
# step in some extreme cases.
|
| 272 |
+
alpha_pos = min(alpha_tr, alpha_bd_pos)
|
| 273 |
+
alpha_neg = max(-alpha_tr, alpha_bd_neg)
|
| 274 |
+
q_val_pos = (
|
| 275 |
+
const + alpha_pos * grad_step + 0.5 * alpha_pos**2.0 * curv_step
|
| 276 |
+
)
|
| 277 |
+
q_val_neg = (
|
| 278 |
+
const + alpha_neg * grad_step + 0.5 * alpha_neg**2.0 * curv_step
|
| 279 |
+
)
|
| 280 |
+
if alpha_quad_pos < alpha_pos:
|
| 281 |
+
q_val_quad_pos = (
|
| 282 |
+
const
|
| 283 |
+
+ alpha_quad_pos * grad_step
|
| 284 |
+
+ 0.5 * alpha_quad_pos**2.0 * curv_step
|
| 285 |
+
)
|
| 286 |
+
if abs(q_val_quad_pos) > abs(q_val_pos):
|
| 287 |
+
alpha_pos = alpha_quad_pos
|
| 288 |
+
q_val_pos = q_val_quad_pos
|
| 289 |
+
if alpha_quad_neg > alpha_neg:
|
| 290 |
+
q_val_quad_neg = (
|
| 291 |
+
const
|
| 292 |
+
+ alpha_quad_neg * grad_step
|
| 293 |
+
+ 0.5 * alpha_quad_neg**2.0 * curv_step
|
| 294 |
+
)
|
| 295 |
+
if abs(q_val_quad_neg) > abs(q_val_neg):
|
| 296 |
+
alpha_neg = alpha_quad_neg
|
| 297 |
+
q_val_neg = q_val_quad_neg
|
| 298 |
+
if abs(q_val_pos) >= abs(q_val_neg) and abs(q_val_pos) > abs(q_val):
|
| 299 |
+
step = np.clip(alpha_pos * xpt[:, k], xl, xu)
|
| 300 |
+
q_val = q_val_pos
|
| 301 |
+
elif abs(q_val_neg) > abs(q_val_pos) and abs(q_val_neg) > abs(q_val):
|
| 302 |
+
step = np.clip(alpha_neg * xpt[:, k], xl, xu)
|
| 303 |
+
q_val = q_val_neg
|
| 304 |
+
|
| 305 |
+
if debug:
|
| 306 |
+
assert np.all(xl <= step)
|
| 307 |
+
assert np.all(step <= xu)
|
| 308 |
+
assert np.linalg.norm(step) < 1.1 * delta
|
| 309 |
+
return step
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _cauchy_geom(const, grad, curv, xl, xu, delta, debug):
|
| 313 |
+
"""
|
| 314 |
+
Same as `bound_constrained_cauchy_step` without the absolute value.
|
| 315 |
+
"""
|
| 316 |
+
# Calculate the initial active set.
|
| 317 |
+
fixed_xl = (xl < 0.0) & (grad > 0.0)
|
| 318 |
+
fixed_xu = (xu > 0.0) & (grad < 0.0)
|
| 319 |
+
|
| 320 |
+
# Calculate the Cauchy step.
|
| 321 |
+
cauchy_step = np.zeros_like(grad)
|
| 322 |
+
cauchy_step[fixed_xl] = xl[fixed_xl]
|
| 323 |
+
cauchy_step[fixed_xu] = xu[fixed_xu]
|
| 324 |
+
if np.linalg.norm(cauchy_step) > delta:
|
| 325 |
+
working = fixed_xl | fixed_xu
|
| 326 |
+
while True:
|
| 327 |
+
# Calculate the Cauchy step for the directions in the working set.
|
| 328 |
+
g_norm = np.linalg.norm(grad[working])
|
| 329 |
+
delta_reduced = np.sqrt(
|
| 330 |
+
delta**2.0 - cauchy_step[~working] @ cauchy_step[~working]
|
| 331 |
+
)
|
| 332 |
+
if g_norm > TINY * abs(delta_reduced):
|
| 333 |
+
mu = max(delta_reduced / g_norm, 0.0)
|
| 334 |
+
else:
|
| 335 |
+
break
|
| 336 |
+
cauchy_step[working] = mu * grad[working]
|
| 337 |
+
|
| 338 |
+
# Update the working set.
|
| 339 |
+
fixed_xl = working & (cauchy_step < xl)
|
| 340 |
+
fixed_xu = working & (cauchy_step > xu)
|
| 341 |
+
if not np.any(fixed_xl) and not np.any(fixed_xu):
|
| 342 |
+
# Stop the calculations as the Cauchy step is now feasible.
|
| 343 |
+
break
|
| 344 |
+
cauchy_step[fixed_xl] = xl[fixed_xl]
|
| 345 |
+
cauchy_step[fixed_xu] = xu[fixed_xu]
|
| 346 |
+
working = working & ~(fixed_xl | fixed_xu)
|
| 347 |
+
|
| 348 |
+
# Calculate the step that maximizes the quadratic along the Cauchy step.
|
| 349 |
+
grad_step = grad @ cauchy_step
|
| 350 |
+
if grad_step >= 0.0:
|
| 351 |
+
# Set alpha_tr to the step size for the trust-region constraint.
|
| 352 |
+
s_norm = np.linalg.norm(cauchy_step)
|
| 353 |
+
if s_norm > TINY * delta:
|
| 354 |
+
alpha_tr = max(delta / s_norm, 0.0)
|
| 355 |
+
else:
|
| 356 |
+
# The Cauchy step is basically zero.
|
| 357 |
+
alpha_tr = 0.0
|
| 358 |
+
|
| 359 |
+
# Set alpha_quad to the step size for the maximization problem.
|
| 360 |
+
curv_step = curv(cauchy_step)
|
| 361 |
+
if curv_step < -TINY * grad_step:
|
| 362 |
+
alpha_quad = max(-grad_step / curv_step, 0.0)
|
| 363 |
+
else:
|
| 364 |
+
alpha_quad = np.inf
|
| 365 |
+
|
| 366 |
+
# Set alpha_bd to the step size for the bound constraints.
|
| 367 |
+
i_xl = (xl > -np.inf) & (cauchy_step < TINY * xl)
|
| 368 |
+
i_xu = (xu < np.inf) & (cauchy_step > TINY * xu)
|
| 369 |
+
alpha_xl = np.min(xl[i_xl] / cauchy_step[i_xl], initial=np.inf)
|
| 370 |
+
alpha_xu = np.min(xu[i_xu] / cauchy_step[i_xu], initial=np.inf)
|
| 371 |
+
alpha_bd = min(alpha_xl, alpha_xu)
|
| 372 |
+
|
| 373 |
+
# Calculate the solution and the corresponding function value.
|
| 374 |
+
alpha = min(alpha_tr, alpha_quad, alpha_bd)
|
| 375 |
+
step = np.clip(alpha * cauchy_step, xl, xu)
|
| 376 |
+
q_val = const + alpha * grad_step + 0.5 * alpha**2.0 * curv_step
|
| 377 |
+
else:
|
| 378 |
+
# This case is never reached in exact arithmetic. It prevents this
|
| 379 |
+
# function to return a step that decreases the objective function.
|
| 380 |
+
step = np.zeros_like(grad)
|
| 381 |
+
q_val = const
|
| 382 |
+
|
| 383 |
+
if debug:
|
| 384 |
+
assert np.all(xl <= step)
|
| 385 |
+
assert np.all(step <= xu)
|
| 386 |
+
assert np.linalg.norm(step) < 1.1 * delta
|
| 387 |
+
return step, q_val
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py
ADDED
|
@@ -0,0 +1,1203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.linalg import qr
|
| 5 |
+
|
| 6 |
+
from ..utils import get_arrays_tol
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
TINY = np.finfo(float).tiny
|
| 10 |
+
EPS = np.finfo(float).eps
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def tangential_byrd_omojokun(grad, hess_prod, xl, xu, delta, debug, **kwargs):
|
| 14 |
+
r"""
|
| 15 |
+
Minimize approximately a quadratic function subject to bound constraints in
|
| 16 |
+
a trust region.
|
| 17 |
+
|
| 18 |
+
This function solves approximately
|
| 19 |
+
|
| 20 |
+
.. math::
|
| 21 |
+
|
| 22 |
+
\min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2}
|
| 23 |
+
s^{\mathsf{T}} H s \quad \text{s.t.} \quad
|
| 24 |
+
\left\{ \begin{array}{l}
|
| 25 |
+
l \le s \le u\\
|
| 26 |
+
\lVert s \rVert \le \Delta,
|
| 27 |
+
\end{array} \right.
|
| 28 |
+
|
| 29 |
+
using an active-set variation of the truncated conjugate gradient method.
|
| 30 |
+
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
grad : `numpy.ndarray`, shape (n,)
|
| 34 |
+
Gradient :math:`g` as shown above.
|
| 35 |
+
hess_prod : callable
|
| 36 |
+
Product of the Hessian matrix :math:`H` with any vector.
|
| 37 |
+
|
| 38 |
+
``hess_prod(s) -> `numpy.ndarray`, shape (n,)``
|
| 39 |
+
|
| 40 |
+
returns the product :math:`H s`.
|
| 41 |
+
xl : `numpy.ndarray`, shape (n,)
|
| 42 |
+
Lower bounds :math:`l` as shown above.
|
| 43 |
+
xu : `numpy.ndarray`, shape (n,)
|
| 44 |
+
Upper bounds :math:`u` as shown above.
|
| 45 |
+
delta : float
|
| 46 |
+
Trust-region radius :math:`\Delta` as shown above.
|
| 47 |
+
debug : bool
|
| 48 |
+
Whether to make debugging tests during the execution.
|
| 49 |
+
|
| 50 |
+
Returns
|
| 51 |
+
-------
|
| 52 |
+
`numpy.ndarray`, shape (n,)
|
| 53 |
+
Approximate solution :math:`s`.
|
| 54 |
+
|
| 55 |
+
Other Parameters
|
| 56 |
+
----------------
|
| 57 |
+
improve_tcg : bool, optional
|
| 58 |
+
If True, a solution generated by the truncated conjugate gradient
|
| 59 |
+
method that is on the boundary of the trust region is improved by
|
| 60 |
+
moving around the trust-region boundary on the two-dimensional space
|
| 61 |
+
spanned by the solution and the gradient of the quadratic function at
|
| 62 |
+
the solution (default is True).
|
| 63 |
+
|
| 64 |
+
Notes
|
| 65 |
+
-----
|
| 66 |
+
This function implements Algorithm 6.2 of [1]_. It is assumed that the
|
| 67 |
+
origin is feasible with respect to the bound constraints and that `delta`
|
| 68 |
+
is finite and positive.
|
| 69 |
+
|
| 70 |
+
References
|
| 71 |
+
----------
|
| 72 |
+
.. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
|
| 73 |
+
and Software*. PhD thesis, Department of Applied Mathematics, The Hong
|
| 74 |
+
Kong Polytechnic University, Hong Kong, China, 2022. URL:
|
| 75 |
+
https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 76 |
+
"""
|
| 77 |
+
if debug:
|
| 78 |
+
assert isinstance(grad, np.ndarray) and grad.ndim == 1
|
| 79 |
+
assert inspect.signature(hess_prod).bind(grad)
|
| 80 |
+
assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
|
| 81 |
+
assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
|
| 82 |
+
assert isinstance(delta, float)
|
| 83 |
+
assert isinstance(debug, bool)
|
| 84 |
+
tol = get_arrays_tol(xl, xu)
|
| 85 |
+
assert np.all(xl <= tol)
|
| 86 |
+
assert np.all(xu >= -tol)
|
| 87 |
+
assert np.isfinite(delta) and delta > 0.0
|
| 88 |
+
xl = np.minimum(xl, 0.0)
|
| 89 |
+
xu = np.maximum(xu, 0.0)
|
| 90 |
+
|
| 91 |
+
# Copy the arrays that may be modified by the code below.
|
| 92 |
+
n = grad.size
|
| 93 |
+
grad = np.copy(grad)
|
| 94 |
+
grad_orig = np.copy(grad)
|
| 95 |
+
|
| 96 |
+
# Calculate the initial active set.
|
| 97 |
+
free_bd = ((xl < 0.0) | (grad < 0.0)) & ((xu > 0.0) | (grad > 0.0))
|
| 98 |
+
|
| 99 |
+
# Set the initial iterate and the initial search direction.
|
| 100 |
+
step = np.zeros_like(grad)
|
| 101 |
+
sd = np.zeros_like(step)
|
| 102 |
+
sd[free_bd] = -grad[free_bd]
|
| 103 |
+
|
| 104 |
+
k = 0
|
| 105 |
+
reduct = 0.0
|
| 106 |
+
boundary_reached = False
|
| 107 |
+
while k < np.count_nonzero(free_bd):
|
| 108 |
+
# Stop the computations if sd is not a descent direction.
|
| 109 |
+
grad_sd = grad @ sd
|
| 110 |
+
if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
|
| 111 |
+
break
|
| 112 |
+
|
| 113 |
+
# Set alpha_tr to the step size for the trust-region constraint.
|
| 114 |
+
try:
|
| 115 |
+
alpha_tr = _alpha_tr(step, sd, delta)
|
| 116 |
+
except ZeroDivisionError:
|
| 117 |
+
break
|
| 118 |
+
|
| 119 |
+
# Stop the computations if a step along sd is expected to give a
|
| 120 |
+
# relatively small reduction in the objective function.
|
| 121 |
+
if -alpha_tr * grad_sd <= 1e-8 * reduct:
|
| 122 |
+
break
|
| 123 |
+
|
| 124 |
+
# Set alpha_quad to the step size for the minimization problem.
|
| 125 |
+
hess_sd = hess_prod(sd)
|
| 126 |
+
curv_sd = sd @ hess_sd
|
| 127 |
+
if curv_sd > TINY * abs(grad_sd):
|
| 128 |
+
alpha_quad = max(-grad_sd / curv_sd, 0.0)
|
| 129 |
+
else:
|
| 130 |
+
alpha_quad = np.inf
|
| 131 |
+
|
| 132 |
+
# Stop the computations if the reduction in the objective function
|
| 133 |
+
# provided by an unconstrained step is small.
|
| 134 |
+
alpha = min(alpha_tr, alpha_quad)
|
| 135 |
+
if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
|
| 136 |
+
break
|
| 137 |
+
|
| 138 |
+
# Set alpha_bd to the step size for the bound constraints.
|
| 139 |
+
i_xl = (xl > -np.inf) & (sd < -TINY * np.abs(xl - step))
|
| 140 |
+
i_xu = (xu < np.inf) & (sd > TINY * np.abs(xu - step))
|
| 141 |
+
all_alpha_xl = np.full_like(step, np.inf)
|
| 142 |
+
all_alpha_xu = np.full_like(step, np.inf)
|
| 143 |
+
all_alpha_xl[i_xl] = np.maximum(
|
| 144 |
+
(xl[i_xl] - step[i_xl]) / sd[i_xl],
|
| 145 |
+
0.0,
|
| 146 |
+
)
|
| 147 |
+
all_alpha_xu[i_xu] = np.maximum(
|
| 148 |
+
(xu[i_xu] - step[i_xu]) / sd[i_xu],
|
| 149 |
+
0.0,
|
| 150 |
+
)
|
| 151 |
+
alpha_xl = np.min(all_alpha_xl)
|
| 152 |
+
alpha_xu = np.min(all_alpha_xu)
|
| 153 |
+
alpha_bd = min(alpha_xl, alpha_xu)
|
| 154 |
+
|
| 155 |
+
# Update the iterate.
|
| 156 |
+
alpha = min(alpha, alpha_bd)
|
| 157 |
+
if alpha > 0.0:
|
| 158 |
+
step[free_bd] = np.clip(
|
| 159 |
+
step[free_bd] + alpha * sd[free_bd],
|
| 160 |
+
xl[free_bd],
|
| 161 |
+
xu[free_bd],
|
| 162 |
+
)
|
| 163 |
+
grad += alpha * hess_sd
|
| 164 |
+
reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
|
| 165 |
+
|
| 166 |
+
if alpha < min(alpha_tr, alpha_bd):
|
| 167 |
+
# The current iteration is a conjugate gradient iteration. Update
|
| 168 |
+
# the search direction so that it is conjugate (with respect to H)
|
| 169 |
+
# to all the previous search directions.
|
| 170 |
+
beta = (grad[free_bd] @ hess_sd[free_bd]) / curv_sd
|
| 171 |
+
sd[free_bd] = beta * sd[free_bd] - grad[free_bd]
|
| 172 |
+
sd[~free_bd] = 0.0
|
| 173 |
+
k += 1
|
| 174 |
+
elif alpha < alpha_tr:
|
| 175 |
+
# The iterate is restricted by a bound constraint. Add this bound
|
| 176 |
+
# constraint to the active set, and restart the calculations.
|
| 177 |
+
if alpha_xl <= alpha:
|
| 178 |
+
i_new = np.argmin(all_alpha_xl)
|
| 179 |
+
step[i_new] = xl[i_new]
|
| 180 |
+
else:
|
| 181 |
+
i_new = np.argmin(all_alpha_xu)
|
| 182 |
+
step[i_new] = xu[i_new]
|
| 183 |
+
free_bd[i_new] = False
|
| 184 |
+
sd[free_bd] = -grad[free_bd]
|
| 185 |
+
sd[~free_bd] = 0.0
|
| 186 |
+
k = 0
|
| 187 |
+
else:
|
| 188 |
+
# The current iterate is on the trust-region boundary. Add all the
|
| 189 |
+
# active bounds to the working set to prepare for the improvement
|
| 190 |
+
# of the solution, and stop the iterations.
|
| 191 |
+
if alpha_xl <= alpha:
|
| 192 |
+
i_new = _argmin(all_alpha_xl)
|
| 193 |
+
step[i_new] = xl[i_new]
|
| 194 |
+
free_bd[i_new] = False
|
| 195 |
+
if alpha_xu <= alpha:
|
| 196 |
+
i_new = _argmin(all_alpha_xu)
|
| 197 |
+
step[i_new] = xu[i_new]
|
| 198 |
+
free_bd[i_new] = False
|
| 199 |
+
boundary_reached = True
|
| 200 |
+
break
|
| 201 |
+
|
| 202 |
+
# Attempt to improve the solution on the trust-region boundary.
|
| 203 |
+
if kwargs.get("improve_tcg", True) and boundary_reached:
|
| 204 |
+
step_base = np.copy(step)
|
| 205 |
+
step_comparator = grad_orig @ step_base + 0.5 * step_base @ hess_prod(
|
| 206 |
+
step_base
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
while np.count_nonzero(free_bd) > 0:
|
| 210 |
+
# Check whether a substantial reduction in the objective function
|
| 211 |
+
# is possible, and set the search direction.
|
| 212 |
+
step_sq = step[free_bd] @ step[free_bd]
|
| 213 |
+
grad_sq = grad[free_bd] @ grad[free_bd]
|
| 214 |
+
grad_step = grad[free_bd] @ step[free_bd]
|
| 215 |
+
grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
|
| 216 |
+
sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd]
|
| 217 |
+
sd[~free_bd] = 0.0
|
| 218 |
+
if grad_sd >= -1e-8 * reduct or np.any(
|
| 219 |
+
grad_sd >= -TINY * np.abs(sd[free_bd])
|
| 220 |
+
):
|
| 221 |
+
break
|
| 222 |
+
sd[free_bd] /= -grad_sd
|
| 223 |
+
|
| 224 |
+
# Calculate an upper bound for the tangent of half the angle theta
|
| 225 |
+
# of this alternative iteration. The step will be updated as:
|
| 226 |
+
# step = cos(theta) * step + sin(theta) * sd.
|
| 227 |
+
temp_xl = np.zeros(n)
|
| 228 |
+
temp_xu = np.zeros(n)
|
| 229 |
+
temp_xl[free_bd] = (
|
| 230 |
+
step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0
|
| 231 |
+
)
|
| 232 |
+
temp_xu[free_bd] = (
|
| 233 |
+
step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0
|
| 234 |
+
)
|
| 235 |
+
temp_xl[temp_xl > 0.0] = (
|
| 236 |
+
np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
|
| 237 |
+
)
|
| 238 |
+
temp_xu[temp_xu > 0.0] = (
|
| 239 |
+
np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
|
| 240 |
+
)
|
| 241 |
+
dist_xl = np.maximum(step - xl, 0.0)
|
| 242 |
+
dist_xu = np.maximum(xu - step, 0.0)
|
| 243 |
+
i_xl = temp_xl > TINY * dist_xl
|
| 244 |
+
i_xu = temp_xu > TINY * dist_xu
|
| 245 |
+
all_t_xl = np.ones(n)
|
| 246 |
+
all_t_xu = np.ones(n)
|
| 247 |
+
all_t_xl[i_xl] = np.minimum(
|
| 248 |
+
all_t_xl[i_xl],
|
| 249 |
+
dist_xl[i_xl] / temp_xl[i_xl],
|
| 250 |
+
)
|
| 251 |
+
all_t_xu[i_xu] = np.minimum(
|
| 252 |
+
all_t_xu[i_xu],
|
| 253 |
+
dist_xu[i_xu] / temp_xu[i_xu],
|
| 254 |
+
)
|
| 255 |
+
t_xl = np.min(all_t_xl)
|
| 256 |
+
t_xu = np.min(all_t_xu)
|
| 257 |
+
t_bd = min(t_xl, t_xu)
|
| 258 |
+
|
| 259 |
+
# Calculate some curvature information.
|
| 260 |
+
hess_step = hess_prod(step)
|
| 261 |
+
hess_sd = hess_prod(sd)
|
| 262 |
+
curv_step = step @ hess_step
|
| 263 |
+
curv_sd = sd @ hess_sd
|
| 264 |
+
curv_step_sd = step @ hess_sd
|
| 265 |
+
|
| 266 |
+
# For a range of equally spaced values of tan(0.5 * theta),
|
| 267 |
+
# calculate the reduction in the objective function that would be
|
| 268 |
+
# obtained by accepting the corresponding angle.
|
| 269 |
+
n_samples = 20
|
| 270 |
+
n_samples = int((n_samples - 3) * t_bd + 3)
|
| 271 |
+
t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples)
|
| 272 |
+
sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0)
|
| 273 |
+
all_reduct = sin_values * (
|
| 274 |
+
grad_step * t_samples
|
| 275 |
+
- grad_sd
|
| 276 |
+
- t_samples * curv_step
|
| 277 |
+
+ sin_values
|
| 278 |
+
* (t_samples * curv_step_sd - 0.5 * (curv_sd - curv_step))
|
| 279 |
+
)
|
| 280 |
+
if np.all(all_reduct <= 0.0):
|
| 281 |
+
# No reduction in the objective function is obtained.
|
| 282 |
+
break
|
| 283 |
+
|
| 284 |
+
# Accept the angle that provides the largest reduction in the
|
| 285 |
+
# objective function, and update the iterate.
|
| 286 |
+
i_max = np.argmax(all_reduct)
|
| 287 |
+
cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
|
| 288 |
+
1.0 + t_samples[i_max] ** 2.0
|
| 289 |
+
)
|
| 290 |
+
step[free_bd] = (
|
| 291 |
+
cos_value * step[free_bd] + sin_values[i_max] * sd[free_bd]
|
| 292 |
+
)
|
| 293 |
+
grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd
|
| 294 |
+
reduct += all_reduct[i_max]
|
| 295 |
+
|
| 296 |
+
# If the above angle is restricted by bound constraints, add them
|
| 297 |
+
# to the working set, and restart the alternative iteration.
|
| 298 |
+
# Otherwise, the calculations are terminated.
|
| 299 |
+
if t_bd < 1.0 and i_max == n_samples - 1:
|
| 300 |
+
if t_xl <= t_bd:
|
| 301 |
+
i_new = _argmin(all_t_xl)
|
| 302 |
+
step[i_new] = xl[i_new]
|
| 303 |
+
free_bd[i_new] = False
|
| 304 |
+
if t_xu <= t_bd:
|
| 305 |
+
i_new = _argmin(all_t_xu)
|
| 306 |
+
step[i_new] = xu[i_new]
|
| 307 |
+
free_bd[i_new] = False
|
| 308 |
+
else:
|
| 309 |
+
break
|
| 310 |
+
|
| 311 |
+
# Ensure that the alternative iteration improves the objective
|
| 312 |
+
# function.
|
| 313 |
+
if grad_orig @ step + 0.5 * step @ hess_prod(step) > step_comparator:
|
| 314 |
+
step = step_base
|
| 315 |
+
|
| 316 |
+
if debug:
|
| 317 |
+
assert np.all(xl <= step)
|
| 318 |
+
assert np.all(step <= xu)
|
| 319 |
+
assert np.linalg.norm(step) < 1.1 * delta
|
| 320 |
+
return step
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def constrained_tangential_byrd_omojokun(
|
| 324 |
+
grad,
|
| 325 |
+
hess_prod,
|
| 326 |
+
xl,
|
| 327 |
+
xu,
|
| 328 |
+
aub,
|
| 329 |
+
bub,
|
| 330 |
+
aeq,
|
| 331 |
+
delta,
|
| 332 |
+
debug,
|
| 333 |
+
**kwargs,
|
| 334 |
+
):
|
| 335 |
+
r"""
|
| 336 |
+
Minimize approximately a quadratic function subject to bound and linear
|
| 337 |
+
constraints in a trust region.
|
| 338 |
+
|
| 339 |
+
This function solves approximately
|
| 340 |
+
|
| 341 |
+
.. math::
|
| 342 |
+
|
| 343 |
+
\min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2}
|
| 344 |
+
s^{\mathsf{T}} H s \quad \text{s.t.} \quad
|
| 345 |
+
\left\{ \begin{array}{l}
|
| 346 |
+
l \le s \le u,\\
|
| 347 |
+
A_{\scriptscriptstyle I} s \le b_{\scriptscriptstyle I},\\
|
| 348 |
+
A_{\scriptscriptstyle E} s = 0,\\
|
| 349 |
+
\lVert s \rVert \le \Delta,
|
| 350 |
+
\end{array} \right.
|
| 351 |
+
|
| 352 |
+
using an active-set variation of the truncated conjugate gradient method.
|
| 353 |
+
|
| 354 |
+
Parameters
|
| 355 |
+
----------
|
| 356 |
+
grad : `numpy.ndarray`, shape (n,)
|
| 357 |
+
Gradient :math:`g` as shown above.
|
| 358 |
+
hess_prod : callable
|
| 359 |
+
Product of the Hessian matrix :math:`H` with any vector.
|
| 360 |
+
|
| 361 |
+
``hess_prod(s) -> `numpy.ndarray`, shape (n,)``
|
| 362 |
+
|
| 363 |
+
returns the product :math:`H s`.
|
| 364 |
+
xl : `numpy.ndarray`, shape (n,)
|
| 365 |
+
Lower bounds :math:`l` as shown above.
|
| 366 |
+
xu : `numpy.ndarray`, shape (n,)
|
| 367 |
+
Upper bounds :math:`u` as shown above.
|
| 368 |
+
aub : `numpy.ndarray`, shape (m_linear_ub, n)
|
| 369 |
+
Coefficient matrix :math:`A_{\scriptscriptstyle I}` as shown above.
|
| 370 |
+
bub : `numpy.ndarray`, shape (m_linear_ub,)
|
| 371 |
+
Right-hand side :math:`b_{\scriptscriptstyle I}` as shown above.
|
| 372 |
+
aeq : `numpy.ndarray`, shape (m_linear_eq, n)
|
| 373 |
+
Coefficient matrix :math:`A_{\scriptscriptstyle E}` as shown above.
|
| 374 |
+
delta : float
|
| 375 |
+
Trust-region radius :math:`\Delta` as shown above.
|
| 376 |
+
debug : bool
|
| 377 |
+
Whether to make debugging tests during the execution.
|
| 378 |
+
|
| 379 |
+
Returns
|
| 380 |
+
-------
|
| 381 |
+
`numpy.ndarray`, shape (n,)
|
| 382 |
+
Approximate solution :math:`s`.
|
| 383 |
+
|
| 384 |
+
Other Parameters
|
| 385 |
+
----------------
|
| 386 |
+
improve_tcg : bool, optional
|
| 387 |
+
If True, a solution generated by the truncated conjugate gradient
|
| 388 |
+
method that is on the boundary of the trust region is improved by
|
| 389 |
+
moving around the trust-region boundary on the two-dimensional space
|
| 390 |
+
spanned by the solution and the gradient of the quadratic function at
|
| 391 |
+
the solution (default is True).
|
| 392 |
+
|
| 393 |
+
Notes
|
| 394 |
+
-----
|
| 395 |
+
This function implements Algorithm 6.3 of [1]_. It is assumed that the
|
| 396 |
+
origin is feasible with respect to the bound and linear constraints, and
|
| 397 |
+
that `delta` is finite and positive.
|
| 398 |
+
|
| 399 |
+
References
|
| 400 |
+
----------
|
| 401 |
+
.. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
|
| 402 |
+
and Software*. PhD thesis, Department of Applied Mathematics, The Hong
|
| 403 |
+
Kong Polytechnic University, Hong Kong, China, 2022. URL:
|
| 404 |
+
https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 405 |
+
"""
|
| 406 |
+
if debug:
|
| 407 |
+
assert isinstance(grad, np.ndarray) and grad.ndim == 1
|
| 408 |
+
assert inspect.signature(hess_prod).bind(grad)
|
| 409 |
+
assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
|
| 410 |
+
assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
|
| 411 |
+
assert (
|
| 412 |
+
isinstance(aub, np.ndarray)
|
| 413 |
+
and aub.ndim == 2
|
| 414 |
+
and aub.shape[1] == grad.size
|
| 415 |
+
)
|
| 416 |
+
assert (
|
| 417 |
+
isinstance(bub, np.ndarray)
|
| 418 |
+
and bub.ndim == 1
|
| 419 |
+
and bub.size == aub.shape[0]
|
| 420 |
+
)
|
| 421 |
+
assert (
|
| 422 |
+
isinstance(aeq, np.ndarray)
|
| 423 |
+
and aeq.ndim == 2
|
| 424 |
+
and aeq.shape[1] == grad.size
|
| 425 |
+
)
|
| 426 |
+
assert isinstance(delta, float)
|
| 427 |
+
assert isinstance(debug, bool)
|
| 428 |
+
tol = get_arrays_tol(xl, xu)
|
| 429 |
+
assert np.all(xl <= tol)
|
| 430 |
+
assert np.all(xu >= -tol)
|
| 431 |
+
assert np.all(bub >= -tol)
|
| 432 |
+
assert np.isfinite(delta) and delta > 0.0
|
| 433 |
+
xl = np.minimum(xl, 0.0)
|
| 434 |
+
xu = np.maximum(xu, 0.0)
|
| 435 |
+
bub = np.maximum(bub, 0.0)
|
| 436 |
+
|
| 437 |
+
# Copy the arrays that may be modified by the code below.
|
| 438 |
+
n = grad.size
|
| 439 |
+
grad = np.copy(grad)
|
| 440 |
+
grad_orig = np.copy(grad)
|
| 441 |
+
|
| 442 |
+
# Calculate the initial active set.
|
| 443 |
+
free_xl = (xl < 0.0) | (grad < 0.0)
|
| 444 |
+
free_xu = (xu > 0.0) | (grad > 0.0)
|
| 445 |
+
free_ub = (bub > 0.0) | (aub @ grad > 0.0)
|
| 446 |
+
n_act, q = qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub)
|
| 447 |
+
|
| 448 |
+
# Set the initial iterate and the initial search direction.
|
| 449 |
+
step = np.zeros_like(grad)
|
| 450 |
+
sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
|
| 451 |
+
resid = np.copy(bub)
|
| 452 |
+
|
| 453 |
+
k = 0
|
| 454 |
+
reduct = 0.0
|
| 455 |
+
boundary_reached = False
|
| 456 |
+
while k < n - n_act:
|
| 457 |
+
# Stop the computations if sd is not a descent direction.
|
| 458 |
+
grad_sd = grad @ sd
|
| 459 |
+
if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
|
| 460 |
+
break
|
| 461 |
+
|
| 462 |
+
# Set alpha_tr to the step size for the trust-region constraint.
|
| 463 |
+
try:
|
| 464 |
+
alpha_tr = _alpha_tr(step, sd, delta)
|
| 465 |
+
except ZeroDivisionError:
|
| 466 |
+
break
|
| 467 |
+
|
| 468 |
+
# Stop the computations if a step along sd is expected to give a
|
| 469 |
+
# relatively small reduction in the objective function.
|
| 470 |
+
if -alpha_tr * grad_sd <= 1e-8 * reduct:
|
| 471 |
+
break
|
| 472 |
+
|
| 473 |
+
# Set alpha_quad to the step size for the minimization problem.
|
| 474 |
+
hess_sd = hess_prod(sd)
|
| 475 |
+
curv_sd = sd @ hess_sd
|
| 476 |
+
if curv_sd > TINY * abs(grad_sd):
|
| 477 |
+
alpha_quad = max(-grad_sd / curv_sd, 0.0)
|
| 478 |
+
else:
|
| 479 |
+
alpha_quad = np.inf
|
| 480 |
+
|
| 481 |
+
# Stop the computations if the reduction in the objective function
|
| 482 |
+
# provided by an unconstrained step is small.
|
| 483 |
+
alpha = min(alpha_tr, alpha_quad)
|
| 484 |
+
if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
|
| 485 |
+
break
|
| 486 |
+
|
| 487 |
+
# Set alpha_bd to the step size for the bound constraints.
|
| 488 |
+
i_xl = free_xl & (xl > -np.inf) & (sd < -TINY * np.abs(xl - step))
|
| 489 |
+
i_xu = free_xu & (xu < np.inf) & (sd > TINY * np.abs(xu - step))
|
| 490 |
+
all_alpha_xl = np.full_like(step, np.inf)
|
| 491 |
+
all_alpha_xu = np.full_like(step, np.inf)
|
| 492 |
+
all_alpha_xl[i_xl] = np.maximum(
|
| 493 |
+
(xl[i_xl] - step[i_xl]) / sd[i_xl],
|
| 494 |
+
0.0,
|
| 495 |
+
)
|
| 496 |
+
all_alpha_xu[i_xu] = np.maximum(
|
| 497 |
+
(xu[i_xu] - step[i_xu]) / sd[i_xu],
|
| 498 |
+
0.0,
|
| 499 |
+
)
|
| 500 |
+
alpha_xl = np.min(all_alpha_xl)
|
| 501 |
+
alpha_xu = np.min(all_alpha_xu)
|
| 502 |
+
alpha_bd = min(alpha_xl, alpha_xu)
|
| 503 |
+
|
| 504 |
+
# Set alpha_ub to the step size for the linear constraints.
|
| 505 |
+
aub_sd = aub @ sd
|
| 506 |
+
i_ub = free_ub & (aub_sd > TINY * np.abs(resid))
|
| 507 |
+
all_alpha_ub = np.full_like(bub, np.inf)
|
| 508 |
+
all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub]
|
| 509 |
+
alpha_ub = np.min(all_alpha_ub, initial=np.inf)
|
| 510 |
+
|
| 511 |
+
# Update the iterate.
|
| 512 |
+
alpha = min(alpha, alpha_bd, alpha_ub)
|
| 513 |
+
if alpha > 0.0:
|
| 514 |
+
step = np.clip(step + alpha * sd, xl, xu)
|
| 515 |
+
grad += alpha * hess_sd
|
| 516 |
+
resid = np.maximum(0.0, resid - alpha * aub_sd)
|
| 517 |
+
reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
|
| 518 |
+
|
| 519 |
+
if alpha < min(alpha_tr, alpha_bd, alpha_ub):
|
| 520 |
+
# The current iteration is a conjugate gradient iteration. Update
|
| 521 |
+
# the search direction so that it is conjugate (with respect to H)
|
| 522 |
+
# to all the previous search directions.
|
| 523 |
+
grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
|
| 524 |
+
beta = (grad_proj @ hess_sd) / curv_sd
|
| 525 |
+
sd = beta * sd - grad_proj
|
| 526 |
+
k += 1
|
| 527 |
+
elif alpha < alpha_tr:
|
| 528 |
+
# The iterate is restricted by a bound/linear constraint. Add this
|
| 529 |
+
# constraint to the active set, and restart the calculations.
|
| 530 |
+
if alpha_xl <= alpha:
|
| 531 |
+
i_new = np.argmin(all_alpha_xl)
|
| 532 |
+
step[i_new] = xl[i_new]
|
| 533 |
+
free_xl[i_new] = False
|
| 534 |
+
elif alpha_xu <= alpha:
|
| 535 |
+
i_new = np.argmin(all_alpha_xu)
|
| 536 |
+
step[i_new] = xu[i_new]
|
| 537 |
+
free_xu[i_new] = False
|
| 538 |
+
else:
|
| 539 |
+
i_new = np.argmin(all_alpha_ub)
|
| 540 |
+
free_ub[i_new] = False
|
| 541 |
+
n_act, q = qr_tangential_byrd_omojokun(
|
| 542 |
+
aub,
|
| 543 |
+
aeq,
|
| 544 |
+
free_xl,
|
| 545 |
+
free_xu,
|
| 546 |
+
free_ub,
|
| 547 |
+
)
|
| 548 |
+
sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
|
| 549 |
+
k = 0
|
| 550 |
+
else:
|
| 551 |
+
# The current iterate is on the trust-region boundary. Add all the
|
| 552 |
+
# active bound/linear constraints to the working set to prepare for
|
| 553 |
+
# the improvement of the solution, and stop the iterations.
|
| 554 |
+
if alpha_xl <= alpha:
|
| 555 |
+
i_new = _argmin(all_alpha_xl)
|
| 556 |
+
step[i_new] = xl[i_new]
|
| 557 |
+
free_xl[i_new] = False
|
| 558 |
+
if alpha_xu <= alpha:
|
| 559 |
+
i_new = _argmin(all_alpha_xu)
|
| 560 |
+
step[i_new] = xu[i_new]
|
| 561 |
+
free_xu[i_new] = False
|
| 562 |
+
if alpha_ub <= alpha:
|
| 563 |
+
i_new = _argmin(all_alpha_ub)
|
| 564 |
+
free_ub[i_new] = False
|
| 565 |
+
n_act, q = qr_tangential_byrd_omojokun(
|
| 566 |
+
aub,
|
| 567 |
+
aeq,
|
| 568 |
+
free_xl,
|
| 569 |
+
free_xu,
|
| 570 |
+
free_ub,
|
| 571 |
+
)
|
| 572 |
+
boundary_reached = True
|
| 573 |
+
break
|
| 574 |
+
|
| 575 |
+
# Attempt to improve the solution on the trust-region boundary.
|
| 576 |
+
if kwargs.get("improve_tcg", True) and boundary_reached and n_act < n:
|
| 577 |
+
step_base = np.copy(step)
|
| 578 |
+
while n_act < n:
|
| 579 |
+
# Check whether a substantial reduction in the objective function
|
| 580 |
+
# is possible, and set the search direction.
|
| 581 |
+
step_proj = q[:, n_act:] @ (q[:, n_act:].T @ step)
|
| 582 |
+
grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
|
| 583 |
+
step_sq = step_proj @ step_proj
|
| 584 |
+
grad_sq = grad_proj @ grad_proj
|
| 585 |
+
grad_step = grad_proj @ step_proj
|
| 586 |
+
grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
|
| 587 |
+
sd = q[:, n_act:] @ (
|
| 588 |
+
q[:, n_act:].T @ (grad_step * step - step_sq * grad)
|
| 589 |
+
)
|
| 590 |
+
if grad_sd >= -1e-8 * reduct or np.any(
|
| 591 |
+
grad_sd >= -TINY * np.abs(sd)
|
| 592 |
+
):
|
| 593 |
+
break
|
| 594 |
+
sd /= -grad_sd
|
| 595 |
+
|
| 596 |
+
# Calculate an upper bound for the tangent of half the angle theta
|
| 597 |
+
# of this alternative iteration for the bound constraints. The step
|
| 598 |
+
# will be updated as:
|
| 599 |
+
# step += (cos(theta) - 1) * step_proj + sin(theta) * sd.
|
| 600 |
+
temp_xl = np.zeros(n)
|
| 601 |
+
temp_xu = np.zeros(n)
|
| 602 |
+
dist_xl = np.maximum(step - xl, 0.0)
|
| 603 |
+
dist_xu = np.maximum(xu - step, 0.0)
|
| 604 |
+
temp_xl[free_xl] = sd[free_xl] ** 2.0 - dist_xl[free_xl] * (
|
| 605 |
+
dist_xl[free_xl] - 2.0 * step_proj[free_xl]
|
| 606 |
+
)
|
| 607 |
+
temp_xu[free_xu] = sd[free_xu] ** 2.0 - dist_xu[free_xu] * (
|
| 608 |
+
dist_xu[free_xu] + 2.0 * step_proj[free_xu]
|
| 609 |
+
)
|
| 610 |
+
temp_xl[temp_xl > 0.0] = (
|
| 611 |
+
np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
|
| 612 |
+
)
|
| 613 |
+
temp_xu[temp_xu > 0.0] = (
|
| 614 |
+
np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
|
| 615 |
+
)
|
| 616 |
+
i_xl = temp_xl > TINY * dist_xl
|
| 617 |
+
i_xu = temp_xu > TINY * dist_xu
|
| 618 |
+
all_t_xl = np.ones(n)
|
| 619 |
+
all_t_xu = np.ones(n)
|
| 620 |
+
all_t_xl[i_xl] = np.minimum(
|
| 621 |
+
all_t_xl[i_xl],
|
| 622 |
+
dist_xl[i_xl] / temp_xl[i_xl],
|
| 623 |
+
)
|
| 624 |
+
all_t_xu[i_xu] = np.minimum(
|
| 625 |
+
all_t_xu[i_xu],
|
| 626 |
+
dist_xu[i_xu] / temp_xu[i_xu],
|
| 627 |
+
)
|
| 628 |
+
t_xl = np.min(all_t_xl)
|
| 629 |
+
t_xu = np.min(all_t_xu)
|
| 630 |
+
t_bd = min(t_xl, t_xu)
|
| 631 |
+
|
| 632 |
+
# Calculate an upper bound for the tangent of half the angle theta
|
| 633 |
+
# of this alternative iteration for the linear constraints.
|
| 634 |
+
temp_ub = np.zeros_like(resid)
|
| 635 |
+
aub_step = aub @ step_proj
|
| 636 |
+
aub_sd = aub @ sd
|
| 637 |
+
temp_ub[free_ub] = aub_sd[free_ub] ** 2.0 - resid[free_ub] * (
|
| 638 |
+
resid[free_ub] + 2.0 * aub_step[free_ub]
|
| 639 |
+
)
|
| 640 |
+
temp_ub[temp_ub > 0.0] = (
|
| 641 |
+
np.sqrt(temp_ub[temp_ub > 0.0]) + aub_sd[temp_ub > 0.0]
|
| 642 |
+
)
|
| 643 |
+
i_ub = temp_ub > TINY * resid
|
| 644 |
+
all_t_ub = np.ones_like(resid)
|
| 645 |
+
all_t_ub[i_ub] = np.minimum(
|
| 646 |
+
all_t_ub[i_ub],
|
| 647 |
+
resid[i_ub] / temp_ub[i_ub],
|
| 648 |
+
)
|
| 649 |
+
t_ub = np.min(all_t_ub, initial=1.0)
|
| 650 |
+
t_min = min(t_bd, t_ub)
|
| 651 |
+
|
| 652 |
+
# Calculate some curvature information.
|
| 653 |
+
hess_step = hess_prod(step_proj)
|
| 654 |
+
hess_sd = hess_prod(sd)
|
| 655 |
+
curv_step = step_proj @ hess_step
|
| 656 |
+
curv_sd = sd @ hess_sd
|
| 657 |
+
curv_step_sd = step_proj @ hess_sd
|
| 658 |
+
|
| 659 |
+
# For a range of equally spaced values of tan(0.5 * theta),
|
| 660 |
+
# calculate the reduction in the objective function that would be
|
| 661 |
+
# obtained by accepting the corresponding angle.
|
| 662 |
+
n_samples = 20
|
| 663 |
+
n_samples = int((n_samples - 3) * t_min + 3)
|
| 664 |
+
t_samples = np.linspace(t_min / n_samples, t_min, n_samples)
|
| 665 |
+
sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0)
|
| 666 |
+
all_reduct = sin_values * (
|
| 667 |
+
grad_step * t_samples
|
| 668 |
+
- grad_sd
|
| 669 |
+
- sin_values
|
| 670 |
+
* (
|
| 671 |
+
0.5 * t_samples**2.0 * curv_step
|
| 672 |
+
- 2.0 * t_samples * curv_step_sd
|
| 673 |
+
+ 0.5 * curv_sd
|
| 674 |
+
)
|
| 675 |
+
)
|
| 676 |
+
if np.all(all_reduct <= 0.0):
|
| 677 |
+
# No reduction in the objective function is obtained.
|
| 678 |
+
break
|
| 679 |
+
|
| 680 |
+
# Accept the angle that provides the largest reduction in the
|
| 681 |
+
# objective function, and update the iterate.
|
| 682 |
+
i_max = np.argmax(all_reduct)
|
| 683 |
+
cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
|
| 684 |
+
1.0 + t_samples[i_max] ** 2.0
|
| 685 |
+
)
|
| 686 |
+
step = np.clip(
|
| 687 |
+
step + (cos_value - 1.0) * step_proj + sin_values[i_max] * sd,
|
| 688 |
+
xl,
|
| 689 |
+
xu,
|
| 690 |
+
)
|
| 691 |
+
grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd
|
| 692 |
+
resid = np.maximum(
|
| 693 |
+
0.0,
|
| 694 |
+
resid
|
| 695 |
+
- (cos_value - 1.0) * aub_step
|
| 696 |
+
- sin_values[i_max] * aub_sd,
|
| 697 |
+
)
|
| 698 |
+
reduct += all_reduct[i_max]
|
| 699 |
+
|
| 700 |
+
# If the above angle is restricted by bound constraints, add them
|
| 701 |
+
# to the working set, and restart the alternative iteration.
|
| 702 |
+
# Otherwise, the calculations are terminated.
|
| 703 |
+
if t_min < 1.0 and i_max == n_samples - 1:
|
| 704 |
+
if t_xl <= t_min:
|
| 705 |
+
i_new = _argmin(all_t_xl)
|
| 706 |
+
step[i_new] = xl[i_new]
|
| 707 |
+
free_xl[i_new] = False
|
| 708 |
+
if t_xu <= t_min:
|
| 709 |
+
i_new = _argmin(all_t_xu)
|
| 710 |
+
step[i_new] = xu[i_new]
|
| 711 |
+
free_xl[i_new] = False
|
| 712 |
+
if t_ub <= t_min:
|
| 713 |
+
i_new = _argmin(all_t_ub)
|
| 714 |
+
free_ub[i_new] = False
|
| 715 |
+
n_act, q = qr_tangential_byrd_omojokun(
|
| 716 |
+
aub,
|
| 717 |
+
aeq,
|
| 718 |
+
free_xl,
|
| 719 |
+
free_xu,
|
| 720 |
+
free_ub,
|
| 721 |
+
)
|
| 722 |
+
else:
|
| 723 |
+
break
|
| 724 |
+
|
| 725 |
+
# Ensure that the alternative iteration improves the objective
|
| 726 |
+
# function.
|
| 727 |
+
if grad_orig @ step + 0.5 * step @ hess_prod(
|
| 728 |
+
step
|
| 729 |
+
) > grad_orig @ step_base + 0.5 * step_base @ hess_prod(step_base):
|
| 730 |
+
step = step_base
|
| 731 |
+
|
| 732 |
+
if debug:
|
| 733 |
+
tol = get_arrays_tol(xl, xu)
|
| 734 |
+
assert np.all(xl <= step)
|
| 735 |
+
assert np.all(step <= xu)
|
| 736 |
+
assert np.all(aub @ step <= bub + tol)
|
| 737 |
+
assert np.all(np.abs(aeq @ step) <= tol)
|
| 738 |
+
assert np.linalg.norm(step) < 1.1 * delta
|
| 739 |
+
return step
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def normal_byrd_omojokun(aub, bub, aeq, beq, xl, xu, delta, debug, **kwargs):
|
| 743 |
+
r"""
|
| 744 |
+
Minimize approximately a linear constraint violation subject to bound
|
| 745 |
+
constraints in a trust region.
|
| 746 |
+
|
| 747 |
+
This function solves approximately
|
| 748 |
+
|
| 749 |
+
.. math::
|
| 750 |
+
|
| 751 |
+
\min_{s \in \mathbb{R}^n} \quad \frac{1}{2} \big( \lVert \max \{
|
| 752 |
+
A_{\scriptscriptstyle I} s - b_{\scriptscriptstyle I}, 0 \} \rVert^2 +
|
| 753 |
+
\lVert A_{\scriptscriptstyle E} s - b_{\scriptscriptstyle E} \rVert^2
|
| 754 |
+
\big) \quad \text{s.t.}
|
| 755 |
+
\quad
|
| 756 |
+
\left\{ \begin{array}{l}
|
| 757 |
+
l \le s \le u,\\
|
| 758 |
+
\lVert s \rVert \le \Delta,
|
| 759 |
+
\end{array} \right.
|
| 760 |
+
|
| 761 |
+
using a variation of the truncated conjugate gradient method.
|
| 762 |
+
|
| 763 |
+
Parameters
|
| 764 |
+
----------
|
| 765 |
+
aub : `numpy.ndarray`, shape (m_linear_ub, n)
|
| 766 |
+
Matrix :math:`A_{\scriptscriptstyle I}` as shown above.
|
| 767 |
+
bub : `numpy.ndarray`, shape (m_linear_ub,)
|
| 768 |
+
Vector :math:`b_{\scriptscriptstyle I}` as shown above.
|
| 769 |
+
aeq : `numpy.ndarray`, shape (m_linear_eq, n)
|
| 770 |
+
Matrix :math:`A_{\scriptscriptstyle E}` as shown above.
|
| 771 |
+
beq : `numpy.ndarray`, shape (m_linear_eq,)
|
| 772 |
+
Vector :math:`b_{\scriptscriptstyle E}` as shown above.
|
| 773 |
+
xl : `numpy.ndarray`, shape (n,)
|
| 774 |
+
Lower bounds :math:`l` as shown above.
|
| 775 |
+
xu : `numpy.ndarray`, shape (n,)
|
| 776 |
+
Upper bounds :math:`u` as shown above.
|
| 777 |
+
delta : float
|
| 778 |
+
Trust-region radius :math:`\Delta` as shown above.
|
| 779 |
+
debug : bool
|
| 780 |
+
Whether to make debugging tests during the execution.
|
| 781 |
+
|
| 782 |
+
Returns
|
| 783 |
+
-------
|
| 784 |
+
`numpy.ndarray`, shape (n,)
|
| 785 |
+
Approximate solution :math:`s`.
|
| 786 |
+
|
| 787 |
+
Other Parameters
|
| 788 |
+
----------------
|
| 789 |
+
improve_tcg : bool, optional
|
| 790 |
+
If True, a solution generated by the truncated conjugate gradient
|
| 791 |
+
method that is on the boundary of the trust region is improved by
|
| 792 |
+
moving around the trust-region boundary on the two-dimensional space
|
| 793 |
+
spanned by the solution and the gradient of the quadratic function at
|
| 794 |
+
the solution (default is True).
|
| 795 |
+
|
| 796 |
+
Notes
|
| 797 |
+
-----
|
| 798 |
+
This function implements Algorithm 6.4 of [1]_. It is assumed that the
|
| 799 |
+
origin is feasible with respect to the bound constraints and that `delta`
|
| 800 |
+
is finite and positive.
|
| 801 |
+
|
| 802 |
+
References
|
| 803 |
+
----------
|
| 804 |
+
.. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
|
| 805 |
+
and Software*. PhD thesis, Department of Applied Mathematics, The Hong
|
| 806 |
+
Kong Polytechnic University, Hong Kong, China, 2022. URL:
|
| 807 |
+
https://theses.lib.polyu.edu.hk/handle/200/12294.
|
| 808 |
+
"""
|
| 809 |
+
if debug:
|
| 810 |
+
assert isinstance(aub, np.ndarray) and aub.ndim == 2
|
| 811 |
+
assert (
|
| 812 |
+
isinstance(bub, np.ndarray)
|
| 813 |
+
and bub.ndim == 1
|
| 814 |
+
and bub.size == aub.shape[0]
|
| 815 |
+
)
|
| 816 |
+
assert (
|
| 817 |
+
isinstance(aeq, np.ndarray)
|
| 818 |
+
and aeq.ndim == 2
|
| 819 |
+
and aeq.shape[1] == aub.shape[1]
|
| 820 |
+
)
|
| 821 |
+
assert (
|
| 822 |
+
isinstance(beq, np.ndarray)
|
| 823 |
+
and beq.ndim == 1
|
| 824 |
+
and beq.size == aeq.shape[0]
|
| 825 |
+
)
|
| 826 |
+
assert isinstance(xl, np.ndarray) and xl.shape == (aub.shape[1],)
|
| 827 |
+
assert isinstance(xu, np.ndarray) and xu.shape == (aub.shape[1],)
|
| 828 |
+
assert isinstance(delta, float)
|
| 829 |
+
assert isinstance(debug, bool)
|
| 830 |
+
tol = get_arrays_tol(xl, xu)
|
| 831 |
+
assert np.all(xl <= tol)
|
| 832 |
+
assert np.all(xu >= -tol)
|
| 833 |
+
assert np.isfinite(delta) and delta > 0.0
|
| 834 |
+
xl = np.minimum(xl, 0.0)
|
| 835 |
+
xu = np.maximum(xu, 0.0)
|
| 836 |
+
|
| 837 |
+
# Calculate the initial active set.
|
| 838 |
+
m_linear_ub, n = aub.shape
|
| 839 |
+
grad = np.r_[aeq.T @ -beq, np.maximum(0.0, -bub)]
|
| 840 |
+
free_xl = (xl < 0.0) | (grad[:n] < 0.0)
|
| 841 |
+
free_xu = (xu > 0.0) | (grad[:n] > 0.0)
|
| 842 |
+
free_slack = bub < 0.0
|
| 843 |
+
free_ub = (bub > 0.0) | (aub @ grad[:n] - grad[n:] > 0.0)
|
| 844 |
+
n_act, q = qr_normal_byrd_omojokun(
|
| 845 |
+
aub,
|
| 846 |
+
free_xl,
|
| 847 |
+
free_xu,
|
| 848 |
+
free_slack,
|
| 849 |
+
free_ub,
|
| 850 |
+
)
|
| 851 |
+
|
| 852 |
+
# Calculate an upper bound on the norm of the slack variables. It is not
|
| 853 |
+
# used in the original algorithm, but it may prevent undesired behaviors
|
| 854 |
+
# engendered by computer rounding errors.
|
| 855 |
+
delta_slack = np.sqrt(beq @ beq + grad[n:] @ grad[n:])
|
| 856 |
+
|
| 857 |
+
# Set the initial iterate and the initial search direction.
|
| 858 |
+
step = np.zeros(n)
|
| 859 |
+
sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
|
| 860 |
+
resid = bub + grad[n:]
|
| 861 |
+
|
| 862 |
+
k = 0
|
| 863 |
+
reduct = 0.0
|
| 864 |
+
boundary_reached = False
|
| 865 |
+
while k < n + m_linear_ub - n_act:
|
| 866 |
+
# Stop the computations if sd is not a descent direction.
|
| 867 |
+
grad_sd = grad @ sd
|
| 868 |
+
if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
|
| 869 |
+
break
|
| 870 |
+
|
| 871 |
+
# Set alpha_tr to the step size for the trust-region constraint.
|
| 872 |
+
try:
|
| 873 |
+
alpha_tr = _alpha_tr(step, sd[:n], delta)
|
| 874 |
+
except ZeroDivisionError:
|
| 875 |
+
alpha_tr = np.inf
|
| 876 |
+
|
| 877 |
+
# Prevent undesired behaviors engendered by computer rounding errors by
|
| 878 |
+
# considering the trust-region constraint on the slack variables.
|
| 879 |
+
try:
|
| 880 |
+
alpha_tr = min(alpha_tr, _alpha_tr(grad[n:], sd[n:], delta_slack))
|
| 881 |
+
except ZeroDivisionError:
|
| 882 |
+
pass
|
| 883 |
+
|
| 884 |
+
# Stop the computations if a step along sd is expected to give a
|
| 885 |
+
# relatively small reduction in the objective function.
|
| 886 |
+
if -alpha_tr * grad_sd <= 1e-8 * reduct:
|
| 887 |
+
break
|
| 888 |
+
|
| 889 |
+
# Set alpha_quad to the step size for the minimization problem.
|
| 890 |
+
hess_sd = np.r_[aeq.T @ (aeq @ sd[:n]), sd[n:]]
|
| 891 |
+
curv_sd = sd @ hess_sd
|
| 892 |
+
if curv_sd > TINY * abs(grad_sd):
|
| 893 |
+
alpha_quad = max(-grad_sd / curv_sd, 0.0)
|
| 894 |
+
else:
|
| 895 |
+
alpha_quad = np.inf
|
| 896 |
+
|
| 897 |
+
# Stop the computations if the reduction in the objective function
|
| 898 |
+
# provided by an unconstrained step is small.
|
| 899 |
+
alpha = min(alpha_tr, alpha_quad)
|
| 900 |
+
if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
|
| 901 |
+
break
|
| 902 |
+
|
| 903 |
+
# Set alpha_bd to the step size for the bound constraints.
|
| 904 |
+
i_xl = free_xl & (xl > -np.inf) & (sd[:n] < -TINY * np.abs(xl - step))
|
| 905 |
+
i_xu = free_xu & (xu < np.inf) & (sd[:n] > TINY * np.abs(xu - step))
|
| 906 |
+
i_slack = free_slack & (sd[n:] < -TINY * np.abs(grad[n:]))
|
| 907 |
+
all_alpha_xl = np.full_like(step, np.inf)
|
| 908 |
+
all_alpha_xu = np.full_like(step, np.inf)
|
| 909 |
+
all_alpha_slack = np.full_like(bub, np.inf)
|
| 910 |
+
all_alpha_xl[i_xl] = np.maximum(
|
| 911 |
+
(xl[i_xl] - step[i_xl]) / sd[:n][i_xl],
|
| 912 |
+
0.0,
|
| 913 |
+
)
|
| 914 |
+
all_alpha_xu[i_xu] = np.maximum(
|
| 915 |
+
(xu[i_xu] - step[i_xu]) / sd[:n][i_xu],
|
| 916 |
+
0.0,
|
| 917 |
+
)
|
| 918 |
+
all_alpha_slack[i_slack] = np.maximum(
|
| 919 |
+
-grad[n:][i_slack] / sd[n:][i_slack],
|
| 920 |
+
0.0,
|
| 921 |
+
)
|
| 922 |
+
alpha_xl = np.min(all_alpha_xl)
|
| 923 |
+
alpha_xu = np.min(all_alpha_xu)
|
| 924 |
+
alpha_slack = np.min(all_alpha_slack, initial=np.inf)
|
| 925 |
+
alpha_bd = min(alpha_xl, alpha_xu, alpha_slack)
|
| 926 |
+
|
| 927 |
+
# Set alpha_ub to the step size for the linear constraints.
|
| 928 |
+
aub_sd = aub @ sd[:n] - sd[n:]
|
| 929 |
+
i_ub = free_ub & (aub_sd > TINY * np.abs(resid))
|
| 930 |
+
all_alpha_ub = np.full_like(bub, np.inf)
|
| 931 |
+
all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub]
|
| 932 |
+
alpha_ub = np.min(all_alpha_ub, initial=np.inf)
|
| 933 |
+
|
| 934 |
+
# Update the iterate.
|
| 935 |
+
alpha = min(alpha, alpha_bd, alpha_ub)
|
| 936 |
+
if alpha > 0.0:
|
| 937 |
+
step = np.clip(step + alpha * sd[:n], xl, xu)
|
| 938 |
+
grad += alpha * hess_sd
|
| 939 |
+
resid = np.maximum(0.0, resid - alpha * aub_sd)
|
| 940 |
+
reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
|
| 941 |
+
|
| 942 |
+
if alpha < min(alpha_tr, alpha_bd, alpha_ub):
|
| 943 |
+
# The current iteration is a conjugate gradient iteration. Update
|
| 944 |
+
# the search direction so that it is conjugate (with respect to H)
|
| 945 |
+
# to all the previous search directions.
|
| 946 |
+
grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
|
| 947 |
+
beta = (grad_proj @ hess_sd) / curv_sd
|
| 948 |
+
sd = beta * sd - grad_proj
|
| 949 |
+
k += 1
|
| 950 |
+
elif alpha < alpha_tr:
|
| 951 |
+
# The iterate is restricted by a bound/linear constraint. Add this
|
| 952 |
+
# constraint to the active set, and restart the calculations.
|
| 953 |
+
if alpha_xl <= alpha:
|
| 954 |
+
i_new = np.argmin(all_alpha_xl)
|
| 955 |
+
step[i_new] = xl[i_new]
|
| 956 |
+
free_xl[i_new] = False
|
| 957 |
+
elif alpha_xu <= alpha:
|
| 958 |
+
i_new = np.argmin(all_alpha_xu)
|
| 959 |
+
step[i_new] = xu[i_new]
|
| 960 |
+
free_xu[i_new] = False
|
| 961 |
+
elif alpha_slack <= alpha:
|
| 962 |
+
i_new = np.argmin(all_alpha_slack)
|
| 963 |
+
free_slack[i_new] = False
|
| 964 |
+
else:
|
| 965 |
+
i_new = np.argmin(all_alpha_ub)
|
| 966 |
+
free_ub[i_new] = False
|
| 967 |
+
n_act, q = qr_normal_byrd_omojokun(
|
| 968 |
+
aub, free_xl, free_xu, free_slack, free_ub
|
| 969 |
+
)
|
| 970 |
+
sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
|
| 971 |
+
k = 0
|
| 972 |
+
else:
|
| 973 |
+
# The current iterate is on the trust-region boundary. Add all the
|
| 974 |
+
# active bound constraints to the working set to prepare for the
|
| 975 |
+
# improvement of the solution, and stop the iterations.
|
| 976 |
+
if alpha_xl <= alpha:
|
| 977 |
+
i_new = _argmin(all_alpha_xl)
|
| 978 |
+
step[i_new] = xl[i_new]
|
| 979 |
+
free_xl[i_new] = False
|
| 980 |
+
if alpha_xu <= alpha:
|
| 981 |
+
i_new = _argmin(all_alpha_xu)
|
| 982 |
+
step[i_new] = xu[i_new]
|
| 983 |
+
free_xu[i_new] = False
|
| 984 |
+
boundary_reached = True
|
| 985 |
+
break
|
| 986 |
+
|
| 987 |
+
# Attempt to improve the solution on the trust-region boundary.
|
| 988 |
+
if kwargs.get("improve_tcg", True) and boundary_reached:
|
| 989 |
+
step_base = np.copy(step)
|
| 990 |
+
free_bd = free_xl & free_xu
|
| 991 |
+
grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ (
|
| 992 |
+
aeq @ step - beq
|
| 993 |
+
)
|
| 994 |
+
sd = np.zeros(n)
|
| 995 |
+
while np.count_nonzero(free_bd) > 0:
|
| 996 |
+
# Check whether a substantial reduction in the objective function
|
| 997 |
+
# is possible, and set the search direction.
|
| 998 |
+
step_sq = step[free_bd] @ step[free_bd]
|
| 999 |
+
grad_sq = grad[free_bd] @ grad[free_bd]
|
| 1000 |
+
grad_step = grad[free_bd] @ step[free_bd]
|
| 1001 |
+
grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
|
| 1002 |
+
sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd]
|
| 1003 |
+
sd[~free_bd] = 0.0
|
| 1004 |
+
if grad_sd >= -1e-8 * reduct or np.any(
|
| 1005 |
+
grad_sd >= -TINY * np.abs(sd[free_bd])
|
| 1006 |
+
):
|
| 1007 |
+
break
|
| 1008 |
+
sd[free_bd] /= -grad_sd
|
| 1009 |
+
|
| 1010 |
+
# Calculate an upper bound for the tangent of half the angle theta
|
| 1011 |
+
# of this alternative iteration. The step will be updated as:
|
| 1012 |
+
# step = cos(theta) * step + sin(theta) * sd.
|
| 1013 |
+
temp_xl = np.zeros(n)
|
| 1014 |
+
temp_xu = np.zeros(n)
|
| 1015 |
+
temp_xl[free_bd] = (
|
| 1016 |
+
step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0
|
| 1017 |
+
)
|
| 1018 |
+
temp_xu[free_bd] = (
|
| 1019 |
+
step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0
|
| 1020 |
+
)
|
| 1021 |
+
temp_xl[temp_xl > 0.0] = (
|
| 1022 |
+
np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
|
| 1023 |
+
)
|
| 1024 |
+
temp_xu[temp_xu > 0.0] = (
|
| 1025 |
+
np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
|
| 1026 |
+
)
|
| 1027 |
+
dist_xl = np.maximum(step - xl, 0.0)
|
| 1028 |
+
dist_xu = np.maximum(xu - step, 0.0)
|
| 1029 |
+
i_xl = temp_xl > TINY * dist_xl
|
| 1030 |
+
i_xu = temp_xu > TINY * dist_xu
|
| 1031 |
+
all_t_xl = np.ones(n)
|
| 1032 |
+
all_t_xu = np.ones(n)
|
| 1033 |
+
all_t_xl[i_xl] = np.minimum(
|
| 1034 |
+
all_t_xl[i_xl],
|
| 1035 |
+
dist_xl[i_xl] / temp_xl[i_xl],
|
| 1036 |
+
)
|
| 1037 |
+
all_t_xu[i_xu] = np.minimum(
|
| 1038 |
+
all_t_xu[i_xu],
|
| 1039 |
+
dist_xu[i_xu] / temp_xu[i_xu],
|
| 1040 |
+
)
|
| 1041 |
+
t_xl = np.min(all_t_xl)
|
| 1042 |
+
t_xu = np.min(all_t_xu)
|
| 1043 |
+
t_bd = min(t_xl, t_xu)
|
| 1044 |
+
|
| 1045 |
+
# For a range of equally spaced values of tan(0.5 * theta),
|
| 1046 |
+
# calculate the reduction in the objective function that would be
|
| 1047 |
+
# obtained by accepting the corresponding angle.
|
| 1048 |
+
n_samples = 20
|
| 1049 |
+
n_samples = int((n_samples - 3) * t_bd + 3)
|
| 1050 |
+
t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples)
|
| 1051 |
+
resid_ub = np.maximum(aub @ step - bub, 0.0)
|
| 1052 |
+
resid_eq = aeq @ step - beq
|
| 1053 |
+
step_proj = np.copy(step)
|
| 1054 |
+
step_proj[~free_bd] = 0.0
|
| 1055 |
+
all_reduct = np.empty(n_samples)
|
| 1056 |
+
for i in range(n_samples):
|
| 1057 |
+
sin_value = 2.0 * t_samples[i] / (1.0 + t_samples[i] ** 2.0)
|
| 1058 |
+
step_alt = np.clip(
|
| 1059 |
+
step + sin_value * (sd - t_samples[i] * step_proj),
|
| 1060 |
+
xl,
|
| 1061 |
+
xu,
|
| 1062 |
+
)
|
| 1063 |
+
resid_ub_alt = np.maximum(aub @ step_alt - bub, 0.0)
|
| 1064 |
+
resid_eq_alt = aeq @ step_alt - beq
|
| 1065 |
+
all_reduct[i] = 0.5 * (
|
| 1066 |
+
resid_ub @ resid_ub
|
| 1067 |
+
+ resid_eq @ resid_eq
|
| 1068 |
+
- resid_ub_alt @ resid_ub_alt
|
| 1069 |
+
- resid_eq_alt @ resid_eq_alt
|
| 1070 |
+
)
|
| 1071 |
+
if np.all(all_reduct <= 0.0):
|
| 1072 |
+
# No reduction in the objective function is obtained.
|
| 1073 |
+
break
|
| 1074 |
+
|
| 1075 |
+
# Accept the angle that provides the largest reduction in the
|
| 1076 |
+
# objective function, and update the iterate.
|
| 1077 |
+
i_max = np.argmax(all_reduct)
|
| 1078 |
+
cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
|
| 1079 |
+
1.0 + t_samples[i_max] ** 2.0
|
| 1080 |
+
)
|
| 1081 |
+
sin_value = (2.0 * t_samples[i_max]
|
| 1082 |
+
/ (1.0 + t_samples[i_max] ** 2.0))
|
| 1083 |
+
step[free_bd] = cos_value * step[free_bd] + sin_value * sd[free_bd]
|
| 1084 |
+
grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ (
|
| 1085 |
+
aeq @ step - beq
|
| 1086 |
+
)
|
| 1087 |
+
reduct += all_reduct[i_max]
|
| 1088 |
+
|
| 1089 |
+
# If the above angle is restricted by bound constraints, add them
|
| 1090 |
+
# to the working set, and restart the alternative iteration.
|
| 1091 |
+
# Otherwise, the calculations are terminated.
|
| 1092 |
+
if t_bd < 1.0 and i_max == n_samples - 1:
|
| 1093 |
+
if t_xl <= t_bd:
|
| 1094 |
+
i_new = _argmin(all_t_xl)
|
| 1095 |
+
step[i_new] = xl[i_new]
|
| 1096 |
+
free_bd[i_new] = False
|
| 1097 |
+
if t_xu <= t_bd:
|
| 1098 |
+
i_new = _argmin(all_t_xu)
|
| 1099 |
+
step[i_new] = xu[i_new]
|
| 1100 |
+
free_bd[i_new] = False
|
| 1101 |
+
else:
|
| 1102 |
+
break
|
| 1103 |
+
|
| 1104 |
+
# Ensure that the alternative iteration improves the objective
|
| 1105 |
+
# function.
|
| 1106 |
+
resid_ub = np.maximum(aub @ step - bub, 0.0)
|
| 1107 |
+
resid_ub_base = np.maximum(aub @ step_base - bub, 0.0)
|
| 1108 |
+
resid_eq = aeq @ step - beq
|
| 1109 |
+
resid_eq_base = aeq @ step_base - beq
|
| 1110 |
+
if (
|
| 1111 |
+
resid_ub @ resid_ub + resid_eq @ resid_eq
|
| 1112 |
+
> resid_ub_base @ resid_ub_base + resid_eq_base @ resid_eq_base
|
| 1113 |
+
):
|
| 1114 |
+
step = step_base
|
| 1115 |
+
|
| 1116 |
+
if debug:
|
| 1117 |
+
assert np.all(xl <= step)
|
| 1118 |
+
assert np.all(step <= xu)
|
| 1119 |
+
assert np.linalg.norm(step) < 1.1 * delta
|
| 1120 |
+
return step
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
def qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub):
|
| 1124 |
+
n = free_xl.size
|
| 1125 |
+
identity = np.eye(n)
|
| 1126 |
+
q, r, _ = qr(
|
| 1127 |
+
np.block(
|
| 1128 |
+
[
|
| 1129 |
+
[aeq],
|
| 1130 |
+
[aub[~free_ub, :]],
|
| 1131 |
+
[-identity[~free_xl, :]],
|
| 1132 |
+
[identity[~free_xu, :]],
|
| 1133 |
+
]
|
| 1134 |
+
).T,
|
| 1135 |
+
pivoting=True,
|
| 1136 |
+
)
|
| 1137 |
+
n_act = np.count_nonzero(
|
| 1138 |
+
np.abs(np.diag(r))
|
| 1139 |
+
>= 10.0
|
| 1140 |
+
* EPS
|
| 1141 |
+
* n
|
| 1142 |
+
* np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0)
|
| 1143 |
+
)
|
| 1144 |
+
return n_act, q
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
def qr_normal_byrd_omojokun(aub, free_xl, free_xu, free_slack, free_ub):
|
| 1148 |
+
m_linear_ub, n = aub.shape
|
| 1149 |
+
identity_n = np.eye(n)
|
| 1150 |
+
identity_m = np.eye(m_linear_ub)
|
| 1151 |
+
q, r, _ = qr(
|
| 1152 |
+
np.block(
|
| 1153 |
+
[
|
| 1154 |
+
[
|
| 1155 |
+
aub[~free_ub, :],
|
| 1156 |
+
-identity_m[~free_ub, :],
|
| 1157 |
+
],
|
| 1158 |
+
[
|
| 1159 |
+
np.zeros((m_linear_ub - np.count_nonzero(free_slack), n)),
|
| 1160 |
+
-identity_m[~free_slack, :],
|
| 1161 |
+
],
|
| 1162 |
+
[
|
| 1163 |
+
-identity_n[~free_xl, :],
|
| 1164 |
+
np.zeros((n - np.count_nonzero(free_xl), m_linear_ub)),
|
| 1165 |
+
],
|
| 1166 |
+
[
|
| 1167 |
+
identity_n[~free_xu, :],
|
| 1168 |
+
np.zeros((n - np.count_nonzero(free_xu), m_linear_ub)),
|
| 1169 |
+
],
|
| 1170 |
+
]
|
| 1171 |
+
).T,
|
| 1172 |
+
pivoting=True,
|
| 1173 |
+
)
|
| 1174 |
+
n_act = np.count_nonzero(
|
| 1175 |
+
np.abs(np.diag(r))
|
| 1176 |
+
>= 10.0
|
| 1177 |
+
* EPS
|
| 1178 |
+
* (n + m_linear_ub)
|
| 1179 |
+
* np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0)
|
| 1180 |
+
)
|
| 1181 |
+
return n_act, q
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
def _alpha_tr(step, sd, delta):
|
| 1185 |
+
step_sd = step @ sd
|
| 1186 |
+
sd_sq = sd @ sd
|
| 1187 |
+
dist_tr_sq = delta**2.0 - step @ step
|
| 1188 |
+
temp = np.sqrt(max(step_sd**2.0 + sd_sq * dist_tr_sq, 0.0))
|
| 1189 |
+
if step_sd <= 0.0 and sd_sq > TINY * abs(temp - step_sd):
|
| 1190 |
+
alpha_tr = max((temp - step_sd) / sd_sq, 0.0)
|
| 1191 |
+
elif abs(temp + step_sd) > TINY * dist_tr_sq:
|
| 1192 |
+
alpha_tr = max(dist_tr_sq / (temp + step_sd), 0.0)
|
| 1193 |
+
else:
|
| 1194 |
+
raise ZeroDivisionError
|
| 1195 |
+
return alpha_tr
|
| 1196 |
+
|
| 1197 |
+
|
| 1198 |
+
def _argmax(x):
|
| 1199 |
+
return np.flatnonzero(x >= np.max(x))
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
def _argmin(x):
|
| 1203 |
+
return np.flatnonzero(x <= np.min(x))
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .exceptions import (
|
| 2 |
+
MaxEvalError,
|
| 3 |
+
TargetSuccess,
|
| 4 |
+
CallbackSuccess,
|
| 5 |
+
FeasibleSuccess,
|
| 6 |
+
)
|
| 7 |
+
from .math import get_arrays_tol, exact_1d_array
|
| 8 |
+
from .versions import show_versions
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"MaxEvalError",
|
| 12 |
+
"TargetSuccess",
|
| 13 |
+
"CallbackSuccess",
|
| 14 |
+
"FeasibleSuccess",
|
| 15 |
+
"get_arrays_tol",
|
| 16 |
+
"exact_1d_array",
|
| 17 |
+
"show_versions",
|
| 18 |
+
]
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (665 Bytes). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-311.pyc
ADDED
|
Binary file (1.41 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/math.cpython-311.pyc
ADDED
|
Binary file (3.25 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/__pycache__/versions.cpython-311.pyc
ADDED
|
Binary file (3.39 kB). View file
|
|
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/exceptions.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class MaxEvalError(Exception):
|
| 2 |
+
"""
|
| 3 |
+
Exception raised when the maximum number of evaluations is reached.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TargetSuccess(Exception):
|
| 8 |
+
"""
|
| 9 |
+
Exception raised when the target value is reached.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CallbackSuccess(StopIteration):
|
| 14 |
+
"""
|
| 15 |
+
Exception raised when the callback function raises a ``StopIteration``.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FeasibleSuccess(Exception):
|
| 20 |
+
"""
|
| 21 |
+
Exception raised when a feasible point of a feasible problem is found.
|
| 22 |
+
"""
|
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/cobyqa/utils/math.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
EPS = np.finfo(float).eps
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def get_arrays_tol(*arrays):
|
| 8 |
+
"""
|
| 9 |
+
Get a relative tolerance for a set of arrays.
|
| 10 |
+
|
| 11 |
+
Parameters
|
| 12 |
+
----------
|
| 13 |
+
*arrays: tuple
|
| 14 |
+
Set of `numpy.ndarray` to get the tolerance for.
|
| 15 |
+
|
| 16 |
+
Returns
|
| 17 |
+
-------
|
| 18 |
+
float
|
| 19 |
+
Relative tolerance for the set of arrays.
|
| 20 |
+
|
| 21 |
+
Raises
|
| 22 |
+
------
|
| 23 |
+
ValueError
|
| 24 |
+
If no array is provided.
|
| 25 |
+
"""
|
| 26 |
+
if len(arrays) == 0:
|
| 27 |
+
raise ValueError("At least one array must be provided.")
|
| 28 |
+
size = max(array.size for array in arrays)
|
| 29 |
+
weight = max(
|
| 30 |
+
np.max(np.abs(array[np.isfinite(array)]), initial=1.0)
|
| 31 |
+
for array in arrays
|
| 32 |
+
)
|
| 33 |
+
return 10.0 * EPS * max(size, 1.0) * weight
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def exact_1d_array(x, message):
|
| 37 |
+
"""
|
| 38 |
+
Preprocess a 1-dimensional array.
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
x : array_like
|
| 43 |
+
Array to be preprocessed.
|
| 44 |
+
message : str
|
| 45 |
+
Error message if `x` cannot be interpreter as a 1-dimensional array.
|
| 46 |
+
|
| 47 |
+
Returns
|
| 48 |
+
-------
|
| 49 |
+
`numpy.ndarray`
|
| 50 |
+
Preprocessed array.
|
| 51 |
+
"""
|
| 52 |
+
x = np.atleast_1d(np.squeeze(x)).astype(float)
|
| 53 |
+
if x.ndim != 1:
|
| 54 |
+
raise ValueError(message)
|
| 55 |
+
return x
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def exact_2d_array(x, message):
|
| 59 |
+
"""
|
| 60 |
+
Preprocess a 2-dimensional array.
|
| 61 |
+
|
| 62 |
+
Parameters
|
| 63 |
+
----------
|
| 64 |
+
x : array_like
|
| 65 |
+
Array to be preprocessed.
|
| 66 |
+
message : str
|
| 67 |
+
Error message if `x` cannot be interpreter as a 2-dimensional array.
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
`numpy.ndarray`
|
| 72 |
+
Preprocessed array.
|
| 73 |
+
"""
|
| 74 |
+
x = np.atleast_2d(x).astype(float)
|
| 75 |
+
if x.ndim != 2:
|
| 76 |
+
raise ValueError(message)
|
| 77 |
+
return x
|