Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_docs_tables.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_no_0d.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_gcutils.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_public_api.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_tmpdirs.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/_uarray/LICENSE +29 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/_uarray/__init__.py +116 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/_uarray/_backend.py +707 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_compat/__init__.py +22 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_compat/_internal.py +77 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_extra/__init__.py +53 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_extra/_delegation.py +1028 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_extra/testing.py +415 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__init__.py +20 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/framework.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/main.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/models.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/problem.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/settings.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/framework.py +1240 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/main.py +1506 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/models.py +1531 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/problem.py +1296 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/settings.py +132 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py +14 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py +387 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py +1203 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/utils/__init__.py +18 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-312.pyc +0 -0
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (584 Bytes). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc
ADDED
|
Binary file (38.2 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc
ADDED
|
Binary file (352 Bytes). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_docs_tables.cpython-312.pyc
ADDED
|
Binary file (9.78 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_no_0d.cpython-312.pyc
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc
ADDED
|
Binary file (5.7 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_bunch.cpython-312.pyc
ADDED
|
Binary file (9.04 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc
ADDED
|
Binary file (9.42 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-312.pyc
ADDED
|
Binary file (8.32 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc
ADDED
|
Binary file (32.6 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc
ADDED
|
Binary file (14.9 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_gcutils.cpython-312.pyc
ADDED
|
Binary file (3.62 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_pep440.cpython-312.pyc
ADDED
|
Binary file (18.8 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_public_api.cpython-312.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc
ADDED
|
Binary file (1.33 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc
ADDED
|
Binary file (16.4 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_tmpdirs.cpython-312.pyc
ADDED
|
Binary file (3.23 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc
ADDED
|
Binary file (56.2 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/doccer.cpython-312.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc
ADDED
|
Binary file (940 Bytes). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/_uarray/LICENSE
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BSD 3-Clause License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2018, Quansight-Labs
|
| 4 |
+
All rights reserved.
|
| 5 |
+
|
| 6 |
+
Redistribution and use in source and binary forms, with or without
|
| 7 |
+
modification, are permitted provided that the following conditions are met:
|
| 8 |
+
|
| 9 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 10 |
+
list of conditions and the following disclaimer.
|
| 11 |
+
|
| 12 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 13 |
+
this list of conditions and the following disclaimer in the documentation
|
| 14 |
+
and/or other materials provided with the distribution.
|
| 15 |
+
|
| 16 |
+
* Neither the name of the copyright holder nor the names of its
|
| 17 |
+
contributors may be used to endorse or promote products derived from
|
| 18 |
+
this software without specific prior written permission.
|
| 19 |
+
|
| 20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 21 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 22 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 23 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 24 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 25 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 26 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 27 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 28 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 29 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/_uarray/__init__.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
.. note:
|
| 3 |
+
If you are looking for overrides for NumPy-specific methods, see the
|
| 4 |
+
documentation for :obj:`unumpy`. This page explains how to write
|
| 5 |
+
back-ends and multimethods.
|
| 6 |
+
|
| 7 |
+
``uarray`` is built around a back-end protocol, and overridable multimethods.
|
| 8 |
+
It is necessary to define multimethods for back-ends to be able to override them.
|
| 9 |
+
See the documentation of :obj:`generate_multimethod` on how to write multimethods.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
Let's start with the simplest:
|
| 14 |
+
|
| 15 |
+
``__ua_domain__`` defines the back-end *domain*. The domain consists of period-
|
| 16 |
+
separated string consisting of the modules you extend plus the submodule. For
|
| 17 |
+
example, if a submodule ``module2.submodule`` extends ``module1``
|
| 18 |
+
(i.e., it exposes dispatchables marked as types available in ``module1``),
|
| 19 |
+
then the domain string should be ``"module1.module2.submodule"``.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
For the purpose of this demonstration, we'll be creating an object and setting
|
| 23 |
+
its attributes directly. However, note that you can use a module or your own type
|
| 24 |
+
as a backend as well.
|
| 25 |
+
|
| 26 |
+
>>> class Backend: pass
|
| 27 |
+
>>> be = Backend()
|
| 28 |
+
>>> be.__ua_domain__ = "ua_examples"
|
| 29 |
+
|
| 30 |
+
It might be useful at this point to sidetrack to the documentation of
|
| 31 |
+
:obj:`generate_multimethod` to find out how to generate a multimethod
|
| 32 |
+
overridable by :obj:`uarray`. Needless to say, writing a backend and
|
| 33 |
+
creating multimethods are mostly orthogonal activities, and knowing
|
| 34 |
+
one doesn't necessarily require knowledge of the other, although it
|
| 35 |
+
is certainly helpful. We expect core API designers/specifiers to write the
|
| 36 |
+
multimethods, and implementors to override them. But, as is often the case,
|
| 37 |
+
similar people write both.
|
| 38 |
+
|
| 39 |
+
Without further ado, here's an example multimethod:
|
| 40 |
+
|
| 41 |
+
>>> import uarray as ua
|
| 42 |
+
>>> from uarray import Dispatchable
|
| 43 |
+
>>> def override_me(a, b):
|
| 44 |
+
... return Dispatchable(a, int),
|
| 45 |
+
>>> def override_replacer(args, kwargs, dispatchables):
|
| 46 |
+
... return (dispatchables[0], args[1]), {}
|
| 47 |
+
>>> overridden_me = ua.generate_multimethod(
|
| 48 |
+
... override_me, override_replacer, "ua_examples"
|
| 49 |
+
... )
|
| 50 |
+
|
| 51 |
+
Next comes the part about overriding the multimethod. This requires
|
| 52 |
+
the ``__ua_function__`` protocol, and the ``__ua_convert__``
|
| 53 |
+
protocol. The ``__ua_function__`` protocol has the signature
|
| 54 |
+
``(method, args, kwargs)`` where ``method`` is the passed
|
| 55 |
+
multimethod, ``args``/``kwargs`` specify the arguments and ``dispatchables``
|
| 56 |
+
is the list of converted dispatchables passed in.
|
| 57 |
+
|
| 58 |
+
>>> def __ua_function__(method, args, kwargs):
|
| 59 |
+
... return method.__name__, args, kwargs
|
| 60 |
+
>>> be.__ua_function__ = __ua_function__
|
| 61 |
+
|
| 62 |
+
The other protocol of interest is the ``__ua_convert__`` protocol. It has the
|
| 63 |
+
signature ``(dispatchables, coerce)``. When ``coerce`` is ``False``, conversion
|
| 64 |
+
between the formats should ideally be an ``O(1)`` operation, but it means that
|
| 65 |
+
no memory copying should be involved, only views of the existing data.
|
| 66 |
+
|
| 67 |
+
>>> def __ua_convert__(dispatchables, coerce):
|
| 68 |
+
... for d in dispatchables:
|
| 69 |
+
... if d.type is int:
|
| 70 |
+
... if coerce and d.coercible:
|
| 71 |
+
... yield str(d.value)
|
| 72 |
+
... else:
|
| 73 |
+
... yield d.value
|
| 74 |
+
>>> be.__ua_convert__ = __ua_convert__
|
| 75 |
+
|
| 76 |
+
Now that we have defined the backend, the next thing to do is to call the multimethod.
|
| 77 |
+
|
| 78 |
+
>>> with ua.set_backend(be):
|
| 79 |
+
... overridden_me(1, "2")
|
| 80 |
+
('override_me', (1, '2'), {})
|
| 81 |
+
|
| 82 |
+
Note that the marked type has no effect on the actual type of the passed object.
|
| 83 |
+
We can also coerce the type of the input.
|
| 84 |
+
|
| 85 |
+
>>> with ua.set_backend(be, coerce=True):
|
| 86 |
+
... overridden_me(1, "2")
|
| 87 |
+
... overridden_me(1.0, "2")
|
| 88 |
+
('override_me', ('1', '2'), {})
|
| 89 |
+
('override_me', ('1.0', '2'), {})
|
| 90 |
+
|
| 91 |
+
Another feature is that if you remove ``__ua_convert__``, the arguments are not
|
| 92 |
+
converted at all and it's up to the backend to handle that.
|
| 93 |
+
|
| 94 |
+
>>> del be.__ua_convert__
|
| 95 |
+
>>> with ua.set_backend(be):
|
| 96 |
+
... overridden_me(1, "2")
|
| 97 |
+
('override_me', (1, '2'), {})
|
| 98 |
+
|
| 99 |
+
You also have the option to return ``NotImplemented``, in which case processing moves on
|
| 100 |
+
to the next back-end, which in this case, doesn't exist. The same applies to
|
| 101 |
+
``__ua_convert__``.
|
| 102 |
+
|
| 103 |
+
>>> be.__ua_function__ = lambda *a, **kw: NotImplemented
|
| 104 |
+
>>> with ua.set_backend(be):
|
| 105 |
+
... overridden_me(1, "2")
|
| 106 |
+
Traceback (most recent call last):
|
| 107 |
+
...
|
| 108 |
+
uarray.BackendNotImplementedError: ...
|
| 109 |
+
|
| 110 |
+
The last possibility is if we don't have ``__ua_convert__``, in which case the job is
|
| 111 |
+
left up to ``__ua_function__``, but putting things back into arrays after conversion
|
| 112 |
+
will not be possible.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
from ._backend import *
|
| 116 |
+
__version__ = '0.8.8.dev0+aa94c5a4.scipy'
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/_uarray/_backend.py
ADDED
|
@@ -0,0 +1,707 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import typing
|
| 2 |
+
import types
|
| 3 |
+
import inspect
|
| 4 |
+
import functools
|
| 5 |
+
from . import _uarray
|
| 6 |
+
import copyreg
|
| 7 |
+
import pickle
|
| 8 |
+
import contextlib
|
| 9 |
+
import threading
|
| 10 |
+
|
| 11 |
+
from ._uarray import ( # type: ignore
|
| 12 |
+
BackendNotImplementedError,
|
| 13 |
+
_Function,
|
| 14 |
+
_SkipBackendContext,
|
| 15 |
+
_SetBackendContext,
|
| 16 |
+
_BackendState,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"set_backend",
|
| 21 |
+
"set_global_backend",
|
| 22 |
+
"skip_backend",
|
| 23 |
+
"register_backend",
|
| 24 |
+
"determine_backend",
|
| 25 |
+
"determine_backend_multi",
|
| 26 |
+
"clear_backends",
|
| 27 |
+
"create_multimethod",
|
| 28 |
+
"generate_multimethod",
|
| 29 |
+
"_Function",
|
| 30 |
+
"BackendNotImplementedError",
|
| 31 |
+
"Dispatchable",
|
| 32 |
+
"wrap_single_convertor",
|
| 33 |
+
"wrap_single_convertor_instance",
|
| 34 |
+
"all_of_type",
|
| 35 |
+
"mark_as",
|
| 36 |
+
"set_state",
|
| 37 |
+
"get_state",
|
| 38 |
+
"reset_state",
|
| 39 |
+
"_BackendState",
|
| 40 |
+
"_SkipBackendContext",
|
| 41 |
+
"_SetBackendContext",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
ArgumentExtractorType = typing.Callable[..., tuple["Dispatchable", ...]]
|
| 45 |
+
ArgumentReplacerType = typing.Callable[
|
| 46 |
+
[tuple, dict, tuple], tuple[tuple, dict]
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
def unpickle_function(mod_name, qname, self_):
|
| 50 |
+
import importlib
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
module = importlib.import_module(mod_name)
|
| 54 |
+
qname = qname.split(".")
|
| 55 |
+
func = module
|
| 56 |
+
for q in qname:
|
| 57 |
+
func = getattr(func, q)
|
| 58 |
+
|
| 59 |
+
if self_ is not None:
|
| 60 |
+
func = types.MethodType(func, self_)
|
| 61 |
+
|
| 62 |
+
return func
|
| 63 |
+
except (ImportError, AttributeError) as e:
|
| 64 |
+
from pickle import UnpicklingError
|
| 65 |
+
|
| 66 |
+
raise UnpicklingError from e
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def pickle_function(func):
|
| 70 |
+
mod_name = getattr(func, "__module__", None)
|
| 71 |
+
qname = getattr(func, "__qualname__", None)
|
| 72 |
+
self_ = getattr(func, "__self__", None)
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
test = unpickle_function(mod_name, qname, self_)
|
| 76 |
+
except pickle.UnpicklingError:
|
| 77 |
+
test = None
|
| 78 |
+
|
| 79 |
+
if test is not func:
|
| 80 |
+
raise pickle.PicklingError(
|
| 81 |
+
f"Can't pickle {func}: it's not the same object as {test}"
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
return unpickle_function, (mod_name, qname, self_)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def pickle_state(state):
|
| 88 |
+
return _uarray._BackendState._unpickle, state._pickle()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def pickle_set_backend_context(ctx):
|
| 92 |
+
return _SetBackendContext, ctx._pickle()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def pickle_skip_backend_context(ctx):
|
| 96 |
+
return _SkipBackendContext, ctx._pickle()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
copyreg.pickle(_Function, pickle_function)
|
| 100 |
+
copyreg.pickle(_uarray._BackendState, pickle_state)
|
| 101 |
+
copyreg.pickle(_SetBackendContext, pickle_set_backend_context)
|
| 102 |
+
copyreg.pickle(_SkipBackendContext, pickle_skip_backend_context)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def get_state():
|
| 106 |
+
"""
|
| 107 |
+
Returns an opaque object containing the current state of all the backends.
|
| 108 |
+
|
| 109 |
+
Can be used for synchronization between threads/processes.
|
| 110 |
+
|
| 111 |
+
See Also
|
| 112 |
+
--------
|
| 113 |
+
set_state
|
| 114 |
+
Sets the state returned by this function.
|
| 115 |
+
"""
|
| 116 |
+
return _uarray.get_state()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@contextlib.contextmanager
|
| 120 |
+
def reset_state():
|
| 121 |
+
"""
|
| 122 |
+
Returns a context manager that resets all state once exited.
|
| 123 |
+
|
| 124 |
+
See Also
|
| 125 |
+
--------
|
| 126 |
+
set_state
|
| 127 |
+
Context manager that sets the backend state.
|
| 128 |
+
get_state
|
| 129 |
+
Gets a state to be set by this context manager.
|
| 130 |
+
"""
|
| 131 |
+
with set_state(get_state()):
|
| 132 |
+
yield
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@contextlib.contextmanager
|
| 136 |
+
def set_state(state):
|
| 137 |
+
"""
|
| 138 |
+
A context manager that sets the state of the backends to one returned by :obj:`get_state`.
|
| 139 |
+
|
| 140 |
+
See Also
|
| 141 |
+
--------
|
| 142 |
+
get_state
|
| 143 |
+
Gets a state to be set by this context manager.
|
| 144 |
+
""" # noqa: E501
|
| 145 |
+
old_state = get_state()
|
| 146 |
+
_uarray.set_state(state)
|
| 147 |
+
try:
|
| 148 |
+
yield
|
| 149 |
+
finally:
|
| 150 |
+
_uarray.set_state(old_state, True)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def create_multimethod(*args, **kwargs):
|
| 154 |
+
"""
|
| 155 |
+
Creates a decorator for generating multimethods.
|
| 156 |
+
|
| 157 |
+
This function creates a decorator that can be used with an argument
|
| 158 |
+
extractor in order to generate a multimethod. Other than for the
|
| 159 |
+
argument extractor, all arguments are passed on to
|
| 160 |
+
:obj:`generate_multimethod`.
|
| 161 |
+
|
| 162 |
+
See Also
|
| 163 |
+
--------
|
| 164 |
+
generate_multimethod
|
| 165 |
+
Generates a multimethod.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def wrapper(a):
|
| 169 |
+
return generate_multimethod(a, *args, **kwargs)
|
| 170 |
+
|
| 171 |
+
return wrapper
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def generate_multimethod(
|
| 175 |
+
argument_extractor: ArgumentExtractorType,
|
| 176 |
+
argument_replacer: ArgumentReplacerType,
|
| 177 |
+
domain: str,
|
| 178 |
+
default: typing.Callable | None = None,
|
| 179 |
+
):
|
| 180 |
+
"""
|
| 181 |
+
Generates a multimethod.
|
| 182 |
+
|
| 183 |
+
Parameters
|
| 184 |
+
----------
|
| 185 |
+
argument_extractor : ArgumentExtractorType
|
| 186 |
+
A callable which extracts the dispatchable arguments. Extracted arguments
|
| 187 |
+
should be marked by the :obj:`Dispatchable` class. It has the same signature
|
| 188 |
+
as the desired multimethod.
|
| 189 |
+
argument_replacer : ArgumentReplacerType
|
| 190 |
+
A callable with the signature (args, kwargs, dispatchables), which should also
|
| 191 |
+
return an (args, kwargs) pair with the dispatchables replaced inside the
|
| 192 |
+
args/kwargs.
|
| 193 |
+
domain : str
|
| 194 |
+
A string value indicating the domain of this multimethod.
|
| 195 |
+
default: Optional[Callable], optional
|
| 196 |
+
The default implementation of this multimethod, where ``None`` (the default)
|
| 197 |
+
specifies there is no default implementation.
|
| 198 |
+
|
| 199 |
+
Examples
|
| 200 |
+
--------
|
| 201 |
+
In this example, ``a`` is to be dispatched over, so we return it, while marking it
|
| 202 |
+
as an ``int``.
|
| 203 |
+
The trailing comma is needed because the args have to be returned as an iterable.
|
| 204 |
+
|
| 205 |
+
>>> def override_me(a, b):
|
| 206 |
+
... return Dispatchable(a, int),
|
| 207 |
+
|
| 208 |
+
Next, we define the argument replacer that replaces the dispatchables inside
|
| 209 |
+
args/kwargs with the supplied ones.
|
| 210 |
+
|
| 211 |
+
>>> def override_replacer(args, kwargs, dispatchables):
|
| 212 |
+
... return (dispatchables[0], args[1]), {}
|
| 213 |
+
|
| 214 |
+
Next, we define the multimethod.
|
| 215 |
+
|
| 216 |
+
>>> overridden_me = generate_multimethod(
|
| 217 |
+
... override_me, override_replacer, "ua_examples"
|
| 218 |
+
... )
|
| 219 |
+
|
| 220 |
+
Notice that there's no default implementation, unless you supply one.
|
| 221 |
+
|
| 222 |
+
>>> overridden_me(1, "a")
|
| 223 |
+
Traceback (most recent call last):
|
| 224 |
+
...
|
| 225 |
+
uarray.BackendNotImplementedError: ...
|
| 226 |
+
|
| 227 |
+
>>> overridden_me2 = generate_multimethod(
|
| 228 |
+
... override_me, override_replacer, "ua_examples", default=lambda x, y: (x, y)
|
| 229 |
+
... )
|
| 230 |
+
>>> overridden_me2(1, "a")
|
| 231 |
+
(1, 'a')
|
| 232 |
+
|
| 233 |
+
See Also
|
| 234 |
+
--------
|
| 235 |
+
uarray
|
| 236 |
+
See the module documentation for how to override the method by creating
|
| 237 |
+
backends.
|
| 238 |
+
"""
|
| 239 |
+
kw_defaults, arg_defaults, opts = get_defaults(argument_extractor)
|
| 240 |
+
ua_func = _Function(
|
| 241 |
+
argument_extractor,
|
| 242 |
+
argument_replacer,
|
| 243 |
+
domain,
|
| 244 |
+
arg_defaults,
|
| 245 |
+
kw_defaults,
|
| 246 |
+
default,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
return functools.update_wrapper(ua_func, argument_extractor)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def set_backend(backend, coerce=False, only=False):
|
| 253 |
+
"""
|
| 254 |
+
A context manager that sets the preferred backend.
|
| 255 |
+
|
| 256 |
+
Parameters
|
| 257 |
+
----------
|
| 258 |
+
backend
|
| 259 |
+
The backend to set.
|
| 260 |
+
coerce
|
| 261 |
+
Whether or not to coerce to a specific backend's types. Implies ``only``.
|
| 262 |
+
only
|
| 263 |
+
Whether or not this should be the last backend to try.
|
| 264 |
+
|
| 265 |
+
See Also
|
| 266 |
+
--------
|
| 267 |
+
skip_backend: A context manager that allows skipping of backends.
|
| 268 |
+
set_global_backend: Set a single, global backend for a domain.
|
| 269 |
+
"""
|
| 270 |
+
tid = threading.get_native_id()
|
| 271 |
+
try:
|
| 272 |
+
return backend.__ua_cache__[tid, "set", coerce, only]
|
| 273 |
+
except AttributeError:
|
| 274 |
+
backend.__ua_cache__ = {}
|
| 275 |
+
except KeyError:
|
| 276 |
+
pass
|
| 277 |
+
|
| 278 |
+
ctx = _SetBackendContext(backend, coerce, only)
|
| 279 |
+
backend.__ua_cache__[tid, "set", coerce, only] = ctx
|
| 280 |
+
return ctx
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def skip_backend(backend):
|
| 284 |
+
"""
|
| 285 |
+
A context manager that allows one to skip a given backend from processing
|
| 286 |
+
entirely. This allows one to use another backend's code in a library that
|
| 287 |
+
is also a consumer of the same backend.
|
| 288 |
+
|
| 289 |
+
Parameters
|
| 290 |
+
----------
|
| 291 |
+
backend
|
| 292 |
+
The backend to skip.
|
| 293 |
+
|
| 294 |
+
See Also
|
| 295 |
+
--------
|
| 296 |
+
set_backend: A context manager that allows setting of backends.
|
| 297 |
+
set_global_backend: Set a single, global backend for a domain.
|
| 298 |
+
"""
|
| 299 |
+
tid = threading.get_native_id()
|
| 300 |
+
try:
|
| 301 |
+
return backend.__ua_cache__[tid, "skip"]
|
| 302 |
+
except AttributeError:
|
| 303 |
+
backend.__ua_cache__ = {}
|
| 304 |
+
except KeyError:
|
| 305 |
+
pass
|
| 306 |
+
|
| 307 |
+
ctx = _SkipBackendContext(backend)
|
| 308 |
+
backend.__ua_cache__[tid, "skip"] = ctx
|
| 309 |
+
return ctx
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def get_defaults(f):
|
| 313 |
+
sig = inspect.signature(f)
|
| 314 |
+
kw_defaults = {}
|
| 315 |
+
arg_defaults = []
|
| 316 |
+
opts = set()
|
| 317 |
+
for k, v in sig.parameters.items():
|
| 318 |
+
if v.default is not inspect.Parameter.empty:
|
| 319 |
+
kw_defaults[k] = v.default
|
| 320 |
+
if v.kind in (
|
| 321 |
+
inspect.Parameter.POSITIONAL_ONLY,
|
| 322 |
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 323 |
+
):
|
| 324 |
+
arg_defaults.append(v.default)
|
| 325 |
+
opts.add(k)
|
| 326 |
+
|
| 327 |
+
return kw_defaults, tuple(arg_defaults), opts
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def set_global_backend(backend, coerce=False, only=False, *, try_last=False):
|
| 331 |
+
"""
|
| 332 |
+
This utility method replaces the default backend for permanent use. It
|
| 333 |
+
will be tried in the list of backends automatically, unless the
|
| 334 |
+
``only`` flag is set on a backend. This will be the first tried
|
| 335 |
+
backend outside the :obj:`set_backend` context manager.
|
| 336 |
+
|
| 337 |
+
Note that this method is not thread-safe.
|
| 338 |
+
|
| 339 |
+
.. warning::
|
| 340 |
+
We caution library authors against using this function in
|
| 341 |
+
their code. We do *not* support this use-case. This function
|
| 342 |
+
is meant to be used only by users themselves, or by a reference
|
| 343 |
+
implementation, if one exists.
|
| 344 |
+
|
| 345 |
+
Parameters
|
| 346 |
+
----------
|
| 347 |
+
backend
|
| 348 |
+
The backend to register.
|
| 349 |
+
coerce : bool
|
| 350 |
+
Whether to coerce input types when trying this backend.
|
| 351 |
+
only : bool
|
| 352 |
+
If ``True``, no more backends will be tried if this fails.
|
| 353 |
+
Implied by ``coerce=True``.
|
| 354 |
+
try_last : bool
|
| 355 |
+
If ``True``, the global backend is tried after registered backends.
|
| 356 |
+
|
| 357 |
+
See Also
|
| 358 |
+
--------
|
| 359 |
+
set_backend: A context manager that allows setting of backends.
|
| 360 |
+
skip_backend: A context manager that allows skipping of backends.
|
| 361 |
+
"""
|
| 362 |
+
_uarray.set_global_backend(backend, coerce, only, try_last)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def register_backend(backend):
|
| 366 |
+
"""
|
| 367 |
+
This utility method sets registers backend for permanent use. It
|
| 368 |
+
will be tried in the list of backends automatically, unless the
|
| 369 |
+
``only`` flag is set on a backend.
|
| 370 |
+
|
| 371 |
+
Note that this method is not thread-safe.
|
| 372 |
+
|
| 373 |
+
Parameters
|
| 374 |
+
----------
|
| 375 |
+
backend
|
| 376 |
+
The backend to register.
|
| 377 |
+
"""
|
| 378 |
+
_uarray.register_backend(backend)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def clear_backends(domain, registered=True, globals=False):
|
| 382 |
+
"""
|
| 383 |
+
This utility method clears registered backends.
|
| 384 |
+
|
| 385 |
+
.. warning::
|
| 386 |
+
We caution library authors against using this function in
|
| 387 |
+
their code. We do *not* support this use-case. This function
|
| 388 |
+
is meant to be used only by users themselves.
|
| 389 |
+
|
| 390 |
+
.. warning::
|
| 391 |
+
Do NOT use this method inside a multimethod call, or the
|
| 392 |
+
program is likely to crash.
|
| 393 |
+
|
| 394 |
+
Parameters
|
| 395 |
+
----------
|
| 396 |
+
domain : Optional[str]
|
| 397 |
+
The domain for which to de-register backends. ``None`` means
|
| 398 |
+
de-register for all domains.
|
| 399 |
+
registered : bool
|
| 400 |
+
Whether or not to clear registered backends. See :obj:`register_backend`.
|
| 401 |
+
globals : bool
|
| 402 |
+
Whether or not to clear global backends. See :obj:`set_global_backend`.
|
| 403 |
+
|
| 404 |
+
See Also
|
| 405 |
+
--------
|
| 406 |
+
register_backend : Register a backend globally.
|
| 407 |
+
set_global_backend : Set a global backend.
|
| 408 |
+
"""
|
| 409 |
+
_uarray.clear_backends(domain, registered, globals)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class Dispatchable:
|
| 413 |
+
"""
|
| 414 |
+
A utility class which marks an argument with a specific dispatch type.
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
Attributes
|
| 418 |
+
----------
|
| 419 |
+
value
|
| 420 |
+
The value of the Dispatchable.
|
| 421 |
+
|
| 422 |
+
type
|
| 423 |
+
The type of the Dispatchable.
|
| 424 |
+
|
| 425 |
+
Examples
|
| 426 |
+
--------
|
| 427 |
+
>>> x = Dispatchable(1, str)
|
| 428 |
+
>>> x
|
| 429 |
+
<Dispatchable: type=<class 'str'>, value=1>
|
| 430 |
+
|
| 431 |
+
See Also
|
| 432 |
+
--------
|
| 433 |
+
all_of_type
|
| 434 |
+
Marks all unmarked parameters of a function.
|
| 435 |
+
|
| 436 |
+
mark_as
|
| 437 |
+
Allows one to create a utility function to mark as a given type.
|
| 438 |
+
"""
|
| 439 |
+
|
| 440 |
+
def __init__(self, value, dispatch_type, coercible=True):
|
| 441 |
+
self.value = value
|
| 442 |
+
self.type = dispatch_type
|
| 443 |
+
self.coercible = coercible
|
| 444 |
+
|
| 445 |
+
def __getitem__(self, index):
|
| 446 |
+
return (self.type, self.value)[index]
|
| 447 |
+
|
| 448 |
+
def __str__(self):
|
| 449 |
+
return f"<{type(self).__name__}: type={self.type!r}, value={self.value!r}>"
|
| 450 |
+
|
| 451 |
+
__repr__ = __str__
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def mark_as(dispatch_type):
|
| 455 |
+
"""
|
| 456 |
+
Creates a utility function to mark something as a specific type.
|
| 457 |
+
|
| 458 |
+
Examples
|
| 459 |
+
--------
|
| 460 |
+
>>> mark_int = mark_as(int)
|
| 461 |
+
>>> mark_int(1)
|
| 462 |
+
<Dispatchable: type=<class 'int'>, value=1>
|
| 463 |
+
"""
|
| 464 |
+
return functools.partial(Dispatchable, dispatch_type=dispatch_type)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def all_of_type(arg_type):
|
| 468 |
+
"""
|
| 469 |
+
Marks all unmarked arguments as a given type.
|
| 470 |
+
|
| 471 |
+
Examples
|
| 472 |
+
--------
|
| 473 |
+
>>> @all_of_type(str)
|
| 474 |
+
... def f(a, b):
|
| 475 |
+
... return a, Dispatchable(b, int)
|
| 476 |
+
>>> f('a', 1)
|
| 477 |
+
(<Dispatchable: type=<class 'str'>, value='a'>,
|
| 478 |
+
<Dispatchable: type=<class 'int'>, value=1>)
|
| 479 |
+
"""
|
| 480 |
+
|
| 481 |
+
def outer(func):
|
| 482 |
+
@functools.wraps(func)
|
| 483 |
+
def inner(*args, **kwargs):
|
| 484 |
+
extracted_args = func(*args, **kwargs)
|
| 485 |
+
return tuple(
|
| 486 |
+
Dispatchable(arg, arg_type)
|
| 487 |
+
if not isinstance(arg, Dispatchable)
|
| 488 |
+
else arg
|
| 489 |
+
for arg in extracted_args
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
return inner
|
| 493 |
+
|
| 494 |
+
return outer
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def wrap_single_convertor(convert_single):
|
| 498 |
+
"""
|
| 499 |
+
Wraps a ``__ua_convert__`` defined for a single element to all elements.
|
| 500 |
+
If any of them return ``NotImplemented``, the operation is assumed to be
|
| 501 |
+
undefined.
|
| 502 |
+
|
| 503 |
+
Accepts a signature of (value, type, coerce).
|
| 504 |
+
"""
|
| 505 |
+
|
| 506 |
+
@functools.wraps(convert_single)
|
| 507 |
+
def __ua_convert__(dispatchables, coerce):
|
| 508 |
+
converted = []
|
| 509 |
+
for d in dispatchables:
|
| 510 |
+
c = convert_single(d.value, d.type, coerce and d.coercible)
|
| 511 |
+
|
| 512 |
+
if c is NotImplemented:
|
| 513 |
+
return NotImplemented
|
| 514 |
+
|
| 515 |
+
converted.append(c)
|
| 516 |
+
|
| 517 |
+
return converted
|
| 518 |
+
|
| 519 |
+
return __ua_convert__
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def wrap_single_convertor_instance(convert_single):
|
| 523 |
+
"""
|
| 524 |
+
Wraps a ``__ua_convert__`` defined for a single element to all elements.
|
| 525 |
+
If any of them return ``NotImplemented``, the operation is assumed to be
|
| 526 |
+
undefined.
|
| 527 |
+
|
| 528 |
+
Accepts a signature of (value, type, coerce).
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
@functools.wraps(convert_single)
|
| 532 |
+
def __ua_convert__(self, dispatchables, coerce):
|
| 533 |
+
converted = []
|
| 534 |
+
for d in dispatchables:
|
| 535 |
+
c = convert_single(self, d.value, d.type, coerce and d.coercible)
|
| 536 |
+
|
| 537 |
+
if c is NotImplemented:
|
| 538 |
+
return NotImplemented
|
| 539 |
+
|
| 540 |
+
converted.append(c)
|
| 541 |
+
|
| 542 |
+
return converted
|
| 543 |
+
|
| 544 |
+
return __ua_convert__
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def determine_backend(value, dispatch_type, *, domain, only=True, coerce=False):
|
| 548 |
+
"""Set the backend to the first active backend that supports ``value``
|
| 549 |
+
|
| 550 |
+
This is useful for functions that call multimethods without any dispatchable
|
| 551 |
+
arguments. You can use :func:`determine_backend` to ensure the same backend
|
| 552 |
+
is used everywhere in a block of multimethod calls.
|
| 553 |
+
|
| 554 |
+
Parameters
|
| 555 |
+
----------
|
| 556 |
+
value
|
| 557 |
+
The value being tested
|
| 558 |
+
dispatch_type
|
| 559 |
+
The dispatch type associated with ``value``, aka
|
| 560 |
+
":ref:`marking <MarkingGlossary>`".
|
| 561 |
+
domain: string
|
| 562 |
+
The domain to query for backends and set.
|
| 563 |
+
coerce: bool
|
| 564 |
+
Whether or not to allow coercion to the backend's types. Implies ``only``.
|
| 565 |
+
only: bool
|
| 566 |
+
Whether or not this should be the last backend to try.
|
| 567 |
+
|
| 568 |
+
See Also
|
| 569 |
+
--------
|
| 570 |
+
set_backend: For when you know which backend to set
|
| 571 |
+
|
| 572 |
+
Notes
|
| 573 |
+
-----
|
| 574 |
+
|
| 575 |
+
Support is determined by the ``__ua_convert__`` protocol. Backends not
|
| 576 |
+
supporting the type must return ``NotImplemented`` from their
|
| 577 |
+
``__ua_convert__`` if they don't support input of that type.
|
| 578 |
+
|
| 579 |
+
Examples
|
| 580 |
+
--------
|
| 581 |
+
|
| 582 |
+
Suppose we have two backends ``BackendA`` and ``BackendB`` each supporting
|
| 583 |
+
different types, ``TypeA`` and ``TypeB``. Neither supporting the other type:
|
| 584 |
+
|
| 585 |
+
>>> with ua.set_backend(ex.BackendA):
|
| 586 |
+
... ex.call_multimethod(ex.TypeB(), ex.TypeB())
|
| 587 |
+
Traceback (most recent call last):
|
| 588 |
+
...
|
| 589 |
+
uarray.BackendNotImplementedError: ...
|
| 590 |
+
|
| 591 |
+
Now consider a multimethod that creates a new object of ``TypeA``, or
|
| 592 |
+
``TypeB`` depending on the active backend.
|
| 593 |
+
|
| 594 |
+
>>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
|
| 595 |
+
... res = ex.creation_multimethod()
|
| 596 |
+
... ex.call_multimethod(res, ex.TypeA())
|
| 597 |
+
Traceback (most recent call last):
|
| 598 |
+
...
|
| 599 |
+
uarray.BackendNotImplementedError: ...
|
| 600 |
+
|
| 601 |
+
``res`` is an object of ``TypeB`` because ``BackendB`` is set in the
|
| 602 |
+
innermost with statement. So, ``call_multimethod`` fails since the types
|
| 603 |
+
don't match.
|
| 604 |
+
|
| 605 |
+
Instead, we need to first find a backend suitable for all of our objects.
|
| 606 |
+
|
| 607 |
+
>>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
|
| 608 |
+
... x = ex.TypeA()
|
| 609 |
+
... with ua.determine_backend(x, "mark", domain="ua_examples"):
|
| 610 |
+
... res = ex.creation_multimethod()
|
| 611 |
+
... ex.call_multimethod(res, x)
|
| 612 |
+
TypeA
|
| 613 |
+
|
| 614 |
+
"""
|
| 615 |
+
dispatchables = (Dispatchable(value, dispatch_type, coerce),)
|
| 616 |
+
backend = _uarray.determine_backend(domain, dispatchables, coerce)
|
| 617 |
+
|
| 618 |
+
return set_backend(backend, coerce=coerce, only=only)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def determine_backend_multi(
|
| 622 |
+
dispatchables, *, domain, only=True, coerce=False, **kwargs
|
| 623 |
+
):
|
| 624 |
+
"""Set a backend supporting all ``dispatchables``
|
| 625 |
+
|
| 626 |
+
This is useful for functions that call multimethods without any dispatchable
|
| 627 |
+
arguments. You can use :func:`determine_backend_multi` to ensure the same
|
| 628 |
+
backend is used everywhere in a block of multimethod calls involving
|
| 629 |
+
multiple arrays.
|
| 630 |
+
|
| 631 |
+
Parameters
|
| 632 |
+
----------
|
| 633 |
+
dispatchables: Sequence[Union[uarray.Dispatchable, Any]]
|
| 634 |
+
The dispatchables that must be supported
|
| 635 |
+
domain: string
|
| 636 |
+
The domain to query for backends and set.
|
| 637 |
+
coerce: bool
|
| 638 |
+
Whether or not to allow coercion to the backend's types. Implies ``only``.
|
| 639 |
+
only: bool
|
| 640 |
+
Whether or not this should be the last backend to try.
|
| 641 |
+
dispatch_type: Optional[Any]
|
| 642 |
+
The default dispatch type associated with ``dispatchables``, aka
|
| 643 |
+
":ref:`marking <MarkingGlossary>`".
|
| 644 |
+
|
| 645 |
+
See Also
|
| 646 |
+
--------
|
| 647 |
+
determine_backend: For a single dispatch value
|
| 648 |
+
set_backend: For when you know which backend to set
|
| 649 |
+
|
| 650 |
+
Notes
|
| 651 |
+
-----
|
| 652 |
+
|
| 653 |
+
Support is determined by the ``__ua_convert__`` protocol. Backends not
|
| 654 |
+
supporting the type must return ``NotImplemented`` from their
|
| 655 |
+
``__ua_convert__`` if they don't support input of that type.
|
| 656 |
+
|
| 657 |
+
Examples
|
| 658 |
+
--------
|
| 659 |
+
|
| 660 |
+
:func:`determine_backend` allows the backend to be set from a single
|
| 661 |
+
object. :func:`determine_backend_multi` allows multiple objects to be
|
| 662 |
+
checked simultaneously for support in the backend. Suppose we have a
|
| 663 |
+
``BackendAB`` which supports ``TypeA`` and ``TypeB`` in the same call,
|
| 664 |
+
and a ``BackendBC`` that doesn't support ``TypeA``.
|
| 665 |
+
|
| 666 |
+
>>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
|
| 667 |
+
... a, b = ex.TypeA(), ex.TypeB()
|
| 668 |
+
... with ua.determine_backend_multi(
|
| 669 |
+
... [ua.Dispatchable(a, "mark"), ua.Dispatchable(b, "mark")],
|
| 670 |
+
... domain="ua_examples"
|
| 671 |
+
... ):
|
| 672 |
+
... res = ex.creation_multimethod()
|
| 673 |
+
... ex.call_multimethod(res, a, b)
|
| 674 |
+
TypeA
|
| 675 |
+
|
| 676 |
+
This won't call ``BackendBC`` because it doesn't support ``TypeA``.
|
| 677 |
+
|
| 678 |
+
We can also use leave out the ``ua.Dispatchable`` if we specify the
|
| 679 |
+
default ``dispatch_type`` for the ``dispatchables`` argument.
|
| 680 |
+
|
| 681 |
+
>>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
|
| 682 |
+
... a, b = ex.TypeA(), ex.TypeB()
|
| 683 |
+
... with ua.determine_backend_multi(
|
| 684 |
+
... [a, b], dispatch_type="mark", domain="ua_examples"
|
| 685 |
+
... ):
|
| 686 |
+
... res = ex.creation_multimethod()
|
| 687 |
+
... ex.call_multimethod(res, a, b)
|
| 688 |
+
TypeA
|
| 689 |
+
|
| 690 |
+
"""
|
| 691 |
+
if "dispatch_type" in kwargs:
|
| 692 |
+
disp_type = kwargs.pop("dispatch_type")
|
| 693 |
+
dispatchables = tuple(
|
| 694 |
+
d if isinstance(d, Dispatchable) else Dispatchable(d, disp_type)
|
| 695 |
+
for d in dispatchables
|
| 696 |
+
)
|
| 697 |
+
else:
|
| 698 |
+
dispatchables = tuple(dispatchables)
|
| 699 |
+
if not all(isinstance(d, Dispatchable) for d in dispatchables):
|
| 700 |
+
raise TypeError("dispatchables must be instances of uarray.Dispatchable")
|
| 701 |
+
|
| 702 |
+
if len(kwargs) != 0:
|
| 703 |
+
raise TypeError(f"Received unexpected keyword arguments: {kwargs}")
|
| 704 |
+
|
| 705 |
+
backend = _uarray.determine_backend(domain, dispatchables, coerce)
|
| 706 |
+
|
| 707 |
+
return set_backend(backend, coerce=coerce, only=only)
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_compat/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NumPy Array API compatibility library
|
| 3 |
+
|
| 4 |
+
This is a small wrapper around NumPy, CuPy, JAX, sparse and others that are
|
| 5 |
+
compatible with the Array API standard https://data-apis.org/array-api/latest/.
|
| 6 |
+
See also NEP 47 https://numpy.org/neps/nep-0047-array-api-standard.html.
|
| 7 |
+
|
| 8 |
+
Unlike array_api_strict, this is not a strict minimal implementation of the
|
| 9 |
+
Array API, but rather just an extension of the main NumPy namespace with
|
| 10 |
+
changes needed to be compliant with the Array API. See
|
| 11 |
+
https://numpy.org/doc/stable/reference/array_api.html for a full list of
|
| 12 |
+
changes. In particular, unlike array_api_strict, this package does not use a
|
| 13 |
+
separate Array object, but rather just uses numpy.ndarray directly.
|
| 14 |
+
|
| 15 |
+
Library authors using the Array API may wish to test against array_api_strict
|
| 16 |
+
to ensure they are not using functionality outside of the standard, but prefer
|
| 17 |
+
this implementation for the default when working with NumPy arrays.
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
__version__ = '1.13.0'
|
| 21 |
+
|
| 22 |
+
from .common import * # noqa: F401, F403
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_compat/_internal.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Internal helpers
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import importlib
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from functools import wraps
|
| 8 |
+
from inspect import signature
|
| 9 |
+
from types import ModuleType
|
| 10 |
+
from typing import TypeVar
|
| 11 |
+
|
| 12 |
+
_T = TypeVar("_T")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_xp(xp: ModuleType) -> Callable[[Callable[..., _T]], Callable[..., _T]]:
|
| 16 |
+
"""
|
| 17 |
+
Decorator to automatically replace xp with the corresponding array module.
|
| 18 |
+
|
| 19 |
+
Use like
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
@get_xp(np)
|
| 24 |
+
def func(x, /, xp, kwarg=None):
|
| 25 |
+
return xp.func(x, kwarg=kwarg)
|
| 26 |
+
|
| 27 |
+
Note that xp must be a keyword argument and come after all non-keyword
|
| 28 |
+
arguments.
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def inner(f: Callable[..., _T], /) -> Callable[..., _T]:
|
| 33 |
+
@wraps(f)
|
| 34 |
+
def wrapped_f(*args: object, **kwargs: object) -> object:
|
| 35 |
+
return f(*args, xp=xp, **kwargs)
|
| 36 |
+
|
| 37 |
+
sig = signature(f)
|
| 38 |
+
new_sig = sig.replace(
|
| 39 |
+
parameters=[par for i, par in sig.parameters.items() if i != "xp"]
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
if wrapped_f.__doc__ is None:
|
| 43 |
+
wrapped_f.__doc__ = f"""\
|
| 44 |
+
Array API compatibility wrapper for {f.__name__}.
|
| 45 |
+
|
| 46 |
+
See the corresponding documentation in NumPy/CuPy and/or the array API
|
| 47 |
+
specification for more details.
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
wrapped_f.__signature__ = new_sig # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]
|
| 51 |
+
return wrapped_f # type: ignore[return-value] # pyright: ignore[reportReturnType]
|
| 52 |
+
|
| 53 |
+
return inner
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def clone_module(mod_name: str, globals_: dict[str, object]) -> list[str]:
|
| 57 |
+
"""Import everything from module, updating globals().
|
| 58 |
+
Returns __all__.
|
| 59 |
+
"""
|
| 60 |
+
mod = importlib.import_module(mod_name)
|
| 61 |
+
# Neither of these two methods is sufficient by itself,
|
| 62 |
+
# depending on various idiosyncrasies of the libraries we're wrapping.
|
| 63 |
+
objs = {}
|
| 64 |
+
exec(f"from {mod.__name__} import *", objs)
|
| 65 |
+
|
| 66 |
+
for n in dir(mod):
|
| 67 |
+
if not n.startswith("_") and hasattr(mod, n):
|
| 68 |
+
objs[n] = getattr(mod, n)
|
| 69 |
+
|
| 70 |
+
globals_.update(objs)
|
| 71 |
+
return list(objs)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
__all__ = ["get_xp", "clone_module"]
|
| 75 |
+
|
| 76 |
+
def __dir__() -> list[str]:
|
| 77 |
+
return __all__
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_extra/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extra array functions built on top of the array API standard."""
|
| 2 |
+
|
| 3 |
+
from ._delegation import (
|
| 4 |
+
argpartition,
|
| 5 |
+
atleast_nd,
|
| 6 |
+
cov,
|
| 7 |
+
create_diagonal,
|
| 8 |
+
expand_dims,
|
| 9 |
+
isclose,
|
| 10 |
+
isin,
|
| 11 |
+
nan_to_num,
|
| 12 |
+
one_hot,
|
| 13 |
+
pad,
|
| 14 |
+
partition,
|
| 15 |
+
setdiff1d,
|
| 16 |
+
sinc,
|
| 17 |
+
)
|
| 18 |
+
from ._lib._at import at
|
| 19 |
+
from ._lib._funcs import (
|
| 20 |
+
apply_where,
|
| 21 |
+
broadcast_shapes,
|
| 22 |
+
default_dtype,
|
| 23 |
+
kron,
|
| 24 |
+
nunique,
|
| 25 |
+
)
|
| 26 |
+
from ._lib._lazy import lazy_apply
|
| 27 |
+
|
| 28 |
+
__version__ = "0.9.1"
|
| 29 |
+
|
| 30 |
+
# pylint: disable=duplicate-code
|
| 31 |
+
__all__ = [
|
| 32 |
+
"__version__",
|
| 33 |
+
"apply_where",
|
| 34 |
+
"argpartition",
|
| 35 |
+
"at",
|
| 36 |
+
"atleast_nd",
|
| 37 |
+
"broadcast_shapes",
|
| 38 |
+
"cov",
|
| 39 |
+
"create_diagonal",
|
| 40 |
+
"default_dtype",
|
| 41 |
+
"expand_dims",
|
| 42 |
+
"isclose",
|
| 43 |
+
"isin",
|
| 44 |
+
"kron",
|
| 45 |
+
"lazy_apply",
|
| 46 |
+
"nan_to_num",
|
| 47 |
+
"nunique",
|
| 48 |
+
"one_hot",
|
| 49 |
+
"pad",
|
| 50 |
+
"partition",
|
| 51 |
+
"setdiff1d",
|
| 52 |
+
"sinc",
|
| 53 |
+
]
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/array_api_extra/_delegation.py
ADDED
|
@@ -0,0 +1,1028 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Delegation to existing implementations for Public API Functions."""
|
| 2 |
+
|
| 3 |
+
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)
|
.venv_haddock/lib/python3.12/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
|
.venv_haddock/lib/python3.12/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"]
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (361 Bytes). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/framework.cpython-312.pyc
ADDED
|
Binary file (50.7 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (58.8 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/models.cpython-312.pyc
ADDED
|
Binary file (63 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/problem.cpython-312.pyc
ADDED
|
Binary file (48 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/__pycache__/settings.cpython-312.pyc
ADDED
|
Binary file (6.41 kB). View file
|
|
|
.venv_haddock/lib/python3.12/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
|
.venv_haddock/lib/python3.12/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"Corres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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 |
+
)
|
.venv_haddock/lib/python3.12/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 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/settings.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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= -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 |
+
)
|
.venv_haddock/lib/python3.12/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 |
+
]
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (488 Bytes). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-312.pyc
ADDED
|
Binary file (15.8 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-312.pyc
ADDED
|
Binary file (44.8 kB). View file
|
|
|
.venv_haddock/lib/python3.12/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
|
.venv_haddock/lib/python3.12/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))
|
.venv_haddock/lib/python3.12/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 |
+
]
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (527 Bytes). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-312.pyc
ADDED
|
Binary file (1.19 kB). View file
|
|
|