diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dca985e576ef21f07e8b480f37101106329324d5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..736796d8fe58f50c8e8a1026ff62603ec56294fa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/_compat.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cda5d442805bdf6004d8c4281e5c8d6171681b13 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/sessions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/sessions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad6779a9489dc8b5a1426accc3e00a2c6c9408f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/sessions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/streaming_iterator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/streaming_iterator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2d4f07ebe4977bfffb13de21d2b0839b735313b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/__pycache__/streaming_iterator.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7195f43e3496b5951f3eab7cba53e69e0d99fcb9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +""" +requests-toolbelt.adapters +========================== + +See https://toolbelt.readthedocs.io/ for documentation + +:copyright: (c) 2014 by Ian Cordasco and Cory Benfield +:license: Apache v2.0, see LICENSE for more details +""" + +from .ssl import SSLAdapter +from .source import SourceAddressAdapter + +__all__ = ['SSLAdapter', 'SourceAddressAdapter'] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/appengine.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/appengine.py new file mode 100644 index 0000000000000000000000000000000000000000..25a70a17625117850c8de99b328e96dc3b67ed65 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/appengine.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- +"""The App Engine Transport Adapter for requests. + +.. versionadded:: 0.6.0 + +This requires a version of requests >= 2.10.0 and Python 2. + +There are two ways to use this library: + +#. If you're using requests directly, you can use code like: + + .. code-block:: python + + >>> import requests + >>> import ssl + >>> import requests.packages.urllib3.contrib.appengine as ul_appengine + >>> from requests_toolbelt.adapters import appengine + >>> s = requests.Session() + >>> if ul_appengine.is_appengine_sandbox(): + ... s.mount('http://', appengine.AppEngineAdapter()) + ... s.mount('https://', appengine.AppEngineAdapter()) + +#. If you depend on external libraries which use requests, you can use code + like: + + .. code-block:: python + + >>> from requests_toolbelt.adapters import appengine + >>> appengine.monkeypatch() + +which will ensure all requests.Session objects use AppEngineAdapter properly. + +You are also able to :ref:`disable certificate validation ` +when monkey-patching. +""" +import requests +import warnings +from requests import adapters +from requests import sessions + +from .. import exceptions as exc +from .._compat import gaecontrib +from .._compat import timeout + + +class AppEngineMROHack(adapters.HTTPAdapter): + """Resolves infinite recursion when monkeypatching. + + This works by injecting itself as the base class of both the + :class:`AppEngineAdapter` and Requests' default HTTPAdapter, which needs to + be done because default HTTPAdapter's MRO is recompiled when we + monkeypatch, at which point this class becomes HTTPAdapter's base class. + In addition, we use an instantiation flag to avoid infinite recursion. + """ + _initialized = False + + def __init__(self, *args, **kwargs): + if not self._initialized: + self._initialized = True + super(AppEngineMROHack, self).__init__(*args, **kwargs) + + +class AppEngineAdapter(AppEngineMROHack, adapters.HTTPAdapter): + """The transport adapter for Requests to use urllib3's GAE support. + + Implements Requests's HTTPAdapter API. + + When deploying to Google's App Engine service, some of Requests' + functionality is broken. There is underlying support for GAE in urllib3. + This functionality, however, is opt-in and needs to be enabled explicitly + for Requests to be able to use it. + """ + + __attrs__ = adapters.HTTPAdapter.__attrs__ + ['_validate_certificate'] + + def __init__(self, validate_certificate=True, *args, **kwargs): + _check_version() + self._validate_certificate = validate_certificate + super(AppEngineAdapter, self).__init__(*args, **kwargs) + + def init_poolmanager(self, connections, maxsize, block=False): + self.poolmanager = _AppEnginePoolManager(self._validate_certificate) + + +class InsecureAppEngineAdapter(AppEngineAdapter): + """An always-insecure GAE adapter for Requests. + + This is a variant of the the transport adapter for Requests to use + urllib3's GAE support that does not validate certificates. Use with + caution! + + .. note:: + The ``validate_certificate`` keyword argument will not be honored here + and is not part of the signature because we always force it to + ``False``. + + See :class:`AppEngineAdapter` for further details. + """ + + def __init__(self, *args, **kwargs): + if kwargs.pop("validate_certificate", False): + warnings.warn("Certificate validation cannot be specified on the " + "InsecureAppEngineAdapter, but was present. This " + "will be ignored and certificate validation will " + "remain off.", exc.IgnoringGAECertificateValidation) + + super(InsecureAppEngineAdapter, self).__init__( + validate_certificate=False, *args, **kwargs) + + +class _AppEnginePoolManager(object): + """Implements urllib3's PoolManager API expected by requests. + + While a real PoolManager map hostnames to reusable Connections, + AppEngine has no concept of a reusable connection to a host. + So instead, this class constructs a small Connection per request, + that is returned to the Adapter and used to access the URL. + """ + + def __init__(self, validate_certificate=True): + self.appengine_manager = gaecontrib.AppEngineManager( + validate_certificate=validate_certificate) + + def connection_from_url(self, url): + return _AppEngineConnection(self.appengine_manager, url) + + def clear(self): + pass + + +class _AppEngineConnection(object): + """Implements urllib3's HTTPConnectionPool API's urlopen(). + + This Connection's urlopen() is called with a host-relative path, + so in order to properly support opening the URL, we need to store + the full URL when this Connection is constructed from the PoolManager. + + This code wraps AppEngineManager.urlopen(), which exposes a different + API than in the original urllib3 urlopen(), and thus needs this adapter. + """ + + def __init__(self, appengine_manager, url): + self.appengine_manager = appengine_manager + self.url = url + + def urlopen(self, method, url, body=None, headers=None, retries=None, + redirect=True, assert_same_host=True, + timeout=timeout.Timeout.DEFAULT_TIMEOUT, + pool_timeout=None, release_conn=None, **response_kw): + # This function's url argument is a host-relative URL, + # but the AppEngineManager expects an absolute URL. + # So we saved out the self.url when the AppEngineConnection + # was constructed, which we then can use down below instead. + + # We once tried to verify our assumptions here, but sometimes the + # passed-in URL differs on url fragments, or "http://a.com" vs "/". + + # urllib3's App Engine adapter only uses Timeout.total, not read or + # connect. + if not timeout.total: + timeout.total = timeout._read or timeout._connect + + # Jump through the hoops necessary to call AppEngineManager's API. + return self.appengine_manager.urlopen( + method, + self.url, + body=body, + headers=headers, + retries=retries, + redirect=redirect, + timeout=timeout, + **response_kw) + + +def monkeypatch(validate_certificate=True): + """Sets up all Sessions to use AppEngineAdapter by default. + + If you don't want to deal with configuring your own Sessions, + or if you use libraries that use requests directly (ie requests.post), + then you may prefer to monkeypatch and auto-configure all Sessions. + + .. warning: : + + If ``validate_certificate`` is ``False``, certification validation will + effectively be disabled for all requests. + """ + _check_version() + # HACK: We should consider modifying urllib3 to support this cleanly, + # so that we can set a module-level variable in the sessions module, + # instead of overriding an imported HTTPAdapter as is done here. + adapter = AppEngineAdapter + if not validate_certificate: + adapter = InsecureAppEngineAdapter + + sessions.HTTPAdapter = adapter + adapters.HTTPAdapter = adapter + + +def _check_version(): + if gaecontrib is None: + raise exc.VersionMismatchError( + "The toolbelt requires at least Requests 2.10.0 to be " + "installed. Version {} was found instead.".format( + requests.__version__ + ) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/fingerprint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/fingerprint.py new file mode 100644 index 0000000000000000000000000000000000000000..6645d349816cf43055861f893f9f2e3d2f301e91 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/fingerprint.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +"""Submodule containing the implementation for the FingerprintAdapter. + +This file contains an implementation of a Transport Adapter that validates +the fingerprints of SSL certificates presented upon connection. +""" +from requests.adapters import HTTPAdapter + +from .._compat import poolmanager + + +class FingerprintAdapter(HTTPAdapter): + """ + A HTTPS Adapter for Python Requests that verifies certificate fingerprints, + instead of certificate hostnames. + + Example usage: + + .. code-block:: python + + import requests + import ssl + from requests_toolbelt.adapters.fingerprint import FingerprintAdapter + + twitter_fingerprint = '...' + s = requests.Session() + s.mount( + 'https://twitter.com', + FingerprintAdapter(twitter_fingerprint) + ) + + The fingerprint should be provided as a hexadecimal string, optionally + containing colons. + """ + + __attrs__ = HTTPAdapter.__attrs__ + ['fingerprint'] + + def __init__(self, fingerprint, **kwargs): + self.fingerprint = fingerprint + + super(FingerprintAdapter, self).__init__(**kwargs) + + def init_poolmanager(self, connections, maxsize, block=False): + self.poolmanager = poolmanager.PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + assert_fingerprint=self.fingerprint) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/host_header_ssl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/host_header_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..f34ed1aa134fb3f1fece5cbb721e95d10c7628d3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/host_header_ssl.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +""" +requests_toolbelt.adapters.host_header_ssl +========================================== + +This file contains an implementation of the HostHeaderSSLAdapter. +""" + +from requests.adapters import HTTPAdapter + + +class HostHeaderSSLAdapter(HTTPAdapter): + """ + A HTTPS Adapter for Python Requests that sets the hostname for certificate + verification based on the Host header. + + This allows requesting the IP address directly via HTTPS without getting + a "hostname doesn't match" exception. + + Example usage: + + >>> s.mount('https://', HostHeaderSSLAdapter()) + >>> s.get("https://93.184.216.34", headers={"Host": "example.org"}) + + """ + + def send(self, request, **kwargs): + # HTTP headers are case-insensitive (RFC 7230) + host_header = None + for header in request.headers: + if header.lower() == "host": + host_header = request.headers[header] + break + + connection_pool_kwargs = self.poolmanager.connection_pool_kw + + if host_header: + connection_pool_kwargs["assert_hostname"] = host_header + elif "assert_hostname" in connection_pool_kwargs: + # an assert_hostname from a previous request may have been left + connection_pool_kwargs.pop("assert_hostname", None) + + return super(HostHeaderSSLAdapter, self).send(request, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/socket_options.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/socket_options.py new file mode 100644 index 0000000000000000000000000000000000000000..86ebe136b448f53fd48a9b8a0142f10b19c81fb4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/socket_options.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +"""The implementation of the SocketOptionsAdapter.""" +import socket +import warnings +import sys + +import requests +from requests import adapters + +from .._compat import connection +from .._compat import poolmanager +from .. import exceptions as exc + + +class SocketOptionsAdapter(adapters.HTTPAdapter): + """An adapter for requests that allows users to specify socket options. + + Since version 2.4.0 of requests, it is possible to specify a custom list + of socket options that need to be set before establishing the connection. + + Example usage:: + + >>> import socket + >>> import requests + >>> from requests_toolbelt.adapters import socket_options + >>> s = requests.Session() + >>> opts = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 0)] + >>> adapter = socket_options.SocketOptionsAdapter(socket_options=opts) + >>> s.mount('http://', adapter) + + You can also take advantage of the list of default options on this class + to keep using the original options in addition to your custom options. In + that case, ``opts`` might look like:: + + >>> opts = socket_options.SocketOptionsAdapter.default_options + opts + + """ + + if connection is not None: + default_options = getattr( + connection.HTTPConnection, + 'default_socket_options', + [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] + ) + else: + default_options = [] + warnings.warn(exc.RequestsVersionTooOld, + "This version of Requests is only compatible with a " + "version of urllib3 which is too old to support " + "setting options on a socket. This adapter is " + "functionally useless.") + + def __init__(self, **kwargs): + self.socket_options = kwargs.pop('socket_options', + self.default_options) + + super(SocketOptionsAdapter, self).__init__(**kwargs) + + def init_poolmanager(self, connections, maxsize, block=False): + if requests.__build__ >= 0x020400: + # NOTE(Ian): Perhaps we should raise a warning + self.poolmanager = poolmanager.PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + socket_options=self.socket_options + ) + else: + super(SocketOptionsAdapter, self).init_poolmanager( + connections, maxsize, block + ) + + +class TCPKeepAliveAdapter(SocketOptionsAdapter): + """An adapter for requests that turns on TCP Keep-Alive by default. + + The adapter sets 4 socket options: + + - ``SOL_SOCKET`` ``SO_KEEPALIVE`` - This turns on TCP Keep-Alive + - ``IPPROTO_TCP`` ``TCP_KEEPINTVL`` 20 - Sets the keep alive interval + - ``IPPROTO_TCP`` ``TCP_KEEPCNT`` 5 - Sets the number of keep alive probes + - ``IPPROTO_TCP`` ``TCP_KEEPIDLE`` 60 - Sets the keep alive time if the + socket library has the ``TCP_KEEPIDLE`` constant + + The latter three can be overridden by keyword arguments (respectively): + + - ``interval`` + - ``count`` + - ``idle`` + + You can use this adapter like so:: + + >>> from requests_toolbelt.adapters import socket_options + >>> tcp = socket_options.TCPKeepAliveAdapter(idle=120, interval=10) + >>> s = requests.Session() + >>> s.mount('http://', tcp) + + """ + + def __init__(self, **kwargs): + socket_options = kwargs.pop('socket_options', + SocketOptionsAdapter.default_options) + idle = kwargs.pop('idle', 60) + interval = kwargs.pop('interval', 20) + count = kwargs.pop('count', 5) + socket_options = socket_options + [ + (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + ] + + # NOTE(Ian): OSX does not have these constants defined, so we + # set them conditionally. + if getattr(socket, 'TCP_KEEPINTVL', None) is not None: + socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, + interval)] + elif sys.platform == 'darwin': + # On OSX, TCP_KEEPALIVE from netinet/tcp.h is not exported + # by python's socket module + TCP_KEEPALIVE = getattr(socket, 'TCP_KEEPALIVE', 0x10) + socket_options += [(socket.IPPROTO_TCP, TCP_KEEPALIVE, interval)] + + if getattr(socket, 'TCP_KEEPCNT', None) is not None: + socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count)] + + if getattr(socket, 'TCP_KEEPIDLE', None) is not None: + socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)] + + super(TCPKeepAliveAdapter, self).__init__( + socket_options=socket_options, **kwargs + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/source.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/source.py new file mode 100644 index 0000000000000000000000000000000000000000..d3dda797acc29c7024f07d1e6dd7c3e688607573 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/source.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +""" +requests_toolbelt.source_adapter +================================ + +This file contains an implementation of the SourceAddressAdapter originally +demonstrated on the Requests GitHub page. +""" +from requests.adapters import HTTPAdapter + +from .._compat import poolmanager, basestring + + +class SourceAddressAdapter(HTTPAdapter): + """ + A Source Address Adapter for Python Requests that enables you to choose the + local address to bind to. This allows you to send your HTTP requests from a + specific interface and IP address. + + Two address formats are accepted. The first is a string: this will set the + local IP address to the address given in the string, and will also choose a + semi-random high port for the local port number. + + The second is a two-tuple of the form (ip address, port): for example, + ``('10.10.10.10', 8999)``. This will set the local IP address to the first + element, and the local port to the second element. If ``0`` is used as the + port number, a semi-random high port will be selected. + + .. warning:: Setting an explicit local port can have negative interactions + with connection-pooling in Requests: in particular, it risks + the possibility of getting "Address in use" errors. The + string-only argument is generally preferred to the tuple-form. + + Example usage: + + .. code-block:: python + + import requests + from requests_toolbelt.adapters.source import SourceAddressAdapter + + s = requests.Session() + s.mount('http://', SourceAddressAdapter('10.10.10.10')) + s.mount('https://', SourceAddressAdapter(('10.10.10.10', 8999))) + """ + def __init__(self, source_address, **kwargs): + if isinstance(source_address, basestring): + self.source_address = (source_address, 0) + elif isinstance(source_address, tuple): + self.source_address = source_address + else: + raise TypeError( + "source_address must be IP address string or (ip, port) tuple" + ) + + super(SourceAddressAdapter, self).__init__(**kwargs) + + def init_poolmanager(self, connections, maxsize, block=False): + self.poolmanager = poolmanager.PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + source_address=self.source_address) + + def proxy_manager_for(self, *args, **kwargs): + kwargs['source_address'] = self.source_address + return super(SourceAddressAdapter, self).proxy_manager_for( + *args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/ssl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a76ae4553984e2b2983a89258704c9e8fd238c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/ssl.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +""" + +requests_toolbelt.ssl_adapter +============================= + +This file contains an implementation of the SSLAdapter originally demonstrated +in this blog post: +https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ + +""" +import requests + +from requests.adapters import HTTPAdapter + +from .._compat import poolmanager + + +class SSLAdapter(HTTPAdapter): + """ + A HTTPS Adapter for Python Requests that allows the choice of the SSL/TLS + version negotiated by Requests. This can be used either to enforce the + choice of high-security TLS versions (where supported), or to work around + misbehaving servers that fail to correctly negotiate the default TLS + version being offered. + + Example usage: + + >>> import requests + >>> import ssl + >>> from requests_toolbelt import SSLAdapter + >>> s = requests.Session() + >>> s.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1)) + + You can replace the chosen protocol with any that are available in the + default Python SSL module. All subsequent requests that match the adapter + prefix will use the chosen SSL version instead of the default. + + This adapter will also attempt to change the SSL/TLS version negotiated by + Requests when using a proxy. However, this may not always be possible: + prior to Requests v2.4.0 the adapter did not have access to the proxy setup + code. In earlier versions of Requests, this adapter will not function + properly when used with proxies. + """ + + __attrs__ = HTTPAdapter.__attrs__ + ['ssl_version'] + + def __init__(self, ssl_version=None, **kwargs): + self.ssl_version = ssl_version + + super(SSLAdapter, self).__init__(**kwargs) + + def init_poolmanager(self, connections, maxsize, block=False): + self.poolmanager = poolmanager.PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + ssl_version=self.ssl_version) + + if requests.__build__ >= 0x020400: + # Earlier versions of requests either don't have this method or, worse, + # don't allow passing arbitrary keyword arguments. As a result, only + # conditionally define this method. + def proxy_manager_for(self, *args, **kwargs): + kwargs['ssl_version'] = self.ssl_version + return super(SSLAdapter, self).proxy_manager_for(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/x509.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/x509.py new file mode 100644 index 0000000000000000000000000000000000000000..aff37706aba6ee920aa3f7775134b43e85d48565 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/adapters/x509.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +"""A X509Adapter for use with the requests library. + +This file contains an implementation of the X509Adapter that will +allow users to authenticate a request using an arbitrary +X.509 certificate without needing to convert it to a .pem file + +""" + +from OpenSSL.crypto import PKey, X509 +from cryptography import x509 +from cryptography.hazmat.primitives.serialization import (load_pem_private_key, + load_der_private_key) +from cryptography.hazmat.primitives.serialization import Encoding +from cryptography.hazmat.backends import default_backend + +from datetime import datetime +from requests.adapters import HTTPAdapter +import requests + +from .. import exceptions as exc + +""" +importing the protocol constants from _ssl instead of ssl because only the +constants are needed and to handle issues caused by importing from ssl on +the 2.7.x line. +""" +try: + from _ssl import PROTOCOL_TLS as PROTOCOL +except ImportError: + from _ssl import PROTOCOL_SSLv23 as PROTOCOL + + +PyOpenSSLContext = None + + +class X509Adapter(HTTPAdapter): + r"""Adapter for use with X.509 certificates. + + Provides an interface for Requests sessions to contact HTTPS urls and + authenticate with an X.509 cert by implementing the Transport Adapter + interface. This class will need to be manually instantiated and mounted + to the session + + :param pool_connections: The number of urllib3 connection pools to + cache. + :param pool_maxsize: The maximum number of connections to save in the + pool. + :param max_retries: The maximum number of retries each connection + should attempt. Note, this applies only to failed DNS lookups, + socket connections and connection timeouts, never to requests where + data has made it to the server. By default, Requests does not retry + failed connections. If you need granular control over the + conditions under which we retry a request, import urllib3's + ``Retry`` class and pass that instead. + :param pool_block: Whether the connection pool should block for + connections. + + :param bytes cert_bytes: + bytes object containing contents of a cryptography.x509Certificate + object using the encoding specified by the ``encoding`` parameter. + :param bytes pk_bytes: + bytes object containing contents of a object that implements + ``cryptography.hazmat.primitives.serialization.PrivateFormat`` + using the encoding specified by the ``encoding`` parameter. + :param password: + string or utf8 encoded bytes containing the passphrase used for the + private key. None if unencrypted. Defaults to None. + :param encoding: + Enumeration detailing the encoding method used on the ``cert_bytes`` + parameter. Can be either PEM or DER. Defaults to PEM. + :type encoding: + :class: `cryptography.hazmat.primitives.serialization.Encoding` + + Usage:: + + >>> import requests + >>> from requests_toolbelt.adapters.x509 import X509Adapter + >>> s = requests.Session() + >>> a = X509Adapter(max_retries=3, + cert_bytes=b'...', pk_bytes=b'...', encoding='...' + >>> s.mount('https://', a) + """ + + def __init__(self, *args, **kwargs): + self._import_pyopensslcontext() + self._check_version() + cert_bytes = kwargs.pop('cert_bytes', None) + pk_bytes = kwargs.pop('pk_bytes', None) + password = kwargs.pop('password', None) + encoding = kwargs.pop('encoding', Encoding.PEM) + + password_bytes = None + + if cert_bytes is None or not isinstance(cert_bytes, bytes): + raise ValueError('Invalid cert content provided. ' + 'You must provide an X.509 cert ' + 'formatted as a byte array.') + if pk_bytes is None or not isinstance(pk_bytes, bytes): + raise ValueError('Invalid private key content provided. ' + 'You must provide a private key ' + 'formatted as a byte array.') + + if isinstance(password, bytes): + password_bytes = password + elif password: + password_bytes = password.encode('utf8') + + self.ssl_context = create_ssl_context(cert_bytes, pk_bytes, + password_bytes, encoding) + + super(X509Adapter, self).__init__(*args, **kwargs) + + def init_poolmanager(self, *args, **kwargs): + if self.ssl_context: + kwargs['ssl_context'] = self.ssl_context + return super(X509Adapter, self).init_poolmanager(*args, **kwargs) + + def proxy_manager_for(self, *args, **kwargs): + if self.ssl_context: + kwargs['ssl_context'] = self.ssl_context + return super(X509Adapter, self).proxy_manager_for(*args, **kwargs) + + def _import_pyopensslcontext(self): + global PyOpenSSLContext + + if requests.__build__ < 0x021200: + PyOpenSSLContext = None + else: + try: + from requests.packages.urllib3.contrib.pyopenssl \ + import PyOpenSSLContext + except ImportError: + try: + from urllib3.contrib.pyopenssl import PyOpenSSLContext + except ImportError: + PyOpenSSLContext = None + + def _check_version(self): + if PyOpenSSLContext is None: + raise exc.VersionMismatchError( + "The X509Adapter requires at least Requests 2.12.0 to be " + "installed. Version {} was found instead.".format( + requests.__version__ + ) + ) + + +def check_cert_dates(cert): + """Verify that the supplied client cert is not invalid.""" + + now = datetime.utcnow() + if cert.not_valid_after < now or cert.not_valid_before > now: + raise ValueError('Client certificate expired: Not After: ' + '{:%Y-%m-%d %H:%M:%SZ} ' + 'Not Before: {:%Y-%m-%d %H:%M:%SZ}' + .format(cert.not_valid_after, cert.not_valid_before)) + + +def create_ssl_context(cert_byes, pk_bytes, password=None, + encoding=Encoding.PEM): + """Create an SSL Context with the supplied cert/password. + + :param cert_bytes array of bytes containing the cert encoded + using the method supplied in the ``encoding`` parameter + :param pk_bytes array of bytes containing the private key encoded + using the method supplied in the ``encoding`` parameter + :param password array of bytes containing the passphrase to be used + with the supplied private key. None if unencrypted. + Defaults to None. + :param encoding ``cryptography.hazmat.primitives.serialization.Encoding`` + details the encoding method used on the ``cert_bytes`` and + ``pk_bytes`` parameters. Can be either PEM or DER. + Defaults to PEM. + """ + backend = default_backend() + + cert = None + key = None + if encoding == Encoding.PEM: + cert = x509.load_pem_x509_certificate(cert_byes, backend) + key = load_pem_private_key(pk_bytes, password, backend) + elif encoding == Encoding.DER: + cert = x509.load_der_x509_certificate(cert_byes, backend) + key = load_der_private_key(pk_bytes, password, backend) + else: + raise ValueError('Invalid encoding provided: Must be PEM or DER') + + if not (cert and key): + raise ValueError('Cert and key could not be parsed from ' + 'provided data') + check_cert_dates(cert) + ssl_context = PyOpenSSLContext(PROTOCOL) + ssl_context._ctx.use_certificate(X509.from_cryptography(cert)) + ssl_context._ctx.use_privatekey(PKey.from_cryptography_key(key)) + return ssl_context diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/_digest_auth_compat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/_digest_auth_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..285a6a76309a2e1775afe13d7184491f80384b99 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/_digest_auth_compat.py @@ -0,0 +1,29 @@ +"""Provide a compatibility layer for requests.auth.HTTPDigestAuth.""" +import requests + + +class _ThreadingDescriptor(object): + def __init__(self, prop, default): + self.prop = prop + self.default = default + + def __get__(self, obj, objtype=None): + return getattr(obj._thread_local, self.prop, self.default) + + def __set__(self, obj, value): + setattr(obj._thread_local, self.prop, value) + + +class _HTTPDigestAuth(requests.auth.HTTPDigestAuth): + init = _ThreadingDescriptor('init', True) + last_nonce = _ThreadingDescriptor('last_nonce', '') + nonce_count = _ThreadingDescriptor('nonce_count', 0) + chal = _ThreadingDescriptor('chal', {}) + pos = _ThreadingDescriptor('pos', None) + num_401_calls = _ThreadingDescriptor('num_401_calls', 1) + + +if requests.__build__ < 0x020800: + HTTPDigestAuth = requests.auth.HTTPDigestAuth +else: + HTTPDigestAuth = _HTTPDigestAuth diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/guess.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/guess.py new file mode 100644 index 0000000000000000000000000000000000000000..ba6de504a85a575b12a24245aec15321c967f7fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/guess.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +"""The module containing the code for GuessAuth.""" +from requests import auth +from requests import cookies + +from . import _digest_auth_compat as auth_compat, http_proxy_digest + + +class GuessAuth(auth.AuthBase): + """Guesses the auth type by the WWW-Authentication header.""" + def __init__(self, username, password): + self.username = username + self.password = password + self.auth = None + self.pos = None + + def _handle_basic_auth_401(self, r, kwargs): + if self.pos is not None: + r.request.body.seek(self.pos) + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + r.content + r.raw.release_conn() + prep = r.request.copy() + if not hasattr(prep, '_cookies'): + prep._cookies = cookies.RequestsCookieJar() + cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw) + prep.prepare_cookies(prep._cookies) + + self.auth = auth.HTTPBasicAuth(self.username, self.password) + prep = self.auth(prep) + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + + def _handle_digest_auth_401(self, r, kwargs): + self.auth = auth_compat.HTTPDigestAuth(self.username, self.password) + try: + self.auth.init_per_thread_state() + except AttributeError: + # If we're not on requests 2.8.0+ this method does not exist and + # is not relevant. + pass + + # Check that the attr exists because much older versions of requests + # set this attribute lazily. For example: + # https://github.com/kennethreitz/requests/blob/33735480f77891754304e7f13e3cdf83aaaa76aa/requests/auth.py#L59 + if (hasattr(self.auth, 'num_401_calls') and + self.auth.num_401_calls is None): + self.auth.num_401_calls = 1 + # Digest auth would resend the request by itself. We can take a + # shortcut here. + return self.auth.handle_401(r, **kwargs) + + def handle_401(self, r, **kwargs): + """Resends a request with auth headers, if needed.""" + + www_authenticate = r.headers.get('www-authenticate', '').lower() + + if 'basic' in www_authenticate: + return self._handle_basic_auth_401(r, kwargs) + + if 'digest' in www_authenticate: + return self._handle_digest_auth_401(r, kwargs) + + def __call__(self, request): + if self.auth is not None: + return self.auth(request) + + try: + self.pos = request.body.tell() + except AttributeError: + pass + + request.register_hook('response', self.handle_401) + return request + + +class GuessProxyAuth(GuessAuth): + """ + Guesses the auth type by WWW-Authentication and Proxy-Authentication + headers + """ + def __init__(self, username=None, password=None, + proxy_username=None, proxy_password=None): + super(GuessProxyAuth, self).__init__(username, password) + self.proxy_username = proxy_username + self.proxy_password = proxy_password + self.proxy_auth = None + + def _handle_basic_auth_407(self, r, kwargs): + if self.pos is not None: + r.request.body.seek(self.pos) + + r.content + r.raw.release_conn() + prep = r.request.copy() + if not hasattr(prep, '_cookies'): + prep._cookies = cookies.RequestsCookieJar() + cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw) + prep.prepare_cookies(prep._cookies) + + self.proxy_auth = auth.HTTPProxyAuth(self.proxy_username, + self.proxy_password) + prep = self.proxy_auth(prep) + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + + def _handle_digest_auth_407(self, r, kwargs): + self.proxy_auth = http_proxy_digest.HTTPProxyDigestAuth( + username=self.proxy_username, + password=self.proxy_password) + + try: + self.auth.init_per_thread_state() + except AttributeError: + pass + + return self.proxy_auth.handle_407(r, **kwargs) + + def handle_407(self, r, **kwargs): + proxy_authenticate = r.headers.get('Proxy-Authenticate', '').lower() + + if 'basic' in proxy_authenticate: + return self._handle_basic_auth_407(r, kwargs) + + if 'digest' in proxy_authenticate: + return self._handle_digest_auth_407(r, kwargs) + + def __call__(self, request): + if self.proxy_auth is not None: + request = self.proxy_auth(request) + + try: + self.pos = request.body.tell() + except AttributeError: + pass + + request.register_hook('response', self.handle_407) + return super(GuessProxyAuth, self).__call__(request) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/handler.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/handler.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4051a8028acc7904faf40a4b8e7fc78c797951 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/handler.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +""" + +requests_toolbelt.auth.handler +============================== + +This holds all of the implementation details of the Authentication Handler. + +""" + +from requests.auth import AuthBase, HTTPBasicAuth +from requests.compat import urlparse, urlunparse + + +class AuthHandler(AuthBase): + + """ + + The ``AuthHandler`` object takes a dictionary of domains paired with + authentication strategies and will use this to determine which credentials + to use when making a request. For example, you could do the following: + + .. code-block:: python + + from requests import HTTPDigestAuth + from requests_toolbelt.auth.handler import AuthHandler + + import requests + + auth = AuthHandler({ + 'https://api.github.com': ('sigmavirus24', 'fakepassword'), + 'https://example.com': HTTPDigestAuth('username', 'password') + }) + + r = requests.get('https://api.github.com/user', auth=auth) + # => + r = requests.get('https://example.com/some/path', auth=auth) + # => + + s = requests.Session() + s.auth = auth + r = s.get('https://api.github.com/user') + # => + + .. warning:: + + :class:`requests.auth.HTTPDigestAuth` is not yet thread-safe. If you + use :class:`AuthHandler` across multiple threads you should + instantiate a new AuthHandler for each thread with a new + HTTPDigestAuth instance for each thread. + + """ + + def __init__(self, strategies): + self.strategies = dict(strategies) + self._make_uniform() + + def __call__(self, request): + auth = self.get_strategy_for(request.url) + return auth(request) + + def __repr__(self): + return ''.format(self.strategies) + + def _make_uniform(self): + existing_strategies = list(self.strategies.items()) + self.strategies = {} + + for (k, v) in existing_strategies: + self.add_strategy(k, v) + + @staticmethod + def _key_from_url(url): + parsed = urlparse(url) + return urlunparse((parsed.scheme.lower(), + parsed.netloc.lower(), + '', '', '', '')) + + def add_strategy(self, domain, strategy): + """Add a new domain and authentication strategy. + + :param str domain: The domain you wish to match against. For example: + ``'https://api.github.com'`` + :param str strategy: The authentication strategy you wish to use for + that domain. For example: ``('username', 'password')`` or + ``requests.HTTPDigestAuth('username', 'password')`` + + .. code-block:: python + + a = AuthHandler({}) + a.add_strategy('https://api.github.com', ('username', 'password')) + + """ + # Turn tuples into Basic Authentication objects + if isinstance(strategy, tuple): + strategy = HTTPBasicAuth(*strategy) + + key = self._key_from_url(domain) + self.strategies[key] = strategy + + def get_strategy_for(self, url): + """Retrieve the authentication strategy for a specified URL. + + :param str url: The full URL you will be making a request against. For + example, ``'https://api.github.com/user'`` + :returns: Callable that adds authentication to a request. + + .. code-block:: python + + import requests + a = AuthHandler({'example.com', ('foo', 'bar')}) + strategy = a.get_strategy_for('http://example.com/example') + assert isinstance(strategy, requests.auth.HTTPBasicAuth) + + """ + key = self._key_from_url(url) + return self.strategies.get(key, NullAuthStrategy()) + + def remove_strategy(self, domain): + """Remove the domain and strategy from the collection of strategies. + + :param str domain: The domain you wish remove. For example, + ``'https://api.github.com'``. + + .. code-block:: python + + a = AuthHandler({'example.com', ('foo', 'bar')}) + a.remove_strategy('example.com') + assert a.strategies == {} + + """ + key = self._key_from_url(domain) + if key in self.strategies: + del self.strategies[key] + + +class NullAuthStrategy(AuthBase): + def __repr__(self): + return '' + + def __call__(self, r): + return r diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/http_proxy_digest.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/http_proxy_digest.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1f69ef7efecf7ae0de20220a03223b4216f6e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/auth/http_proxy_digest.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +"""The module containing HTTPProxyDigestAuth.""" +import re + +from requests import cookies, utils + +from . import _digest_auth_compat as auth + + +class HTTPProxyDigestAuth(auth.HTTPDigestAuth): + """HTTP digest authentication between proxy + + :param stale_rejects: The number of rejects indicate that: + the client may wish to simply retry the request + with a new encrypted response, without reprompting the user for a + new username and password. i.e., retry build_digest_header + :type stale_rejects: int + """ + _pat = re.compile(r'digest ', flags=re.IGNORECASE) + + def __init__(self, *args, **kwargs): + super(HTTPProxyDigestAuth, self).__init__(*args, **kwargs) + self.stale_rejects = 0 + + self.init_per_thread_state() + + @property + def stale_rejects(self): + thread_local = getattr(self, '_thread_local', None) + if thread_local is None: + return self._stale_rejects + return thread_local.stale_rejects + + @stale_rejects.setter + def stale_rejects(self, value): + thread_local = getattr(self, '_thread_local', None) + if thread_local is None: + self._stale_rejects = value + else: + thread_local.stale_rejects = value + + def init_per_thread_state(self): + try: + super(HTTPProxyDigestAuth, self).init_per_thread_state() + except AttributeError: + # If we're not on requests 2.8.0+ this method does not exist + pass + + def handle_407(self, r, **kwargs): + """Handle HTTP 407 only once, otherwise give up + + :param r: current response + :returns: responses, along with the new response + """ + if r.status_code == 407 and self.stale_rejects < 2: + s_auth = r.headers.get("proxy-authenticate") + if s_auth is None: + raise IOError( + "proxy server violated RFC 7235:" + "407 response MUST contain header proxy-authenticate") + elif not self._pat.match(s_auth): + return r + + self.chal = utils.parse_dict_header( + self._pat.sub('', s_auth, count=1)) + + # if we present the user/passwd and still get rejected + # https://tools.ietf.org/html/rfc2617#section-3.2.1 + if ('Proxy-Authorization' in r.request.headers and + 'stale' in self.chal): + if self.chal['stale'].lower() == 'true': # try again + self.stale_rejects += 1 + # wrong user/passwd + elif self.chal['stale'].lower() == 'false': + raise IOError("User or password is invalid") + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + r.content + r.close() + prep = r.request.copy() + cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw) + prep.prepare_cookies(prep._cookies) + + prep.headers['Proxy-Authorization'] = self.build_digest_header( + prep.method, prep.url) + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + else: # give up authenticate + return r + + def __call__(self, r): + self.init_per_thread_state() + # if we have nonce, then just use it, otherwise server will tell us + if self.last_nonce: + r.headers['Proxy-Authorization'] = self.build_digest_header( + r.method, r.url + ) + r.register_hook('response', self.handle_407) + return r diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/cookies/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/cookies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/cookies/forgetful.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/cookies/forgetful.py new file mode 100644 index 0000000000000000000000000000000000000000..33203638470956e2eb42b3d518f2be6882ac2079 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/cookies/forgetful.py @@ -0,0 +1,7 @@ +"""The module containing the code for ForgetfulCookieJar.""" +from requests.cookies import RequestsCookieJar + + +class ForgetfulCookieJar(RequestsCookieJar): + def set_cookie(self, *args, **kwargs): + return diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/stream.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/stream.py new file mode 100644 index 0000000000000000000000000000000000000000..7253d96e019e46a60aae2644aaf0149a49e337f6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/stream.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +"""Utilities for dealing with streamed requests.""" +import os.path +import re + +from .. import exceptions as exc + +# Regular expressions stolen from werkzeug/http.py +# cd2c97bb0a076da2322f11adce0b2731f9193396 L62-L64 +_QUOTED_STRING_RE = r'"[^"\\]*(?:\\.[^"\\]*)*"' +_OPTION_HEADER_PIECE_RE = re.compile( + r';\s*(%s|[^\s;=]+)\s*(?:=\s*(%s|[^;]+))?\s*' % (_QUOTED_STRING_RE, + _QUOTED_STRING_RE) +) +_DEFAULT_CHUNKSIZE = 512 + + +def _get_filename(content_disposition): + for match in _OPTION_HEADER_PIECE_RE.finditer(content_disposition): + k, v = match.groups() + if k == 'filename': + # ignore any directory paths in the filename + return os.path.split(v)[1] + return None + + +def get_download_file_path(response, path): + """ + Given a response and a path, return a file path for a download. + + If a ``path`` parameter is a directory, this function will parse the + ``Content-Disposition`` header on the response to determine the name of the + file as reported by the server, and return a file path in the specified + directory. + + If ``path`` is empty or None, this function will return a path relative + to the process' current working directory. + + If path is a full file path, return it. + + :param response: A Response object from requests + :type response: requests.models.Response + :param str path: Directory or file path. + :returns: full file path to download as + :rtype: str + :raises: :class:`requests_toolbelt.exceptions.StreamingError` + """ + path_is_dir = path and os.path.isdir(path) + + if path and not path_is_dir: + # fully qualified file path + filepath = path + else: + response_filename = _get_filename( + response.headers.get('content-disposition', '') + ) + if not response_filename: + raise exc.StreamingError('No filename given to stream response to') + + if path_is_dir: + # directory to download to + filepath = os.path.join(path, response_filename) + else: + # fallback to downloading to current working directory + filepath = response_filename + + return filepath + + +def stream_response_to_file(response, path=None, chunksize=_DEFAULT_CHUNKSIZE): + """Stream a response body to the specified file. + + Either use the ``path`` provided or use the name provided in the + ``Content-Disposition`` header. + + .. warning:: + + If you pass this function an open file-like object as the ``path`` + parameter, the function will not close that file for you. + + .. warning:: + + This function will not automatically close the response object + passed in as the ``response`` parameter. + + If a ``path`` parameter is a directory, this function will parse the + ``Content-Disposition`` header on the response to determine the name of the + file as reported by the server, and return a file path in the specified + directory. If no ``path`` parameter is supplied, this function will default + to the process' current working directory. + + .. code-block:: python + + import requests + from requests_toolbelt import exceptions + from requests_toolbelt.downloadutils import stream + + r = requests.get(url, stream=True) + try: + filename = stream.stream_response_to_file(r) + except exceptions.StreamingError as e: + # The toolbelt could not find the filename in the + # Content-Disposition + print(e.message) + + You can also specify the filename as a string. This will be passed to + the built-in :func:`open` and we will read the content into the file. + + .. code-block:: python + + import requests + from requests_toolbelt.downloadutils import stream + + r = requests.get(url, stream=True) + filename = stream.stream_response_to_file(r, path='myfile') + + If the calculated download file path already exists, this function will + raise a StreamingError. + + Instead, if you want to manage the file object yourself, you need to + provide either a :class:`io.BytesIO` object or a file opened with the + `'b'` flag. See the two examples below for more details. + + .. code-block:: python + + import requests + from requests_toolbelt.downloadutils import stream + + with open('myfile', 'wb') as fd: + r = requests.get(url, stream=True) + filename = stream.stream_response_to_file(r, path=fd) + + print('{} saved to {}'.format(url, filename)) + + .. code-block:: python + + import io + import requests + from requests_toolbelt.downloadutils import stream + + b = io.BytesIO() + r = requests.get(url, stream=True) + filename = stream.stream_response_to_file(r, path=b) + assert filename is None + + :param response: A Response object from requests + :type response: requests.models.Response + :param path: *(optional)*, Either a string with the path to the location + to save the response content, or a file-like object expecting bytes. + :type path: :class:`str`, or object with a :meth:`write` + :param int chunksize: (optional), Size of chunk to attempt to stream + (default 512B). + :returns: The name of the file, if one can be determined, else None + :rtype: str + :raises: :class:`requests_toolbelt.exceptions.StreamingError` + """ + pre_opened = False + fd = None + filename = None + if path and callable(getattr(path, 'write', None)): + pre_opened = True + fd = path + filename = getattr(fd, 'name', None) + else: + filename = get_download_file_path(response, path) + if os.path.exists(filename): + raise exc.StreamingError("File already exists: %s" % filename) + fd = open(filename, 'wb') + + for chunk in response.iter_content(chunk_size=chunksize): + fd.write(chunk) + + if not pre_opened: + fd.close() + + return filename diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/tee.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/tee.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc7d0cddb99a4bf3664fb7b63b81afabbaff614 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/downloadutils/tee.py @@ -0,0 +1,123 @@ +"""Tee function implementations.""" +import io + +_DEFAULT_CHUNKSIZE = 65536 + +__all__ = ['tee', 'tee_to_file', 'tee_to_bytearray'] + + +def _tee(response, callback, chunksize, decode_content): + for chunk in response.raw.stream(amt=chunksize, + decode_content=decode_content): + callback(chunk) + yield chunk + + +def tee(response, fileobject, chunksize=_DEFAULT_CHUNKSIZE, + decode_content=None): + """Stream the response both to the generator and a file. + + This will stream the response body while writing the bytes to + ``fileobject``. + + Example usage: + + .. code-block:: python + + resp = requests.get(url, stream=True) + with open('save_file', 'wb') as save_file: + for chunk in tee(resp, save_file): + # do stuff with chunk + + .. code-block:: python + + import io + + resp = requests.get(url, stream=True) + fileobject = io.BytesIO() + + for chunk in tee(resp, fileobject): + # do stuff with chunk + + :param response: Response from requests. + :type response: requests.Response + :param fileobject: Writable file-like object. + :type fileobject: file, io.BytesIO + :param int chunksize: (optional), Size of chunk to attempt to stream. + :param bool decode_content: (optional), If True, this will decode the + compressed content of the response. + :raises: TypeError if the fileobject wasn't opened with the right mode + or isn't a BytesIO object. + """ + # We will be streaming the raw bytes from over the wire, so we need to + # ensure that writing to the fileobject will preserve those bytes. On + # Python3, if the user passes an io.StringIO, this will fail, so we need + # to check for BytesIO instead. + if not ('b' in getattr(fileobject, 'mode', '') or + isinstance(fileobject, io.BytesIO)): + raise TypeError('tee() will write bytes directly to this fileobject' + ', it must be opened with the "b" flag if it is a file' + ' or inherit from io.BytesIO.') + + return _tee(response, fileobject.write, chunksize, decode_content) + + +def tee_to_file(response, filename, chunksize=_DEFAULT_CHUNKSIZE, + decode_content=None): + """Stream the response both to the generator and a file. + + This will open a file named ``filename`` and stream the response body + while writing the bytes to the opened file object. + + Example usage: + + .. code-block:: python + + resp = requests.get(url, stream=True) + for chunk in tee_to_file(resp, 'save_file'): + # do stuff with chunk + + :param response: Response from requests. + :type response: requests.Response + :param str filename: Name of file in which we write the response content. + :param int chunksize: (optional), Size of chunk to attempt to stream. + :param bool decode_content: (optional), If True, this will decode the + compressed content of the response. + """ + with open(filename, 'wb') as fd: + for chunk in tee(response, fd, chunksize, decode_content): + yield chunk + + +def tee_to_bytearray(response, bytearr, chunksize=_DEFAULT_CHUNKSIZE, + decode_content=None): + """Stream the response both to the generator and a bytearray. + + This will stream the response provided to the function, add them to the + provided :class:`bytearray` and yield them to the user. + + .. note:: + + This uses the :meth:`bytearray.extend` by default instead of passing + the bytearray into the ``readinto`` method. + + Example usage: + + .. code-block:: python + + b = bytearray() + resp = requests.get(url, stream=True) + for chunk in tee_to_bytearray(resp, b): + # do stuff with chunk + + :param response: Response from requests. + :type response: requests.Response + :param bytearray bytearr: Array to add the streamed bytes to. + :param int chunksize: (optional), Size of chunk to attempt to stream. + :param bool decode_content: (optional), If True, this will decode the + compressed content of the response. + """ + if not isinstance(bytearr, bytearray): + raise TypeError('tee_to_bytearray() expects bytearr to be a ' + 'bytearray') + return _tee(response, bytearr.extend, chunksize, decode_content) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3bced1c85849e4562ce94216e38cea47406ec89 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/__init__.py @@ -0,0 +1,31 @@ +""" +requests_toolbelt.multipart +=========================== + +See https://toolbelt.readthedocs.io/ for documentation + +:copyright: (c) 2014 by Ian Cordasco and Cory Benfield +:license: Apache v2.0, see LICENSE for more details +""" + +from .encoder import MultipartEncoder, MultipartEncoderMonitor +from .decoder import MultipartDecoder +from .decoder import ImproperBodyPartContentException +from .decoder import NonMultipartContentTypeException + +__title__ = 'requests-toolbelt' +__authors__ = 'Ian Cordasco, Cory Benfield' +__license__ = 'Apache v2.0' +__copyright__ = 'Copyright 2014 Ian Cordasco, Cory Benfield' + +__all__ = [ + 'MultipartEncoder', + 'MultipartEncoderMonitor', + 'MultipartDecoder', + 'ImproperBodyPartContentException', + 'NonMultipartContentTypeException', + '__title__', + '__authors__', + '__license__', + '__copyright__', +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/decoder.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2a0d1c46d7bb47c262a6cb30b100f7300512dbb0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/decoder.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +""" + +requests_toolbelt.multipart.decoder +=================================== + +This holds all the implementation details of the MultipartDecoder + +""" + +import sys +import email.parser +from .encoder import encode_with +from requests.structures import CaseInsensitiveDict + + +def _split_on_find(content, bound): + point = content.find(bound) + return content[:point], content[point + len(bound):] + + +class ImproperBodyPartContentException(Exception): + pass + + +class NonMultipartContentTypeException(Exception): + pass + + +def _header_parser(string, encoding): + major = sys.version_info[0] + if major == 3: + string = string.decode(encoding) + headers = email.parser.HeaderParser().parsestr(string).items() + return ( + (encode_with(k, encoding), encode_with(v, encoding)) + for k, v in headers + ) + + +class BodyPart(object): + """ + + The ``BodyPart`` object is a ``Response``-like interface to an individual + subpart of a multipart response. It is expected that these will + generally be created by objects of the ``MultipartDecoder`` class. + + Like ``Response``, there is a ``CaseInsensitiveDict`` object named headers, + ``content`` to access bytes, ``text`` to access unicode, and ``encoding`` + to access the unicode codec. + + """ + + def __init__(self, content, encoding): + self.encoding = encoding + headers = {} + # Split into header section (if any) and the content + if b'\r\n\r\n' in content: + first, self.content = _split_on_find(content, b'\r\n\r\n') + if first != b'': + headers = _header_parser(first.lstrip(), encoding) + else: + raise ImproperBodyPartContentException( + 'content does not contain CR-LF-CR-LF' + ) + self.headers = CaseInsensitiveDict(headers) + + @property + def text(self): + """Content of the ``BodyPart`` in unicode.""" + return self.content.decode(self.encoding) + + +class MultipartDecoder(object): + """ + + The ``MultipartDecoder`` object parses the multipart payload of + a bytestring into a tuple of ``Response``-like ``BodyPart`` objects. + + The basic usage is:: + + import requests + from requests_toolbelt import MultipartDecoder + + response = requests.get(url) + decoder = MultipartDecoder.from_response(response) + for part in decoder.parts: + print(part.headers['content-type']) + + If the multipart content is not from a response, basic usage is:: + + from requests_toolbelt import MultipartDecoder + + decoder = MultipartDecoder(content, content_type) + for part in decoder.parts: + print(part.headers['content-type']) + + For both these usages, there is an optional ``encoding`` parameter. This is + a string, which is the name of the unicode codec to use (default is + ``'utf-8'``). + + """ + def __init__(self, content, content_type, encoding='utf-8'): + #: Original Content-Type header + self.content_type = content_type + #: Response body encoding + self.encoding = encoding + #: Parsed parts of the multipart response body + self.parts = tuple() + self._find_boundary() + self._parse_body(content) + + def _find_boundary(self): + ct_info = tuple(x.strip() for x in self.content_type.split(';')) + mimetype = ct_info[0] + if mimetype.split('/')[0].lower() != 'multipart': + raise NonMultipartContentTypeException( + "Unexpected mimetype in content-type: '{}'".format(mimetype) + ) + for item in ct_info[1:]: + attr, value = _split_on_find( + item, + '=' + ) + if attr.lower() == 'boundary': + self.boundary = encode_with(value.strip('"'), self.encoding) + + @staticmethod + def _fix_first_part(part, boundary_marker): + bm_len = len(boundary_marker) + if boundary_marker == part[:bm_len]: + return part[bm_len:] + else: + return part + + def _parse_body(self, content): + boundary = b''.join((b'--', self.boundary)) + + def body_part(part): + fixed = MultipartDecoder._fix_first_part(part, boundary) + return BodyPart(fixed, self.encoding) + + def test_part(part): + return (part != b'' and + part != b'\r\n' and + part[:4] != b'--\r\n' and + part != b'--') + + parts = content.split(b''.join((b'\r\n', boundary))) + self.parts = tuple(body_part(x) for x in parts if test_part(x)) + + @classmethod + def from_response(cls, response, encoding='utf-8'): + content = response.content + content_type = response.headers.get('content-type', None) + return cls(content, content_type, encoding) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/encoder.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5396172c4046a53a15af1d480d4c85a903bcec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/multipart/encoder.py @@ -0,0 +1,655 @@ +# -*- coding: utf-8 -*- +""" + +requests_toolbelt.multipart.encoder +=================================== + +This holds all of the implementation details of the MultipartEncoder + +""" +import contextlib +import io +import os +from uuid import uuid4 + +import requests + +from .._compat import fields + + +class FileNotSupportedError(Exception): + """File not supported error.""" + + +class MultipartEncoder(object): + + """ + + The ``MultipartEncoder`` object is a generic interface to the engine that + will create a ``multipart/form-data`` body for you. + + The basic usage is: + + .. code-block:: python + + import requests + from requests_toolbelt import MultipartEncoder + + encoder = MultipartEncoder({'field': 'value', + 'other_field': 'other_value'}) + r = requests.post('https://httpbin.org/post', data=encoder, + headers={'Content-Type': encoder.content_type}) + + If you do not need to take advantage of streaming the post body, you can + also do: + + .. code-block:: python + + r = requests.post('https://httpbin.org/post', + data=encoder.to_string(), + headers={'Content-Type': encoder.content_type}) + + If you want the encoder to use a specific order, you can use an + OrderedDict or more simply, a list of tuples: + + .. code-block:: python + + encoder = MultipartEncoder([('field', 'value'), + ('other_field', 'other_value')]) + + .. versionchanged:: 0.4.0 + + You can also provide tuples as part values as you would provide them to + requests' ``files`` parameter. + + .. code-block:: python + + encoder = MultipartEncoder({ + 'field': ('file_name', b'{"a": "b"}', 'application/json', + {'X-My-Header': 'my-value'}) + ]) + + .. warning:: + + This object will end up directly in :mod:`httplib`. Currently, + :mod:`httplib` has a hard-coded read size of **8192 bytes**. This + means that it will loop until the file has been read and your upload + could take a while. This is **not** a bug in requests. A feature is + being considered for this object to allow you, the user, to specify + what size should be returned on a read. If you have opinions on this, + please weigh in on `this issue`_. + + .. _this issue: + https://github.com/requests/toolbelt/issues/75 + + """ + + def __init__(self, fields, boundary=None, encoding='utf-8'): + #: Boundary value either passed in by the user or created + self.boundary_value = boundary or uuid4().hex + + # Computed boundary + self.boundary = '--{}'.format(self.boundary_value) + + #: Encoding of the data being passed in + self.encoding = encoding + + # Pre-encoded boundary + self._encoded_boundary = b''.join([ + encode_with(self.boundary, self.encoding), + encode_with('\r\n', self.encoding) + ]) + + #: Fields provided by the user + self.fields = fields + + #: Whether or not the encoder is finished + self.finished = False + + #: Pre-computed parts of the upload + self.parts = [] + + # Pre-computed parts iterator + self._iter_parts = iter([]) + + # The part we're currently working with + self._current_part = None + + # Cached computation of the body's length + self._len = None + + # Our buffer + self._buffer = CustomBytesIO(encoding=encoding) + + # Pre-compute each part's headers + self._prepare_parts() + + # Load boundary into buffer + self._write_boundary() + + @property + def len(self): + """Length of the multipart/form-data body. + + requests will first attempt to get the length of the body by calling + ``len(body)`` and then by checking for the ``len`` attribute. + + On 32-bit systems, the ``__len__`` method cannot return anything + larger than an integer (in C) can hold. If the total size of the body + is even slightly larger than 4GB users will see an OverflowError. This + manifested itself in `bug #80`_. + + As such, we now calculate the length lazily as a property. + + .. _bug #80: + https://github.com/requests/toolbelt/issues/80 + """ + # If _len isn't already calculated, calculate, return, and set it + return self._len or self._calculate_length() + + def __repr__(self): + return ''.format(self.fields) + + def _calculate_length(self): + """ + This uses the parts to calculate the length of the body. + + This returns the calculated length so __len__ can be lazy. + """ + boundary_len = len(self.boundary) # Length of --{boundary} + # boundary length + header length + body length + len('\r\n') * 2 + self._len = sum( + (boundary_len + total_len(p) + 4) for p in self.parts + ) + boundary_len + 4 + return self._len + + def _calculate_load_amount(self, read_size): + """This calculates how many bytes need to be added to the buffer. + + When a consumer read's ``x`` from the buffer, there are two cases to + satisfy: + + 1. Enough data in the buffer to return the requested amount + 2. Not enough data + + This function uses the amount of unread bytes in the buffer and + determines how much the Encoder has to load before it can return the + requested amount of bytes. + + :param int read_size: the number of bytes the consumer requests + :returns: int -- the number of bytes that must be loaded into the + buffer before the read can be satisfied. This will be strictly + non-negative + """ + amount = read_size - total_len(self._buffer) + return amount if amount > 0 else 0 + + def _load(self, amount): + """Load ``amount`` number of bytes into the buffer.""" + self._buffer.smart_truncate() + part = self._current_part or self._next_part() + while amount == -1 or amount > 0: + written = 0 + if part and not part.bytes_left_to_write(): + written += self._write(b'\r\n') + written += self._write_boundary() + part = self._next_part() + + if not part: + written += self._write_closing_boundary() + self.finished = True + break + + written += part.write_to(self._buffer, amount) + + if amount != -1: + amount -= written + + def _next_part(self): + try: + p = self._current_part = next(self._iter_parts) + except StopIteration: + p = None + return p + + def _iter_fields(self): + _fields = self.fields + if hasattr(self.fields, 'items'): + _fields = list(self.fields.items()) + for k, v in _fields: + file_name = None + file_type = None + file_headers = None + if isinstance(v, (list, tuple)): + if len(v) == 2: + file_name, file_pointer = v + elif len(v) == 3: + file_name, file_pointer, file_type = v + else: + file_name, file_pointer, file_type, file_headers = v + else: + file_pointer = v + + field = fields.RequestField(name=k, data=file_pointer, + filename=file_name, + headers=file_headers) + field.make_multipart(content_type=file_type) + yield field + + def _prepare_parts(self): + """This uses the fields provided by the user and creates Part objects. + + It populates the `parts` attribute and uses that to create a + generator for iteration. + """ + enc = self.encoding + self.parts = [Part.from_field(f, enc) for f in self._iter_fields()] + self._iter_parts = iter(self.parts) + + def _write(self, bytes_to_write): + """Write the bytes to the end of the buffer. + + :param bytes bytes_to_write: byte-string (or bytearray) to append to + the buffer + :returns: int -- the number of bytes written + """ + return self._buffer.append(bytes_to_write) + + def _write_boundary(self): + """Write the boundary to the end of the buffer.""" + return self._write(self._encoded_boundary) + + def _write_closing_boundary(self): + """Write the bytes necessary to finish a multipart/form-data body.""" + with reset(self._buffer): + self._buffer.seek(-2, 2) + self._buffer.write(b'--\r\n') + return 2 + + def _write_headers(self, headers): + """Write the current part's headers to the buffer.""" + return self._write(encode_with(headers, self.encoding)) + + @property + def content_type(self): + return str( + 'multipart/form-data; boundary={}'.format(self.boundary_value) + ) + + def to_string(self): + """Return the entirety of the data in the encoder. + + .. note:: + + This simply reads all of the data it can. If you have started + streaming or reading data from the encoder, this method will only + return whatever data is left in the encoder. + + .. note:: + + This method affects the internal state of the encoder. Calling + this method will exhaust the encoder. + + :returns: the multipart message + :rtype: bytes + """ + + return self.read() + + def read(self, size=-1): + """Read data from the streaming encoder. + + :param int size: (optional), If provided, ``read`` will return exactly + that many bytes. If it is not provided, it will return the + remaining bytes. + :returns: bytes + """ + if self.finished: + return self._buffer.read(size) + + bytes_to_load = size + if bytes_to_load != -1 and bytes_to_load is not None: + bytes_to_load = self._calculate_load_amount(int(size)) + + self._load(bytes_to_load) + return self._buffer.read(size) + + +def IDENTITY(monitor): + return monitor + + +class MultipartEncoderMonitor(object): + + """ + An object used to monitor the progress of a :class:`MultipartEncoder`. + + The :class:`MultipartEncoder` should only be responsible for preparing and + streaming the data. For anyone who wishes to monitor it, they shouldn't be + using that instance to manage that as well. Using this class, they can + monitor an encoder and register a callback. The callback receives the + instance of the monitor. + + To use this monitor, you construct your :class:`MultipartEncoder` as you + normally would. + + .. code-block:: python + + from requests_toolbelt import (MultipartEncoder, + MultipartEncoderMonitor) + import requests + + def callback(monitor): + # Do something with this information + pass + + m = MultipartEncoder(fields={'field0': 'value0'}) + monitor = MultipartEncoderMonitor(m, callback) + headers = {'Content-Type': monitor.content_type} + r = requests.post('https://httpbin.org/post', data=monitor, + headers=headers) + + Alternatively, if your use case is very simple, you can use the following + pattern. + + .. code-block:: python + + from requests_toolbelt import MultipartEncoderMonitor + import requests + + def callback(monitor): + # Do something with this information + pass + + monitor = MultipartEncoderMonitor.from_fields( + fields={'field0': 'value0'}, callback + ) + headers = {'Content-Type': montior.content_type} + r = requests.post('https://httpbin.org/post', data=monitor, + headers=headers) + + """ + + def __init__(self, encoder, callback=None): + #: Instance of the :class:`MultipartEncoder` being monitored + self.encoder = encoder + + #: Optionally function to call after a read + self.callback = callback or IDENTITY + + #: Number of bytes already read from the :class:`MultipartEncoder` + #: instance + self.bytes_read = 0 + + #: Avoid the same problem in bug #80 + self.len = self.encoder.len + + @classmethod + def from_fields(cls, fields, boundary=None, encoding='utf-8', + callback=None): + encoder = MultipartEncoder(fields, boundary, encoding) + return cls(encoder, callback) + + @property + def content_type(self): + return self.encoder.content_type + + def to_string(self): + return self.read() + + def read(self, size=-1): + string = self.encoder.read(size) + self.bytes_read += len(string) + self.callback(self) + return string + + +def encode_with(string, encoding): + """Encoding ``string`` with ``encoding`` if necessary. + + :param str string: If string is a bytes object, it will not encode it. + Otherwise, this function will encode it with the provided encoding. + :param str encoding: The encoding with which to encode string. + :returns: encoded bytes object + """ + if not (string is None or isinstance(string, bytes)): + return string.encode(encoding) + return string + + +def readable_data(data, encoding): + """Coerce the data to an object with a ``read`` method.""" + if hasattr(data, 'read'): + return data + + return CustomBytesIO(data, encoding) + + +def total_len(o): + if hasattr(o, '__len__'): + return len(o) + + if hasattr(o, 'len'): + return o.len + + if hasattr(o, 'fileno'): + try: + fileno = o.fileno() + except io.UnsupportedOperation: + pass + else: + return os.fstat(fileno).st_size + + if hasattr(o, 'getvalue'): + # e.g. BytesIO, cStringIO.StringIO + return len(o.getvalue()) + + +@contextlib.contextmanager +def reset(buffer): + """Keep track of the buffer's current position and write to the end. + + This is a context manager meant to be used when adding data to the buffer. + It eliminates the need for every function to be concerned with the + position of the cursor in the buffer. + """ + original_position = buffer.tell() + buffer.seek(0, 2) + yield + buffer.seek(original_position, 0) + + +def coerce_data(data, encoding): + """Ensure that every object's __len__ behaves uniformly.""" + if not isinstance(data, CustomBytesIO): + if hasattr(data, 'getvalue'): + return CustomBytesIO(data.getvalue(), encoding) + + if hasattr(data, 'fileno'): + return FileWrapper(data) + + if not hasattr(data, 'read'): + return CustomBytesIO(data, encoding) + + return data + + +def to_list(fields): + if hasattr(fields, 'items'): + return list(fields.items()) + return list(fields) + + +class Part(object): + def __init__(self, headers, body): + self.headers = headers + self.body = body + self.headers_unread = True + self.len = len(self.headers) + total_len(self.body) + + @classmethod + def from_field(cls, field, encoding): + """Create a part from a Request Field generated by urllib3.""" + headers = encode_with(field.render_headers(), encoding) + body = coerce_data(field.data, encoding) + return cls(headers, body) + + def bytes_left_to_write(self): + """Determine if there are bytes left to write. + + :returns: bool -- ``True`` if there are bytes left to write, otherwise + ``False`` + """ + to_read = 0 + if self.headers_unread: + to_read += len(self.headers) + + return (to_read + total_len(self.body)) > 0 + + def write_to(self, buffer, size): + """Write the requested amount of bytes to the buffer provided. + + The number of bytes written may exceed size on the first read since we + load the headers ambitiously. + + :param CustomBytesIO buffer: buffer we want to write bytes to + :param int size: number of bytes requested to be written to the buffer + :returns: int -- number of bytes actually written + """ + written = 0 + if self.headers_unread: + written += buffer.append(self.headers) + self.headers_unread = False + + while total_len(self.body) > 0 and (size == -1 or written < size): + amount_to_read = size + if size != -1: + amount_to_read = size - written + written += buffer.append(self.body.read(amount_to_read)) + + return written + + +class CustomBytesIO(io.BytesIO): + def __init__(self, buffer=None, encoding='utf-8'): + buffer = encode_with(buffer, encoding) + super(CustomBytesIO, self).__init__(buffer) + + def _get_end(self): + current_pos = self.tell() + self.seek(0, 2) + length = self.tell() + self.seek(current_pos, 0) + return length + + @property + def len(self): + length = self._get_end() + return length - self.tell() + + def append(self, bytes): + with reset(self): + written = self.write(bytes) + return written + + def smart_truncate(self): + to_be_read = total_len(self) + already_read = self._get_end() - to_be_read + + if already_read >= to_be_read: + old_bytes = self.read() + self.seek(0, 0) + self.truncate() + self.write(old_bytes) + self.seek(0, 0) # We want to be at the beginning + + +class FileWrapper(object): + def __init__(self, file_object): + self.fd = file_object + + @property + def len(self): + return total_len(self.fd) - self.fd.tell() + + def read(self, length=-1): + return self.fd.read(length) + + +class FileFromURLWrapper(object): + """File from URL wrapper. + + The :class:`FileFromURLWrapper` object gives you the ability to stream file + from provided URL in chunks by :class:`MultipartEncoder`. + Provide a stateless solution for streaming file from one server to another. + You can use the :class:`FileFromURLWrapper` without a session or with + a session as demonstated by the examples below: + + .. code-block:: python + # no session + + import requests + from requests_toolbelt import MultipartEncoder, FileFromURLWrapper + + url = 'https://httpbin.org/image/png' + streaming_encoder = MultipartEncoder( + fields={ + 'file': FileFromURLWrapper(url) + } + ) + r = requests.post( + 'https://httpbin.org/post', data=streaming_encoder, + headers={'Content-Type': streaming_encoder.content_type} + ) + + .. code-block:: python + # using a session + + import requests + from requests_toolbelt import MultipartEncoder, FileFromURLWrapper + + session = requests.Session() + url = 'https://httpbin.org/image/png' + streaming_encoder = MultipartEncoder( + fields={ + 'file': FileFromURLWrapper(url, session=session) + } + ) + r = session.post( + 'https://httpbin.org/post', data=streaming_encoder, + headers={'Content-Type': streaming_encoder.content_type} + ) + + """ + + def __init__(self, file_url, session=None): + self.session = session or requests.Session() + requested_file = self._request_for_file(file_url) + self.len = int(requested_file.headers['content-length']) + self.raw_data = requested_file.raw + + def _request_for_file(self, file_url): + """Make call for file under provided URL.""" + response = self.session.get(file_url, stream=True) + content_length = response.headers.get('content-length', None) + if content_length is None: + error_msg = ( + "Data from provided URL {url} is not supported. Lack of " + "content-length Header in requested file response.".format( + url=file_url) + ) + raise FileNotSupportedError(error_msg) + elif not content_length.isdigit(): + error_msg = ( + "Data from provided URL {url} is not supported. content-length" + " header value is not a digit.".format(url=file_url) + ) + raise FileNotSupportedError(error_msg) + return response + + def read(self, chunk_size): + """Read file in chunks.""" + chunk_size = chunk_size if chunk_size >= 0 else self.len + chunk = self.raw_data.read(chunk_size) or b'' + self.len -= len(chunk) if chunk else 0 # left to read + return chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..984f1e8014ba15c93500f55086ab892dc9b46755 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__init__.py @@ -0,0 +1,97 @@ +""" +This module provides the API for ``requests_toolbelt.threaded``. + +The module provides a clean and simple API for making requests via a thread +pool. The thread pool will use sessions for increased performance. + +A simple use-case is: + +.. code-block:: python + + from requests_toolbelt import threaded + + urls_to_get = [{ + 'url': 'https://api.github.com/users/sigmavirus24', + 'method': 'GET', + }, { + 'url': 'https://api.github.com/repos/requests/toolbelt', + 'method': 'GET', + }, { + 'url': 'https://google.com', + 'method': 'GET', + }] + responses, errors = threaded.map(urls_to_get) + +By default, the threaded submodule will detect the number of CPUs your +computer has and use that if no other number of processes is selected. To +change this, always use the keyword argument ``num_processes``. Using the +above example, we would expand it like so: + +.. code-block:: python + + responses, errors = threaded.map(urls_to_get, num_processes=10) + +You can also customize how a :class:`requests.Session` is initialized by +creating a callback function: + +.. code-block:: python + + from requests_toolbelt import user_agent + + def initialize_session(session): + session.headers['User-Agent'] = user_agent('my-scraper', '0.1') + session.headers['Accept'] = 'application/json' + + responses, errors = threaded.map(urls_to_get, + initializer=initialize_session) + +.. autofunction:: requests_toolbelt.threaded.map + +Inspiration is blatantly drawn from the standard library's multiprocessing +library. See the following references: + +- multiprocessing's `pool source`_ + +- map and map_async `inspiration`_ + +.. _pool source: + https://hg.python.org/cpython/file/8ef4f75a8018/Lib/multiprocessing/pool.py +.. _inspiration: + https://hg.python.org/cpython/file/8ef4f75a8018/Lib/multiprocessing/pool.py#l340 +""" +from . import pool +from .._compat import queue + + +def map(requests, **kwargs): + r"""Simple interface to the threaded Pool object. + + This function takes a list of dictionaries representing requests to make + using Sessions in threads and returns a tuple where the first item is + a generator of successful responses and the second is a generator of + exceptions. + + :param list requests: + Collection of dictionaries representing requests to make with the Pool + object. + :param \*\*kwargs: + Keyword arguments that are passed to the + :class:`~requests_toolbelt.threaded.pool.Pool` object. + :returns: Tuple of responses and exceptions from the pool + :rtype: (:class:`~requests_toolbelt.threaded.pool.ThreadResponse`, + :class:`~requests_toolbelt.threaded.pool.ThreadException`) + """ + if not (requests and all(isinstance(r, dict) for r in requests)): + raise ValueError('map expects a list of dictionaries.') + + # Build our queue of requests + job_queue = queue.Queue() + for request in requests: + job_queue.put(request) + + # Ensure the user doesn't try to pass their own job_queue + kwargs['job_queue'] = job_queue + + threadpool = pool.Pool(**kwargs) + threadpool.join_all() + return threadpool.responses(), threadpool.exceptions() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac29c9948336e04d9ee788991926a9347d199850 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/pool.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/pool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2b854dacdc24e8a53fa5fd9eeb6474a373823c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/pool.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/thread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/thread.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..021920c440a079c00b702b6e3a5f5dc15db633c6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/__pycache__/thread.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/pool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/pool.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe81461a9b4491c4f03411a889ccabdf235b9d6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/pool.py @@ -0,0 +1,211 @@ +"""Module implementing the Pool for :mod:``requests_toolbelt.threaded``.""" +import multiprocessing +import requests + +from . import thread +from .._compat import queue + + +class Pool(object): + """Pool that manages the threads containing sessions. + + :param queue: + The queue you're expected to use to which you should add items. + :type queue: queue.Queue + :param initializer: + Function used to initialize an instance of ``session``. + :type initializer: collections.Callable + :param auth_generator: + Function used to generate new auth credentials for the session. + :type auth_generator: collections.Callable + :param int num_process: + Number of threads to create. + :param session: + :type session: requests.Session + """ + + def __init__(self, job_queue, initializer=None, auth_generator=None, + num_processes=None, session=requests.Session): + if num_processes is None: + num_processes = multiprocessing.cpu_count() or 1 + + if num_processes < 1: + raise ValueError("Number of processes should at least be 1.") + + self._job_queue = job_queue + self._response_queue = queue.Queue() + self._exc_queue = queue.Queue() + self._processes = num_processes + self._initializer = initializer or _identity + self._auth = auth_generator or _identity + self._session = session + self._pool = [ + thread.SessionThread(self._new_session(), self._job_queue, + self._response_queue, self._exc_queue) + for _ in range(self._processes) + ] + + def _new_session(self): + return self._auth(self._initializer(self._session())) + + @classmethod + def from_exceptions(cls, exceptions, **kwargs): + r"""Create a :class:`~Pool` from an :class:`~ThreadException`\ s. + + Provided an iterable that provides :class:`~ThreadException` objects, + this classmethod will generate a new pool to retry the requests that + caused the exceptions. + + :param exceptions: + Iterable that returns :class:`~ThreadException` + :type exceptions: iterable + :param kwargs: + Keyword arguments passed to the :class:`~Pool` initializer. + :returns: An initialized :class:`~Pool` object. + :rtype: :class:`~Pool` + """ + job_queue = queue.Queue() + for exc in exceptions: + job_queue.put(exc.request_kwargs) + + return cls(job_queue=job_queue, **kwargs) + + @classmethod + def from_urls(cls, urls, request_kwargs=None, **kwargs): + """Create a :class:`~Pool` from an iterable of URLs. + + :param urls: + Iterable that returns URLs with which we create a pool. + :type urls: iterable + :param dict request_kwargs: + Dictionary of other keyword arguments to provide to the request + method. + :param kwargs: + Keyword arguments passed to the :class:`~Pool` initializer. + :returns: An initialized :class:`~Pool` object. + :rtype: :class:`~Pool` + """ + request_dict = {'method': 'GET'} + request_dict.update(request_kwargs or {}) + job_queue = queue.Queue() + for url in urls: + job = request_dict.copy() + job.update({'url': url}) + job_queue.put(job) + + return cls(job_queue=job_queue, **kwargs) + + def exceptions(self): + """Iterate over all the exceptions in the pool. + + :returns: Generator of :class:`~ThreadException` + """ + while True: + exc = self.get_exception() + if exc is None: + break + yield exc + + def get_exception(self): + """Get an exception from the pool. + + :rtype: :class:`~ThreadException` + """ + try: + (request, exc) = self._exc_queue.get_nowait() + except queue.Empty: + return None + else: + return ThreadException(request, exc) + + def get_response(self): + """Get a response from the pool. + + :rtype: :class:`~ThreadResponse` + """ + try: + (request, response) = self._response_queue.get_nowait() + except queue.Empty: + return None + else: + return ThreadResponse(request, response) + + def responses(self): + """Iterate over all the responses in the pool. + + :returns: Generator of :class:`~ThreadResponse` + """ + while True: + resp = self.get_response() + if resp is None: + break + yield resp + + def join_all(self): + """Join all the threads to the master thread.""" + for session_thread in self._pool: + session_thread.join() + + +class ThreadProxy(object): + proxied_attr = None + + def __getattr__(self, attr): + """Proxy attribute accesses to the proxied object.""" + get = object.__getattribute__ + if attr not in self.attrs: + response = get(self, self.proxied_attr) + return getattr(response, attr) + else: + return get(self, attr) + + +class ThreadResponse(ThreadProxy): + """A wrapper around a requests Response object. + + This will proxy most attribute access actions to the Response object. For + example, if you wanted the parsed JSON from the response, you might do: + + .. code-block:: python + + thread_response = pool.get_response() + json = thread_response.json() + + """ + proxied_attr = 'response' + attrs = frozenset(['request_kwargs', 'response']) + + def __init__(self, request_kwargs, response): + #: The original keyword arguments provided to the queue + self.request_kwargs = request_kwargs + #: The wrapped response + self.response = response + + +class ThreadException(ThreadProxy): + """A wrapper around an exception raised during a request. + + This will proxy most attribute access actions to the exception object. For + example, if you wanted the message from the exception, you might do: + + .. code-block:: python + + thread_exc = pool.get_exception() + msg = thread_exc.message + + """ + proxied_attr = 'exception' + attrs = frozenset(['request_kwargs', 'exception']) + + def __init__(self, request_kwargs, exception): + #: The original keyword arguments provided to the queue + self.request_kwargs = request_kwargs + #: The captured and wrapped exception + self.exception = exception + + +def _identity(session_obj): + return session_obj + + +__all__ = ['ThreadException', 'ThreadResponse', 'Pool'] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/thread.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/thread.py new file mode 100644 index 0000000000000000000000000000000000000000..542813c1fdb7de6fa1bedc55c0601a35c5f44abf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/threaded/thread.py @@ -0,0 +1,53 @@ +"""Module containing the SessionThread class.""" +import threading +import uuid + +import requests.exceptions as exc + +from .._compat import queue + + +class SessionThread(object): + def __init__(self, initialized_session, job_queue, response_queue, + exception_queue): + self._session = initialized_session + self._jobs = job_queue + self._create_worker() + self._responses = response_queue + self._exceptions = exception_queue + + def _create_worker(self): + self._worker = threading.Thread( + target=self._make_request, + name=uuid.uuid4(), + ) + self._worker.daemon = True + self._worker._state = 0 + self._worker.start() + + def _handle_request(self, kwargs): + try: + response = self._session.request(**kwargs) + except exc.RequestException as e: + self._exceptions.put((kwargs, e)) + else: + self._responses.put((kwargs, response)) + finally: + self._jobs.task_done() + + def _make_request(self): + while True: + try: + kwargs = self._jobs.get_nowait() + except queue.Empty: + break + + self._handle_request(kwargs) + + def is_alive(self): + """Proxy to the thread's ``is_alive`` method.""" + return self._worker.is_alive() + + def join(self): + """Join this thread to the master thread.""" + self._worker.join() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace2cc27c6034937d46e8188a86311c2d78e6f8b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/deprecated.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/deprecated.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ed4f439fb465ab4b8eda4e6b471040ae979be9c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/deprecated.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/dump.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/dump.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2aa63c3bead3746b7b8b53b3fe77fb6e734e732 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/dump.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/formdata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/formdata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f63472267c1d5031f784785d21160418d01aaa18 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/formdata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/user_agent.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/user_agent.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c294211d5e8e53ade4cf19d8d464160f3eb34ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/__pycache__/user_agent.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/deprecated.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..c935783bdcf9c2233295f11c9c389b72524345ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/deprecated.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +"""A collection of functions deprecated in requests.utils.""" +import re +import sys + +from requests import utils + +find_charset = re.compile( + br']', flags=re.I +).findall + +find_pragma = re.compile( + br']', flags=re.I +).findall + +find_xml = re.compile( + br'^<\?xml.*?encoding=["\']*(.+?)["\'>]' +).findall + + +def get_encodings_from_content(content): + """Return encodings from given content string. + + .. code-block:: python + + import requests + from requests_toolbelt.utils import deprecated + + r = requests.get(url) + encodings = deprecated.get_encodings_from_content(r) + + :param content: bytestring to extract encodings from + :type content: bytes + :return: encodings detected in the provided content + :rtype: list(str) + """ + encodings = (find_charset(content) + find_pragma(content) + + find_xml(content)) + if (3, 0) <= sys.version_info < (4, 0): + encodings = [encoding.decode('utf8') for encoding in encodings] + return encodings + + +def get_unicode_from_response(response): + """Return the requested content back in unicode. + + This will first attempt to retrieve the encoding from the response + headers. If that fails, it will use + :func:`requests_toolbelt.utils.deprecated.get_encodings_from_content` + to determine encodings from HTML elements. + + .. code-block:: python + + import requests + from requests_toolbelt.utils import deprecated + + r = requests.get(url) + text = deprecated.get_unicode_from_response(r) + + :param response: Response object to get unicode content from. + :type response: requests.models.Response + """ + tried_encodings = set() + + # Try charset from content-type + encoding = utils.get_encoding_from_headers(response.headers) + + if encoding: + try: + return str(response.content, encoding) + except UnicodeError: + tried_encodings.add(encoding.lower()) + + encodings = get_encodings_from_content(response.content) + + for _encoding in encodings: + _encoding = _encoding.lower() + if _encoding in tried_encodings: + continue + try: + return str(response.content, _encoding) + except UnicodeError: + tried_encodings.add(_encoding) + + # Fall back: + if encoding: + try: + return str(response.content, encoding, errors='replace') + except TypeError: + pass + return response.text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/dump.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/dump.py new file mode 100644 index 0000000000000000000000000000000000000000..dec0e376648287ca0a331e5f8d60f2ca73970030 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/dump.py @@ -0,0 +1,198 @@ +"""This module provides functions for dumping information about responses.""" +import collections + +from requests import compat + + +__all__ = ('dump_response', 'dump_all') + +HTTP_VERSIONS = { + 9: b'0.9', + 10: b'1.0', + 11: b'1.1', +} + +_PrefixSettings = collections.namedtuple('PrefixSettings', + ['request', 'response']) + + +class PrefixSettings(_PrefixSettings): + def __new__(cls, request, response): + request = _coerce_to_bytes(request) + response = _coerce_to_bytes(response) + return super(PrefixSettings, cls).__new__(cls, request, response) + + +def _get_proxy_information(response): + if getattr(response.connection, 'proxy_manager', False): + proxy_info = {} + request_url = response.request.url + if request_url.startswith('https://'): + proxy_info['method'] = 'CONNECT' + + proxy_info['request_path'] = request_url + return proxy_info + return None + + +def _format_header(name, value): + return (_coerce_to_bytes(name) + b': ' + _coerce_to_bytes(value) + + b'\r\n') + + +def _build_request_path(url, proxy_info): + uri = compat.urlparse(url) + proxy_url = proxy_info.get('request_path') + if proxy_url is not None: + request_path = _coerce_to_bytes(proxy_url) + return request_path, uri + + request_path = _coerce_to_bytes(uri.path) + if uri.query: + request_path += b'?' + _coerce_to_bytes(uri.query) + + return request_path, uri + + +def _dump_request_data(request, prefixes, bytearr, proxy_info=None): + if proxy_info is None: + proxy_info = {} + + prefix = prefixes.request + method = _coerce_to_bytes(proxy_info.pop('method', request.method)) + request_path, uri = _build_request_path(request.url, proxy_info) + + # HTTP/1.1 + bytearr.extend(prefix + method + b' ' + request_path + b' HTTP/1.1\r\n') + + # Host: OR host header specified by user + headers = request.headers.copy() + host_header = _coerce_to_bytes(headers.pop('Host', uri.netloc)) + bytearr.extend(prefix + b'Host: ' + host_header + b'\r\n') + + for name, value in headers.items(): + bytearr.extend(prefix + _format_header(name, value)) + + bytearr.extend(prefix + b'\r\n') + if request.body: + if isinstance(request.body, compat.basestring): + bytearr.extend(prefix + _coerce_to_bytes(request.body)) + else: + # In the event that the body is a file-like object, let's not try + # to read everything into memory. + bytearr.extend(b'<< Request body is not a string-like type >>') + bytearr.extend(b'\r\n') + bytearr.extend(b'\r\n') + + +def _dump_response_data(response, prefixes, bytearr): + prefix = prefixes.response + # Let's interact almost entirely with urllib3's response + raw = response.raw + + # Let's convert the version int from httplib to bytes + version_str = HTTP_VERSIONS.get(raw.version, b'?') + + # HTTP/ + bytearr.extend(prefix + b'HTTP/' + version_str + b' ' + + str(raw.status).encode('ascii') + b' ' + + _coerce_to_bytes(response.reason) + b'\r\n') + + headers = raw.headers + for name in headers.keys(): + for value in headers.getlist(name): + bytearr.extend(prefix + _format_header(name, value)) + + bytearr.extend(prefix + b'\r\n') + + bytearr.extend(response.content) + + +def _coerce_to_bytes(data): + if not isinstance(data, bytes) and hasattr(data, 'encode'): + data = data.encode('utf-8') + # Don't bail out with an exception if data is None + return data if data is not None else b'' + + +def dump_response(response, request_prefix=b'< ', response_prefix=b'> ', + data_array=None): + """Dump a single request-response cycle's information. + + This will take a response object and dump only the data that requests can + see for that single request-response cycle. + + Example:: + + import requests + from requests_toolbelt.utils import dump + + resp = requests.get('https://api.github.com/users/sigmavirus24') + data = dump.dump_response(resp) + print(data.decode('utf-8')) + + :param response: + The response to format + :type response: :class:`requests.Response` + :param request_prefix: (*optional*) + Bytes to prefix each line of the request data + :type request_prefix: :class:`bytes` + :param response_prefix: (*optional*) + Bytes to prefix each line of the response data + :type response_prefix: :class:`bytes` + :param data_array: (*optional*) + Bytearray to which we append the request-response cycle data + :type data_array: :class:`bytearray` + :returns: Formatted bytes of request and response information. + :rtype: :class:`bytearray` + """ + data = data_array if data_array is not None else bytearray() + prefixes = PrefixSettings(request_prefix, response_prefix) + + if not hasattr(response, 'request'): + raise ValueError('Response has no associated request') + + proxy_info = _get_proxy_information(response) + _dump_request_data(response.request, prefixes, data, + proxy_info=proxy_info) + _dump_response_data(response, prefixes, data) + return data + + +def dump_all(response, request_prefix=b'< ', response_prefix=b'> '): + """Dump all requests and responses including redirects. + + This takes the response returned by requests and will dump all + request-response pairs in the redirect history in order followed by the + final request-response. + + Example:: + + import requests + from requests_toolbelt.utils import dump + + resp = requests.get('https://httpbin.org/redirect/5') + data = dump.dump_all(resp) + print(data.decode('utf-8')) + + :param response: + The response to format + :type response: :class:`requests.Response` + :param request_prefix: (*optional*) + Bytes to prefix each line of the request data + :type request_prefix: :class:`bytes` + :param response_prefix: (*optional*) + Bytes to prefix each line of the response data + :type response_prefix: :class:`bytes` + :returns: Formatted bytes of request and response information. + :rtype: :class:`bytearray` + """ + data = bytearray() + + history = list(response.history[:]) + history.append(response) + + for response in history: + dump_response(response, request_prefix, response_prefix, data) + + return data diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/formdata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/formdata.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a909d24c175f63e133f1cfb64adf90154afca6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/formdata.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +"""Implementation of nested form-data encoding function(s).""" +from .._compat import basestring +from .._compat import urlencode as _urlencode + + +__all__ = ('urlencode',) + + +def urlencode(query, *args, **kwargs): + """Handle nested form-data queries and serialize them appropriately. + + There are times when a website expects a nested form data query to be sent + but, the standard library's urlencode function does not appropriately + handle the nested structures. In that case, you need this function which + will flatten the structure first and then properly encode it for you. + + When using this to send data in the body of a request, make sure you + specify the appropriate Content-Type header for the request. + + .. code-block:: python + + import requests + from requests_toolbelt.utils import formdata + + query = { + 'my_dict': { + 'foo': 'bar', + 'biz': 'baz", + }, + 'a': 'b', + } + + resp = requests.get(url, params=formdata.urlencode(query)) + # or + resp = requests.post( + url, + data=formdata.urlencode(query), + headers={ + 'Content-Type': 'application/x-www-form-urlencoded' + }, + ) + + Similarly, you can specify a list of nested tuples, e.g., + + .. code-block:: python + + import requests + from requests_toolbelt.utils import formdata + + query = [ + ('my_list', [ + ('foo', 'bar'), + ('biz', 'baz'), + ]), + ('a', 'b'), + ] + + resp = requests.get(url, params=formdata.urlencode(query)) + # or + resp = requests.post( + url, + data=formdata.urlencode(query), + headers={ + 'Content-Type': 'application/x-www-form-urlencoded' + }, + ) + + For additional parameter and return information, see the official + `urlencode`_ documentation. + + .. _urlencode: + https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode + """ + expand_classes = (dict, list, tuple) + original_query_list = _to_kv_list(query) + + if not all(_is_two_tuple(i) for i in original_query_list): + raise ValueError("Expected query to be able to be converted to a " + "list comprised of length 2 tuples.") + + query_list = original_query_list + while any(isinstance(v, expand_classes) for _, v in query_list): + query_list = _expand_query_values(query_list) + + return _urlencode(query_list, *args, **kwargs) + + +def _to_kv_list(dict_or_list): + if hasattr(dict_or_list, 'items'): + return list(dict_or_list.items()) + return dict_or_list + + +def _is_two_tuple(item): + return isinstance(item, (list, tuple)) and len(item) == 2 + + +def _expand_query_values(original_query_list): + query_list = [] + for key, value in original_query_list: + if isinstance(value, basestring): + query_list.append((key, value)) + else: + key_fmt = key + '[%s]' + value_list = _to_kv_list(value) + query_list.extend((key_fmt % k, v) for k, v in value_list) + return query_list diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/user_agent.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/user_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..e9636a41c802e6680e429207515e336a44f8dbbc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/requests_toolbelt/utils/user_agent.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +import collections +import platform +import sys + + +def user_agent(name, version, extras=None): + """Return an internet-friendly user_agent string. + + The majority of this code has been wilfully stolen from the equivalent + function in Requests. + + :param name: The intended name of the user-agent, e.g. "python-requests". + :param version: The version of the user-agent, e.g. "0.0.1". + :param extras: List of two-item tuples that are added to the user-agent + string. + :returns: Formatted user-agent string + :rtype: str + """ + if extras is None: + extras = [] + + return UserAgentBuilder( + name, version + ).include_extras( + extras + ).include_implementation( + ).include_system().build() + + +class UserAgentBuilder(object): + """Class to provide a greater level of control than :func:`user_agent`. + + This is used by :func:`user_agent` to build its User-Agent string. + + .. code-block:: python + + user_agent_str = UserAgentBuilder( + name='requests-toolbelt', + version='17.4.0', + ).include_implementation( + ).include_system( + ).include_extras([ + ('requests', '2.14.2'), + ('urllib3', '1.21.2'), + ]).build() + + """ + + format_string = '%s/%s' + + def __init__(self, name, version): + """Initialize our builder with the name and version of our user agent. + + :param str name: + Name of our user-agent. + :param str version: + The version string for user-agent. + """ + self._pieces = collections.deque([(name, version)]) + + def build(self): + """Finalize the User-Agent string. + + :returns: + Formatted User-Agent string. + :rtype: + str + """ + return " ".join([self.format_string % piece for piece in self._pieces]) + + def include_extras(self, extras): + """Include extra portions of the User-Agent. + + :param list extras: + list of tuples of extra-name and extra-version + """ + if any(len(extra) != 2 for extra in extras): + raise ValueError('Extras should be a sequence of two item tuples.') + + self._pieces.extend(extras) + return self + + def include_implementation(self): + """Append the implementation string to the user-agent string. + + This adds the the information that you're using CPython 2.7.13 to the + User-Agent. + """ + self._pieces.append(_implementation_tuple()) + return self + + def include_system(self): + """Append the information about the Operating System.""" + self._pieces.append(_platform_tuple()) + return self + + +def _implementation_tuple(): + """Return the tuple of interpreter name and version. + + Returns a string that provides both the name and the version of the Python + implementation currently running. For example, on CPython 2.7.5 it will + return "CPython/2.7.5". + + This function works best on CPython and PyPy: in particular, it probably + doesn't work for Jython or IronPython. Future investigation should be done + to work out the correct shape of the code for those platforms. + """ + implementation = platform.python_implementation() + + if implementation == 'CPython': + implementation_version = platform.python_version() + elif implementation == 'PyPy': + implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, + sys.pypy_version_info.minor, + sys.pypy_version_info.micro) + if sys.pypy_version_info.releaselevel != 'final': + implementation_version = ''.join([ + implementation_version, sys.pypy_version_info.releaselevel + ]) + elif implementation == 'Jython': + implementation_version = platform.python_version() # Complete Guess + elif implementation == 'IronPython': + implementation_version = platform.python_version() # Complete Guess + else: + implementation_version = 'Unknown' + + return (implementation, implementation_version) + + +def _implementation_string(): + return "%s/%s" % _implementation_tuple() + + +def _platform_tuple(): + try: + p_system = platform.system() + p_release = platform.release() + except IOError: + p_system = 'Unknown' + p_release = 'Unknown' + return (p_system, p_release) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich-15.0.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich-15.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4415505566f261c802b671426be529a31f914137 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich-15.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020 Will McGugan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c34b6c18c9184505afbff92cab877679f5b9fabb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a19cbdc2c75a30659d2256a925282b389267188c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_emoji_replace.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_emoji_replace.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96018f691837b55a763232ce89ca3b2f7193bcfa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_emoji_replace.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_export_format.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_export_format.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c76dff0e8f201f5fdb96cf97185e4b80e2f57c97 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_export_format.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_extension.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_extension.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..633dd94e56e81c2313019472b1ec5c2b5249c5eb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_extension.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_fileno.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_fileno.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e27933e815192dc273ddbf6062c12db121c7c143 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_fileno.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_inspect.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_inspect.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f6b74814b4e413ed9c8824164407a5aea8c4f4a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_inspect.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_log_render.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_log_render.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c53e318577c57a93f8063fa6c2822ea2e8b72d7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_log_render.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_loop.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_loop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4e436075593409b77ea4f67d6bf9a85cbd990b7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_loop.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_null_file.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_null_file.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d4ee5a3df64e7308d58cd3ac92c414c0872080c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_null_file.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_palettes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_palettes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0d3ee9bed9d5a9a0497d7dc6a90b86bf8543b3a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_palettes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_pick.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_pick.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc39f3f52fdcf550a2f58f5fcec8b6ec14104d2c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_pick.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_ratio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_ratio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..330355cdbdd37689bd3bb665a7191ce2d3090e83 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_ratio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_spinners.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_spinners.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e37cc4b91dfa31c14f652d59d985f59aad81c73 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_spinners.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_stack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_stack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cea2177e4ef7e257269bcd7d1cba80b2edac3443 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_stack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_timer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_timer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d6a3d867711310e467ae51cc1efcc129f9291d2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_timer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_win32_console.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_win32_console.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49e8438b80285057c3380c16b64660f0cc0cde78 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_win32_console.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_windows.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_windows.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..134b9e8cfb56ee4213ce3231ca207b98de8c139b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_windows.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_windows_renderer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_windows_renderer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..768bd33df1c815506a89f11b3d999751574125a3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_windows_renderer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_wrap.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_wrap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867d36613db2df427aee7c2fcf4301d05b005913 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/_wrap.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/abc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2bec7b77086be34fcb90f841ea04c1c02e87112 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/abc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/align.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/align.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6efb9b91b6ec22640d67058b5ac42f4d0afeb02d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/align.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/ansi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/ansi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2ecac407f2468929d0c73ca383461c97afe3a5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/ansi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/bar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/bar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ff9cde89e0659719942125ddf3369cd3ba97fc9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/bar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/box.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/box.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37a79ba677b38eff16ab7d57cc1b0de314c0fcaf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/box.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/cells.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/cells.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5cb8ac070a7330605a38e3ac59851511251311b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/cells.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/color.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/color.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5935b859f4edbf8da9926e141e67b6c102511de0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/color.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/color_triplet.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/color_triplet.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36f99b3171759ef305c2f20ab18de1a4393690b5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/color_triplet.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/columns.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/columns.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71a746a862316b7dd0cd196c1efb4aaa8f60d437 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/columns.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/constrain.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/constrain.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bd42dd173cd43c5655a8186748f238a7316b3b9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/constrain.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/containers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/containers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46cf29d4a9a04bde2d11af13a4f574aa3a303a77 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/containers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/control.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/control.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c9d80e9f888b563d028ff7b982c86bfa173aea3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/control.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/default_styles.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/default_styles.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..114c4d44b747e6e1001e2efdbabd52d8947e4c9a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/default_styles.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/diagnose.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/diagnose.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a5243e395fa1829a59943cf29ba23c351b49e2b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/diagnose.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/emoji.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/emoji.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37a16aa7023ca45bb693d2f21315e4de1ae8d79a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/emoji.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/errors.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc2cbbc53d9d2ba5562cf8d79193fc3dfcec32c8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/errors.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/file_proxy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/file_proxy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99843815c957c7d6ab9a22adedd21b99857397a4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/file_proxy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/filesize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/filesize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..656446d3d836c28858ba0d07178429e806b8ff91 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/filesize.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/highlighter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/highlighter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..293bbc74e07092665deab91e52da926e0f6c5d6e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/highlighter.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/json.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/json.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7333c30bf19ff86037815e59a732ee712d753a22 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/json.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/jupyter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/jupyter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6ebed77c1a6d0155905baafe1a44892835f8082 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/jupyter.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/layout.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/layout.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c88a8eb6c5de29fd374e2f3e11e9e6edbece351 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/layout.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/live.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/live.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9add8c3053a8a828b1f4c6a00c891442aba2eccf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/live.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/live_render.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/live_render.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a831478e59037eb3e066a884fbf60c2c4898171 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/live_render.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26aca81ef1d97aebba7c95712924b1a2957cddd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/logging.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/markdown.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/markdown.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ef1873d45e8234185a869bac49f6f9ef17aefac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/markdown.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/markup.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/markup.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4633a3fe1b9f8161b855fa57955b01bd867fb100 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/markup.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/measure.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/measure.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49fd7a62445fdc1a05ea383e05135c6b8272b7b1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/measure.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/padding.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/padding.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd2dd819ad58f550d1813123125c27cf96a20d55 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/padding.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/pager.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/pager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e94f2ea3cd4ce4da6d618a878f723083ec149068 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/pager.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/palette.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/palette.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833d292f89bca004c8950e3169e0ce1acffb460f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/palette.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/panel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/panel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..407af4fd47ced1e4114df8eecad88c8416e288cc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/panel.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/pretty.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/pretty.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..633a8a58f85477b84f5265a5b146f64a6b46f1af Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/pretty.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/progress.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/progress.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..238161d914fc7c1711a46fad1294ee4d8fcf3572 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/progress.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/progress_bar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/progress_bar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a7e29feac51e1cb61c6b8b28bc63fe9dcab555c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/progress_bar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/prompt.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/prompt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea18fb2b6a37e4979622985a5283a2252f9b2128 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/prompt.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/protocol.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b07c9208392f17d962d65e0a38e9989a4774a7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/protocol.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/region.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/region.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5e316e55131c1a6a53dea2a1e114a400ea69e6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/region.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/repr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/repr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d58e7db9bfbf9386cfe30acc4893391b5235c4d9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/repr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/rule.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/rule.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a6f26d4de395849e9e187423d1d6a459100dd2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/rule.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/scope.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/scope.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7618752e4c6e8da30cb025af524d5116278ac0e5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/scope.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/screen.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/screen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a78aabbe1bb0102d7b4c27de5afe9b5ef1ef9a1a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/screen.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/segment.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/segment.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19290b976cccdcc11fd4e32fdf4972e42eae99f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/segment.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/spinner.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/spinner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5009c91c459edad4c5005becbd9f1bfce201846a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/spinner.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/status.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/status.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9824a40b4cd77065e0120b83dfba89e653761418 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/status.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/style.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/style.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb93094eb4915c143a0cf4827f2c17de39f196ae Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/style.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/styled.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/styled.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e7f7e66bb108e5a76cdcc331f590fd71ab7d5c7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/styled.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/syntax.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/syntax.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f91d1bdf2570a4104bc7fcea0f301bbf477f590 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/syntax.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/table.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/table.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..608e46c7f2c7ba1e7fdf3db739a720775ce5cc33 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/table.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/terminal_theme.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/terminal_theme.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38f68d0c3aafb25e17c9c9771e4f5cddf039acfb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/terminal_theme.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/text.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4466565816ebebf958b8967cbbb020ae364832b1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/text.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/theme.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/theme.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e286049c3802eaa5699ebc30f683ef1d4f822b0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/theme.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/themes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/themes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7878db31ce39b82c5d88bb76fd0e3b7315bf069 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/themes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/traceback.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/traceback.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c53ea759a30e190f293cf8ca7a31c750bb7457a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/traceback.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/tree.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/tree.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e8880c0d6780a51a69fe5b61f91af172def2c04 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/__pycache__/tree.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce54baef4e5124dd7c9e711604d00dcb001749c9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__init__.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import bisect +import os +import sys + +if sys.version_info[:2] >= (3, 9): + from functools import cache +else: + from functools import lru_cache as cache # pragma: no cover + +from importlib import import_module +from typing import TYPE_CHECKING, cast + +from rich._unicode_data._versions import VERSIONS + +if TYPE_CHECKING: + from rich.cells import CellTable + +VERSION_ORDER = sorted( + [ + tuple( + map(int, version.split(".")), + ) + for version in VERSIONS + ] +) +VERSION_SET = frozenset(VERSIONS) + + +def _parse_version(version: str) -> tuple[int, int, int]: + """Parse a version string into a tuple of 3 integers. + + Args: + version: A version string. + + Raises: + ValueError: If the version string is invalid. + + Returns: + A tuple of 3 integers. + """ + version_integers: tuple[int, ...] + try: + version_integers = tuple( + map(int, version.split(".")), + ) + except ValueError: + raise ValueError( + f"unicode version string {version!r} is badly formatted" + ) from None + while len(version_integers) < 3: + version_integers = version_integers + (0,) + triple = cast("tuple[int, int, int]", version_integers[:3]) + return triple + + +@cache +def load(unicode_version: str = "auto") -> CellTable: + """Load a cell table for the given unicode version. + + Args: + unicode_version: Unicode version, or `None` to auto-detect. + + """ + if unicode_version == "auto": + unicode_version = os.environ.get("UNICODE_VERSION", "latest") + try: + _parse_version(unicode_version) + except ValueError: + # The environment variable is invalid + # Fallback to using the latest version seems reasonable + unicode_version = "latest" + + if unicode_version == "latest": + version = VERSIONS[-1] + else: + try: + version_numbers = _parse_version(unicode_version) + except ValueError: + version_numbers = _parse_version(VERSIONS[-1]) + major, minor, patch = version_numbers + version = f"{major}.{minor}.{patch}" + if version not in VERSION_SET: + insert_position = bisect.bisect_left(VERSION_ORDER, version_numbers) + version = VERSIONS[max(0, insert_position - 1)] + + version_path_component = version.replace(".", "-") + module_name = f".unicode{version_path_component}" + module = import_module(module_name, "rich._unicode_data") + if TYPE_CHECKING: + assert isinstance(module.cell_table, CellTable) + return module.cell_table diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3c4edaa41192535cddc32c2e7d1ab359dd6eb5e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/_versions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/_versions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ccb0f8f6879391ee0b1e20ba0c9f3812050d3c5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/_versions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode10-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode10-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66812d5858391603c62dea43fe64d4c073ab5db8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode10-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode11-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode11-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11a5e73df0d2b904b2454b8cb3243a694577b8aa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode11-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode12-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode12-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bba1619722ad7c3b45f0f10e7dc41370ba20adb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode12-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode12-1-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode12-1-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e668f1138fd1dcb8e69234f50457e0cd5baa3fbf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode12-1-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode13-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode13-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1edea954b889e762b776d35a9682d31301ded6b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode13-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode14-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode14-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f02af815c2f92c627edd207fd48f549a75096a8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode14-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode15-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode15-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..877d76397c18cc9ef81da5fdd3358582e0f19cd5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode15-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode15-1-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode15-1-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69c03751b7daa7aab7c11a4fcc649015746472fc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode15-1-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode16-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode16-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd91b00ce3909557c9186dddb03d3b270cad156e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode16-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode17-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode17-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de25e77de694903269527dea3a218b189508570d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode17-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode4-1-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode4-1-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88acabbeafea29babfe0a8706fc6697defd49eac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode4-1-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..763d5725918701ccb6c3f39199d788e4f5c4a888 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-1-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-1-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9656b3b7307bbb1f38561264929e9219564e505f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-1-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-2-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-2-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84f0608abd11a377642e030e943a7bf9272e33c2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode5-2-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85a22eabeb0b40f1d3971ea3f9e1d5cc50b4ee2b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-1-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-1-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb46d0e4347012a84f79427cd64ce84f8646eebc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-1-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-2-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-2-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06d2f72cb32310d03436a77c64b9f4d7661ba627 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-2-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-3-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-3-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdabc895960fa0e55bbf13948c497da46e907fe1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode6-3-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode7-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode7-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f35d83694713bd74dd361f2143a24d877284f7e2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode7-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode8-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode8-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0cdedeb4417bebdca2026c8877115e1a4bc3b2b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode8-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode9-0-0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode9-0-0.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb9a4cb05ff23c77467eee931241767dd7a9c633 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/__pycache__/unicode9-0-0.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/_versions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..be98418d13d224ccd94f97f0ce8e31fe43f63540 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/_versions.py @@ -0,0 +1,23 @@ +VERSIONS = ( + "4.1.0", + "5.0.0", + "5.1.0", + "5.2.0", + "6.0.0", + "6.1.0", + "6.2.0", + "6.3.0", + "7.0.0", + "8.0.0", + "9.0.0", + "10.0.0", + "11.0.0", + "12.0.0", + "12.1.0", + "13.0.0", + "14.0.0", + "15.0.0", + "15.1.0", + "16.0.0", + "17.0.0", +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode10-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode10-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..f318087837c2cfb464c7bb9979f7ed067bc71bea --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode10-0-0.py @@ -0,0 +1,611 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "10.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2260, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6846, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7415, 7417, 0), + (7616, 7673, 0), + (7675, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12590, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70090, 70092, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70460, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (94176, 94177, 2), + (94208, 100332, 2), + (100352, 101106, 2), + (110592, 110878, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128747, 128748, 2), + (128756, 128760, 2), + (129296, 129342, 2), + (129344, 129356, 2), + (129360, 129387, 2), + (129408, 129431, 2), + (129472, 129472, 2), + (129488, 129510, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode11-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode11-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..058bb342cac0eb3cae529a0a1933c89dabaa5fbd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode11-0-0.py @@ -0,0 +1,625 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "11.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2259, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6846, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7415, 7417, 0), + (7616, 7673, 0), + (7675, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (69446, 69456, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (94176, 94177, 2), + (94208, 100337, 2), + (100352, 101106, 2), + (110592, 110878, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128747, 128748, 2), + (128756, 128761, 2), + (129296, 129342, 2), + (129344, 129392, 2), + (129395, 129398, 2), + (129402, 129402, 2), + (129404, 129442, 2), + (129456, 129465, 2), + (129472, 129474, 2), + (129488, 129535, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode12-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode12-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..7b0022513d4517f1704e3f54c3dcc7a4f8816773 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode12-0-0.py @@ -0,0 +1,637 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "12.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2259, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6846, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7673, 0), + (7675, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (69446, 69456, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (78896, 78904, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94208, 100343, 2), + (100352, 101106, 2), + (110592, 110878, 2), + (110928, 110930, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123184, 123190, 0), + (123628, 123631, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128725, 2), + (128747, 128748, 2), + (128756, 128762, 2), + (128992, 129003, 2), + (129293, 129393, 2), + (129395, 129398, 2), + (129402, 129442, 2), + (129445, 129450, 2), + (129454, 129482, 2), + (129485, 129535, 2), + (129648, 129651, 2), + (129656, 129658, 2), + (129664, 129666, 2), + (129680, 129685, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode12-1-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode12-1-0.py new file mode 100644 index 0000000000000000000000000000000000000000..2dbcf3794e45d16f46ce68d81f5eea63e39aa42d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode12-1-0.py @@ -0,0 +1,636 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "12.1.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2259, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6846, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7673, 0), + (7675, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (69446, 69456, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (78896, 78904, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94208, 100343, 2), + (100352, 101106, 2), + (110592, 110878, 2), + (110928, 110930, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123184, 123190, 0), + (123628, 123631, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128725, 2), + (128747, 128748, 2), + (128756, 128762, 2), + (128992, 129003, 2), + (129293, 129393, 2), + (129395, 129398, 2), + (129402, 129442, 2), + (129445, 129450, 2), + (129454, 129482, 2), + (129485, 129535, 2), + (129648, 129651, 2), + (129656, 129658, 2), + (129664, 129666, 2), + (129680, 129685, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode13-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode13-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..13fbc74b0ac34d1c28f5ee77359a520512bf7e8a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode13-0-0.py @@ -0,0 +1,648 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "13.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2259, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2901, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3457, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6848, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7673, 0), + (7675, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43052, 43052, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (69291, 69292, 0), + (69446, 69456, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70094, 70095, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (71984, 71989, 0), + (71991, 71992, 0), + (71995, 71998, 0), + (72000, 72000, 0), + (72002, 72003, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (78896, 78904, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94180, 94180, 0), + (94192, 94193, 0), + (94208, 100343, 2), + (100352, 101589, 2), + (101632, 101640, 2), + (110592, 110878, 2), + (110928, 110930, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123184, 123190, 0), + (123628, 123631, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128727, 2), + (128747, 128748, 2), + (128756, 128764, 2), + (128992, 129003, 2), + (129292, 129338, 2), + (129340, 129349, 2), + (129351, 129400, 2), + (129402, 129483, 2), + (129485, 129535, 2), + (129648, 129652, 2), + (129656, 129658, 2), + (129664, 129670, 2), + (129680, 129704, 2), + (129712, 129718, 2), + (129728, 129730, 2), + (129744, 129750, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode14-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode14-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa9e29e7f3027b8aafbd59731fab0d70bd05c5d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode14-0-0.py @@ -0,0 +1,661 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "14.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2200, 2207, 0), + (2250, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2901, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3132, 3132, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3457, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5909, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6159, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6862, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43052, 43052, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (69291, 69292, 0), + (69446, 69456, 0), + (69506, 69509, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69744, 69744, 0), + (69747, 69748, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69826, 69826, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70094, 70095, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (71984, 71989, 0), + (71991, 71992, 0), + (71995, 71998, 0), + (72000, 72000, 0), + (72002, 72003, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (78896, 78904, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94180, 94180, 0), + (94192, 94193, 0), + (94208, 100343, 2), + (100352, 101589, 2), + (101632, 101640, 2), + (110576, 110579, 2), + (110581, 110587, 2), + (110589, 110590, 2), + (110592, 110882, 2), + (110928, 110930, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (118528, 118573, 0), + (118576, 118598, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123184, 123190, 0), + (123566, 123566, 0), + (123628, 123631, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128727, 2), + (128733, 128735, 2), + (128747, 128748, 2), + (128756, 128764, 2), + (128992, 129003, 2), + (129008, 129008, 2), + (129292, 129338, 2), + (129340, 129349, 2), + (129351, 129535, 2), + (129648, 129652, 2), + (129656, 129660, 2), + (129664, 129670, 2), + (129680, 129708, 2), + (129712, 129722, 2), + (129728, 129733, 2), + (129744, 129753, 2), + (129760, 129767, 2), + (129776, 129782, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode15-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode15-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..84dd5be9365bb226620059b80353dd1ce26f8064 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode15-0-0.py @@ -0,0 +1,671 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "15.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2200, 2207, 0), + (2250, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2901, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3132, 3132, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3315, 3315, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3457, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3790, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5909, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6159, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6862, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43052, 43052, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (69291, 69292, 0), + (69373, 69375, 0), + (69446, 69456, 0), + (69506, 69509, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69744, 69744, 0), + (69747, 69748, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69826, 69826, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70094, 70095, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70209, 70209, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (71984, 71989, 0), + (71991, 71992, 0), + (71995, 71998, 0), + (72000, 72000, 0), + (72002, 72003, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (73472, 73473, 0), + (73475, 73475, 0), + (73524, 73530, 0), + (73534, 73538, 0), + (78896, 78912, 0), + (78919, 78933, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94180, 94180, 0), + (94192, 94193, 0), + (94208, 100343, 2), + (100352, 101589, 2), + (101632, 101640, 2), + (110576, 110579, 2), + (110581, 110587, 2), + (110589, 110590, 2), + (110592, 110882, 2), + (110898, 110898, 2), + (110928, 110930, 2), + (110933, 110933, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (118528, 118573, 0), + (118576, 118598, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123023, 123023, 0), + (123184, 123190, 0), + (123566, 123566, 0), + (123628, 123631, 0), + (124140, 124143, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128727, 2), + (128732, 128735, 2), + (128747, 128748, 2), + (128756, 128764, 2), + (128992, 129003, 2), + (129008, 129008, 2), + (129292, 129338, 2), + (129340, 129349, 2), + (129351, 129535, 2), + (129648, 129660, 2), + (129664, 129672, 2), + (129680, 129725, 2), + (129727, 129733, 2), + (129742, 129755, 2), + (129760, 129768, 2), + (129776, 129784, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode15-1-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode15-1-0.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9f2c3e3170538c22fda8d0df91d488c232131f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode15-1-0.py @@ -0,0 +1,670 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "15.1.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2200, 2207, 0), + (2250, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2901, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3132, 3132, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3315, 3315, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3457, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3790, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5909, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6159, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6862, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12771, 2), + (12783, 12830, 2), + (12832, 12871, 2), + (12880, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43052, 43052, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (69291, 69292, 0), + (69373, 69375, 0), + (69446, 69456, 0), + (69506, 69509, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69744, 69744, 0), + (69747, 69748, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69826, 69826, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70094, 70095, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70209, 70209, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (71984, 71989, 0), + (71991, 71992, 0), + (71995, 71998, 0), + (72000, 72000, 0), + (72002, 72003, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (73472, 73473, 0), + (73475, 73475, 0), + (73524, 73530, 0), + (73534, 73538, 0), + (78896, 78912, 0), + (78919, 78933, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94180, 94180, 0), + (94192, 94193, 0), + (94208, 100343, 2), + (100352, 101589, 2), + (101632, 101640, 2), + (110576, 110579, 2), + (110581, 110587, 2), + (110589, 110590, 2), + (110592, 110882, 2), + (110898, 110898, 2), + (110928, 110930, 2), + (110933, 110933, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (118528, 118573, 0), + (118576, 118598, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123023, 123023, 0), + (123184, 123190, 0), + (123566, 123566, 0), + (123628, 123631, 0), + (124140, 124143, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128727, 2), + (128732, 128735, 2), + (128747, 128748, 2), + (128756, 128764, 2), + (128992, 129003, 2), + (129008, 129008, 2), + (129292, 129338, 2), + (129340, 129349, 2), + (129351, 129535, 2), + (129648, 129660, 2), + (129664, 129672, 2), + (129680, 129725, 2), + (129727, 129733, 2), + (129742, 129755, 2), + (129760, 129768, 2), + (129776, 129784, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode16-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode16-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..b3fe2359dfc70e6c8e13be5c6e74887ba581338e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode16-0-0.py @@ -0,0 +1,683 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "16.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2199, 2207, 0), + (2250, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2901, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3132, 3132, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3315, 3315, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3457, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3790, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5909, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6159, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6862, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9776, 9783, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9866, 9871, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12773, 2), + (12783, 12830, 2), + (12832, 12871, 2), + (12880, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43052, 43052, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (68969, 68973, 0), + (69291, 69292, 0), + (69372, 69375, 0), + (69446, 69456, 0), + (69506, 69509, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69744, 69744, 0), + (69747, 69748, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69826, 69826, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70094, 70095, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70209, 70209, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70584, 70592, 0), + (70594, 70594, 0), + (70597, 70597, 0), + (70599, 70602, 0), + (70604, 70608, 0), + (70610, 70610, 0), + (70625, 70626, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (71984, 71989, 0), + (71991, 71992, 0), + (71995, 71998, 0), + (72000, 72000, 0), + (72002, 72003, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (73472, 73473, 0), + (73475, 73475, 0), + (73524, 73530, 0), + (73534, 73538, 0), + (73562, 73562, 0), + (78896, 78912, 0), + (78919, 78933, 0), + (90398, 90415, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94180, 94180, 0), + (94192, 94193, 0), + (94208, 100343, 2), + (100352, 101589, 2), + (101631, 101640, 2), + (110576, 110579, 2), + (110581, 110587, 2), + (110589, 110590, 2), + (110592, 110882, 2), + (110898, 110898, 2), + (110928, 110930, 2), + (110933, 110933, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (118528, 118573, 0), + (118576, 118598, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (119552, 119638, 2), + (119648, 119670, 2), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123023, 123023, 0), + (123184, 123190, 0), + (123566, 123566, 0), + (123628, 123631, 0), + (124140, 124143, 0), + (124398, 124399, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128727, 2), + (128732, 128735, 2), + (128747, 128748, 2), + (128756, 128764, 2), + (128992, 129003, 2), + (129008, 129008, 2), + (129292, 129338, 2), + (129340, 129349, 2), + (129351, 129535, 2), + (129648, 129660, 2), + (129664, 129673, 2), + (129679, 129734, 2), + (129742, 129756, 2), + (129759, 129769, 2), + (129776, 129784, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode17-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode17-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..4108bb44de77d023d5b9dadf3601ad1141f7aeae --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode17-0-0.py @@ -0,0 +1,691 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "17.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2045, 2045, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2199, 2207, 0), + (2250, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2558, 2558, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2810, 2815, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2901, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3076, 0), + (3132, 3132, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3315, 3315, 0), + (3328, 3331, 0), + (3387, 3388, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3457, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3772, 0), + (3784, 3790, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5909, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6159, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6877, 0), + (6880, 6891, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7412, 7412, 0), + (7415, 7417, 0), + (7616, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9776, 9783, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9866, 9871, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12591, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12773, 2), + (12783, 12830, 2), + (12832, 12871, 2), + (12880, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43052, 43052, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43263, 43263, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (68900, 68903, 0), + (68969, 68973, 0), + (69291, 69292, 0), + (69370, 69375, 0), + (69446, 69456, 0), + (69506, 69509, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69744, 69744, 0), + (69747, 69748, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69826, 69826, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (69957, 69958, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70089, 70092, 0), + (70094, 70095, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70209, 70209, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70459, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70584, 70592, 0), + (70594, 70594, 0), + (70597, 70597, 0), + (70599, 70602, 0), + (70604, 70608, 0), + (70610, 70610, 0), + (70625, 70626, 0), + (70709, 70726, 0), + (70750, 70750, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (71724, 71738, 0), + (71984, 71989, 0), + (71991, 71992, 0), + (71995, 71998, 0), + (72000, 72000, 0), + (72002, 72003, 0), + (72145, 72151, 0), + (72154, 72160, 0), + (72164, 72164, 0), + (72193, 72202, 0), + (72243, 72249, 0), + (72251, 72254, 0), + (72263, 72263, 0), + (72273, 72283, 0), + (72330, 72345, 0), + (72544, 72551, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (73009, 73014, 0), + (73018, 73018, 0), + (73020, 73021, 0), + (73023, 73029, 0), + (73031, 73031, 0), + (73098, 73102, 0), + (73104, 73105, 0), + (73107, 73111, 0), + (73459, 73462, 0), + (73472, 73473, 0), + (73475, 73475, 0), + (73524, 73530, 0), + (73534, 73538, 0), + (73562, 73562, 0), + (78896, 78912, 0), + (78919, 78933, 0), + (90398, 90415, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94031, 94031, 0), + (94033, 94087, 0), + (94095, 94098, 0), + (94176, 94179, 2), + (94180, 94180, 0), + (94192, 94193, 0), + (94194, 94198, 2), + (94208, 101589, 2), + (101631, 101662, 2), + (101760, 101874, 2), + (110576, 110579, 2), + (110581, 110587, 2), + (110589, 110590, 2), + (110592, 110882, 2), + (110898, 110898, 2), + (110928, 110930, 2), + (110933, 110933, 2), + (110948, 110951, 2), + (110960, 111355, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (118528, 118573, 0), + (118576, 118598, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (119552, 119638, 2), + (119648, 119670, 2), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (123023, 123023, 0), + (123184, 123190, 0), + (123566, 123566, 0), + (123628, 123631, 0), + (124140, 124143, 0), + (124398, 124399, 0), + (124643, 124643, 0), + (124646, 124646, 0), + (124654, 124655, 0), + (124661, 124661, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127584, 127589, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128725, 128728, 2), + (128732, 128735, 2), + (128747, 128748, 2), + (128756, 128764, 2), + (128992, 129003, 2), + (129008, 129008, 2), + (129292, 129338, 2), + (129340, 129349, 2), + (129351, 129535, 2), + (129648, 129660, 2), + (129664, 129674, 2), + (129678, 129734, 2), + (129736, 129736, 2), + (129741, 129756, 2), + (129759, 129770, 2), + (129775, 129784, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode4-1-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode4-1-0.py new file mode 100644 index 0000000000000000000000000000000000000000..23ff5cf1d0cccdc6fe6503c410e900c4d83eb49a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode4-1-0.py @@ -0,0 +1,425 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "4.1.0", + [ + (0, 8, 0), + (14, 31, 0), + (127, 132, 0), + (134, 159, 0), + (768, 879, 0), + (1155, 1158, 0), + (1160, 1161, 0), + (1425, 1465, 0), + (1467, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1539, 0), + (1552, 1557, 0), + (1611, 1630, 0), + (1648, 1648, 0), + (1750, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2305, 2307, 0), + (2364, 2364, 0), + (2366, 2381, 0), + (2385, 2388, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2672, 2673, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2883, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3330, 3331, 0), + (3390, 3395, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3984, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4140, 4146, 0), + (4150, 4153, 0), + (4182, 4185, 0), + (4352, 4441, 2), + (4447, 4447, 2), + (4448, 4607, 0), + (4959, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6157, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (7616, 7619, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8427, 0), + (9001, 9002, 2), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12588, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12727, 2), + (12736, 12751, 2), + (12784, 12830, 2), + (12832, 12867, 2), + (12880, 13054, 2), + (13056, 19893, 2), + (19968, 40891, 2), + (40960, 42124, 2), + (42128, 42182, 2), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (44032, 55203, 2), + (55216, 57343, 0), + (63744, 64045, 2), + (64048, 64106, 2), + (64112, 64217, 2), + (64286, 64286, 0), + (64976, 65007, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65059, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (65534, 65535, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (131070, 131071, 0), + (131072, 196605, 2), + (196606, 196607, 0), + (196608, 262141, 2), + (262142, 262143, 0), + (327678, 327679, 0), + (393214, 393215, 0), + (458750, 458751, 0), + (524286, 524287, 0), + (589822, 589823, 0), + (655358, 655359, 0), + (720894, 720895, 0), + (786430, 786431, 0), + (851966, 851967, 0), + (917502, 921599, 0), + (983038, 983039, 0), + (1048574, 1048575, 0), + (1114110, 1114111, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..599fb785709d40ca23eee7e8e9cbededc8ad389b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-0-0.py @@ -0,0 +1,430 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "5.0.0", + [ + (0, 8, 0), + (14, 31, 0), + (127, 132, 0), + (134, 159, 0), + (768, 879, 0), + (1155, 1158, 0), + (1160, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1539, 0), + (1552, 1557, 0), + (1611, 1630, 0), + (1648, 1648, 0), + (1750, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2305, 2307, 0), + (2364, 2364, 0), + (2366, 2381, 0), + (2385, 2388, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2672, 2673, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2883, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3330, 3331, 0), + (3390, 3395, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3984, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4140, 4146, 0), + (4150, 4153, 0), + (4182, 4185, 0), + (4352, 4441, 2), + (4447, 4447, 2), + (4448, 4607, 0), + (4959, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6157, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7616, 7626, 0), + (7678, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8431, 0), + (9001, 9002, 2), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12588, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12727, 2), + (12736, 12751, 2), + (12784, 12830, 2), + (12832, 12867, 2), + (12880, 13054, 2), + (13056, 19893, 2), + (19968, 40891, 2), + (40960, 42124, 2), + (42128, 42182, 2), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (44032, 55203, 2), + (55216, 57343, 0), + (63744, 64045, 2), + (64048, 64106, 2), + (64112, 64217, 2), + (64286, 64286, 0), + (64976, 65007, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65059, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (65534, 65535, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (131070, 131071, 0), + (131072, 196605, 2), + (196606, 196607, 0), + (196608, 262141, 2), + (262142, 262143, 0), + (327678, 327679, 0), + (393214, 393215, 0), + (458750, 458751, 0), + (524286, 524287, 0), + (589822, 589823, 0), + (655358, 655359, 0), + (720894, 720895, 0), + (786430, 786431, 0), + (851966, 851967, 0), + (917502, 921599, 0), + (983038, 983039, 0), + (1048574, 1048575, 0), + (1114110, 1114111, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-1-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-1-0.py new file mode 100644 index 0000000000000000000000000000000000000000..016e7825eccd6b87410741db79948bb0b99ea921 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-1-0.py @@ -0,0 +1,433 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "5.1.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1539, 0), + (1552, 1562, 0), + (1611, 1630, 0), + (1648, 1648, 0), + (1750, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2305, 2307, 0), + (2364, 2364, 0), + (2366, 2381, 0), + (2385, 2388, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3330, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3984, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4352, 4441, 2), + (4447, 4447, 2), + (4448, 4607, 0), + (4959, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6157, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7082, 0), + (7204, 7223, 0), + (7616, 7654, 0), + (7678, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12727, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12867, 2), + (12880, 13054, 2), + (13056, 19893, 2), + (19968, 40899, 2), + (40960, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42620, 42621, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64045, 2), + (64048, 64106, 2), + (64112, 64217, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65062, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-2-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-2-0.py new file mode 100644 index 0000000000000000000000000000000000000000..e984f12e95eed5eb67cedad1d3b92f5f23c718ed --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode5-2-0.py @@ -0,0 +1,461 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "5.2.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1539, 0), + (1552, 1562, 0), + (1611, 1630, 0), + (1648, 1648, 0), + (1750, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2304, 2307, 0), + (2364, 2364, 0), + (2366, 2382, 0), + (2385, 2389, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3330, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3984, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4959, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6157, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7082, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7410, 0), + (7616, 7654, 0), + (7677, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11503, 11505, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12727, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42620, 42621, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43643, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65062, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (69760, 69762, 0), + (69808, 69818, 0), + (69821, 69821, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (127488, 127488, 2), + (127504, 127537, 2), + (127552, 127560, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..8d5abb455c390f585f67ed844e3fa18510d92a28 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-0-0.py @@ -0,0 +1,469 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "6.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1539, 0), + (1552, 1562, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1757, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2304, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3330, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6157, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7082, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7410, 0), + (7616, 7654, 0), + (7676, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42620, 42621, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43643, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65062, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69760, 69762, 0), + (69808, 69818, 0), + (69821, 69821, 0), + (110592, 110593, 2), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (127488, 127490, 2), + (127504, 127546, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-1-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-1-0.py new file mode 100644 index 0000000000000000000000000000000000000000..29d3e9298806c875b8969195a1cb6a39c9918cb9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-1-0.py @@ -0,0 +1,480 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "6.1.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1540, 0), + (1552, 1562, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1757, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2276, 2302, 0), + (2304, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3330, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6157, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7616, 7654, 0), + (7676, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42655, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43643, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65062, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69760, 69762, 0), + (69808, 69818, 0), + (69821, 69821, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (71339, 71351, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (110592, 110593, 2), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (127488, 127490, 2), + (127504, 127546, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-2-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-2-0.py new file mode 100644 index 0000000000000000000000000000000000000000..d0cda351a493664500d0179ab6dac7b2f978c69d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-2-0.py @@ -0,0 +1,480 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "6.2.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1540, 0), + (1552, 1562, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1757, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2276, 2302, 0), + (2304, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3330, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6157, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7616, 7654, 0), + (7676, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42655, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43643, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65062, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69760, 69762, 0), + (69808, 69818, 0), + (69821, 69821, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (71339, 71351, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (110592, 110593, 2), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (127488, 127490, 2), + (127504, 127546, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-3-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-3-0.py new file mode 100644 index 0000000000000000000000000000000000000000..cffb7ee942eb8f175e182d0105c4e356ad8519fb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode6-3-0.py @@ -0,0 +1,481 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "6.3.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1540, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1757, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2276, 2302, 0), + (2304, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3073, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3202, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3330, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7616, 7654, 0), + (7676, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42655, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43643, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65062, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69760, 69762, 0), + (69808, 69818, 0), + (69821, 69821, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (71339, 71351, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (110592, 110593, 2), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (127488, 127490, 2), + (127504, 127546, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode7-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode7-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..996478ac24a54b844beb0d209fe43db9a7a2a014 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode7-0-0.py @@ -0,0 +1,507 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "7.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1541, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1757, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2276, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3329, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6576, 6592, 0), + (6600, 6601, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6846, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7416, 7417, 0), + (7616, 7669, 0), + (7676, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42655, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65069, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69821, 69821, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70188, 70199, 0), + (70367, 70378, 0), + (70401, 70403, 0), + (70460, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (110592, 110593, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (125136, 125142, 0), + (127488, 127490, 2), + (127504, 127546, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode8-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode8-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..ae34a382a6a8b486c5fc2d4c6491cd6c3ab56d77 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode8-0-0.py @@ -0,0 +1,515 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "8.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1536, 1541, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1757, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1807, 1807, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3329, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6846, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7416, 7417, 0), + (7616, 7669, 0), + (7676, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (9001, 9002, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43204, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69821, 69821, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70090, 70092, 0), + (70188, 70199, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70460, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (110592, 110593, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (125136, 125142, 0), + (127488, 127490, 2), + (127504, 127546, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127995, 127999, 0), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode9-0-0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode9-0-0.py new file mode 100644 index 0000000000000000000000000000000000000000..b15f67d44eb15e2388aa52089922eaf77916d578 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rich/_unicode_data/unicode9-0-0.py @@ -0,0 +1,598 @@ +# Auto generated by tools/make_width_tables.py +# Data from wcwidth project (https://github.com/jquast/wcwidth) + +from rich.cells import CellTable + +cell_table = CellTable( + "9.0.0", + [ + (0, 0, 0), + (768, 879, 0), + (1155, 1161, 0), + (1425, 1469, 0), + (1471, 1471, 0), + (1473, 1474, 0), + (1476, 1477, 0), + (1479, 1479, 0), + (1552, 1562, 0), + (1564, 1564, 0), + (1611, 1631, 0), + (1648, 1648, 0), + (1750, 1756, 0), + (1759, 1764, 0), + (1767, 1768, 0), + (1770, 1773, 0), + (1809, 1809, 0), + (1840, 1866, 0), + (1958, 1968, 0), + (2027, 2035, 0), + (2070, 2073, 0), + (2075, 2083, 0), + (2085, 2087, 0), + (2089, 2093, 0), + (2137, 2139, 0), + (2260, 2273, 0), + (2275, 2307, 0), + (2362, 2364, 0), + (2366, 2383, 0), + (2385, 2391, 0), + (2402, 2403, 0), + (2433, 2435, 0), + (2492, 2492, 0), + (2494, 2500, 0), + (2503, 2504, 0), + (2507, 2509, 0), + (2519, 2519, 0), + (2530, 2531, 0), + (2561, 2563, 0), + (2620, 2620, 0), + (2622, 2626, 0), + (2631, 2632, 0), + (2635, 2637, 0), + (2641, 2641, 0), + (2672, 2673, 0), + (2677, 2677, 0), + (2689, 2691, 0), + (2748, 2748, 0), + (2750, 2757, 0), + (2759, 2761, 0), + (2763, 2765, 0), + (2786, 2787, 0), + (2817, 2819, 0), + (2876, 2876, 0), + (2878, 2884, 0), + (2887, 2888, 0), + (2891, 2893, 0), + (2902, 2903, 0), + (2914, 2915, 0), + (2946, 2946, 0), + (3006, 3010, 0), + (3014, 3016, 0), + (3018, 3021, 0), + (3031, 3031, 0), + (3072, 3075, 0), + (3134, 3140, 0), + (3142, 3144, 0), + (3146, 3149, 0), + (3157, 3158, 0), + (3170, 3171, 0), + (3201, 3203, 0), + (3260, 3260, 0), + (3262, 3268, 0), + (3270, 3272, 0), + (3274, 3277, 0), + (3285, 3286, 0), + (3298, 3299, 0), + (3329, 3331, 0), + (3390, 3396, 0), + (3398, 3400, 0), + (3402, 3405, 0), + (3415, 3415, 0), + (3426, 3427, 0), + (3458, 3459, 0), + (3530, 3530, 0), + (3535, 3540, 0), + (3542, 3542, 0), + (3544, 3551, 0), + (3570, 3571, 0), + (3633, 3633, 0), + (3636, 3642, 0), + (3655, 3662, 0), + (3761, 3761, 0), + (3764, 3769, 0), + (3771, 3772, 0), + (3784, 3789, 0), + (3864, 3865, 0), + (3893, 3893, 0), + (3895, 3895, 0), + (3897, 3897, 0), + (3902, 3903, 0), + (3953, 3972, 0), + (3974, 3975, 0), + (3981, 3991, 0), + (3993, 4028, 0), + (4038, 4038, 0), + (4139, 4158, 0), + (4182, 4185, 0), + (4190, 4192, 0), + (4194, 4196, 0), + (4199, 4205, 0), + (4209, 4212, 0), + (4226, 4237, 0), + (4239, 4239, 0), + (4250, 4253, 0), + (4352, 4447, 2), + (4448, 4607, 0), + (4957, 4959, 0), + (5906, 5908, 0), + (5938, 5940, 0), + (5970, 5971, 0), + (6002, 6003, 0), + (6068, 6099, 0), + (6109, 6109, 0), + (6155, 6158, 0), + (6277, 6278, 0), + (6313, 6313, 0), + (6432, 6443, 0), + (6448, 6459, 0), + (6679, 6683, 0), + (6741, 6750, 0), + (6752, 6780, 0), + (6783, 6783, 0), + (6832, 6846, 0), + (6912, 6916, 0), + (6964, 6980, 0), + (7019, 7027, 0), + (7040, 7042, 0), + (7073, 7085, 0), + (7142, 7155, 0), + (7204, 7223, 0), + (7376, 7378, 0), + (7380, 7400, 0), + (7405, 7405, 0), + (7410, 7412, 0), + (7416, 7417, 0), + (7616, 7669, 0), + (7675, 7679, 0), + (8203, 8207, 0), + (8232, 8238, 0), + (8288, 8303, 0), + (8400, 8432, 0), + (8986, 8987, 2), + (9001, 9002, 2), + (9193, 9196, 2), + (9200, 9200, 2), + (9203, 9203, 2), + (9725, 9726, 2), + (9748, 9749, 2), + (9800, 9811, 2), + (9855, 9855, 2), + (9875, 9875, 2), + (9889, 9889, 2), + (9898, 9899, 2), + (9917, 9918, 2), + (9924, 9925, 2), + (9934, 9934, 2), + (9940, 9940, 2), + (9962, 9962, 2), + (9970, 9971, 2), + (9973, 9973, 2), + (9978, 9978, 2), + (9981, 9981, 2), + (9989, 9989, 2), + (9994, 9995, 2), + (10024, 10024, 2), + (10060, 10060, 2), + (10062, 10062, 2), + (10067, 10069, 2), + (10071, 10071, 2), + (10133, 10135, 2), + (10160, 10160, 2), + (10175, 10175, 2), + (11035, 11036, 2), + (11088, 11088, 2), + (11093, 11093, 2), + (11503, 11505, 0), + (11647, 11647, 0), + (11744, 11775, 0), + (11904, 11929, 2), + (11931, 12019, 2), + (12032, 12245, 2), + (12272, 12283, 2), + (12288, 12329, 2), + (12330, 12335, 0), + (12336, 12350, 2), + (12353, 12438, 2), + (12441, 12442, 0), + (12443, 12543, 2), + (12549, 12589, 2), + (12593, 12643, 2), + (12644, 12644, 0), + (12645, 12686, 2), + (12688, 12730, 2), + (12736, 12771, 2), + (12784, 12830, 2), + (12832, 12871, 2), + (12880, 13054, 2), + (13056, 19903, 2), + (19968, 42124, 2), + (42128, 42182, 2), + (42607, 42610, 0), + (42612, 42621, 0), + (42654, 42655, 0), + (42736, 42737, 0), + (43010, 43010, 0), + (43014, 43014, 0), + (43019, 43019, 0), + (43043, 43047, 0), + (43136, 43137, 0), + (43188, 43205, 0), + (43232, 43249, 0), + (43302, 43309, 0), + (43335, 43347, 0), + (43360, 43388, 2), + (43392, 43395, 0), + (43443, 43456, 0), + (43493, 43493, 0), + (43561, 43574, 0), + (43587, 43587, 0), + (43596, 43597, 0), + (43643, 43645, 0), + (43696, 43696, 0), + (43698, 43700, 0), + (43703, 43704, 0), + (43710, 43711, 0), + (43713, 43713, 0), + (43755, 43759, 0), + (43765, 43766, 0), + (44003, 44010, 0), + (44012, 44013, 0), + (44032, 55203, 2), + (55216, 55295, 0), + (63744, 64255, 2), + (64286, 64286, 0), + (65024, 65039, 0), + (65040, 65049, 2), + (65056, 65071, 0), + (65072, 65106, 2), + (65108, 65126, 2), + (65128, 65131, 2), + (65279, 65279, 0), + (65281, 65376, 2), + (65440, 65440, 0), + (65504, 65510, 2), + (65520, 65531, 0), + (66045, 66045, 0), + (66272, 66272, 0), + (66422, 66426, 0), + (68097, 68099, 0), + (68101, 68102, 0), + (68108, 68111, 0), + (68152, 68154, 0), + (68159, 68159, 0), + (68325, 68326, 0), + (69632, 69634, 0), + (69688, 69702, 0), + (69759, 69762, 0), + (69808, 69818, 0), + (69888, 69890, 0), + (69927, 69940, 0), + (70003, 70003, 0), + (70016, 70018, 0), + (70067, 70080, 0), + (70090, 70092, 0), + (70188, 70199, 0), + (70206, 70206, 0), + (70367, 70378, 0), + (70400, 70403, 0), + (70460, 70460, 0), + (70462, 70468, 0), + (70471, 70472, 0), + (70475, 70477, 0), + (70487, 70487, 0), + (70498, 70499, 0), + (70502, 70508, 0), + (70512, 70516, 0), + (70709, 70726, 0), + (70832, 70851, 0), + (71087, 71093, 0), + (71096, 71104, 0), + (71132, 71133, 0), + (71216, 71232, 0), + (71339, 71351, 0), + (71453, 71467, 0), + (72751, 72758, 0), + (72760, 72767, 0), + (72850, 72871, 0), + (72873, 72886, 0), + (92912, 92916, 0), + (92976, 92982, 0), + (94033, 94078, 0), + (94095, 94098, 0), + (94176, 94176, 2), + (94208, 100332, 2), + (100352, 101106, 2), + (110592, 110593, 2), + (113821, 113822, 0), + (113824, 113827, 0), + (119141, 119145, 0), + (119149, 119170, 0), + (119173, 119179, 0), + (119210, 119213, 0), + (119362, 119364, 0), + (121344, 121398, 0), + (121403, 121452, 0), + (121461, 121461, 0), + (121476, 121476, 0), + (121499, 121503, 0), + (121505, 121519, 0), + (122880, 122886, 0), + (122888, 122904, 0), + (122907, 122913, 0), + (122915, 122916, 0), + (122918, 122922, 0), + (125136, 125142, 0), + (125252, 125258, 0), + (126980, 126980, 2), + (127183, 127183, 2), + (127374, 127374, 2), + (127377, 127386, 2), + (127488, 127490, 2), + (127504, 127547, 2), + (127552, 127560, 2), + (127568, 127569, 2), + (127744, 127776, 2), + (127789, 127797, 2), + (127799, 127868, 2), + (127870, 127891, 2), + (127904, 127946, 2), + (127951, 127955, 2), + (127968, 127984, 2), + (127988, 127988, 2), + (127992, 127994, 2), + (127995, 127999, 0), + (128000, 128062, 2), + (128064, 128064, 2), + (128066, 128252, 2), + (128255, 128317, 2), + (128331, 128334, 2), + (128336, 128359, 2), + (128378, 128378, 2), + (128405, 128406, 2), + (128420, 128420, 2), + (128507, 128591, 2), + (128640, 128709, 2), + (128716, 128716, 2), + (128720, 128722, 2), + (128747, 128748, 2), + (128756, 128758, 2), + (129296, 129310, 2), + (129312, 129319, 2), + (129328, 129328, 2), + (129331, 129342, 2), + (129344, 129355, 2), + (129360, 129374, 2), + (129408, 129425, 2), + (129472, 129472, 2), + (131072, 196605, 2), + (196608, 262141, 2), + (917504, 921599, 0), + ], + frozenset( + [ + "#", + "*", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "©", + "®", + "‼", + "⁉", + "™", + "ℹ", + "↔", + "↕", + "↖", + "↗", + "↘", + "↙", + "↩", + "↪", + "⌨", + "⏏", + "⏭", + "⏮", + "⏯", + "⏱", + "⏲", + "⏸", + "⏹", + "⏺", + "Ⓜ", + "▪", + "▫", + "▶", + "◀", + "◻", + "◼", + "☀", + "☁", + "☂", + "☃", + "☄", + "☎", + "☑", + "☘", + "☝", + "☠", + "☢", + "☣", + "☦", + "☪", + "☮", + "☯", + "☸", + "☹", + "☺", + "♀", + "♂", + "♟", + "♠", + "♣", + "♥", + "♦", + "♨", + "♻", + "♾", + "⚒", + "⚔", + "⚕", + "⚖", + "⚗", + "⚙", + "⚛", + "⚜", + "⚠", + "⚧", + "⚰", + "⚱", + "⛈", + "⛏", + "⛑", + "⛓", + "⛩", + "⛰", + "⛱", + "⛴", + "⛷", + "⛸", + "⛹", + "✂", + "✈", + "✉", + "✌", + "✍", + "✏", + "✒", + "✔", + "✖", + "✝", + "✡", + "✳", + "✴", + "❄", + "❇", + "❣", + "❤", + "➡", + "⤴", + "⤵", + "⬅", + "⬆", + "⬇", + "🅰", + "🅱", + "🅾", + "🅿", + "🌡", + "🌤", + "🌥", + "🌦", + "🌧", + "🌨", + "🌩", + "🌪", + "🌫", + "🌬", + "🌶", + "🍽", + "🎖", + "🎗", + "🎙", + "🎚", + "🎛", + "🎞", + "🎟", + "🏋", + "🏌", + "🏍", + "🏎", + "🏔", + "🏕", + "🏖", + "🏗", + "🏘", + "🏙", + "🏚", + "🏛", + "🏜", + "🏝", + "🏞", + "🏟", + "🏳", + "🏵", + "🏷", + "🐿", + "👁", + "📽", + "🕉", + "🕊", + "🕯", + "🕰", + "🕳", + "🕴", + "🕵", + "🕶", + "🕷", + "🕸", + "🕹", + "🖇", + "🖊", + "🖋", + "🖌", + "🖍", + "🖐", + "🖥", + "🖨", + "🖱", + "🖲", + "🖼", + "🗂", + "🗃", + "🗄", + "🗑", + "🗒", + "🗓", + "🗜", + "🗝", + "🗞", + "🗡", + "🗣", + "🗨", + "🗯", + "🗳", + "🗺", + "🛋", + "🛍", + "🛎", + "🛏", + "🛠", + "🛡", + "🛢", + "🛣", + "🛤", + "🛥", + "🛩", + "🛰", + "🛳", + ] + ), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rpds/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/rpds/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39d2487ff0b5be15dc75776196111af439704bd5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/rpds/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/rpds_py-0.30.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/rpds_py-0.30.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9a3970a75793bcf642507d42ffafaf2986e84075 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/rpds_py-0.30.0.dist-info/licenses/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2023 Julian Berman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors-0.7.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors-0.7.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors-0.7.0.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6da04b73ed0d7f6270b9dca923a192539974c9b0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/flax.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/flax.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49226d906f24b2c7cb4308b58d2c236380d6febd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/flax.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/mlx.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/mlx.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e42981f2671a18934572a5740caad5d6d41e256 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/mlx.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/numpy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/numpy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48b6e1f277d28b26d1da0339e6a72c51606d7170 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/numpy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/paddle.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/paddle.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f93a2a77db22513e27dc7ebc97b0ba3cedc1ba1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/paddle.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/tensorflow.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/tensorflow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ffd3642447fd91c55b7903015e59019a084e1eb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/tensorflow.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/torch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/torch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc2baa91c4a2f37457d339f977efad609926c28c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/safetensors/__pycache__/torch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/README.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5947f0da4723b42a55c8ce5650df8ddb0a176e58 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/README.md @@ -0,0 +1,56 @@ +# Embedding Function Schemas + +This directory contains JSON schemas for all embedding functions in Chroma. The purpose of having these schemas is to support cross-language compatibility and to validate that changes in one client library do not accidentally diverge from others. + +## Schema Structure + +Each schema follows the JSON Schema Draft-07 specification and includes: + +- `version`: The version of the schema +- `title`: The title of the schema +- `description`: A description of the schema +- `properties`: The properties that can be configured for the embedding function +- `required`: The properties that are required for the embedding function +- `additionalProperties`: Whether additional properties are allowed (always set to `false` to ensure strict validation) + +## Usage + +These schemas are used by both the Python and JavaScript clients to validate embedding function configurations. + +### Python + +```python +from chromadb.utils.embedding_functions.schemas import validate_config + +# Validate a configuration +config = { + "api_key_env_var": "CHROMA_OPENAI_API_KEY", + "model_name": "text-embedding-ada-002" +} +validate_config(config, "openai") +``` + +### JavaScript + +```typescript +import { validateConfig } from '@chromadb/core'; + +// Validate a configuration +const config = { + api_key_env_var: "CHROMA_OPENAI_API_KEY", + model_name: "text-embedding-ada-002" +}; +validateConfig(config, "openai"); +``` + +## Adding New Schemas + +To add a new schema: + +1. Create a new JSON file in this directory with the name of the embedding function (e.g., `new_function.json`) +2. Define the schema following the JSON Schema Draft-07 specification +3. Update the embedding function implementations in both Python and JavaScript to use the schema for validation + +## Schema Versioning + +Each schema includes a version number to support future changes to embedding function configurations. When making changes to a schema, increment the version number to ensure backward compatibility. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/amazon_bedrock.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/amazon_bedrock.json new file mode 100644 index 0000000000000000000000000000000000000000..5b90d8df31727f7649855c4c6b45a8997e23dfa2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/amazon_bedrock.json @@ -0,0 +1,27 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Amazon Bedrock Embedding Function Schema", + "description": "Schema for the Amazon Bedrock embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "session_args": { + "type": "object", + "description": "The arguments to pass to the boto3 session" + }, + "model_name": { + "type": "string", + "description": "The name of the model to use for embeddings" + }, + "kwargs": { + "type": "object", + "description": "Additional arguments to pass to the Amazon Bedrock client" + } + }, + "required": [ + "session_args", + "model_name", + "kwargs" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/base_schema.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/base_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..267bd6cd99f89d5ccc79aa22a3d14d96d1aeafc9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/base_schema.json @@ -0,0 +1,26 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Embedding Function Base Schema", + "description": "Base schema for all embedding functions in Chroma", + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "Schema version for the embedding function" + }, + "name": { + "type": "string", + "description": "Name of the embedding function" + }, + "config": { + "type": "object", + "description": "Configuration parameters for the embedding function" + } + }, + "required": [ + "version", + "name", + "config" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/baseten.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/baseten.json new file mode 100644 index 0000000000000000000000000000000000000000..27657361699761cb96a6d54988ecf9671952b651 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/baseten.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Baseten Embedding Function Schema", + "description": "Schema for the Baseten embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "api_base": { + "type": "string", + "description": "The Baseten URL of the deployment" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Baseten API" + } + }, + "required": [ + "api_base", + "api_key_env_var" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/bm25.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/bm25.json new file mode 100644 index 0000000000000000000000000000000000000000..7f464be045f67ff596ff81195640984bfab2aad7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/bm25.json @@ -0,0 +1,103 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "BM25 Embedding Function Schema", + "description": "Schema for the BM25 sparse embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "task": { + "type": "string", + "enum": [ + "document", + "query" + ], + "description": "Task to perform, can be 'document' or 'query'" + }, + "query_config": { + "type": "object", + "description": "Configuration for the query", + "properties": { + "task": { + "type": "string", + "enum": [ + "document", + "query" + ], + "description": "Task to perform for query embedding" + } + }, + "additionalProperties": false + }, + "cache_dir": { + "type": [ + "string", + "null" + ], + "description": "The path to the cache directory" + }, + "k": { + "type": [ + "number", + "null" + ], + "description": "The k parameter in the BM25 formula. Defines the saturation of the term frequency" + }, + "b": { + "type": [ + "number", + "null" + ], + "description": "The b parameter in the BM25 formula. Defines the importance of the document length" + }, + "avg_len": { + "type": [ + "number", + "null" + ], + "description": "The average length of the documents in the corpus" + }, + "language": { + "type": [ + "string", + "null" + ], + "description": "Specifies the language for the stemmer" + }, + "token_max_length": { + "type": [ + "integer", + "null" + ], + "description": "The maximum length of the tokens" + }, + "disable_stemmer": { + "type": [ + "boolean", + "null" + ], + "description": "Disable the stemmer" + }, + "specific_model_path": { + "type": [ + "string", + "null" + ], + "description": "The path to the specific model" + }, + "kwargs": { + "type": "object", + "description": "Additional arguments to pass to the BM25 model", + "additionalProperties": { + "type": [ + "string", + "integer", + "number", + "boolean", + "array", + "object" + ] + } + } + }, + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma-cloud-qwen.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma-cloud-qwen.json new file mode 100644 index 0000000000000000000000000000000000000000..17ec2c569fe008c30450037839d4297fa0ea1402 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma-cloud-qwen.json @@ -0,0 +1,61 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Chroma Cloud Qwen Embedding Function Schema", + "description": "Schema for the Chroma Cloud Qwen embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model": { + "type": "string", + "enum": [ + "Qwen/Qwen3-Embedding-0.6B" + ], + "description": "The specific Qwen model to use for embeddings" + }, + "task": { + "type": [ + "string", + "null" + ], + "description": "The task for which embeddings are being generated. If null or empty, empty instructions will be used." + }, + "instructions": { + "type": "object", + "description": "A mapping of tasks to instructions for targets (documents/queries)", + "properties": { + "nl_to_code": { + "type": "object", + "properties": { + "documents": { + "type": "string", + "description": "Instructions for embedding documents" + }, + "query": { + "type": "string", + "description": "Instructions for embedding queries" + } + }, + "required": [ + "documents", + "query" + ], + "additionalProperties": false + } + }, + "required": [ + "nl_to_code" + ], + "additionalProperties": false + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Chroma Embedding API", + "default": "CHROMA_API_KEY" + } + }, + "required": [ + "model", + "task" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma-cloud-splade.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma-cloud-splade.json new file mode 100644 index 0000000000000000000000000000000000000000..2f6c1b719cf109f56c7bfc41e152ebf08a6a4e8e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma-cloud-splade.json @@ -0,0 +1,31 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Chroma Cloud Splade Embedding Function Schema", + "description": "Schema for the Chroma Cloud Splade sparse embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model": { + "type": "string", + "enum": [ + "prithivida/Splade_PP_en_v1" + ], + "description": "The specific Splade model to use for sparse embeddings" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Chroma Embedding API", + "default": "CHROMA_API_KEY" + }, + "include_tokens": { + "type": "boolean", + "description": "Whether to store token labels in the sparse vector output", + "default": false + } + }, + "required": [ + "api_key_env_var", + "model" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma_bm25.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma_bm25.json new file mode 100644 index 0000000000000000000000000000000000000000..b3c9e05eebee6091509bf1c91729c54b22ed93da --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma_bm25.json @@ -0,0 +1,37 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Chroma BM25 Embedding Function Schema", + "description": "Schema for the Chroma BM25 sparse embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "k": { + "type": "number", + "description": "BM25 saturation parameter controlling term frequency scaling" + }, + "b": { + "type": "number", + "description": "BM25 length normalization parameter" + }, + "avg_doc_length": { + "type": "number", + "description": "Average document length in tokens used for normalization" + }, + "token_max_length": { + "type": "number", + "description": "Maximum token length allowed before filtering" + }, + "stopwords": { + "type": "array", + "description": "Optional custom stopword list (in lowercase) to override the defaults", + "items": { + "type": "string" + } + }, + "include_tokens": { + "type": "boolean", + "description": "Whether to store token strings in the sparse vectors (default: true)" + } + }, + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma_langchain.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma_langchain.json new file mode 100644 index 0000000000000000000000000000000000000000..6677c388c834ab235ac5e716d5d600d4eaa93d49 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/chroma_langchain.json @@ -0,0 +1,17 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Langchain Embedding Function Schema", + "description": "Schema for the langchain embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "embedding_function": { + "type": "string", + "description": "Parameter embedding_function for the langchain embedding function" + } + }, + "required": [ + "embedding_function" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/cloudflare_workers_ai.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/cloudflare_workers_ai.json new file mode 100644 index 0000000000000000000000000000000000000000..ba512e689fa8d375e137b3e23082550a729f85a5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/cloudflare_workers_ai.json @@ -0,0 +1,34 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Cloudflare Workers AI Embedding Function Schema", + "description": "Schema for the Cloudflare Workers AI embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "account_id": { + "type": "string", + "description": "The account ID for the Cloudflare Workers AI API" + }, + "api_key_env_var": { + "type": "string", + "description": "The environment variable name that contains your API key for the Cloudflare Workers AI API" + }, + "gateway_id": { + "type": [ + "string", + "null" + ], + "description": "The ID of the Cloudflare AI Gateway to use for a more customized solution" + } + }, + "required": [ + "api_key_env_var", + "model_name", + "account_id" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/cohere.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/cohere.json new file mode 100644 index 0000000000000000000000000000000000000000..b46af3d3bce14b51e0f6323b559452d314a81d21 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/cohere.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Cohere Embedding Function Schema", + "description": "Schema for the Cohere embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Cohere API" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/default.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/default.json new file mode 100644 index 0000000000000000000000000000000000000000..9dfaa724ff23139b804367cdc50054212b42e23e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/default.json @@ -0,0 +1,10 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Default Embedding Function Schema", + "description": "Schema for the default embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/fastembed_sparse.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/fastembed_sparse.json new file mode 100644 index 0000000000000000000000000000000000000000..e989b9eee3dafdc370a379f8465f01b651d644f7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/fastembed_sparse.json @@ -0,0 +1,92 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Fastembed Sparse Embedding Function Schema", + "description": "Schema for the Fastembed sparse embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Identifier of the Fastembed model. List of commonly used models: Qdrant/bm25, prithivida/Splade_PP_en_v1, Qdrant/minicoil-v1" + }, + "task": { + "type": "string", + "enum": [ + "document", + "query" + ], + "description": "Task to perform, can be 'document' or 'query'" + }, + "query_config": { + "type": "object", + "description": "Configuration for the query", + "properties": { + "task": { + "type": "string", + "enum": [ + "document", + "query" + ], + "description": "Task to perform for query embedding" + } + }, + "additionalProperties": false + }, + "cache_dir": { + "type": [ + "string", + "null" + ], + "description": "The path to the cache directory" + }, + "threads": { + "type": [ + "integer", + "null" + ], + "description": "The number of threads to use for the model" + }, + "cuda": { + "type": [ + "boolean", + "null" + ], + "description": "Whether to use CUDA" + }, + "device_ids": { + "type": [ + "array", + "null" + ], + "description": "The device IDs to use for the model", + "items": { + "type": "integer" + } + }, + "lazy_load": { + "type": [ + "boolean", + "null" + ], + "description": "Whether to lazy load the model" + }, + "kwargs": { + "type": "object", + "description": "Additional arguments to pass to the model", + "additionalProperties": { + "type": [ + "string", + "integer", + "number", + "boolean", + "array", + "object" + ] + } + } + }, + "required": [ + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_gemini.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_gemini.json new file mode 100644 index 0000000000000000000000000000000000000000..a54387fbafce741e69e61386f154c24496264e81 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_gemini.json @@ -0,0 +1,53 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Google Gemini Embedding Function Schema", + "description": "Schema for the Google Gemini embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "task_type": { + "type": "string", + "description": "The task type for the embeddings (e.g., RETRIEVAL_DOCUMENT, SEMANTIC_SIMILARITY)" + }, + "dimension": { + "type": "integer", + "description": "The output dimensionality for the embeddings. If not specified, the model's default dimensionality is used." + }, + "api_key_env_var": { + "type": [ + "string", + "null" + ], + "description": "Environment variable name that contains your API key for the Gemini API" + }, + "vertexai": { + "type": [ + "boolean", + "null" + ], + "description": "Whether to use Vertex AI" + }, + "project": { + "type": [ + "string", + "null" + ], + "description": "The Google Cloud project ID (required for Vertex AI)" + }, + "location": { + "type": [ + "string", + "null" + ], + "description": "The Google Cloud location/region (required for Vertex AI)" + } + }, + "required": [ + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_genai.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_genai.json new file mode 100644 index 0000000000000000000000000000000000000000..935e826748b4cf7c2c97744c782df299157fd8a0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_genai.json @@ -0,0 +1,50 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Google GenAI Embedding Function Schema", + "description": "Schema for the Google GenAI embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "task_type": { + "type": "string", + "description": "The task type for the embeddings (e.g., RETRIEVAL_DOCUMENT, SEMANTIC_SIMILARITY)" + }, + "dimension": { + "type": "integer", + "description": "The output dimensionality for the embeddings. If not specified, the model's default dimensionality is used." + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Gemini API" + }, + "vertexai": { + "type": [ + "boolean", + "null" + ], + "description": "Whether to use Vertex AI" + }, + "project": { + "type": [ + "string", + "null" + ], + "description": "The Google Cloud project ID (required for Vertex AI)" + }, + "location": { + "type": [ + "string", + "null" + ], + "description": "The Google Cloud location/region (required for Vertex AI)" + } + }, + "required": [ + "model_name" + ], + "additionalProperties": false +} \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_generative_ai.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_generative_ai.json new file mode 100644 index 0000000000000000000000000000000000000000..0850f206930d5b17c5dbaef1f2d57e3657a29d1e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_generative_ai.json @@ -0,0 +1,31 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Google Generative AI Embedding Function Schema", + "description": "Schema for the Google Generative AI embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "task_type": { + "type": "string", + "description": "The task type for the embeddings (e.g., RETRIEVAL_DOCUMENT)" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Google Generative AI API" + }, + "dimension": { + "type": "integer", + "description": "The output dimensionality for the embeddings. If not specified, the model's default dimensionality is used." + } + }, + "required": [ + "api_key_env_var", + "model_name", + "task_type" + ], + "additionalProperties": false +} \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_palm.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_palm.json new file mode 100644 index 0000000000000000000000000000000000000000..01534afb1cf285ace3410673b9a0905ce26ed9e6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_palm.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Google PaLM Embedding Function Schema", + "description": "Schema for the Google PaLM embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Google PaLM API" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_vertex.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_vertex.json new file mode 100644 index 0000000000000000000000000000000000000000..63198cc0d24bf5786679236ef8aaf12a070a4eb0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/google_vertex.json @@ -0,0 +1,32 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Google Vertex Embedding Function Schema", + "description": "Schema for the Google Vertex embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "project_id": { + "type": "string", + "description": "The Google Cloud project ID" + }, + "region": { + "type": "string", + "description": "The Google Cloud region" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Google Vertex API" + } + }, + "required": [ + "api_key_env_var", + "model_name", + "project_id", + "region" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface.json new file mode 100644 index 0000000000000000000000000000000000000000..a398b18d64736d0382654a83bf70f5dc304041a3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "HuggingFace Embedding Function Schema", + "description": "Schema for the HuggingFace embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the HuggingFace API" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface_server.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface_server.json new file mode 100644 index 0000000000000000000000000000000000000000..42af0659fb70332347454f967c78da76651eb691 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface_server.json @@ -0,0 +1,24 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "HuggingFace Embedding Server Schema", + "description": "Schema for the HuggingFace embedding server configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL of the HuggingFace Embedding Server" + }, + "api_key_env_var": { + "type": [ + "string", + "null" + ], + "description": "The environment variable name that contains your API key for the HuggingFace API" + } + }, + "required": [ + "url" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface_sparse.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface_sparse.json new file mode 100644 index 0000000000000000000000000000000000000000..5fc84a7768bfe0e78eb36a568d9a3e040a4a4212 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/huggingface_sparse.json @@ -0,0 +1,59 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "HuggingFace Sparse Embedding Function Schema", + "description": "Schema for the HuggingFace sparse embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Identifier of the Huggingface SparseEncoder model. Some common models: prithivida/Splade_PP_en_v1, naver/splade-cocondenser-ensembledistil, naver/splade-v3" + }, + "device": { + "type": "string", + "description": "Device used for computation" + }, + "task": { + "type": "string", + "enum": [ + "document", + "query" + ], + "description": "Task to perform, can be 'document' or 'query'" + }, + "query_config": { + "type": "object", + "description": "Configuration for the query", + "properties": { + "task": { + "type": "string", + "enum": [ + "document", + "query" + ], + "description": "Task to perform for query embedding" + } + }, + "additionalProperties": false + }, + "kwargs": { + "type": "object", + "description": "Additional arguments to pass to the Splade model", + "additionalProperties": { + "type": [ + "string", + "integer", + "number", + "boolean", + "array", + "object" + ] + } + } + }, + "required": [ + "model_name", + "device" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/instructor.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/instructor.json new file mode 100644 index 0000000000000000000000000000000000000000..f6dcc2f74745484d81b4ddc11f573a514de0c3b5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/instructor.json @@ -0,0 +1,29 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Instructor Embedding Function Schema", + "description": "Schema for the instructor embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Parameter model_name for the instructor embedding function" + }, + "device": { + "type": "string", + "description": "Parameter device for the instructor embedding function" + }, + "instruction": { + "type": [ + "string", + "null" + ], + "description": "Parameter instruction for the instructor embedding function" + } + }, + "required": [ + "model_name", + "device" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/jina.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/jina.json new file mode 100644 index 0000000000000000000000000000000000000000..91913b12c5c107a829d8693eca9e9e5dcb623982 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/jina.json @@ -0,0 +1,71 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Jina Embedding Function Schema", + "description": "Schema for the jina embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Parameter model_name for the jina embedding function" + }, + "api_key_env_var": { + "type": "string", + "description": "Parameter api_key_env_var for the jina embedding function" + }, + "task": { + "type": [ + "string", + "null" + ], + "description": "Parameter task for the jina embedding function" + }, + "late_chunking": { + "type": [ + "boolean", + "null" + ], + "description": "Parameter late_chunking for the jina embedding function" + }, + "truncate": { + "type": [ + "boolean", + "null" + ], + "description": "Parameter truncate for the jina embedding function" + }, + "dimensions": { + "type": [ + "integer", + "null" + ], + "description": "Parameter dimensions for the jina embedding function" + }, + "embedding_type": { + "type": [ + "string", + "null" + ], + "description": "Parameter embedding_type for the jina embedding function" + }, + "normalized": { + "type": [ + "boolean", + "null" + ], + "description": "Parameter normalized for the jina embedding function" + }, + "query_config": { + "type": [ + "object", + "null" + ], + "description": "Parameter query_config for the jina embedding function" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/mistral.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/mistral.json new file mode 100644 index 0000000000000000000000000000000000000000..2907bb45cde8ec1eb8396cb053801432a067fc65 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/mistral.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Mistral Embedding Function Schema", + "description": "Schema for the Mistral embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model": { + "type": "string", + "description": "Parameter model for the Mistral embedding function" + }, + "api_key_env_var": { + "type": "string", + "description": "Parameter api_key_env_var for the Mistral embedding function" + } + }, + "required": [ + "api_key_env_var", + "model" + ], + "additionalProperties": false +} \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/morph.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/morph.json new file mode 100644 index 0000000000000000000000000000000000000000..1d7edc49890d4d2c280c6ffb8c8aa62124ebfb37 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/morph.json @@ -0,0 +1,36 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Morph Embedding Function Schema", + "description": "Schema for the Morph embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for embeddings" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the Morph API" + }, + "api_base": { + "type": [ + "string", + "null" + ], + "description": "The base URL for the Morph API" + }, + "encoding_format": { + "type": [ + "string", + "null" + ], + "description": "The format for embeddings (float or base64)" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/nomic.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/nomic.json new file mode 100644 index 0000000000000000000000000000000000000000..2f6db6f144045cdae3c19445b61103bb9dfe451d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/nomic.json @@ -0,0 +1,21 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Nomic Embedding Function Schema", + "description": "Schema for the Nomic embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model": { + "type": "string", + "description": "Parameter model for the Nomic embedding function" + }, + "api_key_env_var": { + "type": "string", + "description": "Parameter api_key_env_var for the Nomic embedding function" + }, + "task_type": { + "type": "string", + "description": "Parameter task_type for the Nomic embedding function" + } + } +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/ollama.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/ollama.json new file mode 100644 index 0000000000000000000000000000000000000000..ef94357621144766d6e4efd40d5fe45c3eec3f58 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/ollama.json @@ -0,0 +1,26 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Ollama Embedding Function Schema", + "description": "Schema for the Ollama embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL of the Ollama server" + }, + "model_name": { + "type": "string", + "description": "The name of the model to use for embeddings" + }, + "timeout": { + "type": "integer", + "description": "Timeout in seconds for the API request" + } + }, + "required": [ + "url", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/onnx_mini_lm_l6_v2.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/onnx_mini_lm_l6_v2.json new file mode 100644 index 0000000000000000000000000000000000000000..6bce046b1967eb2c694a2b2927b1a992727808a3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/onnx_mini_lm_l6_v2.json @@ -0,0 +1,21 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Onnx_mini_lm_l6_v2 Embedding Function Schema", + "description": "Schema for the onnx_mini_lm_l6_v2 embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "preferred_providers": { + "type": [ + "array", + "null" + ], + "items": { + "type": "string" + }, + "description": "Parameter preferred_providers for the onnx_mini_lm_l6_v2 embedding function" + } + }, + "required": [], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/open_clip.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/open_clip.json new file mode 100644 index 0000000000000000000000000000000000000000..f9882ffa34ecc55ae2a1443a88881a04d0b5b214 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/open_clip.json @@ -0,0 +1,30 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Open_clip Embedding Function Schema", + "description": "Schema for the open_clip embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Parameter model_name for the open_clip embedding function" + }, + "checkpoint": { + "type": "string", + "description": "Parameter checkpoint for the open_clip embedding function" + }, + "device": { + "type": [ + "string", + "null" + ], + "description": "Parameter device for the open_clip embedding function" + } + }, + "required": [ + "model_name", + "checkpoint", + "device" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/openai.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/openai.json new file mode 100644 index 0000000000000000000000000000000000000000..8d1b1d8cf129d244560622d14d3d33c0bb6042a0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/openai.json @@ -0,0 +1,71 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "OpenAI Embedding Function Schema", + "description": "Schema for the OpenAI embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "organization_id": { + "type": [ + "string", + "null" + ], + "description": "The OpenAI organization ID if applicable" + }, + "api_base": { + "type": [ + "string", + "null" + ], + "description": "The base path for the API" + }, + "api_type": { + "type": [ + "string", + "null" + ], + "description": "The type of the API deployment" + }, + "api_version": { + "type": [ + "string", + "null" + ], + "description": "The api version for the API" + }, + "deployment_id": { + "type": [ + "string", + "null" + ], + "description": "Deployment ID for Azure OpenAI" + }, + "default_headers": { + "type": [ + "object", + "null" + ], + "description": "A mapping of default headers to be sent with each API request" + }, + "dimensions": { + "type": [ + "integer", + "null" + ], + "description": "The number of dimensions for the embeddings" + }, + "api_key_env_var": { + "type": "string", + "description": "Environment variable name that contains your API key for the OpenAI API" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/perplexity.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/perplexity.json new file mode 100644 index 0000000000000000000000000000000000000000..6e8edd4db09a76a5123e123617b4454d9a389835 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/perplexity.json @@ -0,0 +1,26 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Perplexity Embedding Function Schema", + "description": "Schema for the perplexity embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Parameter model_name for the perplexity embedding function" + }, + "api_key_env_var": { + "type": "string", + "description": "Parameter api_key_env_var for the perplexity embedding function" + }, + "dimensions": { + "type": "number", + "description": "Matryoshka dimension (128-1024 for 0.6b, 128-2560 for 4b)" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/roboflow.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/roboflow.json new file mode 100644 index 0000000000000000000000000000000000000000..65ecd13d602db9f59dbede8bfe041a370eefce04 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/roboflow.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Roboflow Embedding Function Schema", + "description": "Schema for the roboflow embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "api_url": { + "type": "string", + "description": "Parameter api_url for the roboflow embedding function" + }, + "api_key_env_var": { + "type": "string", + "description": "Parameter api_key_env_var for the roboflow embedding function" + } + }, + "required": [ + "api_key_env_var", + "api_url" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/sentence_transformer.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/sentence_transformer.json new file mode 100644 index 0000000000000000000000000000000000000000..b9d5102b23aab25ad5c83127ed28c237f4815a8c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/sentence_transformer.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SentenceTransformer Embedding Function Schema", + "description": "Schema for the SentenceTransformer embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Identifier of the SentenceTransformer model" + }, + "device": { + "type": "string", + "description": "Device used for computation" + }, + "normalize_embeddings": { + "type": "boolean", + "description": "Whether to normalize returned vectors" + }, + "kwargs": { + "type": "object", + "description": "Additional arguments to pass to the SentenceTransformer model", + "additionalProperties": { + "type": [ + "string", + "integer", + "number", + "boolean", + "array", + "object" + ] + } + } + }, + "required": [ + "model_name", + "device", + "normalize_embeddings" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/text2vec.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/text2vec.json new file mode 100644 index 0000000000000000000000000000000000000000..7338d010813ae84d1906e24ff64dea700e4928b3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/text2vec.json @@ -0,0 +1,17 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Text2vec Embedding Function Schema", + "description": "Schema for the text2vec embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Parameter model_name for the text2vec embedding function" + } + }, + "required": [ + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/together_ai.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/together_ai.json new file mode 100644 index 0000000000000000000000000000000000000000..2f45cc492a88ea4eff433a50f37b2136f733597c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/together_ai.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Together AI Embedding Function Schema", + "description": "Schema for the Together AI embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model to use for text embeddings" + }, + "api_key_env_var": { + "type": "string", + "description": "The environment variable name that contains your API key for the Together AI API" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/transformers.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/transformers.json new file mode 100644 index 0000000000000000000000000000000000000000..fb2c080f7406c689165d23a83b0161963aaf3408 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/transformers.json @@ -0,0 +1,27 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Transformers Embedding Function Schema", + "description": "Schema for the Transformers embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model": { + "type": "string", + "description": "Identifier of the SentenceTransformer model" + }, + "revision": { + "type": "string", + "description": "Specific model version to use (can be a branch, tag name, or commit id)" + }, + "quantized": { + "type": "boolean", + "description": "Whether to load the 8-bit quantized version of the model" + } + }, + "required": [ + "model", + "revision", + "quantized" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/voyageai.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/voyageai.json new file mode 100644 index 0000000000000000000000000000000000000000..32f74639250170e2e641a80f3f71f108ff44d19f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/schemas/embedding_functions/voyageai.json @@ -0,0 +1,33 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Voyageai Embedding Function Schema", + "description": "Schema for the voyageai embedding function configuration", + "version": "1.0.0", + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "Parameter model_name for the voyageai embedding function" + }, + "api_key_env_var": { + "type": "string", + "description": "Parameter api_key_env_var for the voyageai embedding function" + }, + "input_type": { + "type": [ + "string", + "null" + ], + "description": "Parameter input_type for the voyageai embedding function" + }, + "truncation": { + "type": "boolean", + "description": "Parameter truncation for the voyageai embedding function" + } + }, + "required": [ + "api_key_env_var", + "model_name" + ], + "additionalProperties": false +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scikit_learn-1.8.0.dist-info/licenses/COPYING b/micromamba_root/envs/pytorch_env/Lib/site-packages/scikit_learn-1.8.0.dist-info/licenses/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..3783232adb3d0ce634b7268efb9f9eace7f515ac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scikit_learn-1.8.0.dist-info/licenses/COPYING @@ -0,0 +1,57 @@ +BSD 3-Clause License + +Copyright (c) 2007-2024 The scikit-learn developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +---- + +This binary distribution of scikit-learn also bundles the following software: + +---- + +Name: Microsoft Visual C++ Runtime Files +Files: sklearn\.libs\*.dll +Availability: https://learn.microsoft.com/en-us/visualstudio/releases/2015/2015-redistribution-vs + +Subject to the License Terms for the software, you may copy and distribute with your +program any of the files within the following folder and its subfolders except as noted +below. You may not modify these files. + +C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist + +You may not distribute the contents of the following folders: + +C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist\debug_nonredist +C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist\onecore\debug_nonredist + +Subject to the License Terms for the software, you may copy and distribute the following +files with your program in your program’s application local folder or by deploying them +into the Global Assembly Cache (GAC): + +VC\atlmfc\lib\mfcmifc80.dll +VC\atlmfc\lib\amd64\mfcmifc80.dll diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58bf2c5709549ffc5f37c483dca5134c051bf2aa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/__pycache__/vq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/__pycache__/vq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36d8ea9bed514caf8b8d2ccb043d9842a83b0169 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/__pycache__/vq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..758324e4e6f882347042c833574040bbd4ac6ac9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2fef5736cc21b7b73cf4f67986dabd9a2417ac2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_disjoint_set.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_disjoint_set.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22ea07ee42aa4a2425810d8cea177fc4e38e8883 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_disjoint_set.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_hierarchy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_hierarchy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b2e7813546f67e09159991df76f78f188120885 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_hierarchy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9517fed34ff3e08b6a9673a0af724ad31dc5f1b7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad7da3af7fa3acf8f399c9eedb149a1420d5a17 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py @@ -0,0 +1,145 @@ +from numpy import array + + +Q_X = array([[5.26563660e-01, 3.14160190e-01, 8.00656370e-02], + [7.50205180e-01, 4.60299830e-01, 8.98696460e-01], + [6.65461230e-01, 6.94011420e-01, 9.10465700e-01], + [9.64047590e-01, 1.43082200e-03, 7.39874220e-01], + [1.08159060e-01, 5.53028790e-01, 6.63804780e-02], + [9.31359130e-01, 8.25424910e-01, 9.52315440e-01], + [6.78086960e-01, 3.41903970e-01, 5.61481950e-01], + [9.82730940e-01, 7.04605210e-01, 8.70978630e-02], + [6.14691610e-01, 4.69989230e-02, 6.02406450e-01], + [5.80161260e-01, 9.17354970e-01, 5.88163850e-01], + [1.38246310e+00, 1.96358160e+00, 1.94437880e+00], + [2.10675860e+00, 1.67148730e+00, 1.34854480e+00], + [1.39880070e+00, 1.66142050e+00, 1.32224550e+00], + [1.71410460e+00, 1.49176380e+00, 1.45432170e+00], + [1.54102340e+00, 1.84374950e+00, 1.64658950e+00], + [2.08512480e+00, 1.84524350e+00, 2.17340850e+00], + [1.30748740e+00, 1.53801650e+00, 2.16007740e+00], + [1.41447700e+00, 1.99329070e+00, 1.99107420e+00], + [1.61943490e+00, 1.47703280e+00, 1.89788160e+00], + [1.59880600e+00, 1.54988980e+00, 1.57563350e+00], + [3.37247380e+00, 2.69635310e+00, 3.39981700e+00], + [3.13705120e+00, 3.36528090e+00, 3.06089070e+00], + [3.29413250e+00, 3.19619500e+00, 2.90700170e+00], + [2.65510510e+00, 3.06785900e+00, 2.97198540e+00], + [3.30941040e+00, 2.59283970e+00, 2.57714110e+00], + [2.59557220e+00, 3.33477370e+00, 3.08793190e+00], + [2.58206180e+00, 3.41615670e+00, 3.26441990e+00], + [2.71127000e+00, 2.77032450e+00, 2.63466500e+00], + [2.79617850e+00, 3.25473720e+00, 3.41801560e+00], + [2.64741750e+00, 2.54538040e+00, 3.25354110e+00]]) + +ytdist = array([662., 877., 255., 412., 996., 295., 468., 268., 400., 754., + 564., 138., 219., 869., 669.]) + +linkage_ytdist_single = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 255., 3.], + [1., 8., 268., 4.], + [6., 9., 295., 6.]]) + +linkage_ytdist_complete = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [1., 6., 400., 3.], + [0., 7., 412., 3.], + [8., 9., 996., 6.]]) + +linkage_ytdist_average = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 333.5, 3.], + [1., 6., 347.5, 3.], + [8., 9., 680.77777778, 6.]]) + +linkage_ytdist_weighted = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 333.5, 3.], + [1., 6., 347.5, 3.], + [8., 9., 670.125, 6.]]) + +# the optimal leaf ordering of linkage_ytdist_single +linkage_ytdist_single_olo = array([[5., 2., 138., 2.], + [4., 3., 219., 2.], + [7., 0., 255., 3.], + [1., 8., 268., 4.], + [6., 9., 295., 6.]]) + +X = array([[1.43054825, -7.5693489], + [6.95887839, 6.82293382], + [2.87137846, -9.68248579], + [7.87974764, -6.05485803], + [8.24018364, -6.09495602], + [7.39020262, 8.54004355]]) + +linkage_X_centroid = array([[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 6.43614494, 4.], + [7., 9., 15.17363237, 6.]]) + +linkage_X_median = array([[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 6.43614494, 4.], + [7., 9., 15.17363237, 6.]]) + +linkage_X_ward = array([[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 9.10208346, 4.], + [7., 9., 24.7784379, 6.]]) + +# the optimal leaf ordering of linkage_X_ward +linkage_X_ward_olo = array([[4., 3., 0.36265956, 2.], + [5., 1., 1.77045373, 2.], + [2., 0., 2.55760419, 2.], + [6., 8., 9.10208346, 4.], + [7., 9., 24.7784379, 6.]]) + +inconsistent_ytdist = { + 1: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [255., 0., 1., 0.], + [268., 0., 1., 0.], + [295., 0., 1., 0.]]), + 2: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [237., 25.45584412, 2., 0.70710678], + [261.5, 9.19238816, 2., 0.70710678], + [233.66666667, 83.9424406, 3., 0.7306594]]), + 3: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [237., 25.45584412, 2., 0.70710678], + [247.33333333, 25.38372182, 3., 0.81417007], + [239., 69.36377537, 4., 0.80733783]]), + 4: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [237., 25.45584412, 2., 0.70710678], + [247.33333333, 25.38372182, 3., 0.81417007], + [235., 60.73302232, 5., 0.98793042]])} + +fcluster_inconsistent = { + 0.8: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 1.0: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1])} + +fcluster_distance = { + 0.6: array([4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 3, + 1, 1, 1, 2, 1, 1, 1, 1, 1]), + 1.0: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1])} + +fcluster_maxclust = { + 8.0: array([5, 5, 5, 5, 5, 5, 5, 6, 5, 5, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 4, + 1, 1, 1, 3, 1, 1, 1, 1, 2]), + 4.0: array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 1.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1])} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..c9518ea1af28df04d811f46ff114d5cf58e594d7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py @@ -0,0 +1,202 @@ +import pytest +from pytest import raises as assert_raises +import numpy as np +from scipy.cluster.hierarchy import DisjointSet +import string + + +def generate_random_token(): + k = len(string.ascii_letters) + tokens = list(np.arange(k, dtype=int)) + tokens += list(np.arange(k, dtype=float)) + tokens += list(string.ascii_letters) + tokens += [None for i in range(k)] + tokens = np.array(tokens, dtype=object) + rng = np.random.RandomState(seed=0) + + while 1: + size = rng.randint(1, 3) + element = rng.choice(tokens, size) + if size == 1: + yield element[0] + else: + yield tuple(element) + + +def get_elements(n): + # dict is deterministic without difficulty of comparing numpy ints + elements = {} + for element in generate_random_token(): + if element not in elements: + elements[element] = len(elements) + if len(elements) >= n: + break + return list(elements.keys()) + + +def test_init(): + n = 10 + elements = get_elements(n) + dis = DisjointSet(elements) + assert dis.n_subsets == n + assert list(dis) == elements + + +def test_len(): + n = 10 + elements = get_elements(n) + dis = DisjointSet(elements) + assert len(dis) == n + + dis.add("dummy") + assert len(dis) == n + 1 + + +@pytest.mark.parametrize("n", [10, 100]) +def test_contains(n): + elements = get_elements(n) + dis = DisjointSet(elements) + for x in elements: + assert x in dis + + assert "dummy" not in dis + + +@pytest.mark.parametrize("n", [10, 100]) +def test_add(n): + elements = get_elements(n) + dis1 = DisjointSet(elements) + + dis2 = DisjointSet() + for i, x in enumerate(elements): + dis2.add(x) + assert len(dis2) == i + 1 + + # test idempotency by adding element again + dis2.add(x) + assert len(dis2) == i + 1 + + assert list(dis1) == list(dis2) + + +def test_element_not_present(): + elements = get_elements(n=10) + dis = DisjointSet(elements) + + with assert_raises(KeyError): + dis["dummy"] + + with assert_raises(KeyError): + dis.merge(elements[0], "dummy") + + with assert_raises(KeyError): + dis.connected(elements[0], "dummy") + + +@pytest.mark.parametrize("direction", ["forwards", "backwards"]) +@pytest.mark.parametrize("n", [10, 100]) +def test_linear_union_sequence(n, direction): + elements = get_elements(n) + dis = DisjointSet(elements) + assert elements == list(dis) + + indices = list(range(n - 1)) + if direction == "backwards": + indices = indices[::-1] + + for it, i in enumerate(indices): + assert not dis.connected(elements[i], elements[i + 1]) + assert dis.merge(elements[i], elements[i + 1]) + assert dis.connected(elements[i], elements[i + 1]) + assert dis.n_subsets == n - 1 - it + + roots = [dis[i] for i in elements] + if direction == "forwards": + assert all(elements[0] == r for r in roots) + else: + assert all(elements[-2] == r for r in roots) + assert not dis.merge(elements[0], elements[-1]) + + +@pytest.mark.parametrize("n", [10, 100]) +def test_self_unions(n): + elements = get_elements(n) + dis = DisjointSet(elements) + + for x in elements: + assert dis.connected(x, x) + assert not dis.merge(x, x) + assert dis.connected(x, x) + assert dis.n_subsets == len(elements) + + assert elements == list(dis) + roots = [dis[x] for x in elements] + assert elements == roots + + +@pytest.mark.parametrize("order", ["ab", "ba"]) +@pytest.mark.parametrize("n", [10, 100]) +def test_equal_size_ordering(n, order): + elements = get_elements(n) + dis = DisjointSet(elements) + + rng = np.random.RandomState(seed=0) + indices = np.arange(n) + rng.shuffle(indices) + + for i in range(0, len(indices), 2): + a, b = elements[indices[i]], elements[indices[i + 1]] + if order == "ab": + assert dis.merge(a, b) + else: + assert dis.merge(b, a) + + expected = elements[min(indices[i], indices[i + 1])] + assert dis[a] == expected + assert dis[b] == expected + + +@pytest.mark.parametrize("kmax", [5, 10]) +def test_binary_tree(kmax): + n = 2**kmax + elements = get_elements(n) + dis = DisjointSet(elements) + rng = np.random.RandomState(seed=0) + + for k in 2**np.arange(kmax): + for i in range(0, n, 2 * k): + r1, r2 = rng.randint(0, k, size=2) + a, b = elements[i + r1], elements[i + k + r2] + assert not dis.connected(a, b) + assert dis.merge(a, b) + assert dis.connected(a, b) + + assert elements == list(dis) + roots = [dis[i] for i in elements] + expected_indices = np.arange(n) - np.arange(n) % (2 * k) + expected = [elements[i] for i in expected_indices] + assert roots == expected + + +@pytest.mark.parametrize("n", [10, 100]) +def test_subsets(n): + elements = get_elements(n) + dis = DisjointSet(elements) + + rng = np.random.RandomState(seed=0) + for i, j in rng.randint(0, n, (n, 2)): + x = elements[i] + y = elements[j] + + expected = {element for element in dis if {dis[element]} == {dis[x]}} + assert dis.subset_size(x) == len(dis.subset(x)) + assert expected == dis.subset(x) + + expected = {dis[element]: set() for element in dis} + for element in dis: + expected[dis[element]].add(element) + expected = list(expected.values()) + assert expected == dis.subsets() + + dis.merge(x, y) + assert dis.subset(x) == dis.subset(y) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py new file mode 100644 index 0000000000000000000000000000000000000000..21c1817efdc020e45d647400b98ac85a42c562b2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py @@ -0,0 +1,1237 @@ +# +# Author: Damian Eads +# Date: April 17, 2008 +# +# Copyright (C) 2008 Damian Eads +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import numpy as np +from numpy.testing import assert_allclose, assert_equal, assert_array_equal, assert_ +import pytest +from pytest import raises as assert_raises + +from scipy.cluster.hierarchy import ( + ClusterWarning, linkage, from_mlab_linkage, to_mlab_linkage, + num_obs_linkage, inconsistent, cophenet, fclusterdata, fcluster, + is_isomorphic, single, ward, leaders, + correspond, is_monotonic, maxdists, maxinconsts, maxRstat, + is_valid_linkage, is_valid_im, to_tree, leaves_list, dendrogram, + set_link_color_palette, cut_tree, optimal_leaf_ordering, + _order_cluster_tree, _hierarchy, _EUCLIDEAN_METHODS, _LINKAGE_METHODS) +from scipy.cluster._hierarchy import Heap +from scipy.spatial.distance import pdist +from scipy._lib._array_api import (eager_warns, make_xp_test_case, + xp_assert_close, xp_assert_equal) +import scipy._lib.array_api_extra as xpx + +from threading import Lock + +from . import hierarchy_test_data + +class eager: + # Bypass xpx.testing.lazy_xp_function when calling + # these functions from this namespace + is_valid_im = is_valid_im + is_valid_linkage = is_valid_linkage + + +# Matplotlib is not a scipy dependency but is optionally used in dendrogram, so +# check if it's available +try: + import matplotlib + # and set the backend to be Agg (no gui) + matplotlib.use('Agg') + # before importing pyplot + import matplotlib.pyplot as plt + have_matplotlib = True +except Exception: + have_matplotlib = False + +skip_xp_backends = pytest.mark.skip_xp_backends + + +@make_xp_test_case(linkage) +class TestLinkage: + + @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback") + def test_linkage_non_finite_elements_in_distance_matrix(self, xp): + # Tests linkage(Y) where Y contains a non-finite element (e.g. NaN or Inf). + # Exception expected. + y = xp.asarray([xp.nan] + [0.0]*5) + assert_raises(ValueError, linkage, y) + + def test_linkage_empty_distance_matrix(self, xp): + # Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected. + y = xp.zeros((0,)) + assert_raises(ValueError, linkage, y) + + def test_linkage_tdist(self, xp): + for method in ['single', 'complete', 'average', 'weighted']: + self.check_linkage_tdist(method, xp) + + def check_linkage_tdist(self, method, xp): + # Tests linkage(Y, method) on the tdist data set. + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), method) + expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_' + method) + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10) + + def test_linkage_X(self, xp): + for method in ['centroid', 'median', 'ward']: + self.check_linkage_q(method, xp) + + def check_linkage_q(self, method, xp): + # Tests linkage(Y, method) on the Q data set. + Z = linkage(xp.asarray(hierarchy_test_data.X), method) + expectedZ = getattr(hierarchy_test_data, 'linkage_X_' + method) + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06) + + X = xp.asarray(hierarchy_test_data.X) + y = pdist(X, metric="euclidean") + Z = linkage(y, method) + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06) + + def test_compare_with_trivial(self, xp): + rng = np.random.RandomState(0) + n = 20 + X = rng.rand(n, 2) + d = pdist(X) + + for method, code in _LINKAGE_METHODS.items(): + Z_trivial = _hierarchy.linkage(d, n, code) + Z = linkage(xp.asarray(d), method) + xp_assert_close(Z, xp.asarray(Z_trivial), rtol=1e-14, atol=1e-15) + + def test_optimal_leaf_ordering(self, xp): + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), optimal_ordering=True) + expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_single_olo') + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10) + + @pytest.mark.parametrize("method,expect", [ + ('single', [[0, 1, 1.41421356, 2], + [2, 3, 1.41421356, 3]]), + ('complete', [[0, 1, 1.41421356, 2], + [2, 3, 2.82842712, 3]]), + ('average', [[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + ('weighted', [[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + ('centroid', [[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + ('median', [[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + ('ward', [[0, 1, 1.41421356, 2], + [2, 3, 2.44948974, 3]]), + ]) + def test_linkage_ties(self, method, expect, xp): + X = xp.asarray([[-1, -1], [0, 0], [1, 1]]) + Z = linkage(X, method=method) + expect = xp.asarray(expect, dtype=xp.float64) + xp_assert_close(Z, expect, atol=1e-06) + + def test_unsupported_uncondensed_distance_matrix_linkage_warning(self, xp): + X = xp.asarray([[0, 1], [1, 0]]) + with eager_warns(ClusterWarning, xp=xp): + linkage(X) + + @pytest.mark.parametrize("method", _EUCLIDEAN_METHODS) + def test_euclidean_linkage_value_error(self, method, xp): + X = xp.asarray([[1, 1], [1, 1]]) + with pytest.raises(ValueError): + linkage(X, method=method, metric='cityblock') + + def test_2x2_linkage(self, xp): + Z1 = linkage(xp.asarray([1]), method='single', metric='euclidean') + Z2 = linkage(xp.asarray([[0, 1], [0, 0]]), method='single', metric='euclidean') + xp_assert_close(Z1, Z2, rtol=1e-15) + + @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback") + def test_centroid_neg_distance(self, xp): + # gh-21011 + values = xp.asarray([0, 0, -1]) + with pytest.raises(ValueError): + # This is just checking that this doesn't crash + linkage(values, method='centroid') + + +@make_xp_test_case(inconsistent) +class TestInconsistent: + + def test_inconsistent_tdist(self, xp): + for depth in hierarchy_test_data.inconsistent_ytdist: + self.check_inconsistent_tdist(depth, xp) + + def check_inconsistent_tdist(self, depth, xp): + Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single) + xp_assert_close(inconsistent(Z, depth), + xp.asarray(hierarchy_test_data.inconsistent_ytdist[depth])) + + +@make_xp_test_case(cophenet) +class TestCopheneticDistance: + + def test_linkage_cophenet_tdist_Z(self, xp): + # Tests cophenet(Z) on tdist data set. + expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, + 295, 138, 219, 295, 295]) + Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single) + M = cophenet(Z) + xp_assert_close(M, xp.asarray(expectedM, dtype=xp.float64), atol=1e-10) + + def test_linkage_cophenet_tdist_Z_Y(self, xp): + # Tests cophenet(Z, Y) on tdist data set. + Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single) + (c, M) = cophenet(Z, xp.asarray(hierarchy_test_data.ytdist)) + expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, + 295, 138, 219, 295, 295], dtype=xp.float64) + expectedc = xp.asarray(0.639931296433393415057366837573, dtype=xp.float64)[()] + xp_assert_close(c, expectedc, atol=1e-10) + xp_assert_close(M, expectedM, atol=1e-10) + + @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback") + def test_gh_22183(self, xp): + # check for lack of segfault + # (out of bounds memory access) + # and correct interception of + # invalid linkage matrix + arr=[[0.0, 1.0, 1.0, 2.0], + [2.0, 12.0, 1.0, 3.0], + [3.0, 4.0, 1.0, 2.0], + [5.0, 14.0, 1.0, 3.0], + [6.0, 7.0, 1.0, 2.0], + [8.0, 16.0, 1.0, 3.0], + [9.0, 10.0, 1.0, 2.0], + [11.0, 18.0, 1.0, 3.0], + [13.0, 15.0, 2.0, 6.0], + [17.0, 20.0, 2.0, 32.0], + [19.0, 21.0, 2.0, 12.0]] + with pytest.raises(ValueError, match="excessive observations"): + cophenet(xp.asarray(arr)) + + +@make_xp_test_case(from_mlab_linkage, to_mlab_linkage) +class TestMLabLinkageConversion: + + def test_mlab_linkage_conversion_empty(self, xp): + # Tests from/to_mlab_linkage on empty linkage array. + X = xp.asarray([], dtype=xp.float64) + xp_assert_equal(from_mlab_linkage(X), X) + xp_assert_equal(to_mlab_linkage(X), X) + + def test_mlab_linkage_conversion_single_row(self, xp): + # Tests from/to_mlab_linkage on linkage array with single row. + Z = xp.asarray([[0., 1., 3., 2.]]) + Zm = xp.asarray([[1, 2, 3]]) + xp_assert_close(from_mlab_linkage(Zm), xp.asarray(Z, dtype=xp.float64), + rtol=1e-15) + xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64), + rtol=1e-15) + + def test_mlab_linkage_conversion_multiple_rows(self, xp): + # Tests from/to_mlab_linkage on linkage array with multiple rows. + Zm = xp.asarray([[3, 6, 138], [4, 5, 219], + [1, 8, 255], [2, 9, 268], [7, 10, 295]]) + Z = xp.asarray([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 255., 3.], + [1., 8., 268., 4.], + [6., 9., 295., 6.]], + dtype=xp.float64) + xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15) + xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64), + rtol=1e-15) + + +@make_xp_test_case(fclusterdata) +class TestFclusterData: + + @make_xp_test_case(is_isomorphic) + @pytest.mark.parametrize("criterion,t", + [("inconsistent", t) for t in hierarchy_test_data.fcluster_inconsistent] + + [("distance", t) for t in hierarchy_test_data.fcluster_distance] + + [("maxclust", t) for t in hierarchy_test_data.fcluster_maxclust] + ) + def test_fclusterdata(self, t, criterion, xp): + # Tests fclusterdata(X, criterion=criterion, t=t) on a random 3-cluster data set + expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t]) + X = xp.asarray(hierarchy_test_data.Q_X) + T = fclusterdata(X, criterion=criterion, t=t) + assert is_isomorphic(T, expectedT) + + +@make_xp_test_case(fcluster) +class TestFcluster: + + @make_xp_test_case(single, is_isomorphic) + @pytest.mark.parametrize("criterion,t", + [("inconsistent", t) for t in hierarchy_test_data.fcluster_inconsistent] + + [("distance", t) for t in hierarchy_test_data.fcluster_distance] + + [("maxclust", t) for t in hierarchy_test_data.fcluster_maxclust] + ) + def test_fcluster(self, t, criterion, xp): + # Tests fcluster(Z, criterion=criterion, t=t) on a random 3-cluster data set. + expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t]) + Z = single(xp.asarray(hierarchy_test_data.Q_X)) + T = fcluster(Z, criterion=criterion, t=t) + assert_(is_isomorphic(T, expectedT)) + + @make_xp_test_case(single, is_isomorphic, maxdists) + @pytest.mark.parametrize("t", hierarchy_test_data.fcluster_distance) + def test_fcluster_monocrit(self, t, xp): + expectedT = xp.asarray(hierarchy_test_data.fcluster_distance[t]) + Z = single(xp.asarray(hierarchy_test_data.Q_X)) + T = fcluster(Z, t, criterion='monocrit', monocrit=maxdists(Z)) + assert_(is_isomorphic(T, expectedT)) + + @make_xp_test_case(single, is_isomorphic, maxdists) + @pytest.mark.parametrize("t", hierarchy_test_data.fcluster_maxclust) + def test_fcluster_maxclust_monocrit(self, t, xp): + expectedT = xp.asarray(hierarchy_test_data.fcluster_maxclust[t]) + Z = single(xp.asarray(hierarchy_test_data.Q_X)) + T = fcluster(Z, t, criterion='maxclust_monocrit', monocrit=maxdists(Z)) + assert_(is_isomorphic(T, expectedT)) + + @make_xp_test_case(single) + def test_fcluster_maxclust_gh_12651(self, xp): + y = xp.asarray([[1], [4], [5]]) + Z = single(y) + assert_array_equal(fcluster(Z, t=1, criterion="maxclust"), + xp.asarray([1, 1, 1])) + assert_array_equal(fcluster(Z, t=2, criterion="maxclust"), + xp.asarray([2, 1, 1])) + assert_array_equal(fcluster(Z, t=3, criterion="maxclust"), + xp.asarray([1, 2, 3])) + assert_array_equal(fcluster(Z, t=5, criterion="maxclust"), + xp.asarray([1, 2, 3])) + + +@make_xp_test_case(leaders) +class TestLeaders: + + def test_leaders_single(self, xp): + # Tests leaders using a flat clustering generated by single linkage. + X = hierarchy_test_data.Q_X + Y = pdist(X) + Z = linkage(Y) + T = fcluster(Z, criterion='maxclust', t=3) + Z = xp.asarray(Z) + T = xp.asarray(T, dtype=xp.int32) + L = leaders(Z, T) + expect = xp.asarray([53, 55, 56, 2, 3, 1], dtype=xp.int32) + xp_assert_close(xp.concat(L), expect, rtol=1e-15) + + +@make_xp_test_case(is_isomorphic) +class TestIsIsomorphic: + + def test_array_like(self): + assert is_isomorphic([1, 1, 1], [2, 2, 2]) + assert is_isomorphic([], []) + + def test_is_isomorphic_1(self, xp): + # Tests is_isomorphic on test case #1 (one flat cluster, different labellings) + a = xp.asarray([1, 1, 1]) + b = xp.asarray([2, 2, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + def test_is_isomorphic_2(self, xp): + # Tests is_isomorphic on test case #2 (two flat clusters, different labelings) + a = xp.asarray([1, 7, 1]) + b = xp.asarray([2, 3, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + def test_is_isomorphic_3(self, xp): + # Tests is_isomorphic on test case #3 (no flat clusters) + a = xp.asarray([]) + b = xp.asarray([]) + assert is_isomorphic(a, b) + + def test_is_isomorphic_4A(self, xp): + # Tests is_isomorphic on test case #4A + # (3 flat clusters, different labelings, isomorphic) + a = xp.asarray([1, 2, 3]) + b = xp.asarray([1, 3, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + def test_is_isomorphic_4B(self, xp): + # Tests is_isomorphic on test case #4B + # (3 flat clusters, different labelings, nonisomorphic) + a = xp.asarray([1, 2, 3, 3]) + b = xp.asarray([1, 3, 2, 3]) + assert not is_isomorphic(a, b) + assert not is_isomorphic(b, a) + + def test_is_isomorphic_4C(self, xp): + # Tests is_isomorphic on test case #4C + # (3 flat clusters, different labelings, isomorphic) + a = xp.asarray([7, 2, 3]) + b = xp.asarray([6, 3, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + @pytest.mark.parametrize("nclusters", [2, 3, 5]) + def test_is_isomorphic_5(self, nclusters, xp): + # Tests is_isomorphic on test case #5 (1000 observations, 2/3/5 random + # clusters, random permutation of the labeling). + self.is_isomorphic_randperm(1000, nclusters, xp=xp) + + @pytest.mark.parametrize("nclusters", [2, 3, 5]) + def test_is_isomorphic_6(self, nclusters, xp): + # Tests is_isomorphic on test case #5A (1000 observations, 2/3/5 random + # clusters, random permutation of the labeling, slightly + # nonisomorphic.) + self.is_isomorphic_randperm(1000, nclusters, True, 5, xp=xp) + + def test_is_isomorphic_7(self, xp): + # Regression test for gh-6271 + a = xp.asarray([1, 2, 3]) + b = xp.asarray([1, 1, 1]) + assert not is_isomorphic(a, b) + + def is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0, *, xp): + rng = np.random.default_rng() + for _ in range(3): + a = rng.integers(0, nclusters, size=nobs) + p = rng.permutation(nclusters) + b = p.take(a.astype(np.intp)) + if noniso: + q = rng.permutation(nobs) + b[q[0:nerrors]] += 1 + b[q[0:nerrors]] %= nclusters + a = xp.asarray(a) + b = xp.asarray(b) + assert is_isomorphic(a, b) == (not noniso) + assert is_isomorphic(b, a) == (not noniso) + + +@make_xp_test_case(is_valid_linkage) +class TestIsValidLinkage: + + @pytest.mark.parametrize("nrow, ncol, valid", [(2, 5, False), (2, 3, False), + (1, 4, True), (2, 4, True)]) + def test_is_valid_linkage_various_size(self, nrow, ncol, valid, xp): + # Tests is_valid_linkage(Z) with linkage matrices of various sizes + Z = xp.asarray([[0, 1, 3.0, 2, 5], + [3, 2, 4.0, 3, 3]], dtype=xp.float64) + Z = Z[:nrow, :ncol] + xp_assert_equal(is_valid_linkage(Z), valid, check_namespace=False) + if not valid: + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_int_type(self, xp): + # Tests is_valid_linkage(Z) with integer type. + Z = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.int64) + xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False) + assert_raises(TypeError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_empty(self, xp): + # Tests is_valid_linkage(Z) with empty linkage. + Z = xp.zeros((0, 4), dtype=xp.float64) + xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False) + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_4_and_up(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + y = xp.asarray(y) + xp_assert_equal(is_valid_linkage(Z), True, check_namespace=False) + + def test_is_valid_linkage_4_and_up_neg_index_left(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative indices (left). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + y = xp.asarray(y) + Z = xpx.at(Z)[i//2, 0].set(-2) + xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False) + with pytest.raises(ValueError): + eager.is_valid_linkage(Z, throw=True) + + def test_is_valid_linkage_4_and_up_neg_index_right(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative indices (right). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + y = xp.asarray(y) + Z = xpx.at(Z)[i//2, 1].set(-2) + xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False) + with pytest.raises(ValueError): + eager.is_valid_linkage(Z, throw=True) + + def test_is_valid_linkage_4_and_up_neg_dist(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative distances. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + y = xp.asarray(y) + Z = xpx.at(Z)[i//2, 2].set(-0.5) + xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False) + with pytest.raises(ValueError): + eager.is_valid_linkage(Z, throw=True) + + def test_is_valid_linkage_4_and_up_neg_counts(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative counts. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + y = xp.asarray(y) + Z = xpx.at(Z)[i//2, 3].set(-2) + xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False) + with pytest.raises(ValueError): + eager.is_valid_linkage(Z, throw=True) + + +@make_xp_test_case(is_valid_im) +class TestIsValidInconsistent: + + def test_is_valid_im_int_type(self, xp): + # Tests is_valid_im(R) with integer type. + R = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.int64) + xp_assert_equal(is_valid_im(R), False, check_namespace=False) + assert_raises(TypeError, is_valid_im, R, throw=True) + + @pytest.mark.parametrize("nrow, ncol, valid", [(2, 5, False), (2, 3, False), + (1, 4, True), (2, 4, True)]) + def test_is_valid_im_various_size(self, nrow, ncol, valid, xp): + # Tests is_valid_im(R) with linkage matrices of various sizes + R = xp.asarray([[0, 1, 3.0, 2, 5], + [3, 2, 4.0, 3, 3]], dtype=xp.float64) + R = R[:nrow, :ncol] + xp_assert_equal(is_valid_im(R), valid, check_namespace=False) + if not valid: + assert_raises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_empty(self, xp): + # Tests is_valid_im(R) with empty inconsistency matrix. + R = xp.zeros((0, 4), dtype=xp.float64) + xp_assert_equal(is_valid_im(R), False, check_namespace=False) + assert_raises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_4_and_up(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = linkage(y) + R = inconsistent(Z) + R = xp.asarray(R) + xp_assert_equal(is_valid_im(R), True, check_namespace=False) + + def test_is_valid_im_4_and_up_neg_index_left(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3) with negative link height means. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = linkage(y) + R = inconsistent(Z) + R = xpx.at(R)[i//2 , 0].set(-2.0) + R = xp.asarray(R) + xp_assert_equal(is_valid_im(R), False, check_namespace=False) + with pytest.raises(ValueError): + eager.is_valid_im(R, throw=True) + + def test_is_valid_im_4_and_up_neg_index_right(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3) with negative link height standard deviations. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = linkage(y) + R = inconsistent(Z) + R = xpx.at(R)[i//2 , 1].set(-2.0) + R = xp.asarray(R) + xp_assert_equal(is_valid_im(R), False, check_namespace=False) + with pytest.raises(ValueError): + eager.is_valid_im(R, throw=True) + + def test_is_valid_im_4_and_up_neg_dist(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3) with negative link counts. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = linkage(y) + R = inconsistent(Z) + R = xpx.at(R)[i//2, 2].set(-0.5) + R = xp.asarray(R) + xp_assert_equal(is_valid_im(R), False, check_namespace=False) + with pytest.raises(ValueError): + eager.is_valid_im(R, throw=True) + + +class TestNumObsLinkage: + + def test_num_obs_linkage_empty(self, xp): + # Tests num_obs_linkage(Z) with empty linkage. + Z = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, num_obs_linkage, Z) + + def test_num_obs_linkage_1x4(self, xp): + # Tests num_obs_linkage(Z) on linkage over 2 observations. + Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64) + assert num_obs_linkage(Z) == 2 + + def test_num_obs_linkage_2x4(self, xp): + # Tests num_obs_linkage(Z) on linkage over 3 observations. + Z = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.float64) + assert num_obs_linkage(Z) == 3 + + def test_num_obs_linkage_4_and_up(self, xp): + # Tests num_obs_linkage(Z) on linkage on observation sets between sizes + # 4 and 15 (step size 3). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + assert num_obs_linkage(Z) == i + + def test_num_obs_linkage_multi_matrix(self, xp): + # Tests num_obs_linkage with observation matrices of multiple sizes. + for n in range(2, 10): + X = np.random.rand(n, 4) + Y = pdist(X) + Z = xp.asarray(linkage(Y)) + assert num_obs_linkage(Z) == n + + +@make_xp_test_case(leaves_list, to_tree) +class TestLeavesList: + + def test_leaves_list_1x4(self, xp): + # Tests leaves_list(Z) on a 1x4 linkage. + Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64) + to_tree(Z) + assert_allclose(leaves_list(Z), [0, 1], rtol=1e-15) + + def test_leaves_list_2x4(self, xp): + # Tests leaves_list(Z) on a 2x4 linkage. + Z = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.float64) + to_tree(Z) + assert_allclose(leaves_list(Z), [0, 1, 2], rtol=1e-15) + + @pytest.mark.parametrize("method", + ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward']) + def test_leaves_list_Q(self, method, xp): + # Tests leaves_list(Z) on the Q data set + X = hierarchy_test_data.Q_X + Z = xp.asarray(linkage(X, method)) + node = to_tree(Z) + assert_allclose(node.pre_order(), leaves_list(Z), rtol=1e-15) + + def test_Q_subtree_pre_order(self, xp): + # Tests that pre_order() works when called on sub-trees. + X = hierarchy_test_data.Q_X + Z = xp.asarray(linkage(X, 'single')) + node = to_tree(Z) + assert_allclose(node.pre_order(), + (node.get_left().pre_order() + node.get_right().pre_order()), + rtol=1e-15) + + +@make_xp_test_case(correspond) +class TestCorrespond: + + def test_correspond_empty(self, xp): + # Tests correspond(Z, y) with empty linkage and condensed distance matrix. + y = xp.zeros((0,), dtype=xp.float64) + Z = xp.zeros((0,4), dtype=xp.float64) + assert_raises(ValueError, correspond, Z, y) + + def test_correspond_2_and_up(self, xp): + # Tests correspond(Z, y) on linkage and CDMs over observation sets of + # different sizes. + for i in range(2, 4): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + y = xp.asarray(y) + assert_(correspond(Z, y)) + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + Z = xp.asarray(linkage(y)) + y = xp.asarray(y) + assert_(correspond(Z, y)) + + def test_correspond_4_and_up(self, xp): + # Tests correspond(Z, y) on linkage and CDMs over observation sets of + # different sizes. Correspondence should be false. + for (i, j) in (list(zip(list(range(2, 4)), list(range(3, 5)))) + + list(zip(list(range(3, 5)), list(range(2, 4))))): + y = np.random.rand(i*(i-1)//2) + y2 = np.random.rand(j*(j-1)//2) + Z = xp.asarray(linkage(y)) + Z2 = xp.asarray(linkage(y2)) + y = xp.asarray(y) + y2 = xp.asarray(y2) + assert not correspond(Z, y2) + assert not correspond(Z2, y) + + def test_correspond_4_and_up_2(self, xp): + # Tests correspond(Z, y) on linkage and CDMs over observation sets of + # different sizes. Correspondence should be false. + for (i, j) in (list(zip(list(range(2, 7)), list(range(16, 21)))) + + list(zip(list(range(2, 7)), list(range(16, 21))))): + y = np.random.rand(i*(i-1)//2) + y2 = np.random.rand(j*(j-1)//2) + Z = xp.asarray(linkage(y)) + Z2 = xp.asarray(linkage(y2)) + y = xp.asarray(y) + y2 = xp.asarray(y2) + assert not correspond(Z, y2) + assert not correspond(Z2, y) + + +@make_xp_test_case(is_monotonic) +class TestIsMonotonic: + + def test_is_monotonic_empty(self, xp): + # Tests is_monotonic(Z) on an empty linkage. + Z = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, is_monotonic, Z) + + def test_is_monotonic_1x4(self, xp): + # Tests is_monotonic(Z) on 1x4 linkage. Expecting True. + Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64) + assert is_monotonic(Z) + + def test_is_monotonic_2x4_T(self, xp): + # Tests is_monotonic(Z) on 2x4 linkage. Expecting True. + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 3]], dtype=xp.float64) + assert is_monotonic(Z) + + def test_is_monotonic_2x4_F(self, xp): + # Tests is_monotonic(Z) on 2x4 linkage. Expecting False. + Z = xp.asarray([[0, 1, 0.4, 2], + [2, 3, 0.3, 3]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_3x4_T(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage. Expecting True. + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 2], + [4, 5, 0.6, 4]], dtype=xp.float64) + assert is_monotonic(Z) + + def test_is_monotonic_3x4_F1(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False. + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.2, 2], + [4, 5, 0.6, 4]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_3x4_F2(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False. + Z = xp.asarray([[0, 1, 0.8, 2], + [2, 3, 0.4, 2], + [4, 5, 0.6, 4]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_3x4_F3(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 2], + [4, 5, 0.2, 4]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_tdist_linkage1(self, xp): + # Tests is_monotonic(Z) on clustering generated by single linkage on + # tdist data set. Expecting True. + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + assert is_monotonic(Z) + + def test_is_monotonic_tdist_linkage2(self, xp): + # Tests is_monotonic(Z) on clustering generated by single linkage on + # tdist data set. Perturbing. Expecting False. + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + Z = xpx.at(Z)[2, 2].set(0.0) + assert not is_monotonic(Z) + + def test_is_monotonic_Q_linkage(self, xp): + # Tests is_monotonic(Z) on clustering generated by single linkage on + # Q data set. Expecting True. + X = hierarchy_test_data.Q_X + Z = xp.asarray(linkage(X, 'single')) + assert is_monotonic(Z) + + +@make_xp_test_case(maxdists) +class TestMaxDists: + + def test_maxdists_empty_linkage(self, xp): + # Tests maxdists(Z) on empty linkage. Expecting exception. + Z = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, maxdists, Z) + + def test_maxdists_one_cluster_linkage(self, xp): + # Tests maxdists(Z) on linkage with one cluster. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + MD = maxdists(Z) + expectedMD = calculate_maximum_distances(Z, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + @pytest.mark.parametrize( + "method", ['single', 'complete', 'ward', 'centroid', 'median']) + def test_maxdists_Q_linkage(self, method, xp): + # Tests maxdists(Z) on the Q data set + X = hierarchy_test_data.Q_X + Z = xp.asarray(linkage(X, method)) + MD = maxdists(Z) + expectedMD = calculate_maximum_distances(Z, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + +@make_xp_test_case(maxinconsts) +class TestMaxInconsts: + + def test_maxinconsts_empty_linkage(self, xp): + # Tests maxinconsts(Z, R) on empty linkage. Expecting exception. + Z = xp.zeros((0, 4), dtype=xp.float64) + R = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, maxinconsts, Z, R) + + def test_maxinconsts_difrow_linkage(self, xp): + # Tests maxinconsts(Z, R) on linkage and inconsistency matrices with + # different numbers of clusters. Expecting exception. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = np.random.rand(2, 4) + R = xp.asarray(R) + assert_raises(ValueError, maxinconsts, Z, R) + + def test_maxinconsts_one_cluster_linkage(self, xp): + # Tests maxinconsts(Z, R) on linkage with one cluster. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64) + MD = maxinconsts(Z, R) + expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + @pytest.mark.parametrize( + "method", ['single', 'complete', 'ward', 'centroid', 'median']) + def test_maxinconsts_Q_linkage(self, method, xp): + # Tests maxinconsts(Z, R) on the Q data set + X = hierarchy_test_data.Q_X + Z = linkage(X, method) + R = xp.asarray(inconsistent(Z)) + Z = xp.asarray(Z) + MD = maxinconsts(Z, R) + expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + +@make_xp_test_case(maxRstat) +class TestMaxRStat: + + def test_maxRstat_invalid_index(self, xp): + # Tests maxRstat(Z, R, i). Expecting exception. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64) + with pytest.raises(TypeError): + maxRstat(Z, R, 3.3) + with pytest.raises(ValueError): + maxRstat(Z, R, -1) + with pytest.raises(ValueError): + maxRstat(Z, R, 4) + + @pytest.mark.parametrize("i", range(4)) + def test_maxRstat_empty_linkage(self, i, xp): + # Tests maxRstat(Z, R, i) on empty linkage. Expecting exception. + Z = xp.zeros((0, 4), dtype=xp.float64) + R = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, maxRstat, Z, R, i) + + @pytest.mark.parametrize("i", range(4)) + def test_maxRstat_difrow_linkage(self, i, xp): + # Tests maxRstat(Z, R, i) on linkage and inconsistency matrices with + # different numbers of clusters. Expecting exception. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = np.random.rand(2, 4) + R = xp.asarray(R) + assert_raises(ValueError, maxRstat, Z, R, i) + + def test_maxRstat_one_cluster_linkage(self, xp): + # Tests maxRstat(Z, R, i) on linkage with one cluster. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64) + MD = maxRstat(Z, R, 1) + expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + @pytest.mark.parametrize( + "method", ['single', 'complete', 'ward', 'centroid', 'median']) + def test_maxRstat_Q_linkage(self, method, xp): + # Tests maxRstat(Z, R, 1) on the Q data set + X = hierarchy_test_data.Q_X + Z = linkage(X, method) + R = xp.asarray(inconsistent(Z)) + Z = xp.asarray(Z) + MD = maxRstat(Z, R, 1) + expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + +@make_xp_test_case(dendrogram) +class TestDendrogram: + + def test_dendrogram_single_linkage_tdist(self, xp): + # Tests dendrogram calculation on single linkage of the tdist data set. + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + R = dendrogram(Z, no_plot=True) + leaves = R["leaves"] + assert_equal(leaves, [2, 5, 1, 0, 3, 4]) + + def test_valid_orientation(self, xp): + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + assert_raises(ValueError, dendrogram, Z, orientation="foo") + + def test_labels_as_array_or_list(self, xp): + # test for gh-12418 + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + labels = [1, 3, 2, 6, 4, 5] + result1 = dendrogram(Z, labels=xp.asarray(labels), no_plot=True) + result2 = dendrogram(Z, labels=labels, no_plot=True) + assert result1 == result2 + + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_valid_label_size(self, xp): + link = xp.asarray([ + [0, 1, 1.0, 4], + [2, 3, 1.0, 5], + [4, 5, 2.0, 6], + ]) + plt.figure() + with pytest.raises(ValueError) as exc_info: + dendrogram(link, labels=list(range(100))) + assert "Dimensions of Z and labels must be consistent."\ + in str(exc_info.value) + + with pytest.raises( + ValueError, + match="Dimensions of Z and labels must be consistent."): + dendrogram(link, labels=[]) + + plt.close() + + @skip_xp_backends('torch', + reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__' + ' and NumPy 2.0' + ) + @skip_xp_backends('dask.array', + reason='dask.array has bad interaction with matplotlib' + ) + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + @pytest.mark.parametrize("orientation", ['top', 'bottom', 'left', 'right']) + def test_dendrogram_plot(self, orientation, xp): + # Tests dendrogram plotting. + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + expected = {'color_list': ['C1', 'C0', 'C0', 'C0', 'C0'], + 'dcoord': [[0.0, 138.0, 138.0, 0.0], + [0.0, 219.0, 219.0, 0.0], + [0.0, 255.0, 255.0, 219.0], + [0.0, 268.0, 268.0, 255.0], + [138.0, 295.0, 295.0, 268.0]], + 'icoord': [[5.0, 5.0, 15.0, 15.0], + [45.0, 45.0, 55.0, 55.0], + [35.0, 35.0, 50.0, 50.0], + [25.0, 25.0, 42.5, 42.5], + [10.0, 10.0, 33.75, 33.75]], + 'ivl': ['2', '5', '1', '0', '3', '4'], + 'leaves': [2, 5, 1, 0, 3, 4], + 'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0', 'C0'], + } + + fig = plt.figure() + ax = fig.add_subplot(221) + + # test that dendrogram accepts ax keyword + R1 = dendrogram(Z, ax=ax, orientation=orientation) + R1['dcoord'] = np.asarray(R1['dcoord']) + assert_equal(R1, expected) + + # test that dendrogram accepts and handle the leaf_font_size and + # leaf_rotation keywords + dendrogram(Z, ax=ax, orientation=orientation, + leaf_font_size=20, leaf_rotation=90) + testlabel = ( + ax.get_xticklabels()[0] + if orientation in ['top', 'bottom'] + else ax.get_yticklabels()[0] + ) + assert_equal(testlabel.get_rotation(), 90) + assert_equal(testlabel.get_size(), 20) + dendrogram(Z, ax=ax, orientation=orientation, + leaf_rotation=90) + testlabel = ( + ax.get_xticklabels()[0] + if orientation in ['top', 'bottom'] + else ax.get_yticklabels()[0] + ) + assert_equal(testlabel.get_rotation(), 90) + dendrogram(Z, ax=ax, orientation=orientation, + leaf_font_size=20) + testlabel = ( + ax.get_xticklabels()[0] + if orientation in ['top', 'bottom'] + else ax.get_yticklabels()[0] + ) + assert_equal(testlabel.get_size(), 20) + plt.close() + + # test plotting to gca (will import pylab) + R2 = dendrogram(Z, orientation=orientation) + plt.close() + R2['dcoord'] = np.asarray(R2['dcoord']) + assert_equal(R2, expected) + + @skip_xp_backends('torch', + reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__' + ' and NumPy 2.0' + ) + @skip_xp_backends('dask.array', + reason='dask.array has bad interaction with matplotlib' + ) + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_dendrogram_truncate_mode(self, xp): + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + + R = dendrogram(Z, 2, 'lastp', show_contracted=True) + plt.close() + R['dcoord'] = np.asarray(R['dcoord']) + assert_equal(R, {'color_list': ['C0'], + 'dcoord': [[0.0, 295.0, 295.0, 0.0]], + 'icoord': [[5.0, 5.0, 15.0, 15.0]], + 'ivl': ['(2)', '(4)'], + 'leaves': [6, 9], + 'leaves_color_list': ['C0', 'C0'], + }) + + R = dendrogram(Z, 2, 'mtica', show_contracted=True) + plt.close() + R['dcoord'] = np.asarray(R['dcoord']) + assert_equal(R, {'color_list': ['C1', 'C0', 'C0', 'C0'], + 'dcoord': [[0.0, 138.0, 138.0, 0.0], + [0.0, 255.0, 255.0, 0.0], + [0.0, 268.0, 268.0, 255.0], + [138.0, 295.0, 295.0, 268.0]], + 'icoord': [[5.0, 5.0, 15.0, 15.0], + [35.0, 35.0, 45.0, 45.0], + [25.0, 25.0, 40.0, 40.0], + [10.0, 10.0, 32.5, 32.5]], + 'ivl': ['2', '5', '1', '0', '(2)'], + 'leaves': [2, 5, 1, 0, 7], + 'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0'], + }) + + @pytest.fixture + def dendrogram_lock(self): + return Lock() + + def test_dendrogram_colors(self, xp, dendrogram_lock): + # Tests dendrogram plots with alternate colors + Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single')) + + with dendrogram_lock: + # Global color palette might be changed concurrently + set_link_color_palette(['c', 'm', 'y', 'k']) + R = dendrogram(Z, no_plot=True, + above_threshold_color='g', color_threshold=250) + set_link_color_palette(['g', 'r', 'c', 'm', 'y', 'k']) + + color_list = R['color_list'] + assert_equal(color_list, ['c', 'm', 'g', 'g', 'g']) + + # reset color palette (global list) + set_link_color_palette(None) + + def test_dendrogram_leaf_colors_zero_dist(self, xp): + # tests that the colors of leafs are correct for tree + # with two identical points + X = np.asarray([[1, 0, 0], + [0, 0, 1], + [0, 2, 0], + [0, 0, 1], + [0, 1, 0], + [0, 1, 0]]) + Z = xp.asarray(linkage(X, "single")) + d = dendrogram(Z, no_plot=True) + exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2'] + colors = d["leaves_color_list"] + assert_equal(colors, exp_colors) + + def test_dendrogram_leaf_colors(self, xp): + # tests that the colors are correct for a tree + # with two near points ((0, 0, 1.1) and (0, 0, 1)) + X = np.asarray([[1, 0, 0], + [0, 0, 1.1], + [0, 2, 0], + [0, 0, 1], + [0, 1, 0], + [0, 1, 0]]) + Z = xp.asarray(linkage(X, "single")) + d = dendrogram(Z, no_plot=True) + exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2'] + colors = d["leaves_color_list"] + assert_equal(colors, exp_colors) + + +def calculate_maximum_distances(Z, xp): + # Used for testing correctness of maxdists. + n = Z.shape[0] + 1 + B = xp.zeros((n-1,), dtype=Z.dtype) + for i in range(0, n - 1): + q = xp.zeros((3,)) + left = Z[i, 0] + right = Z[i, 1] + if left >= n: + b_left = B[xp.asarray(left, dtype=xp.int64) - n] + q = xpx.at(q, 0).set(b_left) + if right >= n: + b_right = B[xp.asarray(right, dtype=xp.int64) - n] + q = xpx.at(q, 1).set(b_right) + q = xpx.at(q, 2).set(Z[i, 2]) + B = xpx.at(B, i).set(xp.max(q)) + return B + + +def calculate_maximum_inconsistencies(Z, R, k=3, xp=np): + # Used for testing correctness of maxinconsts. + n = Z.shape[0] + 1 + dtype = xp.result_type(Z, R) + B = xp.zeros((n-1,), dtype=dtype) + for i in range(0, n - 1): + q = xp.zeros((3,)) + left = Z[i, 0] + right = Z[i, 1] + if left >= n: + b_left = B[xp.asarray(left, dtype=xp.int64) - n] + q = xpx.at(q, 0).set(b_left) + if right >= n: + b_right = B[xp.asarray(right, dtype=xp.int64) - n] + q = xpx.at(q, 1).set(b_right) + q = xpx.at(q, 2).set(R[i, k]) + B = xpx.at(B, i).set(xp.max(q)) + return B + + +@make_xp_test_case(to_tree) +def test_node_compare(xp): + np.random.seed(23) + nobs = 50 + X = np.random.randn(nobs, 4) + Z = xp.asarray(ward(X)) + tree = to_tree(Z) + assert_(tree > tree.get_left()) + assert_(tree.get_right() > tree.get_left()) + assert_(tree.get_right() == tree.get_right()) + assert_(tree.get_right() != tree.get_left()) + + +@make_xp_test_case(cut_tree) +def test_cut_tree(xp): + np.random.seed(23) + nobs = 50 + X = np.random.randn(nobs, 4) + Z = xp.asarray(ward(X)) + cutree = cut_tree(Z) + + # cutree.dtype varies between int32 and int64 over platforms + xp_assert_close(cutree[:, 0], xp.arange(nobs), rtol=1e-15, check_dtype=False) + xp_assert_close(cutree[:, -1], xp.zeros(nobs), rtol=1e-15, check_dtype=False) + assert_equal(np.asarray(cutree).max(0), np.arange(nobs - 1, -1, -1)) + + xp_assert_close(cutree[:, [-5]], cut_tree(Z, n_clusters=5), rtol=1e-15) + xp_assert_close(cutree[:, [-5, -10]], cut_tree(Z, n_clusters=[5, 10]), rtol=1e-15) + xp_assert_close(cutree[:, [-10, -5]], cut_tree(Z, n_clusters=[10, 5]), rtol=1e-15) + + nodes = _order_cluster_tree(Z) + heights = xp.asarray([node.dist for node in nodes]) + + xp_assert_close(cutree[:, np.searchsorted(heights, [5])], + cut_tree(Z, height=5), rtol=1e-15) + xp_assert_close(cutree[:, np.searchsorted(heights, [5, 10])], + cut_tree(Z, height=[5, 10]), rtol=1e-15) + xp_assert_close(cutree[:, np.searchsorted(heights, [10, 5])], + cut_tree(Z, height=[10, 5]), rtol=1e-15) + + +@make_xp_test_case(optimal_leaf_ordering) +def test_optimal_leaf_ordering(xp): + # test with the distance vector y + Z = optimal_leaf_ordering(xp.asarray(linkage(hierarchy_test_data.ytdist)), + xp.asarray(hierarchy_test_data.ytdist)) + expectedZ = hierarchy_test_data.linkage_ytdist_single_olo + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10) + + # test with the observation matrix X + Z = optimal_leaf_ordering(xp.asarray(linkage(hierarchy_test_data.X, 'ward')), + xp.asarray(hierarchy_test_data.X)) + expectedZ = hierarchy_test_data.linkage_X_ward_olo + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06) + + +@skip_xp_backends(np_only=True, reason='`Heap` only supports NumPy backend') +def test_Heap(xp): + values = xp.asarray([2, -1, 0, -1.5, 3]) + heap = Heap(values) + + pair = heap.get_min() + assert_equal(pair['key'], 3) + assert_equal(pair['value'], -1.5) + + heap.remove_min() + pair = heap.get_min() + assert_equal(pair['key'], 1) + assert_equal(pair['value'], -1) + + heap.change_value(1, 2.5) + pair = heap.get_min() + assert_equal(pair['key'], 2) + assert_equal(pair['value'], 0) + + heap.remove_min() + heap.remove_min() + + heap.change_value(1, 10) + pair = heap.get_min() + assert_equal(pair['key'], 4) + assert_equal(pair['value'], 3) + + heap.remove_min() + pair = heap.get_min() + assert_equal(pair['key'], 1) + assert_equal(pair['value'], 10) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_vq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_vq.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1a1c81e49a3e16305e2d4402f3d539d6507b08 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/cluster/tests/test_vq.py @@ -0,0 +1,437 @@ +import math +import sys +import warnings +from copy import deepcopy +from threading import Lock + +import numpy as np +from numpy.testing import assert_array_equal +import pytest +from pytest import raises as assert_raises + +from scipy.cluster.vq import (kmeans, kmeans2, py_vq, vq, whiten, + ClusterError, _krandinit) +from scipy.cluster import _vq +from scipy.sparse._sputils import matrix + +from scipy._lib import array_api_extra as xpx +from scipy._lib._array_api import ( + SCIPY_ARRAY_API, eager_warns, is_lazy_array, make_xp_test_case, + xp_copy, xp_assert_close, xp_assert_equal +) + +xfail_xp_backends = pytest.mark.xfail_xp_backends +skip_xp_backends = pytest.mark.skip_xp_backends + +TESTDATA_2D = np.array([ + -2.2, 1.17, -1.63, 1.69, -2.04, 4.38, -3.09, 0.95, -1.7, 4.79, -1.68, 0.68, + -2.26, 3.34, -2.29, 2.55, -1.72, -0.72, -1.99, 2.34, -2.75, 3.43, -2.45, + 2.41, -4.26, 3.65, -1.57, 1.87, -1.96, 4.03, -3.01, 3.86, -2.53, 1.28, + -4.0, 3.95, -1.62, 1.25, -3.42, 3.17, -1.17, 0.12, -3.03, -0.27, -2.07, + -0.55, -1.17, 1.34, -2.82, 3.08, -2.44, 0.24, -1.71, 2.48, -5.23, 4.29, + -2.08, 3.69, -1.89, 3.62, -2.09, 0.26, -0.92, 1.07, -2.25, 0.88, -2.25, + 2.02, -4.31, 3.86, -2.03, 3.42, -2.76, 0.3, -2.48, -0.29, -3.42, 3.21, + -2.3, 1.73, -2.84, 0.69, -1.81, 2.48, -5.24, 4.52, -2.8, 1.31, -1.67, + -2.34, -1.18, 2.17, -2.17, 2.82, -1.85, 2.25, -2.45, 1.86, -6.79, 3.94, + -2.33, 1.89, -1.55, 2.08, -1.36, 0.93, -2.51, 2.74, -2.39, 3.92, -3.33, + 2.99, -2.06, -0.9, -2.83, 3.35, -2.59, 3.05, -2.36, 1.85, -1.69, 1.8, + -1.39, 0.66, -2.06, 0.38, -1.47, 0.44, -4.68, 3.77, -5.58, 3.44, -2.29, + 2.24, -1.04, -0.38, -1.85, 4.23, -2.88, 0.73, -2.59, 1.39, -1.34, 1.75, + -1.95, 1.3, -2.45, 3.09, -1.99, 3.41, -5.55, 5.21, -1.73, 2.52, -2.17, + 0.85, -2.06, 0.49, -2.54, 2.07, -2.03, 1.3, -3.23, 3.09, -1.55, 1.44, + -0.81, 1.1, -2.99, 2.92, -1.59, 2.18, -2.45, -0.73, -3.12, -1.3, -2.83, + 0.2, -2.77, 3.24, -1.98, 1.6, -4.59, 3.39, -4.85, 3.75, -2.25, 1.71, -3.28, + 3.38, -1.74, 0.88, -2.41, 1.92, -2.24, 1.19, -2.48, 1.06, -1.68, -0.62, + -1.3, 0.39, -1.78, 2.35, -3.54, 2.44, -1.32, 0.66, -2.38, 2.76, -2.35, + 3.95, -1.86, 4.32, -2.01, -1.23, -1.79, 2.76, -2.13, -0.13, -5.25, 3.84, + -2.24, 1.59, -4.85, 2.96, -2.41, 0.01, -0.43, 0.13, -3.92, 2.91, -1.75, + -0.53, -1.69, 1.69, -1.09, 0.15, -2.11, 2.17, -1.53, 1.22, -2.1, -0.86, + -2.56, 2.28, -3.02, 3.33, -1.12, 3.86, -2.18, -1.19, -3.03, 0.79, -0.83, + 0.97, -3.19, 1.45, -1.34, 1.28, -2.52, 4.22, -4.53, 3.22, -1.97, 1.75, + -2.36, 3.19, -0.83, 1.53, -1.59, 1.86, -2.17, 2.3, -1.63, 2.71, -2.03, + 3.75, -2.57, -0.6, -1.47, 1.33, -1.95, 0.7, -1.65, 1.27, -1.42, 1.09, -3.0, + 3.87, -2.51, 3.06, -2.6, 0.74, -1.08, -0.03, -2.44, 1.31, -2.65, 2.99, + -1.84, 1.65, -4.76, 3.75, -2.07, 3.98, -2.4, 2.67, -2.21, 1.49, -1.21, + 1.22, -5.29, 2.38, -2.85, 2.28, -5.6, 3.78, -2.7, 0.8, -1.81, 3.5, -3.75, + 4.17, -1.29, 2.99, -5.92, 3.43, -1.83, 1.23, -1.24, -1.04, -2.56, 2.37, + -3.26, 0.39, -4.63, 2.51, -4.52, 3.04, -1.7, 0.36, -1.41, 0.04, -2.1, 1.0, + -1.87, 3.78, -4.32, 3.59, -2.24, 1.38, -1.99, -0.22, -1.87, 1.95, -0.84, + 2.17, -5.38, 3.56, -1.27, 2.9, -1.79, 3.31, -5.47, 3.85, -1.44, 3.69, + -2.02, 0.37, -1.29, 0.33, -2.34, 2.56, -1.74, -1.27, -1.97, 1.22, -2.51, + -0.16, -1.64, -0.96, -2.99, 1.4, -1.53, 3.31, -2.24, 0.45, -2.46, 1.71, + -2.88, 1.56, -1.63, 1.46, -1.41, 0.68, -1.96, 2.76, -1.61, + 2.11]).reshape((200, 2)) + + +# Global data +X = np.array([[3.0, 3], [4, 3], [4, 2], + [9, 2], [5, 1], [6, 2], [9, 4], + [5, 2], [5, 4], [7, 4], [6, 5]]) + +CODET1 = np.array([[3.0000, 3.0000], + [6.2000, 4.0000], + [5.8000, 1.8000]]) + +CODET2 = np.array([[11.0/3, 8.0/3], + [6.7500, 4.2500], + [6.2500, 1.7500]]) + +LABEL1 = np.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1]) + + +@make_xp_test_case(whiten) +class TestWhiten: + + def test_whiten(self, xp): + desired = xp.asarray([[5.08738849, 2.97091878], + [3.19909255, 0.69660580], + [4.51041982, 0.02640918], + [4.38567074, 0.95120889], + [2.32191480, 1.63195503]]) + + obs = xp.asarray([[0.98744510, 0.82766775], + [0.62093317, 0.19406729], + [0.87545741, 0.00735733], + [0.85124403, 0.26499712], + [0.45067590, 0.45464607]]) + xp_assert_close(whiten(obs), desired, rtol=1e-5) + + def test_whiten_zero_std(self, xp): + desired = xp.asarray([[0., 1.0, 2.86666544], + [0., 1.0, 1.32460034], + [0., 1.0, 3.74382172]]) + + obs = xp.asarray([[0., 1., 0.74109533], + [0., 1., 0.34243798], + [0., 1., 0.96785929]]) + + with eager_warns(RuntimeWarning, match="Some columns have standard...", xp=xp): + actual = whiten(obs) + xp_assert_close(actual, desired, rtol=1e-5) + + @pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning:dask") + @pytest.mark.parametrize("bad_value", [math.nan, math.inf, -math.inf]) + def test_whiten_not_finite(self, bad_value, xp): + obs = xp.asarray([[0.98744510, bad_value], + [0.62093317, 0.19406729], + [0.87545741, 0.00735733], + [0.85124403, 0.26499712], + [0.45067590, 0.45464607]]) + + if is_lazy_array(obs): + desired = xp.asarray([[5.08738849, math.nan], + [3.19909255, math.nan], + [4.51041982, math.nan], + [4.38567074, math.nan], + [2.32191480, math.nan]]) + xp_assert_close(whiten(obs), desired, rtol=1e-5) + else: + assert_raises(ValueError, whiten, obs) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_whiten_not_finite_matrix(self): + for bad_value in np.nan, np.inf, -np.inf: + obs = matrix([[0.98744510, bad_value], + [0.62093317, 0.19406729], + [0.87545741, 0.00735733], + [0.85124403, 0.26499712], + [0.45067590, 0.45464607]]) + assert_raises(ValueError, whiten, obs) + + +@make_xp_test_case(vq) +class TestVq: + + def test_py_vq(self, xp): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + # label1.dtype varies between int32 and int64 over platforms + label1 = py_vq(xp.asarray(X), xp.asarray(initc))[0] + xp_assert_equal(label1, xp.asarray(LABEL1, dtype=xp.int64), + check_dtype=False) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_py_vq_matrix(self): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + # label1.dtype varies between int32 and int64 over platforms + label1 = py_vq(matrix(X), matrix(initc))[0] + assert_array_equal(label1, LABEL1) + + def test_vq(self, xp): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + label1, _ = _vq.vq(X, initc) + assert_array_equal(label1, LABEL1) + _, _ = vq(xp.asarray(X), xp.asarray(initc)) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_vq_matrix(self): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + label1, _ = _vq.vq(matrix(X), matrix(initc)) + assert_array_equal(label1, LABEL1) + _, _ = vq(matrix(X), matrix(initc)) + + def test_vq_1d(self, xp): + # Test special rank 1 vq algo, python implementation. + data = X[:, 0] + initc = data[:3] + a, b = _vq.vq(data, initc) + data = xp.asarray(data) + initc = xp.asarray(initc) + ta, tb = py_vq(data[:, np.newaxis], initc[:, np.newaxis]) + # ta.dtype varies between int32 and int64 over platforms + xp_assert_equal(ta, xp.asarray(a, dtype=xp.int64), check_dtype=False) + xp_assert_equal(tb, xp.asarray(b)) + + def test__vq_sametype(self): + a = np.asarray([1.0, 2.0]) + b = a.astype(np.float32) + assert_raises(TypeError, _vq.vq, a, b) + + def test__vq_invalid_type(self): + a = np.asarray([1, 2], dtype=int) + assert_raises(TypeError, _vq.vq, a, a) + + def test_vq_large_nfeat(self, xp): + X = np.random.rand(20, 20) + code_book = np.random.rand(3, 20) + + codes0, dis0 = _vq.vq(X, code_book) + codes1, dis1 = py_vq( + xp.asarray(X), xp.asarray(code_book) + ) + xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5) + # codes1.dtype varies between int32 and int64 over platforms + xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False) + + X = X.astype(np.float32) + code_book = code_book.astype(np.float32) + + codes0, dis0 = _vq.vq(X, code_book) + codes1, dis1 = py_vq( + xp.asarray(X), xp.asarray(code_book) + ) + xp_assert_close(dis1, xp.asarray(dis0, dtype=xp.float64), rtol=1e-5) + # codes1.dtype varies between int32 and int64 over platforms + xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False) + + def test_vq_large_features(self, xp): + X = np.random.rand(10, 5) * 1000000 + code_book = np.random.rand(2, 5) * 1000000 + + codes0, dis0 = _vq.vq(X, code_book) + codes1, dis1 = py_vq( + xp.asarray(X), xp.asarray(code_book) + ) + xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5) + # codes1.dtype varies between int32 and int64 over platforms + xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False) + + +# Whole class skipped on GPU for now; +# once pdist/cdist are hooked up for CuPy, more tests will work +@make_xp_test_case(kmeans, kmeans2) +class TestKMeans: + + def test_large_features(self, xp): + # Generate a data set with large values, and run kmeans on it to + # (regression for 1077). + d = 300 + n = 100 + + m1 = np.random.randn(d) + m2 = np.random.randn(d) + x = 10000 * np.random.randn(n, d) - 20000 * m1 + y = 10000 * np.random.randn(n, d) + 20000 * m2 + + data = np.empty((x.shape[0] + y.shape[0], d), np.float64) + data[:x.shape[0]] = x + data[x.shape[0]:] = y + + # use `seed` to ensure backwards compatibility after SPEC7 + kmeans(xp.asarray(data), 2, seed=1) + + def test_kmeans_simple(self, xp): + rng = np.random.default_rng(54321) + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + code1 = kmeans(xp.asarray(X), xp.asarray(initc), iter=1, rng=rng)[0] + xp_assert_close(code1, xp.asarray(CODET2)) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_kmeans_simple_matrix(self): + rng = np.random.default_rng(54321) + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + code1 = kmeans(matrix(X), matrix(initc), iter=1, rng=rng)[0] + xp_assert_close(code1, CODET2) + + def test_kmeans_lost_cluster(self, xp): + # This will cause kmeans to have a cluster with no points. + data = xp.asarray(TESTDATA_2D) + initk = xp.asarray([[-1.8127404, -0.67128041], + [2.04621601, 0.07401111], + [-2.31149087, -0.05160469]]) + + kmeans(data, initk) + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + ("One of the clusters is empty. Re-run kmeans with a different " + "initialization"), + UserWarning, + ) + kmeans2(data, initk, missing='warn') + + assert_raises(ClusterError, kmeans2, data, initk, missing='raise') + + def test_kmeans2_simple(self, xp): + rng = np.random.default_rng(12345678) + initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]])) + arrays = [xp.asarray] if SCIPY_ARRAY_API else [np.asarray, matrix] + for tp in arrays: + code1 = kmeans2(tp(X), tp(initc), iter=1, rng=rng)[0] + code2 = kmeans2(tp(X), tp(initc), iter=2, rng=rng)[0] + + xp_assert_close(code1, xp.asarray(CODET1)) + xp_assert_close(code2, xp.asarray(CODET2)) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_kmeans2_simple_matrix(self): + rng = np.random.default_rng(12345678) + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + code1 = kmeans2(matrix(X), matrix(initc), iter=1, rng=rng)[0] + code2 = kmeans2(matrix(X), matrix(initc), iter=2, rng=rng)[0] + + xp_assert_close(code1, CODET1) + xp_assert_close(code2, CODET2) + + def test_kmeans2_rank1(self, xp): + data = xp.asarray(TESTDATA_2D) + data1 = data[:, 0] + + initc = data1[:3] + code = xp_copy(initc, xp=xp) + + # use `seed` to ensure backwards compatibility after SPEC7 + kmeans2(data1, code, iter=1, seed=1)[0] + kmeans2(data1, code, iter=2)[0] + + def test_kmeans2_rank1_2(self, xp): + data = xp.asarray(TESTDATA_2D) + data1 = data[:, 0] + kmeans2(data1, 2, iter=1) + + def test_kmeans2_high_dim(self, xp): + # test kmeans2 when the number of dimensions exceeds the number + # of input points + data = xp.asarray(TESTDATA_2D) + data = xp.reshape(data, (20, 20))[:10, :] + kmeans2(data, 2) + + def test_kmeans2_init(self, xp): + rng = np.random.default_rng(12345678) + data = xp.asarray(TESTDATA_2D) + k = 3 + + kmeans2(data, k, minit='points', rng=rng) + kmeans2(data[:, 1], k, minit='points', rng=rng) # special case (1-D) + + kmeans2(data, k, minit='++', rng=rng) + kmeans2(data[:, 1], k, minit='++', rng=rng) # special case (1-D) + + # minit='random' can give warnings, filter those + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "One of the clusters is empty. Re-run.") + kmeans2(data, k, minit='random', rng=rng) + kmeans2(data[:, 1], k, minit='random', rng=rng) # special case (1-D) + + @pytest.fixture + def krand_lock(self): + return Lock() + + @xfail_xp_backends('dask.array', reason="Wrong answer") + @pytest.mark.skipif(sys.platform == 'win32', + reason='Fails with MemoryError in Wine.') + def test_krandinit(self, xp, krand_lock): + data = xp.asarray(TESTDATA_2D) + datas = [xp.reshape(data, (200, 2)), + xp.reshape(data, (20, 20))[:10, :]] + k = int(1e6) + with krand_lock: + for data in datas: + rng = np.random.default_rng(1234) + init = _krandinit(data, k, rng, xp) + orig_cov = xpx.cov(data.T, xp=xp) + init_cov = xpx.cov(init.T, xp=xp) + xp_assert_close(orig_cov, init_cov, atol=1.1e-2) + + def test_kmeans2_empty(self, xp): + # Regression test for gh-1032. + assert_raises(ValueError, kmeans2, xp.asarray([]), 2) + + def test_kmeans_0k(self, xp): + # Regression test for gh-1073: fail when k arg is 0. + assert_raises(ValueError, kmeans, xp.asarray(X), 0) + assert_raises(ValueError, kmeans2, xp.asarray(X), 0) + assert_raises(ValueError, kmeans2, xp.asarray(X), xp.asarray([])) + + def test_kmeans_large_thres(self, xp): + # Regression test for gh-1774 + x = xp.asarray([1, 2, 3, 4, 10], dtype=xp.float64) + res = kmeans(x, 1, thresh=1e16) + xp_assert_close(res[0], xp.asarray([4.], dtype=xp.float64)) + xp_assert_close(res[1], xp.asarray(2.3999999999999999, dtype=xp.float64)[()]) + + def test_kmeans2_kpp_low_dim(self, xp): + # Regression test for gh-11462 + rng = np.random.default_rng(2358792345678234568) + prev_res = xp.asarray([[-1.95266667, 0.898], + [-3.153375, 3.3945]], dtype=xp.float64) + res, _ = kmeans2(xp.asarray(TESTDATA_2D), 2, minit='++', rng=rng) + xp_assert_close(res, prev_res) + + def test_kmeans2_kpp_high_dim(self, xp): + # Regression test for gh-11462 + rng = np.random.default_rng(23587923456834568) + n_dim = 100 + size = 10 + centers = np.vstack([5 * np.ones(n_dim), + -5 * np.ones(n_dim)]) + + data = np.vstack([ + rng.multivariate_normal(centers[0], np.eye(n_dim), size=size), + rng.multivariate_normal(centers[1], np.eye(n_dim), size=size) + ]) + + data = xp.asarray(data) + res, _ = kmeans2(data, 2, minit='++', rng=rng) + xp_assert_equal(xp.sign(res), xp.sign(xp.asarray(centers))) + + def test_kmeans_diff_convergence(self, xp): + # Regression test for gh-8727 + obs = xp.asarray([-3, -1, 0, 1, 1, 8], dtype=xp.float64) + res = kmeans(obs, xp.asarray([-3., 0.99])) + xp_assert_close(res[0], xp.asarray([-0.4, 8.], dtype=xp.float64)) + xp_assert_close(res[1], xp.asarray(1.0666666666666667, dtype=xp.float64)[()]) + + def test_kmeans_and_kmeans2_random_seed(self, xp): + + seed_list = [ + 1234, np.random.RandomState(1234), np.random.default_rng(1234) + ] + + for seed in seed_list: + seed1 = deepcopy(seed) + seed2 = deepcopy(seed) + data = xp.asarray(TESTDATA_2D) + # test for kmeans + res1, _ = kmeans(data, 2, seed=seed1) + res2, _ = kmeans(data, 2, seed=seed2) + xp_assert_close(res1, res2) # should be same results + # test for kmeans2 + for minit in ["random", "points", "++"]: + res1, _ = kmeans2(data, 2, minit=minit, seed=seed1) + res2, _ = kmeans2(data, 2, minit=minit, seed=seed2) + xp_assert_close(res1, res2) # should be same results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4a17fed8e553f62689892107a1f2b1674173540 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/_constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/_constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bb6d75cb8168f9ddd9f82d8f31c45f984226fb7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/_constants.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/codata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/codata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e81eec3cbc59bb7771843cdcade9f95832e5192 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/codata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..492ead7b2034cd74609b4f49c159576258d9f257 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/__pycache__/constants.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..142a335b6b169e0a4b0df0a100e81702703eb066 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ed0398e0dd8345cef3e2013d5acd40aa4916c33 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..757efce34283c8531e53c62afe520be179b105e1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/test_codata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/test_codata.py new file mode 100644 index 0000000000000000000000000000000000000000..78ea323913013a8b7efc1c1247daa7578d791218 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/test_codata.py @@ -0,0 +1,78 @@ +from scipy.constants import find, value, c, speed_of_light, precision +from numpy.testing import assert_equal, assert_, assert_almost_equal +import scipy.constants._codata as _cd +from scipy import constants + + +def test_find(): + keys = find('weak mixing', disp=False) + assert_equal(keys, ['weak mixing angle']) + + keys = find('qwertyuiop', disp=False) + assert_equal(keys, []) + + keys = find('natural unit', disp=False) + assert_equal(keys, sorted(['natural unit of velocity', + 'natural unit of action', + 'natural unit of action in eV s', + 'natural unit of mass', + 'natural unit of energy', + 'natural unit of energy in MeV', + 'natural unit of momentum', + 'natural unit of momentum in MeV/c', + 'natural unit of length', + 'natural unit of time'])) + + +def test_basic_table_parse(): + c_s = 'speed of light in vacuum' + assert_equal(value(c_s), c) + assert_equal(value(c_s), speed_of_light) + + +def test_basic_lookup(): + assert_equal('{} {}'.format(int(_cd.value('speed of light in vacuum')), + _cd.unit('speed of light in vacuum')), + '299792458 m s^-1') + + +def test_find_all(): + assert_(len(find(disp=False)) > 300) + + +def test_find_single(): + assert_equal(find('Wien freq', disp=False)[0], + 'Wien frequency displacement law constant') + + +def test_2002_vs_2006(): + assert_almost_equal(value('magn. flux quantum'), + value('mag. flux quantum')) + + +def test_exact_values(): + # Check that updating stored values with exact ones worked. + exact = dict((k, v[0]) for k, v in _cd._physical_constants_2018.items()) + replace = _cd.exact2018(exact) + for key, val in replace.items(): + assert_equal(val, value(key)) + assert precision(key) == 0 + + +def test_gh11341(): + # gh-11341 noted that these three constants should exist (for backward + # compatibility) and should always have the same value: + a = constants.epsilon_0 + b = constants.physical_constants['electric constant'][0] + c = constants.physical_constants['vacuum electric permittivity'][0] + assert a == b == c + + +def test_gh14467(): + # gh-14467 noted that some physical constants in CODATA are rounded + # to only ten significant figures even though they are supposed to be + # exact. Check that (at least) the case mentioned in the issue is resolved. + res = constants.physical_constants['Boltzmann constant in eV/K'][0] + ref = (constants.physical_constants['Boltzmann constant'][0] + / constants.physical_constants['elementary charge'][0]) + assert res == ref diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/test_constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/test_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6a9a9035674bc9ed53143020a1e3f60b2c99cb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/constants/tests/test_constants.py @@ -0,0 +1,83 @@ +import pytest + +import scipy.constants as sc +from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close +from scipy._lib._array_api import make_xp_test_case + +lazy_xp_modules = [sc] + + +@make_xp_test_case(sc.convert_temperature) +class TestConvertTemperature: + def test_convert_temperature(self, xp): + xp_assert_equal(sc.convert_temperature(xp.asarray(32.), 'f', 'Celsius'), + xp.asarray(0.0)) + xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), + 'celsius', 'Kelvin'), + xp.asarray([273.15, 273.15])) + xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'kelvin', 'c'), + xp.asarray([-273.15, -273.15])) + xp_assert_equal(sc.convert_temperature(xp.asarray([32., 32.]), 'f', 'k'), + xp.asarray([273.15, 273.15])) + xp_assert_equal(sc.convert_temperature(xp.asarray([273.15, 273.15]), + 'kelvin', 'F'), + xp.asarray([32., 32.])) + xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'C', 'fahrenheit'), + xp.asarray([32., 32.])) + xp_assert_close(sc.convert_temperature(xp.asarray([0., 0.], dtype=xp.float64), + 'c', 'r'), + xp.asarray([491.67, 491.67], dtype=xp.float64), + rtol=0., atol=1e-13) + xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67], + dtype=xp.float64), + 'Rankine', 'C'), + xp.asarray([0., 0.], dtype=xp.float64), rtol=0., atol=1e-13) + xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67], + dtype=xp.float64), + 'r', 'F'), + xp.asarray([32., 32.], dtype=xp.float64), rtol=0., atol=1e-13) + xp_assert_close(sc.convert_temperature(xp.asarray([32., 32.], dtype=xp.float64), + 'fahrenheit', 'R'), + xp.asarray([491.67, 491.67], dtype=xp.float64), + rtol=0., atol=1e-13) + xp_assert_close(sc.convert_temperature(xp.asarray([273.15, 273.15], + dtype=xp.float64), + 'K', 'R'), + xp.asarray([491.67, 491.67], dtype=xp.float64), + rtol=0., atol=1e-13) + xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 0.], + dtype=xp.float64), + 'rankine', 'kelvin'), + xp.asarray([273.15, 0.], dtype=xp.float64), rtol=0., atol=1e-13) + + def test_convert_temperature_array_like(self): + xp_assert_close(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'), + [273.15, 0.], rtol=0., atol=1e-13) + + + def test_convert_temperature_errors(self): + with pytest.raises(NotImplementedError, match="old_scale="): + sc.convert_temperature(1, old_scale="cheddar", new_scale="kelvin") + with pytest.raises(NotImplementedError, match="new_scale="): + sc.convert_temperature(1, old_scale="kelvin", new_scale="brie") + + +@make_xp_test_case(sc.lambda2nu) +class TestLambdaToNu: + def test_lambda_to_nu(self, xp): + xp_assert_equal(sc.lambda2nu(xp.asarray([sc.speed_of_light, 1])), + xp.asarray([1, sc.speed_of_light])) + + + def test_lambda_to_nu_array_like(self): + xp_assert_close(sc.lambda2nu([sc.speed_of_light, 1]), [1, sc.speed_of_light]) + + +@make_xp_test_case(sc.nu2lambda) +class TestNuToLambda: + def test_nu_to_lambda(self, xp): + xp_assert_equal(sc.nu2lambda(xp.asarray([sc.speed_of_light, 1])), + xp.asarray([1, sc.speed_of_light])) + + def test_nu_to_lambda_array_like(self): + xp_assert_close(sc.nu2lambda([sc.speed_of_light, 1]), [1, sc.speed_of_light]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa47ef9f45479763237b567b58053aae7eca8fd7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_download_all.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_download_all.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baae2e4d0841d9affc46a5c20f5718367e3a9e67 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_download_all.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..889f271de0f03a0359e8f21b5609107d06c6da96 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_registry.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_registry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e81036a3d54234af55245c51d4da497aa08bc87 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_registry.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d883b101810d07758b370d22db1907ff6ed726 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/__pycache__/_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89202a89b5b2cb2f735fc8df4a879155087faedb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db199b27f17eed9db8499343dd0aa7e6fef98968 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/test_data.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc27bdae480ef00346f3b9808884fbc48738512 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/datasets/tests/test_data.py @@ -0,0 +1,128 @@ +from scipy.datasets._registry import registry +from scipy.datasets._fetchers import data_fetcher +from scipy.datasets._utils import _clear_cache +from scipy.datasets import ascent, face, electrocardiogram, download_all +from numpy.testing import assert_equal, assert_almost_equal +import os +from threading import get_ident +import pytest + +try: + import pooch +except ImportError: + raise ImportError("Missing optional dependency 'pooch' required " + "for scipy.datasets module. Please use pip or " + "conda to install 'pooch'.") + + +data_dir = data_fetcher.path # type: ignore + + +def _has_hash(path, expected_hash): + """Check if the provided path has the expected hash.""" + if not os.path.exists(path): + return False + return pooch.file_hash(path) == expected_hash + + +class TestDatasets: + + @pytest.fixture(scope='module', autouse=True) + def test_download_all(self): + # This fixture requires INTERNET CONNECTION + + # test_setup phase + download_all() + + yield + + @pytest.mark.fail_slow(10) + def test_existence_all(self): + assert len(os.listdir(data_dir)) >= len(registry) + + def test_ascent(self): + assert_equal(ascent().shape, (512, 512)) + + # hash check + assert _has_hash(os.path.join(data_dir, "ascent.dat"), + registry["ascent.dat"]) + + def test_face(self): + assert_equal(face().shape, (768, 1024, 3)) + + # hash check + assert _has_hash(os.path.join(data_dir, "face.dat"), + registry["face.dat"]) + + def test_electrocardiogram(self): + # Test shape, dtype and stats of signal + ecg = electrocardiogram() + assert_equal(ecg.dtype, float) + assert_equal(ecg.shape, (108000,)) + assert_almost_equal(ecg.mean(), -0.16510875) + assert_almost_equal(ecg.std(), 0.5992473991177294) + + # hash check + assert _has_hash(os.path.join(data_dir, "ecg.dat"), + registry["ecg.dat"]) + + +def test_clear_cache(tmp_path): + # Note: `tmp_path` is a pytest fixture, it handles cleanup + thread_basepath = tmp_path / str(get_ident()) + thread_basepath.mkdir() + + dummy_basepath = thread_basepath / "dummy_cache_dir" + dummy_basepath.mkdir() + + # Create three dummy dataset files for dummy dataset methods + dummy_method_map = {} + for i in range(4): + dummy_method_map[f"data{i}"] = [f"data{i}.dat"] + data_filepath = dummy_basepath / f"data{i}.dat" + data_filepath.write_text("") + + # clear files associated to single dataset method data0 + # also test callable argument instead of list of callables + def data0(): + pass + _clear_cache(datasets=data0, cache_dir=dummy_basepath, + method_map=dummy_method_map) + assert not os.path.exists(dummy_basepath/"data0.dat") + + # clear files associated to multiple dataset methods "data3" and "data4" + def data1(): + pass + + def data2(): + pass + _clear_cache(datasets=[data1, data2], cache_dir=dummy_basepath, + method_map=dummy_method_map) + assert not os.path.exists(dummy_basepath/"data1.dat") + assert not os.path.exists(dummy_basepath/"data2.dat") + + # clear multiple dataset files "data3_0.dat" and "data3_1.dat" + # associated with dataset method "data3" + def data4(): + pass + # create files + (dummy_basepath / "data4_0.dat").write_text("") + (dummy_basepath / "data4_1.dat").write_text("") + + dummy_method_map["data4"] = ["data4_0.dat", "data4_1.dat"] + _clear_cache(datasets=[data4], cache_dir=dummy_basepath, + method_map=dummy_method_map) + assert not os.path.exists(dummy_basepath/"data4_0.dat") + assert not os.path.exists(dummy_basepath/"data4_1.dat") + + # wrong dataset method should raise ValueError since it + # doesn't exist in the dummy_method_map + def data5(): + pass + with pytest.raises(ValueError): + _clear_cache(datasets=[data5], cache_dir=dummy_basepath, + method_map=dummy_method_map) + + # remove all dataset cache + _clear_cache(datasets=None, cache_dir=dummy_basepath) + assert not os.path.exists(dummy_basepath) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..369e74d3160db0d70192c91b7687c9e233e28011 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/__pycache__/_differentiate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/__pycache__/_differentiate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc204bf8ba1fb24e90db31fc208b7e979d9e49a5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/__pycache__/_differentiate.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fde4d697363411ec1143bac3e08bb2c90231010b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__pycache__/test_differentiate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__pycache__/test_differentiate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7212c378bafe93474056058974055d89cf90c330 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/__pycache__/test_differentiate.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py new file mode 100644 index 0000000000000000000000000000000000000000..00b800833d1aca192b53621a28ac287fcf34d76d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py @@ -0,0 +1,690 @@ +import math +import pytest + +import numpy as np + +import scipy._lib._elementwise_iterative_method as eim +import scipy._lib.array_api_extra as xpx +from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal, xp_assert_less +from scipy._lib._array_api import is_numpy, is_torch, make_xp_test_case + +from scipy import stats, optimize, special +from scipy.differentiate import derivative, jacobian, hessian +from scipy.differentiate._differentiate import _EERRORINCREASE + + + +@make_xp_test_case(derivative) +class TestDerivative: + + def f(self, x): + return special.ndtr(x) + + @pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)]) + def test_basic(self, x, xp): + # Invert distribution CDF and compare against distribution `ppf` + default_dtype = xp.asarray(1.).dtype + res = derivative(self.f, xp.asarray(x, dtype=default_dtype)) + ref = xp.asarray(stats.norm().pdf(x), dtype=default_dtype) + xp_assert_close(res.df, ref) + # This would be nice, but doesn't always work out. `error` is an + # estimate, not a bound. + if not is_torch(xp): + xp_assert_less(xp.abs(res.df - ref), res.error) + + @pytest.mark.parametrize('case', stats._distr_params.distcont) + def test_accuracy(self, case): + distname, params = case + dist = getattr(stats, distname)(*params) + x = dist.median() + 0.1 + res = derivative(dist.cdf, x) + ref = dist.pdf(x) + xp_assert_close(res.df, ref, atol=1e-10) + + @pytest.mark.parametrize('order', [1, 6]) + @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) + def test_vectorization(self, order, shape, xp): + # Test for correct functionality, output shapes, and dtypes for various + # input shapes. + x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6 + n = np.size(x) + state = {} + + @np.vectorize + def _derivative_single(x): + return derivative(self.f, x, order=order) + + def f(x, *args, **kwargs): + state['nit'] += 1 + state['feval'] += 1 if (x.size == n or x.ndim <=1) else x.shape[-1] + return self.f(x, *args, **kwargs) + + state['nit'] = -1 + state['feval'] = 0 + + res = derivative(f, xp.asarray(x, dtype=xp.float64), order=order) + refs = _derivative_single(x).ravel() + + ref_x = [ref.x for ref in refs] + xp_assert_close(xp.reshape(res.x, (-1,)), xp.asarray(ref_x)) + + ref_df = [ref.df for ref in refs] + xp_assert_close(xp.reshape(res.df, (-1,)), xp.asarray(ref_df)) + + ref_error = [ref.error for ref in refs] + xp_assert_close(xp.reshape(res.error, (-1,)), xp.asarray(ref_error), + atol=1e-12) + + ref_success = [bool(ref.success) for ref in refs] + xp_assert_equal(xp.reshape(res.success, (-1,)), xp.asarray(ref_success)) + + ref_flag = [np.int32(ref.status) for ref in refs] + xp_assert_equal(xp.reshape(res.status, (-1,)), xp.asarray(ref_flag)) + + ref_nfev = [np.int32(ref.nfev) for ref in refs] + xp_assert_equal(xp.reshape(res.nfev, (-1,)), xp.asarray(ref_nfev)) + if is_numpy(xp): # can't expect other backends to be exactly the same + assert xp.max(res.nfev) == state['feval'] + + ref_nit = [np.int32(ref.nit) for ref in refs] + xp_assert_equal(xp.reshape(res.nit, (-1,)), xp.asarray(ref_nit)) + if is_numpy(xp): # can't expect other backends to be exactly the same + assert xp.max(res.nit) == state['nit'] + + def test_flags(self, xp): + # Test cases that should produce different status flags; show that all + # can be produced simultaneously. + rng = np.random.default_rng(5651219684984213) + def f(xs, js): + f.nit += 1 + funcs = [lambda x: x - 2.5, # converges + lambda x: xp.exp(x)*rng.random(), # error increases + lambda x: xp.exp(x), # reaches maxiter due to order=2 + lambda x: xp.full_like(x, xp.nan)] # stops due to NaN + res = [funcs[int(j)](x) for x, j in zip(xs, xp.reshape(js, (-1,)))] + return xp.stack(res) + f.nit = 0 + + args = (xp.arange(4, dtype=xp.int64),) + res = derivative(f, xp.ones(4, dtype=xp.float64), + tolerances=dict(rtol=1e-14), + order=2, args=args) + + ref_flags = xp.asarray([eim._ECONVERGED, + _EERRORINCREASE, + eim._ECONVERR, + eim._EVALUEERR], dtype=xp.int32) + xp_assert_equal(res.status, ref_flags) + + def test_flags_preserve_shape(self, xp): + # Same test as above but using `preserve_shape` option to simplify. + rng = np.random.default_rng(5651219684984213) + def f(x): + out = [x - 2.5, # converges + xp.exp(x)*rng.random(), # error increases + xp.exp(x), # reaches maxiter due to order=2 + xp.full_like(x, xp.nan)] # stops due to NaN + return xp.stack(out) + + res = derivative(f, xp.asarray(1, dtype=xp.float64), + tolerances=dict(rtol=1e-14), + order=2, preserve_shape=True) + + ref_flags = xp.asarray([eim._ECONVERGED, + _EERRORINCREASE, + eim._ECONVERR, + eim._EVALUEERR], dtype=xp.int32) + xp_assert_equal(res.status, ref_flags) + + def test_preserve_shape(self, xp): + # Test `preserve_shape` option + def f(x): + out = [x, xp.sin(3*x), x+xp.sin(10*x), xp.sin(20*x)*(x-1)**2] + return xp.stack(out) + + x = xp.asarray(0.) + ref = xp.asarray([xp.asarray(1), 3*xp.cos(3*x), 1+10*xp.cos(10*x), + 20*xp.cos(20*x)*(x-1)**2 + 2*xp.sin(20*x)*(x-1)]) + res = derivative(f, x, preserve_shape=True) + xp_assert_close(res.df, ref) + + def test_convergence(self, xp): + # Test that the convergence tolerances behave as expected + x = xp.asarray(1., dtype=xp.float64) + f = special.ndtr + ref = float(stats.norm.pdf(1.)) + tolerances0 = dict(atol=0, rtol=0) + + tolerances = tolerances0.copy() + tolerances['atol'] = 1e-3 + res1 = derivative(f, x, tolerances=tolerances, order=4) + assert abs(res1.df - ref) < 1e-3 + tolerances['atol'] = 1e-6 + res2 = derivative(f, x, tolerances=tolerances, order=4) + assert abs(res2.df - ref) < 1e-6 + assert abs(res2.df - ref) < abs(res1.df - ref) + + tolerances = tolerances0.copy() + tolerances['rtol'] = 1e-3 + res1 = derivative(f, x, tolerances=tolerances, order=4) + assert abs(res1.df - ref) < 1e-3 * ref + tolerances['rtol'] = 1e-6 + res2 = derivative(f, x, tolerances=tolerances, order=4) + assert abs(res2.df - ref) < 1e-6 * ref + assert abs(res2.df - ref) < abs(res1.df - ref) + + def test_step_parameters(self, xp): + # Test that step factors have the expected effect on accuracy + x = xp.asarray(1., dtype=xp.float64) + f = special.ndtr + ref = float(stats.norm.pdf(1.)) + + res1 = derivative(f, x, initial_step=0.5, maxiter=1) + res2 = derivative(f, x, initial_step=0.05, maxiter=1) + assert abs(res2.df - ref) < abs(res1.df - ref) + + res1 = derivative(f, x, step_factor=2, maxiter=1) + res2 = derivative(f, x, step_factor=20, maxiter=1) + assert abs(res2.df - ref) < abs(res1.df - ref) + + # `step_factor` can be less than 1: `initial_step` is the minimum step + kwargs = dict(order=4, maxiter=1, step_direction=0) + res = derivative(f, x, initial_step=0.5, step_factor=0.5, **kwargs) + ref = derivative(f, x, initial_step=1, step_factor=2, **kwargs) + xp_assert_close(res.df, ref.df, rtol=5e-15) + + # This is a similar test for one-sided difference + kwargs = dict(order=2, maxiter=1, step_direction=1) + res = derivative(f, x, initial_step=1, step_factor=2, **kwargs) + ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs) + xp_assert_close(res.df, ref.df, rtol=5e-15) + + kwargs['step_direction'] = -1 + res = derivative(f, x, initial_step=1, step_factor=2, **kwargs) + ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs) + xp_assert_close(res.df, ref.df, rtol=5e-15) + + def test_step_direction(self, xp): + # test that `step_direction` works as expected + def f(x): + y = xp.exp(x) + y = xpx.at(y)[(x < 0) + (x > 2)].set(xp.nan) + return y + + x = xp.linspace(0, 2, 10) + step_direction = xp.zeros_like(x) + step_direction = xpx.at(step_direction)[x < 0.6].set(1) + step_direction = xpx.at(step_direction)[x > 1.4].set(-1) + res = derivative(f, x, step_direction=step_direction) + xp_assert_close(res.df, xp.exp(x)) + assert xp.all(res.success) + + def test_vectorized_step_direction_args(self, xp): + # test that `step_direction` and `args` are vectorized properly + def f(x, p): + return x ** p + + def df(x, p): + return p * x ** (p - 1) + + x = xp.reshape(xp.asarray([1, 2, 3, 4]), (-1, 1, 1)) + hdir = xp.reshape(xp.asarray([-1, 0, 1]), (1, -1, 1)) + p = xp.reshape(xp.asarray([2, 3]), (1, 1, -1)) + res = derivative(f, x, step_direction=hdir, args=(p,)) + ref = xp.broadcast_to(df(x, p), res.df.shape) + ref = xp.asarray(ref, dtype=xp.asarray(1.).dtype) + xp_assert_close(res.df, ref) + + def test_initial_step(self, xp): + # Test that `initial_step` works as expected and is vectorized + def f(x): + return xp.exp(x) + + x = xp.asarray(0., dtype=xp.float64) + step_direction = xp.asarray([-1, 0, 1]) + h0 = xp.reshape(xp.logspace(-3, 0, 10), (-1, 1)) + res = derivative(f, x, initial_step=h0, order=2, maxiter=1, + step_direction=step_direction) + err = xp.abs(res.df - f(x)) + + # error should be smaller for smaller step sizes + assert xp.all(err[:-1, ...] < err[1:, ...]) + + # results of vectorized call should match results with + # initial_step taken one at a time + for i in range(h0.shape[0]): + ref = derivative(f, x, initial_step=h0[i, 0], order=2, maxiter=1, + step_direction=step_direction) + xp_assert_close(res.df[i, :], ref.df, rtol=1e-14) + + def test_maxiter_callback(self, xp): + # Test behavior of `maxiter` parameter and `callback` interface + x = xp.asarray(0.612814, dtype=xp.float64) + maxiter = 3 + + def f(x): + res = special.ndtr(x) + return res + + default_order = 8 + res = derivative(f, x, maxiter=maxiter, tolerances=dict(rtol=1e-15)) + assert not xp.any(res.success) + assert xp.all(res.nfev == default_order + 1 + (maxiter - 1)*2) + assert xp.all(res.nit == maxiter) + + def callback(res): + callback.iter += 1 + callback.res = res + assert hasattr(res, 'x') + assert float(res.df) not in callback.dfs + callback.dfs.add(float(res.df)) + assert res.status == eim._EINPROGRESS + if callback.iter == maxiter: + raise StopIteration + callback.iter = -1 # callback called once before first iteration + callback.res = None + callback.dfs = set() + + res2 = derivative(f, x, callback=callback, tolerances=dict(rtol=1e-15)) + # terminating with callback is identical to terminating due to maxiter + # (except for `status`) + for key in res.keys(): + if key == 'status': + assert res[key] == eim._ECONVERR + assert res2[key] == eim._ECALLBACK + elif key == 'error': + # switched from equality check to accommodate + # macosx-x86_64/Accelerate + xp_assert_close(res2[key], res[key], atol=1e-14) + xp_assert_close(callback.res[key], res[key], atol=1e-14) + else: + assert res2[key] == callback.res[key] == res[key] + + @pytest.mark.parametrize("hdir", (-1, 0, 1)) + @pytest.mark.parametrize("x", (0.65, [0.65, 0.7])) + @pytest.mark.parametrize("dtype", ('float32', 'float64')) + def test_dtype(self, hdir, x, dtype, xp): + # Test that dtypes are preserved + dtype = getattr(xp, dtype) + x = xp.asarray(x, dtype=dtype) + + def f(x): + assert x.dtype == dtype + return xp.exp(x) + + def callback(res): + assert res.x.dtype == dtype + assert res.df.dtype == dtype + assert res.error.dtype == dtype + + res = derivative(f, x, order=4, step_direction=hdir, callback=callback) + assert res.x.dtype == dtype + assert res.df.dtype == dtype + assert res.error.dtype == dtype + eps = xp.finfo(dtype).eps + # not sure why torch is less accurate here; might be worth investigating + rtol = eps**0.5 * 50 if is_torch(xp) else eps**0.5 + xp_assert_close(res.df, xp.exp(res.x), rtol=rtol) + + def test_input_validation(self, xp): + # Test input validation for appropriate error messages + one = xp.asarray(1) + + message = '`f` must be callable.' + with pytest.raises(ValueError, match=message): + derivative(None, one) + + message = 'Abscissae and function output must be real numbers.' + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, xp.asarray(-4+1j)) + + message = "When `preserve_shape=False`, the shape of the array..." + with pytest.raises(ValueError, match=message): + derivative(lambda x: [1, 2, 3], xp.asarray([-2, -3])) + + message = 'Tolerances and step parameters must be non-negative...' + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, tolerances=dict(atol=-1)) + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, tolerances=dict(rtol='ekki')) + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, step_factor=object()) + + message = '`maxiter` must be a positive integer.' + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, maxiter=1.5) + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, maxiter=0) + + message = '`order` must be a positive integer' + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, order=1.5) + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, order=0) + + message = '`preserve_shape` must be True or False.' + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, preserve_shape='herring') + + message = '`callback` must be callable.' + with pytest.raises(ValueError, match=message): + derivative(lambda x: x, one, callback='shrubbery') + + def test_special_cases(self, xp): + # Test edge cases and other special cases + + # Test that integers are not passed to `f` + # (otherwise this would overflow) + def f(x): + assert xp.isdtype(x.dtype, 'real floating') + return x ** 99 - 1 + + if not is_torch(xp): # torch defaults to float32 + res = derivative(f, xp.asarray(7), tolerances=dict(rtol=1e-10)) + assert res.success + xp_assert_close(res.df, xp.asarray(99*7.**98)) + + # Test invalid step size and direction + res = derivative(xp.exp, xp.asarray(1), step_direction=xp.nan) + xp_assert_equal(res.df, xp.asarray(xp.nan)) + xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32)) + + res = derivative(xp.exp, xp.asarray(1), initial_step=0) + xp_assert_equal(res.df, xp.asarray(xp.nan)) + xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32)) + + # Test that if success is achieved in the correct number + # of iterations if function is a polynomial. Ideally, all polynomials + # of order 0-2 would get exact result with 0 refinement iterations, + # all polynomials of order 3-4 would be differentiated exactly after + # 1 iteration, etc. However, it seems that `derivative` needs an + # extra iteration to detect convergence based on the error estimate. + + for n in range(6): + x = xp.asarray(1.5, dtype=xp.float64) + def f(x): + return 2*x**n + + ref = 2*n*x**(n-1) + + res = derivative(f, x, maxiter=1, order=max(1, n)) + xp_assert_close(res.df, ref, rtol=1e-15) + xp_assert_equal(res.error, xp.asarray(xp.nan, dtype=xp.float64)) + + res = derivative(f, x, order=max(1, n)) + assert res.success + assert res.nit == 2 + xp_assert_close(res.df, ref, rtol=1e-15) + + # Test scalar `args` (not in tuple) + def f(x, c): + return c*x - 1 + + res = derivative(f, xp.asarray(2), args=xp.asarray(3)) + xp_assert_close(res.df, xp.asarray(3.)) + + # no need to run a test on multiple backends if it's xfailed + @pytest.mark.skip_xp_backends(np_only=True) + @pytest.mark.xfail + @pytest.mark.parametrize("case", ( # function, evaluation point + (lambda x: (x - 1) ** 3, 1), + (lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1) + )) + def test_saddle_gh18811(self, case, xp): + # With default settings, `derivative` will not always converge when + # the true derivative is exactly zero. This tests that specifying a + # (tight) `atol` alleviates the problem. See discussion in gh-18811. + atol = 1e-16 + res = derivative(*case, step_direction=[-1, 0, 1], atol=atol) + assert np.all(res.success) + xp_assert_close(res.df, 0, atol=atol) + + +class JacobianHessianTest: + def test_iv(self, xp): + jh_func = self.jh_func.__func__ + + # Test input validation + message = "Argument `x` must be at least 1-D." + with pytest.raises(ValueError, match=message): + jh_func(xp.sin, 1, tolerances=dict(atol=-1)) + + # Confirm that other parameters are being passed to `derivative`, + # which raises an appropriate error message. + x = xp.ones(3) + func = optimize.rosen + message = 'Tolerances and step parameters must be non-negative scalars.' + with pytest.raises(ValueError, match=message): + jh_func(func, x, tolerances=dict(atol=-1)) + with pytest.raises(ValueError, match=message): + jh_func(func, x, tolerances=dict(rtol=-1)) + with pytest.raises(ValueError, match=message): + jh_func(func, x, step_factor=-1) + + message = '`order` must be a positive integer.' + with pytest.raises(ValueError, match=message): + jh_func(func, x, order=-1) + + message = '`maxiter` must be a positive integer.' + with pytest.raises(ValueError, match=message): + jh_func(func, x, maxiter=-1) + + +@make_xp_test_case(jacobian) +class TestJacobian(JacobianHessianTest): + jh_func = jacobian + + # Example functions and Jacobians from Wikipedia: + # https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Examples + + def f1(z, xp): + x, y = z + return xp.stack([x ** 2 * y, 5 * x + xp.sin(y)]) + + def df1(z): + x, y = z + return [[2 * x * y, x ** 2], [np.full_like(x, 5), np.cos(y)]] + + f1.mn = 2, 2 # type: ignore[attr-defined] + f1.ref = df1 # type: ignore[attr-defined] + + def f2(z, xp): + r, phi = z + return xp.stack([r * xp.cos(phi), r * xp.sin(phi)]) + + def df2(z): + r, phi = z + return [[np.cos(phi), -r * np.sin(phi)], + [np.sin(phi), r * np.cos(phi)]] + + f2.mn = 2, 2 # type: ignore[attr-defined] + f2.ref = df2 # type: ignore[attr-defined] + + def f3(z, xp): + r, phi, th = z + return xp.stack([r * xp.sin(phi) * xp.cos(th), r * xp.sin(phi) * xp.sin(th), + r * xp.cos(phi)]) + + def df3(z): + r, phi, th = z + return [[np.sin(phi) * np.cos(th), r * np.cos(phi) * np.cos(th), + -r * np.sin(phi) * np.sin(th)], + [np.sin(phi) * np.sin(th), r * np.cos(phi) * np.sin(th), + r * np.sin(phi) * np.cos(th)], + [np.cos(phi), -r * np.sin(phi), np.zeros_like(r)]] + + f3.mn = 3, 3 # type: ignore[attr-defined] + f3.ref = df3 # type: ignore[attr-defined] + + def f4(x, xp): + x1, x2, x3 = x + return xp.stack([x1, 5 * x3, 4 * x2 ** 2 - 2 * x3, x3 * xp.sin(x1)]) + + def df4(x): + x1, x2, x3 = x + one = np.ones_like(x1) + return [[one, 0 * one, 0 * one], + [0 * one, 0 * one, 5 * one], + [0 * one, 8 * x2, -2 * one], + [x3 * np.cos(x1), 0 * one, np.sin(x1)]] + + f4.mn = 3, 4 # type: ignore[attr-defined] + f4.ref = df4 # type: ignore[attr-defined] + + def f5(x, xp): + x1, x2, x3 = x + return xp.stack([5 * x2, 4 * x1 ** 2 - 2 * xp.sin(x2 * x3), x2 * x3]) + + def df5(x): + x1, x2, x3 = x + one = np.ones_like(x1) + return [[0 * one, 5 * one, 0 * one], + [8 * x1, -2 * x3 * np.cos(x2 * x3), -2 * x2 * np.cos(x2 * x3)], + [0 * one, x3, x2]] + + f5.mn = 3, 3 # type: ignore[attr-defined] + f5.ref = df5 # type: ignore[attr-defined] + + def rosen(x, _): return optimize.rosen(x) + rosen.mn = 5, 1 # type: ignore[attr-defined] + rosen.ref = optimize.rosen_der # type: ignore[attr-defined] + + @pytest.mark.parametrize('dtype', ('float32', 'float64')) + @pytest.mark.parametrize('size', [(), (6,), (2, 3)]) + @pytest.mark.parametrize('func', [f1, f2, f3, f4, f5, rosen]) + def test_examples(self, dtype, size, func, xp): + atol = 1e-10 if dtype == 'float64' else 1.99e-3 + dtype = getattr(xp, dtype) + rng = np.random.default_rng(458912319542) + m, n = func.mn + x = rng.random(size=(m,) + size) + res = jacobian(lambda x: func(x , xp), xp.asarray(x, dtype=dtype)) + # convert list of arrays to single array before converting to xp array + ref = xp.asarray(np.asarray(func.ref(x)), dtype=dtype) + xp_assert_close(res.df, ref, atol=atol) + + def test_attrs(self, xp): + # Test attributes of result object + z = xp.asarray([0.5, 0.25]) + + # case in which some elements of the Jacobian are harder + # to calculate than others + def df1(z): + x, y = z + return xp.stack([xp.cos(0.5*x) * xp.cos(y), xp.sin(2*x) * y**2]) + + def df1_0xy(x, y): + return xp.cos(0.5*x) * xp.cos(y) + + def df1_1xy(x, y): + return xp.sin(2*x) * y**2 + + res = jacobian(df1, z, initial_step=10) + # FIXME https://github.com/scipy/scipy/pull/22320#discussion_r1914898175 + if not is_torch(xp): + assert xpx.nunique(res.nit) == 4 + assert xpx.nunique(res.nfev) == 4 + + res00 = jacobian(lambda x: df1_0xy(x, z[1]), z[0:1], initial_step=10) + res01 = jacobian(lambda y: df1_0xy(z[0], y), z[1:2], initial_step=10) + res10 = jacobian(lambda x: df1_1xy(x, z[1]), z[0:1], initial_step=10) + res11 = jacobian(lambda y: df1_1xy(z[0], y), z[1:2], initial_step=10) + ref = optimize.OptimizeResult() + for attr in ['success', 'status', 'df', 'nit', 'nfev']: + ref_attr = xp.asarray([[getattr(res00, attr), getattr(res01, attr)], + [getattr(res10, attr), getattr(res11, attr)]]) + ref[attr] = xp.squeeze( + ref_attr, + axis=tuple(ax for ax, size in enumerate(ref_attr.shape) if size == 1) + ) + rtol = 1.5e-5 if res[attr].dtype == xp.float32 else 1.5e-14 + xp_assert_close(res[attr], ref[attr], rtol=rtol) + + def test_step_direction_size(self, xp): + # Check that `step_direction` and `initial_step` can be used to ensure that + # the usable domain of a function is respected. + rng = np.random.default_rng(23892589425245) + b = rng.random(3) + eps = 1e-7 # torch needs wiggle room? + + def f(x): + x = xpx.at(x)[0, x[0] < b[0]].set(xp.nan) + x = xpx.at(x)[0, x[0] > b[0] + 0.25].set(xp.nan) + x = xpx.at(x)[1, x[1] > b[1]].set(xp.nan) + x = xpx.at(x)[1, x[1] < b[1] - 0.1-eps].set(xp.nan) + return TestJacobian.f5(x, xp) + + dir = [1, -1, 0] + h0 = [0.25, 0.1, 0.5] + atol = {'atol': 1e-8} + res = jacobian(f, xp.asarray(b, dtype=xp.float64), initial_step=h0, + step_direction=dir, tolerances=atol) + ref = xp.asarray(TestJacobian.df5(b), dtype=xp.float64) + xp_assert_close(res.df, ref, atol=1e-8) + assert xp.all(xp.isfinite(ref)) + + +@make_xp_test_case(hessian) +class TestHessian(JacobianHessianTest): + jh_func = hessian + + @pytest.mark.parametrize('shape', [(), (4,), (2, 4)]) + def test_example(self, shape, xp): + rng = np.random.default_rng(458912319542) + m = 3 + x = xp.asarray(rng.random((m,) + shape), dtype=xp.float64) + res = hessian(optimize.rosen, x) + if shape: + x = xp.reshape(x, (m, -1)) + ref = xp.stack([optimize.rosen_hess(xi) for xi in x.T]) + ref = xp.moveaxis(ref, 0, -1) + ref = xp.reshape(ref, (m, m,) + shape) + else: + ref = optimize.rosen_hess(x) + xp_assert_close(res.ddf, ref, atol=1e-8) + + # # Removed symmetry enforcement; consider adding back in as a feature + # # check symmetry + # for key in ['ddf', 'error', 'nfev', 'success', 'status']: + # assert_equal(res[key], np.swapaxes(res[key], 0, 1)) + + def test_float32(self, xp): + rng = np.random.default_rng(458912319542) + x = xp.asarray(rng.random(3), dtype=xp.float32) + res = hessian(optimize.rosen, x) + ref = optimize.rosen_hess(x) + mask = (ref != 0) + xp_assert_close(res.ddf[mask], ref[mask]) + atol = 1e-2 * xp.abs(xp.min(ref[mask])) + xp_assert_close(res.ddf[~mask], ref[~mask], atol=atol) + + def test_nfev(self, xp): + z = xp.asarray([0.5, 0.25]) + + def f1(z): + x, y = xp.broadcast_arrays(*z) + f1.nfev = f1.nfev + (math.prod(x.shape[2:]) if x.ndim > 2 else 1) + return xp.sin(x) * y ** 3 + f1.nfev = 0 + + + res = hessian(f1, z, initial_step=10) + f1.nfev = 0 + res00 = hessian(lambda x: f1([x[0], z[1]]), z[0:1], initial_step=10) + assert res.nfev[0, 0] == f1.nfev == res00.nfev[0, 0] + + f1.nfev = 0 + res11 = hessian(lambda y: f1([z[0], y[0]]), z[1:2], initial_step=10) + assert res.nfev[1, 1] == f1.nfev == res11.nfev[0, 0] + + # Removed symmetry enforcement; consider adding back in as a feature + # assert_equal(res.nfev, res.nfev.T) # check symmetry + # assert np.unique(res.nfev).size == 3 + + + @pytest.mark.skip_xp_backends(np_only=True, + reason='Python list input uses NumPy backend') + def test_small_rtol_warning(self, xp): + message = 'The specified `rtol=1e-15`, but...' + with pytest.warns(RuntimeWarning, match=message): + hessian(xp.sin, [1.], tolerances=dict(rtol=1e-15)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..511c5f5cf0062ae1d4a3e8319093d10e91a5319e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_backend.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_backend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5be799c3ddefe0f9b8c80db1e60f11698cc4f761 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_backend.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a5bcb297fbbb489ec7e8638c96a5ed44e579439 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feda8496cc2beb14e789c1b71b9d908bec1a8dee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_debug_backends.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_debug_backends.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14352912c1c3b0d90294ee53cc8b92e115700734 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_debug_backends.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_fftlog.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_fftlog.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fd5eca27e9429e86dcfaf0453a4dc78c91d56c7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_fftlog.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f7186e34477da98100a292375758a8a78d0db6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_helper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_helper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f29930e7601baf0e6c9c6061c22c64c021f504e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_helper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b1a10e30cdc5b7d24085390471e09f93a1c7288 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfa2c127cbdef492df97964187f2c6cb89abd7ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/LICENSE.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..b5aa9769746affa6c430599612a3146108f0a974 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/LICENSE.md @@ -0,0 +1,25 @@ +Copyright (C) 2010-2019 Max-Planck-Society +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c792b8c23a0fc76098950623875e45427d848077 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__init__.py @@ -0,0 +1,9 @@ +""" FFT backend using pypocketfft """ + +from .basic import * +from .realtransforms import * +from .helper import * + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6956ce306975204c05a4949d6a20d1fa36d429d9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e21ef446f05f120a2426608a36e31df015a0dd9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b0ffbd11f305d8f681d9f23bb00ebf1b5a2f183 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6a0dbfe711c48b48abcb1bc2d3f30a9db196848 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/basic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..928335c2cd0a1d3a0250278179dae773243808d4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/basic.py @@ -0,0 +1,251 @@ +""" +Discrete Fourier Transforms - basic.py +""" +import numpy as np +import functools +from . import pypocketfft as pfft +from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied, + _fix_shape, _fix_shape_1d, _normalization, + _workers) + +def c2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ Return discrete Fourier transform of real or complex sequence. """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + overwrite_x = overwrite_x or _datacopied(tmp, x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if n is not None: + tmp, copied = _fix_shape_1d(tmp, n, axis) + overwrite_x = overwrite_x or copied + elif tmp.shape[axis] < 1: + message = f"invalid number of data points ({tmp.shape[axis]}) specified" + raise ValueError(message) + + out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None) + + return pfft.c2c(tmp, (axis,), forward, norm, out, workers) + + +fft = functools.partial(c2c, True) +fft.__name__ = 'fft' +ifft = functools.partial(c2c, False) +ifft.__name__ = 'ifft' + + +def r2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ + Discrete Fourier transform of a real sequence. + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if not np.isrealobj(tmp): + raise TypeError("x must be a real sequence") + + if n is not None: + tmp, _ = _fix_shape_1d(tmp, n, axis) + elif tmp.shape[axis] < 1: + raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified") + + # Note: overwrite_x is not utilised + return pfft.r2c(tmp, (axis,), forward, norm, None, workers) + + +rfft = functools.partial(r2c, True) +rfft.__name__ = 'rfft' +ihfft = functools.partial(r2c, False) +ihfft.__name__ = 'ihfft' + + +def c2r(forward, x, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ + Return inverse discrete Fourier transform of real sequence x. + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + # TODO: Optimize for hermitian and real? + if np.isrealobj(tmp): + tmp = tmp + 0.j + + # Last axis utilizes hermitian symmetry + if n is None: + n = (tmp.shape[axis] - 1) * 2 + if n < 1: + raise ValueError(f"Invalid number of data points ({n}) specified") + else: + tmp, _ = _fix_shape_1d(tmp, (n//2) + 1, axis) + + # Note: overwrite_x is not utilized + return pfft.c2r(tmp, (axis,), n, forward, norm, None, workers) + + +hfft = functools.partial(c2r, True) +hfft.__name__ = 'hfft' +irfft = functools.partial(c2r, False) +irfft.__name__ = 'irfft' + + +def hfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None, + *, plan=None): + """ + 2-D discrete Fourier transform of a Hermitian sequence + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + return hfftn(x, s, axes, norm, overwrite_x, workers) + + +def ihfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None, + *, plan=None): + """ + 2-D discrete inverse Fourier transform of a Hermitian sequence + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + return ihfftn(x, s, axes, norm, overwrite_x, workers) + + +def c2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ + Return multidimensional discrete Fourier transform. + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + overwrite_x = overwrite_x or _datacopied(tmp, x) + workers = _workers(workers) + + if len(axes) == 0: + return x + + tmp, copied = _fix_shape(tmp, shape, axes) + overwrite_x = overwrite_x or copied + + norm = _normalization(norm, forward) + out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None) + + return pfft.c2c(tmp, axes, forward, norm, out, workers) + + +fftn = functools.partial(c2cn, True) +fftn.__name__ = 'fftn' +ifftn = functools.partial(c2cn, False) +ifftn.__name__ = 'ifftn' + +def r2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """Return multidimensional discrete Fourier transform of real input""" + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + + if not np.isrealobj(tmp): + raise TypeError("x must be a real sequence") + + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + tmp, _ = _fix_shape(tmp, shape, axes) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if len(axes) == 0: + raise ValueError("at least 1 axis must be transformed") + + # Note: overwrite_x is not utilized + return pfft.r2c(tmp, axes, forward, norm, None, workers) + + +rfftn = functools.partial(r2cn, True) +rfftn.__name__ = 'rfftn' +ihfftn = functools.partial(r2cn, False) +ihfftn.__name__ = 'ihfftn' + + +def c2rn(forward, x, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """Multidimensional inverse discrete fourier transform with real output""" + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + + # TODO: Optimize for hermitian and real? + if np.isrealobj(tmp): + tmp = tmp + 0.j + + noshape = s is None + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + + if len(axes) == 0: + raise ValueError("at least 1 axis must be transformed") + + shape = list(shape) + if noshape: + shape[-1] = (x.shape[axes[-1]] - 1) * 2 + + norm = _normalization(norm, forward) + workers = _workers(workers) + + # Last axis utilizes hermitian symmetry + lastsize = shape[-1] + shape[-1] = (shape[-1] // 2) + 1 + + tmp, _ = tuple(_fix_shape(tmp, shape, axes)) + + # Note: overwrite_x is not utilized + return pfft.c2r(tmp, axes, lastsize, forward, norm, None, workers) + + +hfftn = functools.partial(c2rn, True) +hfftn.__name__ = 'hfftn' +irfftn = functools.partial(c2rn, False) +irfftn.__name__ = 'irfftn' + + +def r2r_fftpack(forward, x, n=None, axis=-1, norm=None, overwrite_x=False): + """FFT of a real sequence, returning fftpack half complex format""" + tmp = _asfarray(x) + overwrite_x = overwrite_x or _datacopied(tmp, x) + norm = _normalization(norm, forward) + workers = _workers(None) + + if tmp.dtype.kind == 'c': + raise TypeError('x must be a real sequence') + + if n is not None: + tmp, copied = _fix_shape_1d(tmp, n, axis) + overwrite_x = overwrite_x or copied + elif tmp.shape[axis] < 1: + raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified") + + out = (tmp if overwrite_x else None) + + return pfft.r2r_fftpack(tmp, (axis,), forward, forward, norm, out, workers) + + +rfft_fftpack = functools.partial(r2r_fftpack, True) +rfft_fftpack.__name__ = 'rfft_fftpack' +irfft_fftpack = functools.partial(r2r_fftpack, False) +irfft_fftpack.__name__ = 'irfft_fftpack' diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/helper.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c2db016b89a3c0ee9125a2c5af9694d57291c5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/helper.py @@ -0,0 +1,252 @@ +from numbers import Number +import operator +import os +import threading +import contextlib + +import numpy as np + +from scipy._lib._util import copy_if_needed +from scipy._lib._array_api import xp_capabilities + +# good_size is exposed (and used) from this import +from .pypocketfft import good_size, prev_good_size + + +__all__ = ['good_size', 'prev_good_size', 'set_workers', 'get_workers'] + +_config = threading.local() +_cpu_count = os.cpu_count() + + +def _iterable_of_int(x, name=None): + """Convert ``x`` to an iterable sequence of int + + Parameters + ---------- + x : value, or sequence of values, convertible to int + name : str, optional + Name of the argument being converted, only used in the error message + + Returns + ------- + y : ``List[int]`` + """ + if isinstance(x, Number): + x = (x,) + + try: + x = [operator.index(a) for a in x] + except TypeError as e: + name = name or "value" + raise ValueError(f"{name} must be a scalar or iterable of integers") from e + + return x + + +def _init_nd_shape_and_axes(x, shape, axes): + """ + Handle shape and axes arguments for N-D transforms. + + Returns the shape and axes in a standard form, taking into account negative + values and checking for various potential errors. + + Parameters + ---------- + x : ndarray + The input array. + shape : int or array_like of ints or None + The shape of the result. If both `shape` and `axes` (see below) are + None, `shape` is ``x.shape``; if `shape` is None but `axes` is + not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``. + If `shape` is -1, the size of the corresponding dimension of `x` is + used. + axes : int or array_like of ints or None + Axes along which the calculation is computed. + The default is over all axes. + Negative indices are automatically converted to their positive + counterparts. + + Returns + ------- + shape : tuple + The shape of the result as a tuple of integers. + axes : list + Axes along which the calculation is computed, as a list of integers. + """ + noshape = shape is None + noaxes = axes is None + + if not noaxes: + axes = _iterable_of_int(axes, 'axes') + axes = [a + x.ndim if a < 0 else a for a in axes] + + if any(a >= x.ndim or a < 0 for a in axes): + raise ValueError("axes exceeds dimensionality of input") + if len(set(axes)) != len(axes): + raise ValueError("all axes must be unique") + + if not noshape: + shape = _iterable_of_int(shape, 'shape') + + if axes and len(axes) != len(shape): + raise ValueError("when given, axes and shape arguments" + " have to be of the same length") + if noaxes: + if len(shape) > x.ndim: + raise ValueError("shape requires more axes than are present") + axes = range(x.ndim - len(shape), x.ndim) + + shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)] + elif noaxes: + shape = list(x.shape) + axes = range(x.ndim) + else: + shape = [x.shape[a] for a in axes] + + if any(s < 1 for s in shape): + raise ValueError( + f"invalid number of data points ({shape}) specified") + + return tuple(shape), list(axes) + + +def _asfarray(x): + """ + Convert to array with floating or complex dtype. + + float16 values are also promoted to float32. + """ + if not hasattr(x, "dtype"): + x = np.asarray(x) + + if x.dtype == np.float16: + return np.asarray(x, np.float32) + elif x.dtype.kind not in 'fc': + return np.asarray(x, np.float64) + + # Require native byte order + dtype = x.dtype.newbyteorder('=') + # Always align input + copy = True if not x.flags['ALIGNED'] else copy_if_needed + return np.array(x, dtype=dtype, copy=copy) + +def _datacopied(arr, original): + """ + Strict check for `arr` not sharing any data with `original`, + under the assumption that arr = asarray(original) + """ + if arr is original: + return False + if not isinstance(original, np.ndarray) and hasattr(original, '__array__'): + return False + return arr.base is None + + +def _fix_shape(x, shape, axes): + """Internal auxiliary function for _raw_fft, _raw_fftnd.""" + must_copy = False + + # Build an nd slice with the dimensions to be read from x + index = [slice(None)]*x.ndim + for n, ax in zip(shape, axes): + if x.shape[ax] >= n: + index[ax] = slice(0, n) + else: + index[ax] = slice(0, x.shape[ax]) + must_copy = True + + index = tuple(index) + + if not must_copy: + return x[index], False + + s = list(x.shape) + for n, axis in zip(shape, axes): + s[axis] = n + + z = np.zeros(s, x.dtype) + z[index] = x[index] + return z, True + + +def _fix_shape_1d(x, n, axis): + if n < 1: + raise ValueError( + f"invalid number of data points ({n}) specified") + + return _fix_shape(x, (n,), (axis,)) + + +_NORM_MAP = {None: 0, 'backward': 0, 'ortho': 1, 'forward': 2} + + +def _normalization(norm, forward): + """Returns the pypocketfft normalization mode from the norm argument""" + try: + inorm = _NORM_MAP[norm] + return inorm if forward else (2 - inorm) + except KeyError: + raise ValueError( + f'Invalid norm value {norm!r}, should ' + 'be "backward", "ortho" or "forward"') from None + + +def _workers(workers): + if workers is None: + return getattr(_config, 'default_workers', 1) + + if workers < 0: + if workers >= -_cpu_count: + workers += 1 + _cpu_count + else: + raise ValueError(f"workers value out of range; got {workers}, must not be" + f" less than {-_cpu_count}") + elif workers == 0: + raise ValueError("workers must not be zero") + + return workers + + +@xp_capabilities(out_of_scope=True) +@contextlib.contextmanager +def set_workers(workers): + """Context manager for the default number of workers used in `scipy.fft` + + Parameters + ---------- + workers : int + The default number of workers to use + + Examples + -------- + >>> import numpy as np + >>> from scipy import fft, signal + >>> rng = np.random.default_rng() + >>> x = rng.standard_normal((128, 64)) + >>> with fft.set_workers(4): + ... y = signal.fftconvolve(x, x) + + """ + old_workers = get_workers() + _config.default_workers = _workers(operator.index(workers)) + try: + yield + finally: + _config.default_workers = old_workers + + +@xp_capabilities(out_of_scope=True) +def get_workers(): + """Returns the default number of workers within the current context + + Examples + -------- + >>> from scipy import fft + >>> fft.get_workers() + 1 + >>> with fft.set_workers(4): + ... fft.get_workers() + 4 + """ + return getattr(_config, 'default_workers', 1) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/pypocketfft.cp311-win_amd64.dll.a b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/pypocketfft.cp311-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..2ed216a49a13f07b050728835c3da44799d8aff1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/pypocketfft.cp311-win_amd64.dll.a differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/realtransforms.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/realtransforms.py new file mode 100644 index 0000000000000000000000000000000000000000..781f04a62a436ec0ad4b73338a9c60737da47fa3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/realtransforms.py @@ -0,0 +1,109 @@ +import numpy as np +from . import pypocketfft as pfft +from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied, + _fix_shape, _fix_shape_1d, _normalization, _workers) +import functools + + +def _r2r(forward, transform, x, type=2, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + """Forward or backward 1-D DCT/DST + + Parameters + ---------- + forward : bool + Transform direction (determines type and normalisation) + transform : {pypocketfft.dct, pypocketfft.dst} + The transform to perform + """ + tmp = _asfarray(x) + overwrite_x = overwrite_x or _datacopied(tmp, x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if not forward: + if type == 2: + type = 3 + elif type == 3: + type = 2 + + if n is not None: + tmp, copied = _fix_shape_1d(tmp, n, axis) + overwrite_x = overwrite_x or copied + elif tmp.shape[axis] < 1: + raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified") + + out = (tmp if overwrite_x else None) + + # For complex input, transform real and imaginary components separably + if np.iscomplexobj(x): + out = np.empty_like(tmp) if out is None else out + transform(tmp.real, type, (axis,), norm, out.real, workers) + transform(tmp.imag, type, (axis,), norm, out.imag, workers) + return out + + return transform(tmp, type, (axis,), norm, out, workers, orthogonalize) + + +dct = functools.partial(_r2r, True, pfft.dct) +dct.__name__ = 'dct' +idct = functools.partial(_r2r, False, pfft.dct) +idct.__name__ = 'idct' + +dst = functools.partial(_r2r, True, pfft.dst) +dst.__name__ = 'dst' +idst = functools.partial(_r2r, False, pfft.dst) +idst.__name__ = 'idst' + + +def _r2rn(forward, transform, x, type=2, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + """Forward or backward nd DCT/DST + + Parameters + ---------- + forward : bool + Transform direction (determines type and normalisation) + transform : {pypocketfft.dct, pypocketfft.dst} + The transform to perform + """ + tmp = _asfarray(x) + + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + overwrite_x = overwrite_x or _datacopied(tmp, x) + + if len(axes) == 0: + return x + + tmp, copied = _fix_shape(tmp, shape, axes) + overwrite_x = overwrite_x or copied + + if not forward: + if type == 2: + type = 3 + elif type == 3: + type = 2 + + norm = _normalization(norm, forward) + workers = _workers(workers) + out = (tmp if overwrite_x else None) + + # For complex input, transform real and imaginary components separably + if np.iscomplexobj(x): + out = np.empty_like(tmp) if out is None else out + transform(tmp.real, type, axes, norm, out.real, workers) + transform(tmp.imag, type, axes, norm, out.imag, workers) + return out + + return transform(tmp, type, axes, norm, out, workers, orthogonalize) + + +dctn = functools.partial(_r2rn, True, pfft.dct) +dctn.__name__ = 'dctn' +idctn = functools.partial(_r2rn, False, pfft.dct) +idctn.__name__ = 'idctn' + +dstn = functools.partial(_r2rn, True, pfft.dst) +dstn.__name__ = 'dstn' +idstn = functools.partial(_r2rn, False, pfft.dst) +idstn.__name__ = 'idstn' diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d840a210670e04972b7c2ff6ebef381499fad4d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71d3df2200df165a5179c4e32c2a70e4ab755076 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_real_transforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_real_transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccb50bf9d154ea25c9915a1bb38ba0af2135e2a9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_real_transforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/test_basic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..33fd72edc8d55defd326801400776081abf099df --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/test_basic.py @@ -0,0 +1,1011 @@ +# Created by Pearu Peterson, September 2002 + +from numpy.testing import (assert_, assert_equal, assert_array_almost_equal, + assert_array_almost_equal_nulp, assert_array_less, + assert_allclose) +import pytest +from pytest import raises as assert_raises +from scipy.fft._pocketfft import (ifft, fft, fftn, ifftn, + rfft, irfft, rfftn, irfftn, + hfft, ihfft, hfftn, ihfftn) + +from numpy import (arange, array, asarray, zeros, dot, exp, pi, + swapaxes, cdouble) +import numpy as np +import numpy.fft +from numpy.random import rand + +# "large" composite numbers supported by FFT._PYPOCKETFFT +LARGE_COMPOSITE_SIZES = [ + 2**13, + 2**5 * 3**5, + 2**3 * 3**3 * 5**2, +] +SMALL_COMPOSITE_SIZES = [ + 2, + 2*3*5, + 2*2*3*3, +] +# prime +LARGE_PRIME_SIZES = [ + 2011 +] +SMALL_PRIME_SIZES = [ + 29 +] + + +def _assert_close_in_norm(x, y, rtol, size, rdt): + # helper function for testing + err_msg = f"size: {size} rdt: {rdt}" + assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg) + + +def random(size): + return rand(*size) + +def swap_byteorder(arr): + """Returns the same array with swapped byteorder""" + dtype = arr.dtype.newbyteorder('S') + return arr.astype(dtype) + +def direct_dft(x): + x = asarray(x) + n = len(x) + y = zeros(n, dtype=cdouble) + w = -arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w), x) + return y + + +def direct_idft(x): + x = asarray(x) + n = len(x) + y = zeros(n, dtype=cdouble) + w = arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w), x)/n + return y + + +def direct_dftn(x): + x = asarray(x) + for axis in range(x.ndim): + x = fft(x, axis=axis) + return x + + +def direct_idftn(x): + x = asarray(x) + for axis in range(x.ndim): + x = ifft(x, axis=axis) + return x + + +def direct_rdft(x): + x = asarray(x) + n = len(x) + w = -arange(n)*(2j*pi/n) + y = zeros(n//2+1, dtype=cdouble) + for i in range(n//2+1): + y[i] = dot(exp(i*w), x) + return y + + +def direct_irdft(x, n): + x = asarray(x) + x1 = zeros(n, dtype=cdouble) + for i in range(n//2+1): + x1[i] = x[i] + if i > 0 and 2*i < n: + x1[n-i] = np.conj(x[i]) + return direct_idft(x1).real + + +def direct_rdftn(x): + return fftn(rfft(x), axes=range(x.ndim - 1)) + + +class _TestFFTBase: + def setup_method(self): + self.cdt = None + self.rdt = None + np.random.seed(1234) + + def test_definition(self): + x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt) + y = fft(x) + assert_equal(y.dtype, self.cdt) + y1 = direct_dft(x) + assert_array_almost_equal(y,y1) + x = np.array([1,2,3,4+0j,5], dtype=self.cdt) + assert_array_almost_equal(fft(x),direct_dft(x)) + + def test_n_argument_real(self): + x1 = np.array([1,2,3,4], dtype=self.rdt) + x2 = np.array([1,2,3,4], dtype=self.rdt) + y = fft([x1,x2],n=4) + assert_equal(y.dtype, self.cdt) + assert_equal(y.shape,(2,4)) + assert_array_almost_equal(y[0],direct_dft(x1)) + assert_array_almost_equal(y[1],direct_dft(x2)) + + def _test_n_argument_complex(self): + x1 = np.array([1,2,3,4+1j], dtype=self.cdt) + x2 = np.array([1,2,3,4+1j], dtype=self.cdt) + y = fft([x1,x2],n=4) + assert_equal(y.dtype, self.cdt) + assert_equal(y.shape,(2,4)) + assert_array_almost_equal(y[0],direct_dft(x1)) + assert_array_almost_equal(y[1],direct_dft(x2)) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(n) + y = fft(x.astype(complex)) + y2 = numpy.fft.fft(x) + assert_array_almost_equal(y,y2) + y = fft(x) + assert_array_almost_equal(y,y2) + + def test_invalid_sizes(self): + assert_raises(ValueError, fft, []) + assert_raises(ValueError, fft, [[1,1],[2,2]], -5) + + +class TestLongDoubleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.clongdouble + self.rdt = np.longdouble + + +class TestDoubleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.cdouble + self.rdt = np.float64 + + +class TestSingleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + + +class TestFloat16FFT: + + def test_1_argument_real(self): + x1 = np.array([1, 2, 3, 4], dtype=np.float16) + y = fft(x1, n=4) + assert_equal(y.dtype, np.complex64) + assert_equal(y.shape, (4, )) + assert_array_almost_equal(y, direct_dft(x1.astype(np.float32))) + + def test_n_argument_real(self): + x1 = np.array([1, 2, 3, 4], dtype=np.float16) + x2 = np.array([1, 2, 3, 4], dtype=np.float16) + y = fft([x1, x2], n=4) + assert_equal(y.dtype, np.complex64) + assert_equal(y.shape, (2, 4)) + assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32))) + assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32))) + + +class _TestIFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt) + y = ifft(x) + y1 = direct_idft(x) + assert_equal(y.dtype, self.cdt) + assert_array_almost_equal(y,y1) + + x = np.array([1,2,3,4+0j,5], self.cdt) + assert_array_almost_equal(ifft(x),direct_idft(x)) + + def test_definition_real(self): + x = np.array([1,2,3,4,1,2,3,4], self.rdt) + y = ifft(x) + assert_equal(y.dtype, self.cdt) + y1 = direct_idft(x) + assert_array_almost_equal(y,y1) + + x = np.array([1,2,3,4,5], dtype=self.rdt) + assert_equal(y.dtype, self.cdt) + assert_array_almost_equal(ifft(x),direct_idft(x)) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(n) + y = ifft(x.astype(self.cdt)) + y2 = numpy.fft.ifft(x.astype(self.cdt)) + assert_allclose(y,y2, rtol=self.rtol, atol=self.atol) + y = ifft(x) + assert_allclose(y,y2, rtol=self.rtol, atol=self.atol) + + def test_random_complex(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.cdt) + x = random([size]).astype(self.cdt) + 1j*x + y1 = ifft(fft(x)) + y2 = fft(ifft(x)) + assert_equal(y1.dtype, self.cdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x) + assert_array_almost_equal(y2, x) + + def test_random_real(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.rdt) + y1 = ifft(fft(x)) + y2 = fft(ifft(x)) + assert_equal(y1.dtype, self.cdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x) + assert_array_almost_equal(y2, x) + + def test_size_accuracy(self): + # Sanity check for the accuracy for prime and non-prime sized inputs + for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: + np.random.seed(1234) + x = np.random.rand(size).astype(self.rdt) + y = ifft(fft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + y = fft(ifft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + + x = (x + 1j*np.random.rand(size)).astype(self.cdt) + y = ifft(fft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + y = fft(ifft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + + def test_invalid_sizes(self): + assert_raises(ValueError, ifft, []) + assert_raises(ValueError, ifft, [[1,1],[2,2]], -5) + + +@pytest.mark.skipif(np.longdouble is np.float64, + reason="Long double is aliased to double") +class TestLongDoubleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.clongdouble + self.rdt = np.longdouble + self.rtol = 1e-10 + self.atol = 1e-10 + + +class TestDoubleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + self.rtol = 1e-10 + self.atol = 1e-10 + + +class TestSingleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + self.rtol = 1e-5 + self.atol = 1e-4 + + +class _TestRFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]: + x = np.array(t, dtype=self.rdt) + y = rfft(x) + y1 = direct_rdft(x) + assert_array_almost_equal(y,y1) + assert_equal(y.dtype, self.cdt) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(n) + y1 = np.fft.rfft(x) + y = rfft(x) + assert_array_almost_equal(y,y1) + + def test_invalid_sizes(self): + assert_raises(ValueError, rfft, []) + assert_raises(ValueError, rfft, [[1,1],[2,2]], -5) + + def test_complex_input(self): + x = np.zeros(10, dtype=self.cdt) + with assert_raises(TypeError, match="x must be a real sequence"): + rfft(x) + + # See gh-5790 + class MockSeries: + def __init__(self, data): + self.data = np.asarray(data) + + def __getattr__(self, item): + try: + return getattr(self.data, item) + except AttributeError as e: + raise AttributeError("'MockSeries' object " + f"has no attribute '{item}'") from e + + def test_non_ndarray_with_dtype(self): + x = np.array([1., 2., 3., 4., 5.]) + xs = _TestRFFTBase.MockSeries(x) + + expected = [1, 2, 3, 4, 5] + rfft(xs) + + # Data should not have been overwritten + assert_equal(x, expected) + assert_equal(xs.data, expected) + +@pytest.mark.skipif(np.longdouble is np.float64, + reason="Long double is aliased to double") +class TestRFFTLongDouble(_TestRFFTBase): + def setup_method(self): + self.cdt = np.clongdouble + self.rdt = np.longdouble + + +class TestRFFTDouble(_TestRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + + +class TestRFFTSingle(_TestRFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + + +class _TestIRFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x1 = [1,2+3j,4+1j,1+2j,3+4j] + x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j] + x1 = x1_1[:5] + x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j] + x2 = x2_1[:5] + + def _test(x, xr): + y = irfft(np.array(x, dtype=self.cdt), n=len(xr)) + y1 = direct_irdft(x, len(xr)) + assert_equal(y.dtype, self.rdt) + assert_array_almost_equal(y,y1, decimal=self.ndec) + assert_array_almost_equal(y,ifft(xr), decimal=self.ndec) + + _test(x1, x1_1) + _test(x2, x2_1) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(-1, n, 2) + 1j * np.arange(0, n+1, 2) + x[0] = 0 + if n % 2 == 0: + x[-1] = np.real(x[-1]) + y1 = np.fft.irfft(x) + y = irfft(x) + assert_array_almost_equal(y,y1) + + def test_random_real(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.rdt) + y1 = irfft(rfft(x), n=size) + y2 = rfft(irfft(x, n=(size*2-1))) + assert_equal(y1.dtype, self.rdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x, decimal=self.ndec, err_msg=f"size={size}") + assert_array_almost_equal(y2, x, decimal=self.ndec, err_msg=f"size={size}") + + def test_size_accuracy(self): + # Sanity check for the accuracy for prime and non-prime sized inputs + if self.rdt == np.float32: + rtol = 1e-5 + elif self.rdt == np.float64: + rtol = 1e-10 + + for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: + np.random.seed(1234) + x = np.random.rand(size).astype(self.rdt) + y = irfft(rfft(x), len(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + y = rfft(irfft(x, 2 * len(x) - 1)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + + def test_invalid_sizes(self): + assert_raises(ValueError, irfft, []) + assert_raises(ValueError, irfft, [[1,1],[2,2]], -5) + + +# self.ndec is bogus; we should have a assert_array_approx_equal for number of +# significant digits + +@pytest.mark.skipif(np.longdouble is np.float64, + reason="Long double is aliased to double") +class TestIRFFTLongDouble(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + self.ndec = 14 + + +class TestIRFFTDouble(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + self.ndec = 14 + + +class TestIRFFTSingle(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + self.ndec = 5 + + +class TestFftnSingle: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(np.array(x, np.float32)) + assert_(y.dtype == np.complex64, + msg="double precision output with single precision") + + y_r = np.array(fftn(x), np.complex64) + assert_array_almost_equal_nulp(y, y_r) + + @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES) + def test_size_accuracy_small(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, size)) + 1j * rng.random((size, size)) + y1 = fftn(x.real.astype(np.float32)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2000) + + @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES) + def test_size_accuracy_large(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, 3)) + 1j * rng.random((size, 3)) + y1 = fftn(x.real.astype(np.float32)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2000) + + def test_definition_float16(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(np.array(x, np.float16)) + assert_equal(y.dtype, np.complex64) + y_r = np.array(fftn(x), np.complex64) + assert_array_almost_equal_nulp(y, y_r) + + @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES) + def test_float16_input_small(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, size)) + 1j*rng.random((size, size)) + y1 = fftn(x.real.astype(np.float16)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 5e5) + + @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES) + def test_float16_input_large(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, 3)) + 1j*rng.random((size, 3)) + y1 = fftn(x.real.astype(np.float16)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2e6) + + +class TestFftn: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(x) + assert_array_almost_equal(y, direct_dftn(x)) + + x = random((20, 26)) + assert_array_almost_equal(fftn(x), direct_dftn(x)) + + x = random((5, 4, 3, 20)) + assert_array_almost_equal(fftn(x), direct_dftn(x)) + + def test_axes_argument(self): + # plane == ji_plane, x== kji_space + plane1 = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + plane2 = [[10, 11, 12], + [13, 14, 15], + [16, 17, 18]] + plane3 = [[19, 20, 21], + [22, 23, 24], + [25, 26, 27]] + ki_plane1 = [[1, 2, 3], + [10, 11, 12], + [19, 20, 21]] + ki_plane2 = [[4, 5, 6], + [13, 14, 15], + [22, 23, 24]] + ki_plane3 = [[7, 8, 9], + [16, 17, 18], + [25, 26, 27]] + jk_plane1 = [[1, 10, 19], + [4, 13, 22], + [7, 16, 25]] + jk_plane2 = [[2, 11, 20], + [5, 14, 23], + [8, 17, 26]] + jk_plane3 = [[3, 12, 21], + [6, 15, 24], + [9, 18, 27]] + kj_plane1 = [[1, 4, 7], + [10, 13, 16], [19, 22, 25]] + kj_plane2 = [[2, 5, 8], + [11, 14, 17], [20, 23, 26]] + kj_plane3 = [[3, 6, 9], + [12, 15, 18], [21, 24, 27]] + ij_plane1 = [[1, 4, 7], + [2, 5, 8], + [3, 6, 9]] + ij_plane2 = [[10, 13, 16], + [11, 14, 17], + [12, 15, 18]] + ij_plane3 = [[19, 22, 25], + [20, 23, 26], + [21, 24, 27]] + ik_plane1 = [[1, 10, 19], + [2, 11, 20], + [3, 12, 21]] + ik_plane2 = [[4, 13, 22], + [5, 14, 23], + [6, 15, 24]] + ik_plane3 = [[7, 16, 25], + [8, 17, 26], + [9, 18, 27]] + ijk_space = [jk_plane1, jk_plane2, jk_plane3] + ikj_space = [kj_plane1, kj_plane2, kj_plane3] + jik_space = [ik_plane1, ik_plane2, ik_plane3] + jki_space = [ki_plane1, ki_plane2, ki_plane3] + kij_space = [ij_plane1, ij_plane2, ij_plane3] + x = array([plane1, plane2, plane3]) + + assert_array_almost_equal(fftn(x), + fftn(x, axes=(-3, -2, -1))) # kji_space + assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2))) + assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1))) + y = fftn(x, axes=(2, 1, 0)) # ijk_space + assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space)) + y = fftn(x, axes=(2, 0, 1)) # ikj_space + assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2), + fftn(ikj_space)) + y = fftn(x, axes=(1, 2, 0)) # jik_space + assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2), + fftn(jik_space)) + y = fftn(x, axes=(1, 0, 2)) # jki_space + assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space)) + y = fftn(x, axes=(0, 2, 1)) # kij_space + assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space)) + + y = fftn(x, axes=(-2, -1)) # ji_plane + assert_array_almost_equal(fftn(plane1), y[0]) + assert_array_almost_equal(fftn(plane2), y[1]) + assert_array_almost_equal(fftn(plane3), y[2]) + + y = fftn(x, axes=(1, 2)) # ji_plane + assert_array_almost_equal(fftn(plane1), y[0]) + assert_array_almost_equal(fftn(plane2), y[1]) + assert_array_almost_equal(fftn(plane3), y[2]) + + y = fftn(x, axes=(-3, -2)) # kj_plane + assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0]) + assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1]) + assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2]) + + y = fftn(x, axes=(-3, -1)) # ki_plane + assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :]) + assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :]) + assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :]) + + y = fftn(x, axes=(-1, -2)) # ij_plane + assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1)) + assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1)) + assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1)) + + y = fftn(x, axes=(-1, -3)) # ik_plane + assert_array_almost_equal(fftn(ik_plane1), + swapaxes(y[:, 0, :], -1, -2)) + assert_array_almost_equal(fftn(ik_plane2), + swapaxes(y[:, 1, :], -1, -2)) + assert_array_almost_equal(fftn(ik_plane3), + swapaxes(y[:, 2, :], -1, -2)) + + y = fftn(x, axes=(-2, -3)) # jk_plane + assert_array_almost_equal(fftn(jk_plane1), + swapaxes(y[:, :, 0], -1, -2)) + assert_array_almost_equal(fftn(jk_plane2), + swapaxes(y[:, :, 1], -1, -2)) + assert_array_almost_equal(fftn(jk_plane3), + swapaxes(y[:, :, 2], -1, -2)) + + y = fftn(x, axes=(-1,)) # i_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :]) + y = fftn(x, axes=(-2,)) # j_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j]) + y = fftn(x, axes=(0,)) # k_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j]) + + y = fftn(x, axes=()) # point + assert_array_almost_equal(y, x) + + def test_shape_argument(self): + small_x = [[1, 2, 3], + [4, 5, 6]] + large_x1 = [[1, 2, 3, 0], + [4, 5, 6, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]] + + y = fftn(small_x, s=(4, 4)) + assert_array_almost_equal(y, fftn(large_x1)) + + y = fftn(small_x, s=(3, 4)) + assert_array_almost_equal(y, fftn(large_x1[:-1])) + + def test_shape_axes_argument(self): + small_x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + large_x1 = array([[1, 2, 3, 0], + [4, 5, 6, 0], + [7, 8, 9, 0], + [0, 0, 0, 0]]) + y = fftn(small_x, s=(4, 4), axes=(-2, -1)) + assert_array_almost_equal(y, fftn(large_x1)) + y = fftn(small_x, s=(4, 4), axes=(-1, -2)) + + assert_array_almost_equal(y, swapaxes( + fftn(swapaxes(large_x1, -1, -2)), -1, -2)) + + def test_shape_axes_argument2(self): + # Change shape of the last axis + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-1,), s=(8,)) + assert_array_almost_equal(y, fft(x, axis=-1, n=8)) + + # Change shape of an arbitrary axis which is not the last one + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-2,), s=(8,)) + assert_array_almost_equal(y, fft(x, axis=-2, n=8)) + + # Change shape of axes: cf #244, where shape and axes were mixed up + x = numpy.random.random((4, 4, 2)) + y = fftn(x, axes=(-3, -2), s=(8, 8)) + assert_array_almost_equal(y, + numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8))) + + def test_shape_argument_more(self): + x = zeros((4, 4, 2)) + with assert_raises(ValueError, + match="shape requires more axes than are present"): + fftn(x, s=(8, 8, 2, 1)) + + def test_invalid_sizes(self): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + fftn([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + fftn([[1, 1], [2, 2]], (4, -3)) + + def test_no_axes(self): + x = numpy.random.random((2,2,2)) + assert_allclose(fftn(x, axes=[]), x, atol=1e-7) + + def test_regression_244(self): + """FFT returns wrong result with axes parameter.""" + # fftn (and hence fft2) used to break when both axes and shape were used + x = numpy.ones((4, 4, 2)) + y = fftn(x, s=(8, 8), axes=(-3, -2)) + y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2)) + assert_allclose(y, y_r) + + +class TestIfftn: + dtype = None + cdtype = None + + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.parametrize('dtype,cdtype,maxnlp', + [(np.float64, np.complex128, 2000), + (np.float32, np.complex64, 3500)]) + def test_definition(self, dtype, cdtype, maxnlp): + rng = np.random.default_rng(1234) + x = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], dtype=dtype) + y = ifftn(x) + assert_equal(y.dtype, cdtype) + assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp) + + x = rng.random((20, 26)) + assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp) + + x = rng.random((5, 4, 3, 20)) + assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp) + + @pytest.mark.parametrize('maxnlp', [2000, 3500]) + @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92]) + def test_random_complex(self, maxnlp, size): + rng = np.random.default_rng(1234) + x = rng.random([size, size]) + 1j * rng.random([size, size]) + assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp) + assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp) + + def test_invalid_sizes(self): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + ifftn([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + ifftn([[1, 1], [2, 2]], (4, -3)) + + def test_no_axes(self): + x = numpy.random.random((2,2,2)) + assert_allclose(ifftn(x, axes=[]), x, atol=1e-7) + +class TestRfftn: + dtype = None + cdtype = None + + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.parametrize('dtype,cdtype,maxnlp', + [(np.float64, np.complex128, 2000), + (np.float32, np.complex64, 3500)]) + def test_definition(self, dtype, cdtype, maxnlp): + rng = np.random.default_rng(1234) + x = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], dtype=dtype) + y = rfftn(x) + assert_equal(y.dtype, cdtype) + assert_array_almost_equal_nulp(y, direct_rdftn(x), maxnlp) + + x = rng.random((20, 26)) + assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp) + + x = rng.random((5, 4, 3, 20)) + assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp) + + @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92]) + def test_random(self, size): + rng = np.random.default_rng(1234) + x = rng.random([size, size]) + assert_allclose(irfftn(rfftn(x), x.shape), x, atol=1e-10) + + @pytest.mark.parametrize('func', [rfftn, irfftn]) + def test_invalid_sizes(self, func): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + func([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + func([[1, 1], [2, 2]], (4, -3)) + + @pytest.mark.parametrize('func', [rfftn, irfftn]) + def test_no_axes(self, func): + with assert_raises(ValueError, + match="at least 1 axis must be transformed"): + func([], axes=[]) + + def test_complex_input(self): + with assert_raises(TypeError, match="x must be a real sequence"): + rfftn(np.zeros(10, dtype=np.complex64)) + + +class FakeArray: + def __init__(self, data): + self._data = data + self.__array_interface__ = data.__array_interface__ + + +class FakeArray2: + def __init__(self, data): + self._data = data + + def __array__(self, dtype=None, copy=None): + return self._data + +# TODO: Is this test actually valuable? The behavior it's testing shouldn't be +# relied upon by users except for overwrite_x = False +class TestOverwrite: + """Check input overwrite behavior of the FFT functions.""" + + real_dtypes = [np.float32, np.float64, np.longdouble] + dtypes = real_dtypes + [np.complex64, np.complex128, np.clongdouble] + fftsizes = [8, 16, 32] + + def _check(self, x, routine, fftsize, axis, overwrite_x, should_overwrite): + x2 = x.copy() + for fake in [lambda x: x, FakeArray, FakeArray2]: + routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x) + + sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, " + f"axis={axis!r}, overwrite_x={overwrite_x!r})") + if not should_overwrite: + assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}") + + def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes, + fftsize, overwrite_x): + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + data = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + data = np.random.randn(*shape) + data = data.astype(dtype) + + should_overwrite = (overwrite_x + and dtype in overwritable_dtypes + and fftsize <= shape[axis]) + self._check(data, routine, fftsize, axis, + overwrite_x=overwrite_x, + should_overwrite=should_overwrite) + + @pytest.mark.parametrize('dtype', dtypes) + @pytest.mark.parametrize('fftsize', fftsizes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), -1), + ((16, 2), 0), + ((2, 16), 1)]) + def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes): + overwritable = (np.clongdouble, np.complex128, np.complex64) + self._check_1d(fft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + self._check_1d(ifft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + + @pytest.mark.parametrize('dtype', real_dtypes) + @pytest.mark.parametrize('fftsize', fftsizes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), -1), + ((16, 2), 0), + ((2, 16), 1)]) + def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes): + overwritable = self.real_dtypes + self._check_1d(irfft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + self._check_1d(rfft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + + def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes, + overwrite_x): + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + data = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + data = np.random.randn(*shape) + data = data.astype(dtype) + + def fftshape_iter(shp): + if len(shp) <= 0: + yield () + else: + for j in (shp[0]//2, shp[0], shp[0]*2): + for rest in fftshape_iter(shp[1:]): + yield (j,) + rest + + def part_shape(shape, axes): + if axes is None: + return shape + else: + return tuple(np.take(shape, axes)) + + def should_overwrite(data, shape, axes): + s = part_shape(data.shape, axes) + return (overwrite_x and + np.prod(shape) <= np.prod(s) + and dtype in overwritable_dtypes) + + for fftshape in fftshape_iter(part_shape(shape, axes)): + self._check(data, routine, fftshape, axes, + overwrite_x=overwrite_x, + should_overwrite=should_overwrite(data, fftshape, axes)) + if data.ndim > 1: + # check fortran order + self._check(data.T, routine, fftshape, axes, + overwrite_x=overwrite_x, + should_overwrite=should_overwrite( + data.T, fftshape, axes)) + + @pytest.mark.parametrize('dtype', dtypes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), None), + ((16,), (0,)), + ((16, 2), (0,)), + ((2, 16), (1,)), + ((8, 16), None), + ((8, 16), (0, 1)), + ((8, 16, 2), (0, 1)), + ((8, 16, 2), (1, 2)), + ((8, 16, 2), (0,)), + ((8, 16, 2), (1,)), + ((8, 16, 2), (2,)), + ((8, 16, 2), None), + ((8, 16, 2), (0, 1, 2))]) + def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes): + overwritable = (np.clongdouble, np.complex128, np.complex64) + self._check_nd_one(fftn, dtype, shape, axes, overwritable, + overwrite_x) + self._check_nd_one(ifftn, dtype, shape, axes, overwritable, + overwrite_x) + + +@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn, + rfft, irfft, rfftn, irfftn]) +def test_invalid_norm(func): + x = np.arange(10, dtype=float) + with assert_raises(ValueError, + match='Invalid norm value \'o\', should be' + ' "backward", "ortho" or "forward"'): + func(x, norm='o') + + +@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn, + irfft, irfftn, hfft, hfftn]) +def test_swapped_byte_order_complex(func): + rng = np.random.RandomState(1234) + x = rng.rand(10) + 1j * rng.rand(10) + assert_allclose(func(swap_byteorder(x)), func(x)) + + +@pytest.mark.parametrize('func', [ihfft, ihfftn, rfft, rfftn]) +def test_swapped_byte_order_real(func): + rng = np.random.RandomState(1234) + x = rng.rand(10) + assert_allclose(func(swap_byteorder(x)), func(x)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..3adf7be0852e91ef3a8b4d160c76373e90f2aae4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py @@ -0,0 +1,506 @@ +from os.path import join, dirname +from collections.abc import Callable +from threading import Lock + +import numpy as np +from numpy.testing import ( + assert_array_almost_equal, assert_equal, assert_allclose) +import pytest +from pytest import raises as assert_raises + +from scipy.fft._pocketfft.realtransforms import ( + dct, idct, dst, idst, dctn, idctn, dstn, idstn) + +fftpack_test_dir = join(dirname(__file__), '..', '..', '..', 'fftpack', 'tests') + +MDATA_COUNT = 8 +FFTWDATA_COUNT = 14 + + +def is_longdouble_binary_compatible(): + try: + one = np.frombuffer( + b'\x00\x00\x00\x00\x00\x00\x00\x80\xff\x3f\x00\x00\x00\x00\x00\x00', + dtype=' decimal +dec_map: DecMapType = { + # DCT + (dct, np.float64, 1): 13, + (dct, np.float32, 1): 6, + + (dct, np.float64, 2): 14, + (dct, np.float32, 2): 5, + + (dct, np.float64, 3): 14, + (dct, np.float32, 3): 5, + + (dct, np.float64, 4): 13, + (dct, np.float32, 4): 6, + + # IDCT + (idct, np.float64, 1): 14, + (idct, np.float32, 1): 6, + + (idct, np.float64, 2): 14, + (idct, np.float32, 2): 5, + + (idct, np.float64, 3): 14, + (idct, np.float32, 3): 5, + + (idct, np.float64, 4): 14, + (idct, np.float32, 4): 6, + + # DST + (dst, np.float64, 1): 13, + (dst, np.float32, 1): 6, + + (dst, np.float64, 2): 14, + (dst, np.float32, 2): 6, + + (dst, np.float64, 3): 14, + (dst, np.float32, 3): 7, + + (dst, np.float64, 4): 13, + (dst, np.float32, 4): 5, + + # IDST + (idst, np.float64, 1): 14, + (idst, np.float32, 1): 6, + + (idst, np.float64, 2): 14, + (idst, np.float32, 2): 6, + + (idst, np.float64, 3): 14, + (idst, np.float32, 3): 6, + + (idst, np.float64, 4): 14, + (idst, np.float32, 4): 6, +} + +for k,v in dec_map.copy().items(): + if k[1] == np.float64: + dec_map[(k[0], np.longdouble, k[2])] = v + elif k[1] == np.float32: + dec_map[(k[0], int, k[2])] = v + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +class TestDCT: + def test_definition(self, rdt, type, fftwdata_size, + reference_data, ref_lock): + with ref_lock: + x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data) + y = dct(x, type=type) + assert_equal(y.dtype, dt) + dec = dec_map[(dct, rdt, type)] + assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec)) + + @pytest.mark.parametrize('size', [7, 8, 9, 16, 32, 64]) + def test_axis(self, rdt, type, size): + nt = 2 + dec = dec_map[(dct, rdt, type)] + x = np.random.randn(nt, size) + y = dct(x, type=type) + for j in range(nt): + assert_array_almost_equal(y[j], dct(x[j], type=type), + decimal=dec) + + x = x.T + y = dct(x, axis=0, type=type) + for j in range(nt): + assert_array_almost_equal(y[:,j], dct(x[:,j], type=type), + decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct1_definition_ortho(rdt, mdata_x): + # Test orthornomal mode. + dec = dec_map[(dct, rdt, 1)] + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dct(x, norm='ortho', type=1) + y2 = naive_dct1(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct2_definition_matlab(mdata_xy, rdt): + # Test correspondence with matlab (orthornomal mode). + dt = np.result_type(np.float32, rdt) + x = np.array(mdata_xy[0], dtype=dt) + + yr = mdata_xy[1] + y = dct(x, norm="ortho", type=2) + dec = dec_map[(dct, rdt, 2)] + assert_equal(y.dtype, dt) + assert_array_almost_equal(y, yr, decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct3_definition_ortho(mdata_x, rdt): + # Test orthornomal mode. + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dct(x, norm='ortho', type=2) + xi = dct(y, norm="ortho", type=3) + dec = dec_map[(dct, rdt, 3)] + assert_equal(xi.dtype, dt) + assert_array_almost_equal(xi, x, decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct4_definition_ortho(mdata_x, rdt): + # Test orthornomal mode. + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dct(x, norm='ortho', type=4) + y2 = naive_dct4(x, norm='ortho') + dec = dec_map[(dct, rdt, 4)] + assert_equal(y.dtype, dt) + assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +def test_idct_definition(fftwdata_size, rdt, type, reference_data, ref_lock): + with ref_lock: + xr, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data) + x = idct(yr, type=type) + dec = dec_map[(idct, rdt, type)] + assert_equal(x.dtype, dt) + assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +def test_definition(fftwdata_size, rdt, type, reference_data, ref_lock): + with ref_lock: + xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data) + y = dst(xr, type=type) + dec = dec_map[(dst, rdt, type)] + assert_equal(y.dtype, dt) + assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dst1_definition_ortho(rdt, mdata_x): + # Test orthornomal mode. + dec = dec_map[(dst, rdt, 1)] + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dst(x, norm='ortho', type=1) + y2 = naive_dst1(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dst4_definition_ortho(rdt, mdata_x): + # Test orthornomal mode. + dec = dec_map[(dst, rdt, 4)] + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dst(x, norm='ortho', type=4) + y2 = naive_dst4(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_array_almost_equal(y, y2, decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +def test_idst_definition(fftwdata_size, rdt, type, reference_data, ref_lock): + with ref_lock: + xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data) + x = idst(yr, type=type) + dec = dec_map[(idst, rdt, type)] + assert_equal(x.dtype, dt) + assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec)) + + +@pytest.mark.parametrize('routine', [dct, dst, idct, idst]) +@pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble]) +@pytest.mark.parametrize('shape, axis', [ + ((16,), -1), ((16, 2), 0), ((2, 16), 1) +]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +@pytest.mark.parametrize('overwrite_x', [True, False]) +@pytest.mark.parametrize('norm', [None, 'ortho']) +def test_overwrite(routine, dtype, shape, axis, type, norm, overwrite_x): + # Check input overwrite behavior + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + x = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + x = np.random.randn(*shape) + x = x.astype(dtype) + x2 = x.copy() + routine(x2, type, None, axis, norm, overwrite_x=overwrite_x) + + sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {None!r}, axis={axis!r}, " + f"overwrite_x={overwrite_x!r})") + if not overwrite_x: + assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}") + + +class Test_DCTN_IDCTN: + dec = 14 + dct_type = [1, 2, 3, 4] + norms = [None, 'backward', 'ortho', 'forward'] + rstate = np.random.RandomState(1234) + shape = (32, 16) + data = rstate.randn(*shape) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + @pytest.mark.parametrize('axes', [None, + 1, (1,), [1], + 0, (0,), [0], + (0, 1), [0, 1], + (-2, -1), [-2, -1]]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', ['ortho']) + def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm): + tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm) + tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm) + assert_array_almost_equal(self.data, tmp, decimal=12) + + @pytest.mark.parametrize('funcn,func', [(dctn, dct), (dstn, dst)]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', norms) + def test_dctn_vs_2d_reference(self, funcn, func, dct_type, norm): + y1 = funcn(self.data, type=dct_type, axes=None, norm=norm) + y2 = ref_2d(func, self.data, type=dct_type, norm=norm) + assert_array_almost_equal(y1, y2, decimal=11) + + @pytest.mark.parametrize('funcn,func', [(idctn, idct), (idstn, idst)]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', norms) + def test_idctn_vs_2d_reference(self, funcn, func, dct_type, norm): + fdata = dctn(self.data, type=dct_type, norm=norm) + y1 = funcn(fdata, type=dct_type, norm=norm) + y2 = ref_2d(func, fdata, type=dct_type, norm=norm) + assert_array_almost_equal(y1, y2, decimal=11) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + def test_axes_and_shape(self, fforward, finverse): + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fforward(self.data, s=self.data.shape[0], axes=(0, 1)) + + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fforward(self.data, s=self.data.shape, axes=0) + + @pytest.mark.parametrize('fforward', [dctn, dstn]) + def test_shape(self, fforward): + tmp = fforward(self.data, s=(128, 128), axes=None) + assert_equal(tmp.shape, (128, 128)) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + @pytest.mark.parametrize('axes', [1, (1,), [1], + 0, (0,), [0]]) + def test_shape_is_none_with_axes(self, fforward, finverse, axes): + tmp = fforward(self.data, s=None, axes=axes, norm='ortho') + tmp = finverse(tmp, s=None, axes=axes, norm='ortho') + assert_array_almost_equal(self.data, tmp, decimal=self.dec) + + +@pytest.mark.parametrize('func', [dct, dctn, idct, idctn, + dst, dstn, idst, idstn]) +def test_swapped_byte_order(func): + rng = np.random.RandomState(1234) + x = rng.rand(10) + swapped_dt = x.dtype.newbyteorder('S') + assert_allclose(func(x.astype(swapped_dt)), func(x)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..059b15c7268e3a6826d969ce81311497ac76fd93 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/mock_backend.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/mock_backend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4ce0ffb98a97fcd63678e4bfd8418070de0681e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/mock_backend.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_backend.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_backend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6cfcc66b4c5294de1e594ec1c2d923b6081b16d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_backend.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e61670a0ef1544b30c449c0ee8930829fe74229 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_fftlog.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_fftlog.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bd3140cf72a6287caf6b95ebfdf924dcaccd27e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_fftlog.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94be1acb870604f3d009f3184dbcb32ca8c630c9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_multithreading.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_multithreading.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89b45518b94d98267c67cf4f51e7b2e46c39af53 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_multithreading.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_real_transforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_real_transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e6462d355b8f32c0836e2f5f126ea692fe12bc2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/__pycache__/test_real_transforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/mock_backend.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/mock_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..73b7c31d12378c23f6f12d2ff3e6ee9503a7ec29 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/mock_backend.py @@ -0,0 +1,96 @@ +import numpy as np +import scipy.fft +import threading + +class _MockFunction: + def __init__(self, return_value = None): + self.number_calls = threading.local() + self.return_value = return_value + self.last_args = threading.local() + + def __call__(self, *args, **kwargs): + if not hasattr(self.number_calls, 'c'): + self.number_calls.c = 0 + + self.number_calls.c += 1 + self.last_args.l = (args, kwargs) + return self.return_value + + +fft = _MockFunction(np.random.random(10)) +fft2 = _MockFunction(np.random.random(10)) +fftn = _MockFunction(np.random.random(10)) + +ifft = _MockFunction(np.random.random(10)) +ifft2 = _MockFunction(np.random.random(10)) +ifftn = _MockFunction(np.random.random(10)) + +rfft = _MockFunction(np.random.random(10)) +rfft2 = _MockFunction(np.random.random(10)) +rfftn = _MockFunction(np.random.random(10)) + +irfft = _MockFunction(np.random.random(10)) +irfft2 = _MockFunction(np.random.random(10)) +irfftn = _MockFunction(np.random.random(10)) + +hfft = _MockFunction(np.random.random(10)) +hfft2 = _MockFunction(np.random.random(10)) +hfftn = _MockFunction(np.random.random(10)) + +ihfft = _MockFunction(np.random.random(10)) +ihfft2 = _MockFunction(np.random.random(10)) +ihfftn = _MockFunction(np.random.random(10)) + +dct = _MockFunction(np.random.random(10)) +idct = _MockFunction(np.random.random(10)) +dctn = _MockFunction(np.random.random(10)) +idctn = _MockFunction(np.random.random(10)) + +dst = _MockFunction(np.random.random(10)) +idst = _MockFunction(np.random.random(10)) +dstn = _MockFunction(np.random.random(10)) +idstn = _MockFunction(np.random.random(10)) + +fht = _MockFunction(np.random.random(10)) +ifht = _MockFunction(np.random.random(10)) + + +__ua_domain__ = "numpy.scipy.fft" + + +_implements = { + scipy.fft.fft: fft, + scipy.fft.fft2: fft2, + scipy.fft.fftn: fftn, + scipy.fft.ifft: ifft, + scipy.fft.ifft2: ifft2, + scipy.fft.ifftn: ifftn, + scipy.fft.rfft: rfft, + scipy.fft.rfft2: rfft2, + scipy.fft.rfftn: rfftn, + scipy.fft.irfft: irfft, + scipy.fft.irfft2: irfft2, + scipy.fft.irfftn: irfftn, + scipy.fft.hfft: hfft, + scipy.fft.hfft2: hfft2, + scipy.fft.hfftn: hfftn, + scipy.fft.ihfft: ihfft, + scipy.fft.ihfft2: ihfft2, + scipy.fft.ihfftn: ihfftn, + scipy.fft.dct: dct, + scipy.fft.idct: idct, + scipy.fft.dctn: dctn, + scipy.fft.idctn: idctn, + scipy.fft.dst: dst, + scipy.fft.idst: idst, + scipy.fft.dstn: dstn, + scipy.fft.idstn: idstn, + scipy.fft.fht: fht, + scipy.fft.ifht: ifht +} + + +def __ua_function__(method, args, kwargs): + fn = _implements.get(method) + return (fn(*args, **kwargs) if fn is not None + else NotImplemented) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_backend.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe89acd12f6b2f2e2cfa7d026455a9b281adf43 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_backend.py @@ -0,0 +1,98 @@ +from functools import partial + +import numpy as np +import scipy.fft +from scipy.fft import _fftlog, _pocketfft, set_backend +from scipy.fft.tests import mock_backend + +from numpy.testing import assert_allclose, assert_equal +import pytest + +fnames = ('fft', 'fft2', 'fftn', + 'ifft', 'ifft2', 'ifftn', + 'rfft', 'rfft2', 'rfftn', + 'irfft', 'irfft2', 'irfftn', + 'dct', 'idct', 'dctn', 'idctn', + 'dst', 'idst', 'dstn', 'idstn', + 'fht', 'ifht') + +np_funcs = (np.fft.fft, np.fft.fft2, np.fft.fftn, + np.fft.ifft, np.fft.ifft2, np.fft.ifftn, + np.fft.rfft, np.fft.rfft2, np.fft.rfftn, + np.fft.irfft, np.fft.irfft2, np.fft.irfftn, + np.fft.hfft, _pocketfft.hfft2, _pocketfft.hfftn, # np has no hfftn + np.fft.ihfft, _pocketfft.ihfft2, _pocketfft.ihfftn, + _pocketfft.dct, _pocketfft.idct, _pocketfft.dctn, _pocketfft.idctn, + _pocketfft.dst, _pocketfft.idst, _pocketfft.dstn, _pocketfft.idstn, + # must provide required kwargs for fht, ifht + partial(_fftlog.fht, dln=2, mu=0.5), + partial(_fftlog.ifht, dln=2, mu=0.5)) + +funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn, + scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn, + scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn, + scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn, + scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn, + scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn, + scipy.fft.dct, scipy.fft.idct, scipy.fft.dctn, scipy.fft.idctn, + scipy.fft.dst, scipy.fft.idst, scipy.fft.dstn, scipy.fft.idstn, + # must provide required kwargs for fht, ifht + partial(scipy.fft.fht, dln=2, mu=0.5), + partial(scipy.fft.ifht, dln=2, mu=0.5)) + +mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn, + mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn, + mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn, + mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn, + mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn, + mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn, + mock_backend.dct, mock_backend.idct, + mock_backend.dctn, mock_backend.idctn, + mock_backend.dst, mock_backend.idst, + mock_backend.dstn, mock_backend.idstn, + mock_backend.fht, mock_backend.ifht) + + +@pytest.mark.parametrize("func, np_func, mock", zip(funcs, np_funcs, mocks)) +def test_backend_call(func, np_func, mock): + x = np.arange(20).reshape((10,2)) + answer = np_func(x.astype(np.float64)) + assert_allclose(func(x), answer, atol=1e-10) + + with set_backend(mock_backend, only=True): + mock.number_calls.c = 0 + y = func(x) + assert_equal(y, mock.return_value) + assert_equal(mock.number_calls.c, 1) + + assert_allclose(func(x), answer, atol=1e-10) + + +plan_funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn, + scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn, + scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn, + scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn, + scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn, + scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn) + +plan_mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn, + mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn, + mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn, + mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn, + mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn, + mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn) + + +@pytest.mark.parametrize("func, mock", zip(plan_funcs, plan_mocks)) +def test_backend_plan(func, mock): + x = np.arange(20).reshape((10, 2)) + + with pytest.raises(NotImplementedError, match='precomputed plan'): + func(x, plan='foo') + + with set_backend(mock_backend, only=True): + mock.number_calls.c = 0 + y = func(x, plan='foo') + assert_equal(y, mock.return_value) + assert_equal(mock.number_calls.c, 1) + assert_equal(mock.last_args.l[1]['plan'], 'foo') diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_basic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..a4fe5fa8fd5cc7eb76fcbcb758eaafef3d55f64f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_basic.py @@ -0,0 +1,549 @@ +import queue +import threading +import multiprocessing +import numpy as np +import pytest +from numpy.random import random +from numpy.testing import assert_array_almost_equal, assert_allclose +from pytest import raises as assert_raises +import scipy.fft as fft +from scipy._lib._array_api import ( + is_numpy, xp_size, xp_assert_close, xp_assert_equal, make_xp_test_case, + make_xp_pytest_param +) + +lazy_xp_modules = [fft] +skip_xp_backends = pytest.mark.skip_xp_backends + + +# Expected input dtypes. Note that `scipy.fft` is more flexible for numpy, +# but for C2C transforms like `fft.fft`, the array API standard only mandates +# that complex dtypes should work, float32/float64 aren't guaranteed to. +def get_expected_input_dtype(func, xp): + # use __name__ so that `lazy_xp_function` doesn't break things + if func.__name__ in ["fft", "fftn", "fft2", "ifft", "ifftn", "ifft2", "hfft", + "hfftn", "hfft2", "irfft", "irfftn", "irfft2"]: + dtype = xp.complex128 + elif func.__name__ in ["rfft", "rfftn", "rfft2", "ihfft", "ihfftn", "ihfft2"]: + dtype = xp.float64 + else: + raise ValueError(f'Unknown FFT function: {func}') + + return dtype + + +def fft1(x): + L = len(x) + phase = -2j*np.pi*(np.arange(L)/float(L)) + phase = np.arange(L).reshape(-1, 1) * phase + return np.sum(x*np.exp(phase), axis=1) + + +class TestFFT: + @make_xp_test_case(fft.ifft, fft.fft, fft.rfft, fft.irfft) + def test_identity(self, xp): + maxlen = 512 + x = xp.asarray(random(maxlen) + 1j*random(maxlen)) + xr = xp.asarray(random(maxlen)) + # Check some powers of 2 and some primes + for i in [1, 2, 16, 128, 512, 53, 149, 281, 397]: + xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i]) + xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i]) + + @skip_xp_backends(np_only=True, reason='significant overhead for some backends') + def test_identity_extensive(self, xp): + maxlen = 512 + x = xp.asarray(random(maxlen) + 1j*random(maxlen)) + xr = xp.asarray(random(maxlen)) + for i in range(1, maxlen): + xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i]) + xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i]) + + @make_xp_test_case(fft.fft) + def test_fft(self, xp): + x = random(30) + 1j*random(30) + expect = xp.asarray(fft1(x)) + x = xp.asarray(x) + xp_assert_close(fft.fft(x), expect) + xp_assert_close(fft.fft(x, norm="backward"), expect) + xp_assert_close(fft.fft(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)),) + xp_assert_close(fft.fft(x, norm="forward"), expect / 30) + + @skip_xp_backends(np_only=True, reason='some backends allow `n=0`') + def test_fft_n(self, xp): + x = xp.asarray([1, 2, 3], dtype=xp.complex128) + assert_raises(ValueError, fft.fft, x, 0) + + @make_xp_test_case(fft.fft, fft.ifft) + def test_ifft(self, xp): + x = xp.asarray(random(30) + 1j*random(30)) + xp_assert_close(fft.ifft(fft.fft(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.ifft(fft.fft(x, norm=norm), norm=norm), x) + + @make_xp_test_case(fft.fft, fft.fft2) + def test_fft2(self, xp): + x = xp.asarray(random((30, 20)) + 1j*random((30, 20))) + expect = fft.fft(fft.fft(x, axis=1), axis=0) + xp_assert_close(fft.fft2(x), expect) + xp_assert_close(fft.fft2(x, norm="backward"), expect) + xp_assert_close(fft.fft2(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))) + xp_assert_close(fft.fft2(x, norm="forward"), expect / (30 * 20)) + + @make_xp_test_case(fft.ifft, fft.ifft2) + def test_ifft2(self, xp): + x = xp.asarray(random((30, 20)) + 1j*random((30, 20))) + expect = fft.ifft(fft.ifft(x, axis=1), axis=0) + xp_assert_close(fft.ifft2(x), expect) + xp_assert_close(fft.ifft2(x, norm="backward"), expect) + xp_assert_close(fft.ifft2(x, norm="ortho"), + expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))) + xp_assert_close(fft.ifft2(x, norm="forward"), expect * (30 * 20)) + + @make_xp_test_case(fft.fft, fft.fftn) + def test_fftn(self, xp): + x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10))) + expect = fft.fft(fft.fft(fft.fft(x, axis=2), axis=1), axis=0) + xp_assert_close(fft.fftn(x), expect) + xp_assert_close(fft.fftn(x, norm="backward"), expect) + xp_assert_close(fft.fftn(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))) + xp_assert_close(fft.fftn(x, norm="forward"), expect / (30 * 20 * 10)) + + @make_xp_test_case(fft.ifft, fft.ifftn) + def test_ifftn(self, xp): + x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10))) + expect = fft.ifft(fft.ifft(fft.ifft(x, axis=2), axis=1), axis=0) + xp_assert_close(fft.ifftn(x), expect, rtol=1e-7) + xp_assert_close(fft.ifftn(x, norm="backward"), expect, rtol=1e-7) + xp_assert_close( + fft.ifftn(x, norm="ortho"), + fft.ifftn(x) * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)) + ) + xp_assert_close(fft.ifftn(x, norm="forward"), + expect * (30 * 20 * 10), + rtol=1e-7) + + @make_xp_test_case(fft.fft, fft.rfft) + def test_rfft(self, xp): + x = xp.asarray(random(29), dtype=xp.float64) + for n in [xp_size(x), 2*xp_size(x)]: + for norm in [None, "backward", "ortho", "forward"]: + xp_assert_close(fft.rfft(x, n=n, norm=norm), + fft.fft(xp.asarray(x, dtype=xp.complex128), + n=n, norm=norm)[:(n//2 + 1)]) + xp_assert_close( + fft.rfft(x, n=n, norm="ortho"), + fft.rfft(x, n=n) / xp.sqrt(xp.asarray(n, dtype=xp.float64)) + ) + + @make_xp_test_case(fft.irfft, fft.rfft) + def test_irfft(self, xp): + x = xp.asarray(random(30)) + xp_assert_close(fft.irfft(fft.rfft(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.irfft(fft.rfft(x, norm=norm), norm=norm), x) + + @make_xp_test_case(fft.rfft2) + def test_rfft2(self, xp): + x = xp.asarray(random((30, 20)), dtype=xp.float64) + expect = fft.fft2(xp.asarray(x, dtype=xp.complex128))[:, :11] + xp_assert_close(fft.rfft2(x), expect) + xp_assert_close(fft.rfft2(x, norm="backward"), expect) + xp_assert_close(fft.rfft2(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))) + xp_assert_close(fft.rfft2(x, norm="forward"), expect / (30 * 20)) + + @make_xp_test_case(fft.rfft2, fft.irfft2) + def test_irfft2(self, xp): + x = xp.asarray(random((30, 20))) + xp_assert_close(fft.irfft2(fft.rfft2(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.irfft2(fft.rfft2(x, norm=norm), norm=norm), x) + + @make_xp_test_case(fft.fftn, fft.rfftn) + def test_rfftn(self, xp): + x = xp.asarray(random((30, 20, 10)), dtype=xp.float64) + expect = fft.fftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6] + xp_assert_close(fft.rfftn(x), expect) + xp_assert_close(fft.rfftn(x, norm="backward"), expect) + xp_assert_close(fft.rfftn(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))) + xp_assert_close(fft.rfftn(x, norm="forward"), expect / (30 * 20 * 10)) + + @make_xp_test_case(fft.irfftn, fft.rfftn) + def test_irfftn(self, xp): + x = xp.asarray(random((30, 20, 10))) + xp_assert_close(fft.irfftn(fft.rfftn(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.irfftn(fft.rfftn(x, norm=norm), norm=norm), x) + + @make_xp_test_case(fft.hfft, fft.fft) + def test_hfft(self, xp): + x = random(14) + 1j*random(14) + x_herm = np.concatenate((random(1), x, random(1))) + x = np.concatenate((x_herm, x[::-1].conj())) + x = xp.asarray(x) + x_herm = xp.asarray(x_herm) + expect = xp.real(fft.fft(x)) + xp_assert_close(fft.hfft(x_herm), expect) + xp_assert_close(fft.hfft(x_herm, norm="backward"), expect) + xp_assert_close(fft.hfft(x_herm, norm="ortho"), + expect / xp.sqrt(xp.asarray(30, dtype=xp.float64))) + xp_assert_close(fft.hfft(x_herm, norm="forward"), expect / 30) + + @make_xp_test_case(fft.hfft, fft.ihfft) + def test_ihfft(self, xp): + x = random(14) + 1j*random(14) + x_herm = np.concatenate((random(1), x, random(1))) + x = np.concatenate((x_herm, x[::-1].conj())) + x = xp.asarray(x) + x_herm = xp.asarray(x_herm) + xp_assert_close(fft.ihfft(fft.hfft(x_herm)), x_herm) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.ihfft(fft.hfft(x_herm, norm=norm), norm=norm), x_herm) + + @make_xp_test_case(fft.hfft2, fft.ihfft2) + def test_hfft2(self, xp): + x = xp.asarray(random((30, 20))) + xp_assert_close(fft.hfft2(fft.ihfft2(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.hfft2(fft.ihfft2(x, norm=norm), norm=norm), x) + + @make_xp_test_case(fft.ifft2) + def test_ihfft2(self, xp): + x = xp.asarray(random((30, 20)), dtype=xp.float64) + expect = fft.ifft2(xp.asarray(x, dtype=xp.complex128))[:, :11] + xp_assert_close(fft.ihfft2(x), expect) + xp_assert_close(fft.ihfft2(x, norm="backward"), expect) + xp_assert_close( + fft.ihfft2(x, norm="ortho"), + expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)) + ) + xp_assert_close(fft.ihfft2(x, norm="forward"), expect * (30 * 20)) + + @make_xp_test_case(fft.hfftn, fft.ihfftn) + def test_hfftn(self, xp): + x = xp.asarray(random((30, 20, 10))) + xp_assert_close(fft.hfftn(fft.ihfftn(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.hfftn(fft.ihfftn(x, norm=norm), norm=norm), x) + + @make_xp_test_case(fft.ifftn, fft.ihfftn) + def test_ihfftn(self, xp): + x = xp.asarray(random((30, 20, 10)), dtype=xp.float64) + expect = fft.ifftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6] + xp_assert_close(expect, fft.ihfftn(x)) + xp_assert_close(expect, fft.ihfftn(x, norm="backward")) + xp_assert_close( + fft.ihfftn(x, norm="ortho"), + expect * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)) + ) + xp_assert_close(fft.ihfftn(x, norm="forward"), expect * (30 * 20 * 10)) + + def _check_axes(self, op, xp): + dtype = get_expected_input_dtype(op, xp) + x = xp.asarray(random((30, 20, 10)), dtype=dtype) + axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] + + for a in axes: + op_tr = op(xp.permute_dims(x, axes=a)) + tr_op = xp.permute_dims(op(x, axes=a), axes=a) + xp_assert_close(op_tr, tr_op) + + @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.fftn), + make_xp_pytest_param(fft.ifftn), + make_xp_pytest_param(fft.rfftn), + make_xp_pytest_param(fft.irfftn)]) + def test_axes_standard(self, op, xp): + self._check_axes(op, xp) + + @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.hfftn), + make_xp_pytest_param(fft.ihfftn)]) + def test_axes_non_standard(self, op, xp): + self._check_axes(op, xp) + + @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.fftn), + make_xp_pytest_param(fft.ifftn), + make_xp_pytest_param(fft.rfftn), + make_xp_pytest_param(fft.irfftn)]) + def test_axes_subset_with_shape_standard(self, op, xp): + dtype = get_expected_input_dtype(op, xp) + x = xp.asarray(random((16, 8, 4)), dtype=dtype) + axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)] + + for a in axes: + # different shape on the first two axes + shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax] + for ax in range(x.ndim)]) + # transform only the first two axes + op_tr = op(xp.permute_dims(x, axes=a), + s=shape[:2], axes=(0, 1)) + tr_op = xp.permute_dims(op(x, s=shape[:2], axes=a[:2]), + axes=a) + xp_assert_close(op_tr, tr_op) + + @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.fft2), + make_xp_pytest_param(fft.ifft2), + make_xp_pytest_param(fft.rfft2), + make_xp_pytest_param(fft.irfft2), + make_xp_pytest_param(fft.hfft2), + make_xp_pytest_param(fft.ihfft2), + make_xp_pytest_param(fft.hfftn), + make_xp_pytest_param(fft.ihfftn)]) + def test_axes_subset_with_shape_non_standard(self, op, xp): + dtype = get_expected_input_dtype(op, xp) + x = xp.asarray(random((16, 8, 4)), dtype=dtype) + axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)] + + for a in axes: + # different shape on the first two axes + shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax] + for ax in range(x.ndim)]) + # transform only the first two axes + op_tr = op(xp.permute_dims(x, axes=a), s=shape[:2], axes=(0, 1)) + tr_op = xp.permute_dims(op(x, s=shape[:2], axes=a[:2]), axes=a) + xp_assert_close(op_tr, tr_op) + + @make_xp_test_case(fft.rfft, fft.irfft, fft.ihfft, fft.hfft, fft.fft, fft.ifft) + def test_all_1d_norm_preserving(self, xp): + # verify that round-trip transforms are norm-preserving + x = xp.asarray(random(30), dtype=xp.float64) + + x_norm = xp.linalg.vector_norm(x) + n = xp_size(x) * 2 + func_pairs = [(fft.rfft, fft.irfft), + # hfft: order so the first function takes x.size samples + # (necessary for comparison to x_norm above) + (fft.ihfft, fft.hfft), + # functions that expect complex dtypes at the end + (fft.fft, fft.ifft), + ] + for forw, back in func_pairs: + if forw == fft.fft: + x = xp.asarray(x, dtype=xp.complex128) + x_norm = xp.linalg.vector_norm(x) + for n in [xp_size(x), 2*xp_size(x)]: + for norm in ['backward', 'ortho', 'forward']: + tmp = forw(x, n=n, norm=norm) + tmp = back(tmp, n=n, norm=norm) + xp_assert_close(xp.linalg.vector_norm(tmp), x_norm) + + @pytest.mark.parametrize("dtype", [np.float16, np.longdouble]) + def test_dtypes_nonstandard(self, dtype): + x = random(30).astype(dtype) + out_dtypes = {np.float16: np.complex64, np.longdouble: np.clongdouble} + x_complex = x.astype(out_dtypes[dtype]) + + res_fft = fft.ifft(fft.fft(x)) + res_rfft = fft.irfft(fft.rfft(x)) + res_hfft = fft.hfft(fft.ihfft(x), x.shape[0]) + # Check both numerical results and exact dtype matches + assert_array_almost_equal(res_fft, x_complex) + assert_array_almost_equal(res_rfft, x) + assert_array_almost_equal(res_hfft, x) + assert res_fft.dtype == x_complex.dtype + assert res_rfft.dtype == np.result_type(np.float32, x.dtype) + assert res_hfft.dtype == np.result_type(np.float32, x.dtype) + + @make_xp_test_case(fft.irfft, fft.rfft) + @pytest.mark.parametrize("dtype", ["float32", "float64"]) + def test_dtypes_real(self, dtype, xp): + x = xp.asarray(random(30), dtype=getattr(xp, dtype)) + + res_rfft = fft.irfft(fft.rfft(x)) + res_hfft = fft.hfft(fft.ihfft(x), x.shape[0]) + # Check both numerical results and exact dtype matches + xp_assert_close(res_rfft, x) + xp_assert_close(res_hfft, x) + + @make_xp_test_case(fft.fft, fft.ifft) + @pytest.mark.parametrize("dtype", ["complex64", "complex128"]) + def test_dtypes_complex(self, dtype, xp): + rng = np.random.default_rng(1234) + x = xp.asarray(rng.random(30), dtype=getattr(xp, dtype)) + + res_fft = fft.ifft(fft.fft(x)) + # Check both numerical results and exact dtype matches + xp_assert_close(res_fft, x) + + @pytest.mark.parametrize("op", [fft.fft, fft.ifft, + fft.fft2, fft.ifft2, + fft.fftn, fft.ifftn, + fft.rfft, fft.irfft, + fft.rfft2, fft.irfft2, + fft.rfftn, fft.irfftn, + fft.hfft, fft.ihfft, + fft.hfft2, fft.ihfft2, + fft.hfftn, fft.ihfftn,]) + def test_array_like(self, op): + x = [[[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]]] + xp_assert_close(op(x), op(np.asarray(x))) + + +@pytest.mark.parametrize( + "dtype", + [np.float32, np.float64, np.longdouble, + np.complex64, np.complex128, np.clongdouble]) +@pytest.mark.parametrize("order", ["F", 'non-contiguous']) +@pytest.mark.parametrize( + "fft", + [fft.fft, fft.fft2, fft.fftn, fft.ifft, fft.ifft2, fft.ifftn]) +def test_fft_with_order(dtype, order, fft): + # Check that FFT/IFFT produces identical results for C, Fortran and + # non contiguous arrays + rng = np.random.RandomState(42) + X = rng.rand(8, 7, 13).astype(dtype, copy=False) + if order == 'F': + Y = np.asfortranarray(X) + else: + # Make a non contiguous array + Y = X[::-1] + X = np.ascontiguousarray(X[::-1]) + + if fft.__name__.endswith('fft'): + for axis in range(3): + X_res = fft(X, axis=axis) + Y_res = fft(Y, axis=axis) + assert_array_almost_equal(X_res, Y_res) + elif fft.__name__.endswith(('fft2', 'fftn')): + axes = [(0, 1), (1, 2), (0, 2)] + if fft.__name__.endswith('fftn'): + axes.extend([(0,), (1,), (2,), None]) + for ax in axes: + X_res = fft(X, axes=ax) + Y_res = fft(Y, axes=ax) + assert_array_almost_equal(X_res, Y_res) + else: + raise ValueError + + +@skip_xp_backends(cpu_only=True) +class TestFFTThreadSafe: + threads = 16 + input_shape = (800, 200) + + def _test_mtsame(self, func, *args, xp=None): + def worker(args, q): + q.put(func(*args)) + + q = queue.Queue() + expected = func(*args) + + # Spin off a bunch of threads to call the same function simultaneously + t = [threading.Thread(target=worker, args=(args, q)) + for i in range(self.threads)] + [x.start() for x in t] + + [x.join() for x in t] + + # Make sure all threads returned the correct value + for i in range(self.threads): + xp_assert_equal( + q.get(timeout=5), expected, + err_msg='Function returned wrong value in multithreaded context' + ) + + @make_xp_test_case(fft.fft) + def test_fft(self, xp): + a = xp.ones(self.input_shape, dtype=xp.complex128) + self._test_mtsame(fft.fft, a, xp=xp) + + @make_xp_test_case(fft.ifft) + def test_ifft(self, xp): + a = xp.full(self.input_shape, 1+0j) + self._test_mtsame(fft.ifft, a, xp=xp) + + @make_xp_test_case(fft.rfft) + def test_rfft(self, xp): + a = xp.ones(self.input_shape) + self._test_mtsame(fft.rfft, a, xp=xp) + + @make_xp_test_case(fft.irfft) + def test_irfft(self, xp): + a = xp.full(self.input_shape, 1+0j) + self._test_mtsame(fft.irfft, a, xp=xp) + + @make_xp_test_case(fft.hfft) + def test_hfft(self, xp): + a = xp.ones(self.input_shape, dtype=xp.complex64) + self._test_mtsame(fft.hfft, a, xp=xp) + + @make_xp_test_case(fft.ihfft) + def test_ihfft(self, xp): + a = xp.ones(self.input_shape) + self._test_mtsame(fft.ihfft, a, xp=xp) + + +@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft]) +def test_multiprocess(func): + # Test that fft still works after fork (gh-10422) + + with multiprocessing.Pool(2) as p: + res = p.map(func, [np.ones(100) for _ in range(4)]) + + expect = func(np.ones(100)) + for x in res: + assert_allclose(x, expect) + + +@make_xp_test_case(fft.irfftn) +class TestIRFFTN: + + def test_not_last_axis_success(self, xp): + ar, ai = np.random.random((2, 16, 8, 32)) + a = ar + 1j*ai + a = xp.asarray(a) + + axes = (-2,) + + # Should not raise error + fft.irfftn(a, axes=axes) + + +@pytest.mark.parametrize("func", [make_xp_pytest_param(fft.fft), + make_xp_pytest_param(fft.ifft), + make_xp_pytest_param(fft.rfft), + make_xp_pytest_param(fft.irfft), + make_xp_pytest_param(fft.fftn), + make_xp_pytest_param(fft.ifftn), + make_xp_pytest_param(fft.rfftn), + make_xp_pytest_param(fft.irfftn), + make_xp_pytest_param(fft.hfft), + make_xp_pytest_param(fft.ihfft)]) +def test_non_standard_params(func, xp): + # use __name__ so that `lazy_xp_function` doesn't break things + if func.__name__ in ["rfft", "rfftn", "ihfft"]: + dtype = xp.float64 + else: + dtype = xp.complex128 + + x = xp.asarray([1, 2, 3], dtype=dtype) + # func(x) should not raise an exception + func(x) + + if is_numpy(xp): + func(x, workers=2) + else: + assert_raises(ValueError, func, x, workers=2) + + # `plan` param is not tested since SciPy does not use it currently + # but should be tested if it comes into use + + +@pytest.mark.parametrize("dtype", ['float32', 'float64']) +@pytest.mark.parametrize("func", [make_xp_pytest_param(fft.fft), + make_xp_pytest_param(fft.ifft), + make_xp_pytest_param(fft.irfft), + make_xp_pytest_param(fft.fftn), + make_xp_pytest_param(fft.ifftn), + make_xp_pytest_param(fft.irfftn), + make_xp_pytest_param(fft.hfft)]) +def test_real_input(func, dtype, xp): + x = xp.asarray([1, 2, 3], dtype=getattr(xp, dtype)) + # func(x) should not raise an exception + func(x) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_fftlog.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_fftlog.py new file mode 100644 index 0000000000000000000000000000000000000000..5fff2edcfc2d68685702dbcf7576a2b53c216dc9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_fftlog.py @@ -0,0 +1,214 @@ +import warnings +import math + +import numpy as np +import pytest + +from scipy.fft._fftlog import fht, ifht, fhtoffset +from scipy.special import poch + +from scipy._lib._array_api import xp_assert_close, xp_assert_less + +skip_xp_backends = pytest.mark.skip_xp_backends + + +def test_fht_agrees_with_fftlog(xp): + # check that fht numerically agrees with the output from Fortran FFTLog, + # the results were generated with the provided `fftlogtest` program, + # after fixing how the k array is generated (divide range by n-1, not n) + + # test function, analytical Hankel transform is of the same form + def f(r, mu): + return r**(mu+1)*np.exp(-r**2/2) + + r = np.logspace(-4, 4, 16) + + dln = math.log(r[1]/r[0]) + mu = 0.3 + offset = 0.0 + bias = 0.0 + + a = xp.asarray(f(r, mu)) + + # test 1: compute as given + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02, + -0.1949518286432330E-02, +0.3789220182554077E-02, + +0.5093959119952945E-03, +0.2785387803618774E-01, + +0.9944952700848897E-01, +0.4599202164586588E+00, + +0.3157462160881342E+00, -0.8201236844404755E-03, + -0.7834031308271878E-03, +0.3931444945110708E-03, + -0.2697710625194777E-03, +0.3568398050238820E-03, + -0.5554454827797206E-03, +0.8286331026468585E-03] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + # test 2: change to optimal offset + offset = fhtoffset(dln, mu, bias=bias) + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05, + +0.3150140927838524E-03, +0.9149121960963704E-03, + +0.5808089753959363E-02, +0.2548065256377240E-01, + +0.1339477692089897E+00, +0.4821530509479356E+00, + +0.2659899781579785E+00, -0.1116475278448113E-01, + +0.1791441617592385E-02, -0.4181810476548056E-03, + +0.1314963536765343E-03, -0.5422057743066297E-04, + +0.3208681804170443E-04, -0.2696849476008234E-04] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + # test 3: positive bias + bias = 0.8 + offset = fhtoffset(dln, mu, bias=bias) + # offset is a np.float64, which array-api-strict disallows + # even if it's technically a subclass of float + offset = float(offset) + + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00, + +0.1065374386206564E+00, -0.5121739602708132E-01, + +0.2636649319269470E-01, +0.1697209218849693E-01, + +0.1250215614723183E+00, +0.4739583261486729E+00, + +0.2841149874912028E+00, -0.8312764741645729E-02, + +0.1024233505508988E-02, -0.1644902767389120E-03, + +0.3305775476926270E-04, -0.7786993194882709E-05, + +0.1962258449520547E-05, -0.8977895734909250E-06] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + # test 4: negative bias + bias = -0.8 + offset = fhtoffset(dln, mu, bias=bias) + offset = float(offset) + + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04, + +0.2123969254700955E-03, +0.1009558244834628E-02, + +0.5131386375222176E-02, +0.2461678673516286E-01, + +0.1235812845384476E+00, +0.4719570096404403E+00, + +0.2893487490631317E+00, -0.1686570611318716E-01, + +0.2231398155172505E-01, -0.1480742256379873E-01, + +0.1692387813500801E+00, +0.3097490354365797E+00, + +2.7593607182401860E+00, 10.5251075070045800E+00] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + +@pytest.mark.parametrize('optimal', [True, False]) +@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0]) +@pytest.mark.parametrize('bias', [0, 0.1, -0.1]) +@pytest.mark.parametrize('n', [64, 63]) +def test_fht_identity(n, bias, offset, optimal, xp): + rng = np.random.RandomState(3491349965) + + a = xp.asarray(rng.standard_normal(n)) + dln = rng.uniform(-1, 1) + mu = rng.uniform(-2, 2) + + if optimal: + offset = fhtoffset(dln, mu, initial=offset, bias=bias) + # offset is a np.float64, which array-api-strict disallows + # even if it's technically a subclass of float + offset = float(offset) + + A = fht(a, dln, mu, offset=offset, bias=bias) + a_ = ifht(A, dln, mu, offset=offset, bias=bias) + + xp_assert_close(a_, a, rtol=1.5e-7) + + + + +def test_fht_special_cases(xp): + rng = np.random.RandomState(3491349965) + + a = xp.asarray(rng.standard_normal(64)) + dln = rng.uniform(-1, 1) + + # let x = (mu+1+q)/2, y = (mu+1-q)/2, M = {0, -1, -2, ...} + + # case 1: x in M, y in M => well-defined transform + mu, bias = -4.0, 1.0 + with warnings.catch_warnings(record=True) as record: + fht(a, dln, mu, bias=bias) + assert not record, 'fht warned about a well-defined transform' + + # case 2: x not in M, y in M => well-defined transform + mu, bias = -2.5, 0.5 + with warnings.catch_warnings(record=True) as record: + fht(a, dln, mu, bias=bias) + assert not record, 'fht warned about a well-defined transform' + + # with fht_lock: + # case 3: x in M, y not in M => singular transform + mu, bias = -3.5, 0.5 + with pytest.warns(Warning) as record: + fht(a, dln, mu, bias=bias) + assert record, 'fht did not warn about a singular transform' + + # with fht_lock: + # case 4: x not in M, y in M => singular inverse transform + mu, bias = -2.5, 0.5 + with pytest.warns(Warning) as record: + ifht(a, dln, mu, bias=bias) + assert record, 'ifht did not warn about a singular transform' + + +@pytest.mark.parametrize('n', [64, 63]) +def test_fht_exact(n, xp): + rng = np.random.RandomState(3491349965) + + # for a(r) a power law r^\gamma, the fast Hankel transform produces the + # exact continuous Hankel transform if biased with q = \gamma + + mu = rng.uniform(0, 3) + + # convergence of HT: -1-mu < gamma < 1/2 + gamma = rng.uniform(-1-mu, 1/2) + + r = np.logspace(-2, 2, n) + a = xp.asarray(r**gamma) + + dln = math.log(r[1]/r[0]) + + offset = fhtoffset(dln, mu, initial=0.0, bias=gamma) + # offset is a np.float64, which array-api-strict disallows + # even if it's technically a subclass of float + offset = float(offset) + + A = fht(a, dln, mu, offset=offset, bias=gamma) + + k = np.exp(offset)/r[::-1] + + # analytical result + At = xp.asarray((2/k)**gamma * poch((mu+1-gamma)/2, gamma)) + + xp_assert_close(A, At) + +@skip_xp_backends(np_only=True, + reason='array-likes only supported for NumPy backend') +@pytest.mark.parametrize("op", [fht, ifht]) +def test_array_like(xp, op): + x = [[[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]]] + xp_assert_close(op(x, 1.0, 2.0), op(xp.asarray(x), 1.0, 2.0)) + +@pytest.mark.parametrize('n', [128, 129]) +def test_gh_21661(xp, n): + one = xp.asarray(1.0) + mu = 0.0 + r = np.logspace(-7, 1, n) + dln = math.log(r[1] / r[0]) + offset = fhtoffset(dln, initial=-6 * np.log(10), mu=mu) + r = xp.asarray(r, dtype=one.dtype) + k = math.exp(offset) / xp.flip(r, axis=-1) + + def f(x, mu): + return x**(mu + 1)*xp.exp(-x**2/2) + + a_r = f(r, mu) + fht_val = fht(a_r, dln, mu=mu, offset=offset) + a_k = f(k, mu) + rel_err = xp.max(xp.abs((fht_val - a_k) / a_k)) + xp_assert_less(rel_err, xp.asarray(7.28e+16)[()]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_helper.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..b7131c7868223a8a43abf6fbbdaa1894d586895c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_helper.py @@ -0,0 +1,555 @@ +"""Includes test functions for fftpack.helper module + +Copied from fftpack.helper by Pearu Peterson, October 2005 +Modified for Array API, 2023 + +""" +from scipy.fft._helper import next_fast_len, prev_fast_len, _init_nd_shape_and_axes +from numpy.testing import assert_equal +from pytest import raises as assert_raises +import pytest +import numpy as np +import sys +from scipy._lib._array_api import xp_assert_close, xp_device +from scipy import fft + +skip_xp_backends = pytest.mark.skip_xp_backends + +_5_smooth_numbers = [ + 2, 3, 4, 5, 6, 8, 9, 10, + 2 * 3 * 5, + 2**3 * 3**5, + 2**3 * 3**3 * 5**2, +] + + +def test_next_fast_len(): + for n in _5_smooth_numbers: + assert_equal(next_fast_len(n), n) + + +def _assert_n_smooth(x, n): + x_orig = x + if n < 2: + assert False + + while True: + q, r = divmod(x, 2) + if r != 0: + break + x = q + + for d in range(3, n+1, 2): + while True: + q, r = divmod(x, d) + if r != 0: + break + x = q + + assert x == 1, \ + f'x={x_orig} is not {n}-smooth, remainder={x}' + + +class TestNextFastLen: + + def test_next_fast_len(self): + np.random.seed(1234) + + def nums(): + yield from range(1, 1000) + yield 2**5 * 3**5 * 4**5 + 1 + + for n in nums(): + m = next_fast_len(n) + _assert_n_smooth(m, 11) + assert m == next_fast_len(n, False) + + m = next_fast_len(n, True) + _assert_n_smooth(m, 5) + + def test_np_integers(self): + ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, np.uint64] + for ityp in ITYPES: + x = ityp(12345) + testN = next_fast_len(x) + assert_equal(testN, next_fast_len(int(x))) + + def testnext_fast_len_small(self): + hams = { + 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8, 8: 8, 14: 15, 15: 15, + 16: 16, 17: 18, 1021: 1024, 1536: 1536, 51200000: 51200000 + } + for x, y in hams.items(): + assert_equal(next_fast_len(x, True), y) + + @pytest.mark.xfail(sys.maxsize < 2**32, + reason="Hamming Numbers too large for 32-bit", + raises=ValueError, strict=True) + def testnext_fast_len_big(self): + hams = { + 510183360: 510183360, 510183360 + 1: 512000000, + 511000000: 512000000, + 854296875: 854296875, 854296875 + 1: 859963392, + 196608000000: 196608000000, 196608000000 + 1: 196830000000, + 8789062500000: 8789062500000, 8789062500000 + 1: 8796093022208, + 206391214080000: 206391214080000, + 206391214080000 + 1: 206624260800000, + 470184984576000: 470184984576000, + 470184984576000 + 1: 470715894135000, + 7222041363087360: 7222041363087360, + 7222041363087360 + 1: 7230196133913600, + # power of 5 5**23 + 11920928955078125: 11920928955078125, + 11920928955078125 - 1: 11920928955078125, + # power of 3 3**34 + 16677181699666569: 16677181699666569, + 16677181699666569 - 1: 16677181699666569, + # power of 2 2**54 + 18014398509481984: 18014398509481984, + 18014398509481984 - 1: 18014398509481984, + # above this, int(ceil(n)) == int(ceil(n+1)) + 19200000000000000: 19200000000000000, + 19200000000000000 + 1: 19221679687500000, + 288230376151711744: 288230376151711744, + 288230376151711744 + 1: 288325195312500000, + 288325195312500000 - 1: 288325195312500000, + 288325195312500000: 288325195312500000, + 288325195312500000 + 1: 288555831593533440, + } + for x, y in hams.items(): + assert_equal(next_fast_len(x, True), y) + + def test_keyword_args(self, xp): + assert next_fast_len(11, real=True) == 12 + assert next_fast_len(target=7, real=False) == 7 + + +class TestPrevFastLen: + + def test_prev_fast_len(self): + np.random.seed(1234) + + def nums(): + yield from range(1, 1000) + yield 2**5 * 3**5 * 4**5 + 1 + + for n in nums(): + m = prev_fast_len(n) + _assert_n_smooth(m, 11) + assert m == prev_fast_len(n, False) + + m = prev_fast_len(n, True) + _assert_n_smooth(m, 5) + + def test_np_integers(self): + ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, + np.uint64] + for ityp in ITYPES: + x = ityp(12345) + testN = prev_fast_len(x) + assert_equal(testN, prev_fast_len(int(x))) + + testN = prev_fast_len(x, real=True) + assert_equal(testN, prev_fast_len(int(x), real=True)) + + def testprev_fast_len_small(self): + hams = { + 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 8, 14: 12, 15: 15, + 16: 16, 17: 16, 1021: 1000, 1536: 1536, 51200000: 51200000 + } + for x, y in hams.items(): + assert_equal(prev_fast_len(x, True), y) + + hams = { + 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, + 11: 11, 12: 12, 13: 12, 14: 14, 15: 15, 16: 16, 17: 16, 18: 18, + 19: 18, 20: 20, 21: 21, 22: 22, 120: 120, 121: 121, 122: 121, + 1021: 1008, 1536: 1536, 51200000: 51200000 + } + for x, y in hams.items(): + assert_equal(prev_fast_len(x, False), y) + + @pytest.mark.xfail(sys.maxsize < 2**32, + reason="Hamming Numbers too large for 32-bit", + raises=ValueError, strict=True) + def testprev_fast_len_big(self): + hams = { + # 2**6 * 3**13 * 5**1 + 510183360: 510183360, + 510183360 + 1: 510183360, + 510183360 - 1: 509607936, # 2**21 * 3**5 + # 2**6 * 5**6 * 7**1 * 73**1 + 511000000: 510183360, + 511000000 + 1: 510183360, + 511000000 - 1: 510183360, # 2**6 * 3**13 * 5**1 + # 3**7 * 5**8 + 854296875: 854296875, + 854296875 + 1: 854296875, + 854296875 - 1: 850305600, # 2**6 * 3**12 * 5**2 + # 2**22 * 3**1 * 5**6 + 196608000000: 196608000000, + 196608000000 + 1: 196608000000, + 196608000000 - 1: 195910410240, # 2**13 * 3**14 * 5**1 + # 2**5 * 3**2 * 5**15 + 8789062500000: 8789062500000, + 8789062500000 + 1: 8789062500000, + 8789062500000 - 1: 8748000000000, # 2**11 * 3**7 * 5**9 + # 2**24 * 3**9 * 5**4 + 206391214080000: 206391214080000, + 206391214080000 + 1: 206391214080000, + 206391214080000 - 1: 206158430208000, # 2**39 * 3**1 * 5**3 + # 2**18 * 3**15 * 5**3 + 470184984576000: 470184984576000, + 470184984576000 + 1: 470184984576000, + 470184984576000 - 1: 469654673817600, # 2**33 * 3**7 **5**2 + # 2**25 * 3**16 * 5**1 + 7222041363087360: 7222041363087360, + 7222041363087360 + 1: 7222041363087360, + 7222041363087360 - 1: 7213895789838336, # 2**40 * 3**8 + # power of 5 5**23 + 11920928955078125: 11920928955078125, + 11920928955078125 + 1: 11920928955078125, + 11920928955078125 - 1: 11901557422080000, # 2**14 * 3**19 * 5**4 + # power of 3 3**34 + 16677181699666569: 16677181699666569, + 16677181699666569 + 1: 16677181699666569, + 16677181699666569 - 1: 16607531250000000, # 2**7 * 3**12 * 5**12 + # power of 2 2**54 + 18014398509481984: 18014398509481984, + 18014398509481984 + 1: 18014398509481984, + 18014398509481984 - 1: 18000000000000000, # 2**16 * 3**2 * 5**15 + # 2**20 * 3**1 * 5**14 + 19200000000000000: 19200000000000000, + 19200000000000000 + 1: 19200000000000000, + 19200000000000000 - 1: 19131876000000000, # 2**11 * 3**14 * 5**9 + # 2**58 + 288230376151711744: 288230376151711744, + 288230376151711744 + 1: 288230376151711744, + 288230376151711744 - 1: 288000000000000000, # 2**20 * 3**2 * 5**15 + # 2**5 * 3**10 * 5**16 + 288325195312500000: 288325195312500000, + 288325195312500000 + 1: 288325195312500000, + 288325195312500000 - 1: 288230376151711744, # 2**58 + } + for x, y in hams.items(): + assert_equal(prev_fast_len(x, True), y) + + def test_keyword_args(self): + assert prev_fast_len(11, real=True) == 10 + assert prev_fast_len(target=7, real=False) == 7 + + +@skip_xp_backends(cpu_only=True) +class Test_init_nd_shape_and_axes: + + def test_py_0d_defaults(self, xp): + x = xp.asarray(4) + shape = None + axes = None + + shape_expected = () + axes_expected = [] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_0d_defaults(self, xp): + x = xp.asarray(7.) + shape = None + axes = None + + shape_expected = () + axes_expected = [] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_py_1d_defaults(self, xp): + x = xp.asarray([1, 2, 3]) + shape = None + axes = None + + shape_expected = (3,) + axes_expected = [0] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_1d_defaults(self, xp): + x = xp.arange(0, 1, .1) + shape = None + axes = None + + shape_expected = (10,) + axes_expected = [0] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_py_2d_defaults(self, xp): + x = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8]]) + shape = None + axes = None + + shape_expected = (2, 4) + axes_expected = [0, 1] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_2d_defaults(self, xp): + x = xp.arange(0, 1, .1) + x = xp.reshape(x, (5, 2)) + shape = None + axes = None + + shape_expected = (5, 2) + axes_expected = [0, 1] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_defaults(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = None + axes = None + + shape_expected = (6, 2, 5, 3, 4) + axes_expected = [0, 1, 2, 3, 4] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_set_shape(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = [10, -1, -1, 1, 4] + axes = None + + shape_expected = (10, 2, 5, 1, 4) + axes_expected = [0, 1, 2, 3, 4] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_set_axes(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = None + axes = [4, 1, 2] + + shape_expected = (4, 2, 5) + axes_expected = [4, 1, 2] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_set_shape_axes(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = [10, -1, 2] + axes = [1, 0, 3] + + shape_expected = (10, 6, 2) + axes_expected = [1, 0, 3] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_shape_axes_subset(self, xp): + x = xp.zeros((2, 3, 4, 5)) + shape, axes = _init_nd_shape_and_axes(x, shape=(5, 5, 5), axes=None) + + assert shape == (5, 5, 5) + assert axes == [1, 2, 3] + + def test_errors(self, xp): + x = xp.zeros(1) + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=None, axes=[[1, 2], [3, 4]]) + + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=None, axes=[1., 2., 3., 4.]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + _init_nd_shape_and_axes(x, shape=None, axes=[1]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + _init_nd_shape_and_axes(x, shape=None, axes=[-2]) + + with assert_raises(ValueError, + match="all axes must be unique"): + _init_nd_shape_and_axes(x, shape=None, axes=[0, 0]) + + with assert_raises(ValueError, match="shape must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=[[1, 2], [3, 4]], axes=None) + + with assert_raises(ValueError, match="shape must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=[1., 2., 3., 4.], axes=None) + + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + _init_nd_shape_and_axes(xp.zeros([1, 1, 1, 1]), + shape=[1, 2, 3], axes=[1]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[0\]\) specified"): + _init_nd_shape_and_axes(x, shape=[0], axes=None) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[-2\]\) specified"): + _init_nd_shape_and_axes(x, shape=-2, axes=None) + + +class TestFFTShift: + + def test_definition(self, xp): + x = xp.asarray([0., 1, 2, 3, 4, -4, -3, -2, -1]) + y = xp.asarray([-4., -3, -2, -1, 0, 1, 2, 3, 4]) + xp_assert_close(fft.fftshift(x), y) + xp_assert_close(fft.ifftshift(y), x) + x = xp.asarray([0., 1, 2, 3, 4, -5, -4, -3, -2, -1]) + y = xp.asarray([-5., -4, -3, -2, -1, 0, 1, 2, 3, 4]) + xp_assert_close(fft.fftshift(x), y) + xp_assert_close(fft.ifftshift(y), x) + + def test_inverse(self, xp): + for n in [1, 4, 9, 100, 211]: + x = xp.asarray(np.random.random((n,))) + xp_assert_close(fft.ifftshift(fft.fftshift(x)), x) + + def test_axes_keyword(self, xp): + freqs = xp.asarray([[0., 1, 2], [3, 4, -4], [-3, -2, -1]]) + shifted = xp.asarray([[-1., -3, -2], [2, 0, 1], [-4, 3, 4]]) + xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shifted) + xp_assert_close(fft.fftshift(freqs, axes=0), fft.fftshift(freqs, axes=(0,))) + xp_assert_close(fft.ifftshift(shifted, axes=(0, 1)), freqs) + xp_assert_close(fft.ifftshift(shifted, axes=0), + fft.ifftshift(shifted, axes=(0,))) + xp_assert_close(fft.fftshift(freqs), shifted) + xp_assert_close(fft.ifftshift(shifted), freqs) + + def test_uneven_dims(self, xp): + """ Test 2D input, which has uneven dimension sizes """ + freqs = xp.asarray([ + [0, 1], + [2, 3], + [4, 5] + ], dtype=xp.float64) + + # shift in dimension 0 + shift_dim0 = xp.asarray([ + [4, 5], + [0, 1], + [2, 3] + ], dtype=xp.float64) + xp_assert_close(fft.fftshift(freqs, axes=0), shift_dim0) + xp_assert_close(fft.ifftshift(shift_dim0, axes=0), freqs) + xp_assert_close(fft.fftshift(freqs, axes=(0,)), shift_dim0) + xp_assert_close(fft.ifftshift(shift_dim0, axes=[0]), freqs) + + # shift in dimension 1 + shift_dim1 = xp.asarray([ + [1, 0], + [3, 2], + [5, 4] + ], dtype=xp.float64) + xp_assert_close(fft.fftshift(freqs, axes=1), shift_dim1) + xp_assert_close(fft.ifftshift(shift_dim1, axes=1), freqs) + + # shift in both dimensions + shift_dim_both = xp.asarray([ + [5, 4], + [1, 0], + [3, 2] + ], dtype=xp.float64) + xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs) + xp_assert_close(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs) + + # axes=None (default) shift in all dimensions + xp_assert_close(fft.fftshift(freqs, axes=None), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both, axes=None), freqs) + xp_assert_close(fft.fftshift(freqs), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both), freqs) + + +class TestFFTFreq: + def test_definition(self, xp): + x = xp.asarray([0, 1, 2, 3, 4, -4, -3, -2, -1], dtype=xp.float64) + x2 = xp.asarray([0, 1, 2, 3, 4, -5, -4, -3, -2, -1], dtype=xp.float64) + + # default dtype varies across backends + + y = 9 * fft.fftfreq(9, xp=xp) + xp_assert_close(y, x, check_dtype=False, check_namespace=True) + + y = 9 * xp.pi * fft.fftfreq(9, xp.pi, xp=xp) + xp_assert_close(y, x, check_dtype=False) + + y = 10 * fft.fftfreq(10, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + y = 10 * xp.pi * fft.fftfreq(10, xp.pi, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + def test_device(self, xp, devices): + for d in devices: + y = fft.fftfreq(9, xp=xp, device=d) + x = xp.empty(0, device=d) + assert xp_device(y) == xp_device(x) + + +class TestRFFTFreq: + + def test_definition(self, xp): + x = xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64) + x2 = xp.asarray([0, 1, 2, 3, 4, 5], dtype=xp.float64) + + # default dtype varies across backends + + y = 9 * fft.rfftfreq(9, xp=xp) + xp_assert_close(y, x, check_dtype=False, check_namespace=True) + + y = 9 * xp.pi * fft.rfftfreq(9, xp.pi, xp=xp) + xp_assert_close(y, x, check_dtype=False) + + y = 10 * fft.rfftfreq(10, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + y = 10 * xp.pi * fft.rfftfreq(10, xp.pi, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + def test_device(self, xp, devices): + for d in devices: + y = fft.rfftfreq(9, xp=xp, device=d) + x = xp.empty(0, device=d) + assert xp_device(y) == xp_device(x) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_multithreading.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_multithreading.py new file mode 100644 index 0000000000000000000000000000000000000000..eddaccf8b063ba0cd1a3727c871bd5df7422f99d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_multithreading.py @@ -0,0 +1,84 @@ +from scipy import fft +import numpy as np +import pytest +from numpy.testing import assert_allclose +import multiprocessing +import os + + +@pytest.fixture(scope='module') +def x(): + return np.random.randn(512, 128) # Must be large enough to qualify for mt + + +@pytest.mark.parametrize("func", [ + fft.fft, fft.ifft, fft.fft2, fft.ifft2, fft.fftn, fft.ifftn, + fft.rfft, fft.irfft, fft.rfft2, fft.irfft2, fft.rfftn, fft.irfftn, + fft.hfft, fft.ihfft, fft.hfft2, fft.ihfft2, fft.hfftn, fft.ihfftn, + fft.dct, fft.idct, fft.dctn, fft.idctn, + fft.dst, fft.idst, fft.dstn, fft.idstn, +]) +@pytest.mark.parametrize("workers", [2, -1]) +def test_threaded_same(x, func, workers): + expected = func(x, workers=1) + actual = func(x, workers=workers) + assert_allclose(actual, expected) + + +def _mt_fft(x): + return fft.fft(x, workers=2) + + +@pytest.mark.slow +def test_mixed_threads_processes(x): + # Test that the fft threadpool is safe to use before & after fork + + expect = fft.fft(x, workers=2) + + with multiprocessing.Pool(2) as p: + res = p.map(_mt_fft, [x for _ in range(4)]) + + for r in res: + assert_allclose(r, expect) + + fft.fft(x, workers=2) + + +def test_invalid_workers(x): + cpus = os.cpu_count() + + fft.ifft([1], workers=-cpus) + + with pytest.raises(ValueError, match='workers must not be zero'): + fft.fft(x, workers=0) + + with pytest.raises(ValueError, match='workers value out of range'): + fft.ifft(x, workers=-cpus-1) + + +def test_set_get_workers(): + cpus = os.cpu_count() + assert fft.get_workers() == 1 + with fft.set_workers(4): + assert fft.get_workers() == 4 + + with fft.set_workers(-1): + assert fft.get_workers() == cpus + + assert fft.get_workers() == 4 + + assert fft.get_workers() == 1 + + with fft.set_workers(-cpus): + assert fft.get_workers() == 1 + + +def test_set_workers_invalid(): + + with pytest.raises(ValueError, match='workers must not be zero'): + with fft.set_workers(0): + pass + + with pytest.raises(ValueError, match='workers value out of range'): + with fft.set_workers(-os.cpu_count()-1): + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_real_transforms.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_real_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..de83cfa64ea235ba13328cfe499c0dac7ddb2df4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fft/tests/test_real_transforms.py @@ -0,0 +1,249 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal +import pytest +import math + +from scipy.fft import dct, idct, dctn, idctn, dst, idst, dstn, idstn +import scipy.fft as fft +from scipy import fftpack +from scipy._lib._array_api import (xp_copy, xp_assert_close, make_xp_test_case, + make_xp_pytest_param) +import scipy._lib.array_api_extra as xpx + +skip_xp_backends = pytest.mark.skip_xp_backends + +SQRT_2 = math.sqrt(2) + +# scipy.fft wraps the fftpack versions but with normalized inverse transforms. +# So, the forward transforms and definitions are already thoroughly tested in +# fftpack/test_real_transforms.py + + +@pytest.mark.parametrize("forward, backward", [make_xp_pytest_param(dct, idct), + make_xp_pytest_param(dst, idst)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("n", [2, 3, 4, 5, 10, 16]) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("orthogonalize", [False, True]) +def test_identity_1d(forward, backward, type, n, axis, norm, orthogonalize, xp): + # Test the identity f^-1(f(x)) == x + x = xp.asarray(np.random.rand(n, n)) + + y = forward(x, type, axis=axis, norm=norm, orthogonalize=orthogonalize) + z = backward(y, type, axis=axis, norm=norm, orthogonalize=orthogonalize) + xp_assert_close(z, x) + + pad = [(0, 0)] * 2 + pad[axis] = (0, 4) + + y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge')) + z2 = backward(y2, type, n, axis, norm, orthogonalize=orthogonalize) + xp_assert_close(z2, x) + + +@skip_xp_backends(np_only=True, + reason='`overwrite_x` only supported for NumPy backend.') +@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64, + np.complex64, np.complex128]) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("overwrite_x", [True, False]) +def test_identity_1d_overwrite(forward, backward, type, dtype, axis, norm, + overwrite_x, xp): + # Test the identity f^-1(f(x)) == x + x = np.random.rand(7, 8).astype(dtype) + x_orig = x.copy() + + y = forward(x, type, axis=axis, norm=norm, overwrite_x=overwrite_x) + y_orig = y.copy() + z = backward(y, type, axis=axis, norm=norm, overwrite_x=overwrite_x) + if not overwrite_x: + assert_allclose(z, x, rtol=1e-6, atol=1e-6) + assert_array_equal(x, x_orig) + assert_array_equal(y, y_orig) + else: + assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6) + + +@pytest.mark.parametrize("forward, backward", [make_xp_pytest_param(dctn, idctn), + make_xp_pytest_param(dstn, idstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("shape, axes", + [ + ((4, 4), 0), + ((4, 4), 1), + ((4, 4), None), + ((4, 4), (0, 1)), + ((10, 12), None), + ((10, 12), (0, 1)), + ((4, 5, 6), None), + ((4, 5, 6), 1), + ((4, 5, 6), (0, 2)), + ]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("orthogonalize", [False, True]) +def test_identity_nd(forward, backward, type, shape, axes, norm, + orthogonalize, xp): + # Test the identity f^-1(f(x)) == x + + x = xp.asarray(np.random.random(shape)) + + if axes is not None: + shape = np.take(shape, axes) + + y = forward(x, type, axes=axes, norm=norm, orthogonalize=orthogonalize) + z = backward(y, type, axes=axes, norm=norm, orthogonalize=orthogonalize) + xp_assert_close(z, x) + + if axes is None: + pad = [(0, 4)] * x.ndim + elif isinstance(axes, int): + pad = [(0, 0)] * x.ndim + pad[axes] = (0, 4) + else: + pad = [(0, 0)] * x.ndim + + for a in axes: + pad[a] = (0, 4) + + # TODO write an array-agnostic pad + y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge')) + z2 = backward(y2, type, shape, axes, norm, orthogonalize=orthogonalize) + xp_assert_close(z2, x) + + +@skip_xp_backends(np_only=True, + reason='`overwrite_x` only supported for NumPy backend.') +@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("shape, axes", + [ + ((4, 5), 0), + ((4, 5), 1), + ((4, 5), None), + ]) +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64, + np.complex64, np.complex128]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("overwrite_x", [False, True]) +def test_identity_nd_overwrite(forward, backward, type, shape, axes, dtype, + norm, overwrite_x, xp): + # Test the identity f^-1(f(x)) == x + + x = np.random.random(shape).astype(dtype) + x_orig = x.copy() + + if axes is not None: + shape = np.take(shape, axes) + + y = forward(x, type, axes=axes, norm=norm) + y_orig = y.copy() + z = backward(y, type, axes=axes, norm=norm) + if overwrite_x: + assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6) + else: + assert_allclose(z, x, rtol=1e-6, atol=1e-6) + assert_array_equal(x, x_orig) + assert_array_equal(y, y_orig) + + +@pytest.mark.parametrize("func", [make_xp_pytest_param(dct), + make_xp_pytest_param(dst), + make_xp_pytest_param(dctn), + make_xp_pytest_param(dstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +def test_fftpack_equivalience(func, type, norm, xp): + x = np.random.rand(8, 16) + fftpack_res = xp.asarray(getattr(fftpack, func.__name__)(x, type, norm=norm)) + x = xp.asarray(x) + fft_res = getattr(fft, func.__name__)(x, type, norm=norm) + + xp_assert_close(fft_res, fftpack_res) + + +@pytest.mark.parametrize("func", [make_xp_pytest_param(dct), + make_xp_pytest_param(dst), + make_xp_pytest_param(dctn), + make_xp_pytest_param(dstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +def test_orthogonalize_default(func, type, xp): + # Test orthogonalize is the default when norm="ortho", but not otherwise + x = xp.asarray(np.random.rand(100)) + + for norm, ortho in [ + ("forward", False), + ("backward", False), + ("ortho", True), + ]: + a = func(x, type=type, norm=norm, orthogonalize=ortho) + b = func(x, type=type, norm=norm) + xp_assert_close(a, b) + + +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func, type", [make_xp_pytest_param(dct, 4), + make_xp_pytest_param(dst, 1), + make_xp_pytest_param(dst, 4)]) +def test_orthogonalize_noop(func, type, norm, xp): + # Transforms where orthogonalize is a no-op + x = xp.asarray(np.random.rand(100)) + y1 = func(x, type=type, norm=norm, orthogonalize=True) + y2 = func(x, type=type, norm=norm, orthogonalize=False) + xp_assert_close(y1, y2) + + +@make_xp_test_case(dct) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +def test_orthogonalize_dct1(norm, xp): + x = xp.asarray(np.random.rand(100)) + + x2 = xp_copy(x, xp=xp) + xpx.at(x2, 0).multiply(SQRT_2) + xpx.at(x2, -1).multiply(SQRT_2) + + y1 = dct(x, type=1, norm=norm, orthogonalize=True) + y2 = dct(x2, type=1, norm=norm, orthogonalize=False) + + xpx.at(y2, 0).divide(SQRT_2) + xpx.at(y2, -1).divide(SQRT_2) + xp_assert_close(y1, y2) + + + +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func", [make_xp_pytest_param(dct), + make_xp_pytest_param(dst)]) +def test_orthogonalize_dcst2(func, norm, xp): + x = xp.asarray(np.random.rand(100)) + y1 = func(x, type=2, norm=norm, orthogonalize=True) + y2 = func(x, type=2, norm=norm, orthogonalize=False) + + xpx.at(y2, 0 if func.__name__ == "dct" else -1).divide(SQRT_2) + xp_assert_close(y1, y2) + + +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func", [make_xp_pytest_param(dct), + make_xp_pytest_param(dst)]) +def test_orthogonalize_dcst3(func, norm, xp): + x = xp.asarray(np.random.rand(100)) + x2 = xp_copy(x, xp=xp) + xpx.at(x2, 0 if func.__name__ == "dct" else -1).multiply(SQRT_2) + + y1 = func(x, type=3, norm=norm, orthogonalize=True) + y2 = func(x2, type=3, norm=norm, orthogonalize=False) + xp_assert_close(y1, y2) + + +@skip_xp_backends(np_only=True, + reason='array-likes only supported for NumPy backend') +@pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn]) +def test_array_like(xp, func): + x = [[[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]]] + xp_assert_close(func(x), func(xp.asarray(x))) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d6305de6d0d806fae72068dd0ae4b52800355a1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc14858b4a4b392c0793d4f2cc972dbb55ccbc77 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_helper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_helper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b39db02620b2320f6bc80f9e158ca209b4217d02 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_helper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37fc4345bd70ba26e2920ea7ef5f07a3c34c0642 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cb40e037affe0c35a1f92a22e4eea81f9e30aee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ee9564f0360ddfffc1a0f86b48f0babaf95db2f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/helper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/helper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d21582379990ec04e195c796f98b758917babfb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/helper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da47db75e6ff5749e91c9e24587dd441609e7d00 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f4daf4b17b603e8d0df558b26e546c2f639af91 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dbff5c7aebab1ae877f96b2ec647502625ec1db Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..063cf9ca50ebd349da6f6980c68f8ff3b17695b0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdfa55223461e5d778918e58874f2b3610d131bc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dbd935998baf9248d9627f872a6025b1f7b9c87 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d250d4cd4b01b3c8820a9d3f01fd004d34c93de Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..800a594266a39e33245d2094e1092102da33b1a5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_basic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..dd4879aa874cca8526d06bfa37378878939a7382 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_basic.py @@ -0,0 +1,877 @@ +# Created by Pearu Peterson, September 2002 + +from numpy.testing import (assert_, assert_equal, assert_array_almost_equal, + assert_array_almost_equal_nulp, assert_array_less) +import pytest +from pytest import raises as assert_raises +from scipy.fftpack import ifft, fft, fftn, ifftn, rfft, irfft, fft2 + +from numpy import (arange, array, asarray, zeros, dot, exp, pi, + swapaxes, double, cdouble) +import numpy as np +import numpy.fft +from numpy.random import rand + +# "large" composite numbers supported by FFTPACK +LARGE_COMPOSITE_SIZES = [ + 2**13, + 2**5 * 3**5, + 2**3 * 3**3 * 5**2, +] +SMALL_COMPOSITE_SIZES = [ + 2, + 2*3*5, + 2*2*3*3, +] +# prime +LARGE_PRIME_SIZES = [ + 2011 +] +SMALL_PRIME_SIZES = [ + 29 +] + + +def _assert_close_in_norm(x, y, rtol, size, rdt): + # helper function for testing + err_msg = f"size: {size} rdt: {rdt}" + assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg) + + +def random(size): + return rand(*size) + + +def direct_dft(x): + x = asarray(x) + n = len(x) + y = zeros(n, dtype=cdouble) + w = -arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w), x) + return y + + +def direct_idft(x): + x = asarray(x) + n = len(x) + y = zeros(n, dtype=cdouble) + w = arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w), x)/n + return y + + +def direct_dftn(x): + x = asarray(x) + for axis in range(len(x.shape)): + x = fft(x, axis=axis) + return x + + +def direct_idftn(x): + x = asarray(x) + for axis in range(len(x.shape)): + x = ifft(x, axis=axis) + return x + + +def direct_rdft(x): + x = asarray(x) + n = len(x) + w = -arange(n)*(2j*pi/n) + r = zeros(n, dtype=double) + for i in range(n//2+1): + y = dot(exp(i*w), x) + if i: + r[2*i-1] = y.real + if 2*i < n: + r[2*i] = y.imag + else: + r[0] = y.real + return r + + +def direct_irdft(x): + x = asarray(x) + n = len(x) + x1 = zeros(n, dtype=cdouble) + for i in range(n//2+1): + if i: + if 2*i < n: + x1[i] = x[2*i-1] + 1j*x[2*i] + x1[n-i] = x[2*i-1] - 1j*x[2*i] + else: + x1[i] = x[2*i-1] + else: + x1[0] = x[0] + return direct_idft(x1).real + + +class _TestFFTBase: + def setup_method(self): + self.cdt = None + self.rdt = None + np.random.seed(1234) + + def test_definition(self): + x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt) + y = fft(x) + assert_equal(y.dtype, self.cdt) + y1 = direct_dft(x) + assert_array_almost_equal(y,y1) + x = np.array([1,2,3,4+0j,5], dtype=self.cdt) + assert_array_almost_equal(fft(x),direct_dft(x)) + + def test_n_argument_real(self): + x1 = np.array([1,2,3,4], dtype=self.rdt) + x2 = np.array([1,2,3,4], dtype=self.rdt) + y = fft([x1,x2],n=4) + assert_equal(y.dtype, self.cdt) + assert_equal(y.shape,(2,4)) + assert_array_almost_equal(y[0],direct_dft(x1)) + assert_array_almost_equal(y[1],direct_dft(x2)) + + def _test_n_argument_complex(self): + x1 = np.array([1,2,3,4+1j], dtype=self.cdt) + x2 = np.array([1,2,3,4+1j], dtype=self.cdt) + y = fft([x1,x2],n=4) + assert_equal(y.dtype, self.cdt) + assert_equal(y.shape,(2,4)) + assert_array_almost_equal(y[0],direct_dft(x1)) + assert_array_almost_equal(y[1],direct_dft(x2)) + + def test_invalid_sizes(self): + assert_raises(ValueError, fft, []) + assert_raises(ValueError, fft, [[1,1],[2,2]], -5) + + +class TestDoubleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + + +class TestSingleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + + reason = ("single-precision FFT implementation is partially disabled, " + "until accuracy issues with large prime powers are resolved") + + @pytest.mark.xfail(run=False, reason=reason) + def test_notice(self): + pass + + +class TestFloat16FFT: + + def test_1_argument_real(self): + x1 = np.array([1, 2, 3, 4], dtype=np.float16) + y = fft(x1, n=4) + assert_equal(y.dtype, np.complex64) + assert_equal(y.shape, (4, )) + assert_array_almost_equal(y, direct_dft(x1.astype(np.float32))) + + def test_n_argument_real(self): + x1 = np.array([1, 2, 3, 4], dtype=np.float16) + x2 = np.array([1, 2, 3, 4], dtype=np.float16) + y = fft([x1, x2], n=4) + assert_equal(y.dtype, np.complex64) + assert_equal(y.shape, (2, 4)) + assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32))) + assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32))) + + +class _TestIFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt) + y = ifft(x) + y1 = direct_idft(x) + assert_equal(y.dtype, self.cdt) + assert_array_almost_equal(y,y1) + + x = np.array([1,2,3,4+0j,5], self.cdt) + assert_array_almost_equal(ifft(x),direct_idft(x)) + + def test_definition_real(self): + x = np.array([1,2,3,4,1,2,3,4], self.rdt) + y = ifft(x) + assert_equal(y.dtype, self.cdt) + y1 = direct_idft(x) + assert_array_almost_equal(y,y1) + + x = np.array([1,2,3,4,5], dtype=self.rdt) + assert_equal(y.dtype, self.cdt) + assert_array_almost_equal(ifft(x),direct_idft(x)) + + def test_random_complex(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.cdt) + x = random([size]).astype(self.cdt) + 1j*x + y1 = ifft(fft(x)) + y2 = fft(ifft(x)) + assert_equal(y1.dtype, self.cdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x) + assert_array_almost_equal(y2, x) + + def test_random_real(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.rdt) + y1 = ifft(fft(x)) + y2 = fft(ifft(x)) + assert_equal(y1.dtype, self.cdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x) + assert_array_almost_equal(y2, x) + + def test_size_accuracy(self): + # Sanity check for the accuracy for prime and non-prime sized inputs + if self.rdt == np.float32: + rtol = 1e-5 + elif self.rdt == np.float64: + rtol = 1e-10 + + for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: + np.random.seed(1234) + x = np.random.rand(size).astype(self.rdt) + y = ifft(fft(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + y = fft(ifft(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + + x = (x + 1j*np.random.rand(size)).astype(self.cdt) + y = ifft(fft(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + y = fft(ifft(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + + def test_invalid_sizes(self): + assert_raises(ValueError, ifft, []) + assert_raises(ValueError, ifft, [[1,1],[2,2]], -5) + + +class TestDoubleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + + +class TestSingleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + + +class _TestRFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]: + x = np.array(t, dtype=self.rdt) + y = rfft(x) + y1 = direct_rdft(x) + assert_array_almost_equal(y,y1) + assert_equal(y.dtype, self.rdt) + + def test_invalid_sizes(self): + assert_raises(ValueError, rfft, []) + assert_raises(ValueError, rfft, [[1,1],[2,2]], -5) + + # See gh-5790 + class MockSeries: + def __init__(self, data): + self.data = np.asarray(data) + + def __getattr__(self, item): + try: + return getattr(self.data, item) + except AttributeError as e: + raise AttributeError("'MockSeries' object " + f"has no attribute '{item}'") from e + + def test_non_ndarray_with_dtype(self): + x = np.array([1., 2., 3., 4., 5.]) + xs = _TestRFFTBase.MockSeries(x) + + expected = [1, 2, 3, 4, 5] + rfft(xs) + + # Data should not have been overwritten + assert_equal(x, expected) + assert_equal(xs.data, expected) + + def test_complex_input(self): + assert_raises(TypeError, rfft, np.arange(4, dtype=np.complex64)) + + +class TestRFFTDouble(_TestRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + + +class TestRFFTSingle(_TestRFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + + +class _TestIRFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x1 = [1,2,3,4,1,2,3,4] + x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j] + x2 = [1,2,3,4,1,2,3,4,5] + x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j] + + def _test(x, xr): + y = irfft(np.array(x, dtype=self.rdt)) + y1 = direct_irdft(x) + assert_equal(y.dtype, self.rdt) + assert_array_almost_equal(y,y1, decimal=self.ndec) + assert_array_almost_equal(y,ifft(xr), decimal=self.ndec) + + _test(x1, x1_1) + _test(x2, x2_1) + + def test_random_real(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.rdt) + y1 = irfft(rfft(x)) + y2 = rfft(irfft(x)) + assert_equal(y1.dtype, self.rdt) + assert_equal(y2.dtype, self.rdt) + assert_array_almost_equal(y1, x, decimal=self.ndec, err_msg=f"size={size}") + assert_array_almost_equal(y2, x, decimal=self.ndec, err_msg=f"size={size}") + + def test_size_accuracy(self): + # Sanity check for the accuracy for prime and non-prime sized inputs + if self.rdt == np.float32: + rtol = 1e-5 + elif self.rdt == np.float64: + rtol = 1e-10 + + for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: + np.random.seed(1234) + x = np.random.rand(size).astype(self.rdt) + y = irfft(rfft(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + y = rfft(irfft(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + + def test_invalid_sizes(self): + assert_raises(ValueError, irfft, []) + assert_raises(ValueError, irfft, [[1,1],[2,2]], -5) + + def test_complex_input(self): + assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64)) + + +# self.ndec is bogus; we should have a assert_array_approx_equal for number of +# significant digits + +class TestIRFFTDouble(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + self.ndec = 14 + + +class TestIRFFTSingle(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + self.ndec = 5 + + +class Testfft2: + def setup_method(self): + np.random.seed(1234) + + def test_regression_244(self): + """FFT returns wrong result with axes parameter.""" + # fftn (and hence fft2) used to break when both axes and shape were + # used + x = numpy.ones((4, 4, 2)) + y = fft2(x, shape=(8, 8), axes=(-3, -2)) + y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2)) + assert_array_almost_equal(y, y_r) + + def test_invalid_sizes(self): + assert_raises(ValueError, fft2, [[]]) + assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3)) + + +class TestFftnSingle: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(np.array(x, np.float32)) + assert_(y.dtype == np.complex64, + msg="double precision output with single precision") + + y_r = np.array(fftn(x), np.complex64) + assert_array_almost_equal_nulp(y, y_r) + + @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES) + def test_size_accuracy_small(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, size)) + 1j*rng.random((size, size)) + y1 = fftn(x.real.astype(np.float32)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2000) + + @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES) + def test_size_accuracy_large(self, size): + rand = np.random.default_rng(1234) + x = rand.random((size, 3)) + 1j*rand.random((size, 3)) + y1 = fftn(x.real.astype(np.float32)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2000) + + def test_definition_float16(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(np.array(x, np.float16)) + assert_equal(y.dtype, np.complex64) + y_r = np.array(fftn(x), np.complex64) + assert_array_almost_equal_nulp(y, y_r) + + @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES) + def test_float16_input_small(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, size)) + 1j * rng.random((size, size)) + y1 = fftn(x.real.astype(np.float16)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 5e5) + + @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES) + def test_float16_input_large(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, 3)) + 1j*rng.random((size, 3)) + y1 = fftn(x.real.astype(np.float16)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2e6) + + +class TestFftn: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(x) + assert_array_almost_equal(y, direct_dftn(x)) + + x = random((20, 26)) + assert_array_almost_equal(fftn(x), direct_dftn(x)) + + x = random((5, 4, 3, 20)) + assert_array_almost_equal(fftn(x), direct_dftn(x)) + + def test_axes_argument(self): + # plane == ji_plane, x== kji_space + plane1 = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + plane2 = [[10, 11, 12], + [13, 14, 15], + [16, 17, 18]] + plane3 = [[19, 20, 21], + [22, 23, 24], + [25, 26, 27]] + ki_plane1 = [[1, 2, 3], + [10, 11, 12], + [19, 20, 21]] + ki_plane2 = [[4, 5, 6], + [13, 14, 15], + [22, 23, 24]] + ki_plane3 = [[7, 8, 9], + [16, 17, 18], + [25, 26, 27]] + jk_plane1 = [[1, 10, 19], + [4, 13, 22], + [7, 16, 25]] + jk_plane2 = [[2, 11, 20], + [5, 14, 23], + [8, 17, 26]] + jk_plane3 = [[3, 12, 21], + [6, 15, 24], + [9, 18, 27]] + kj_plane1 = [[1, 4, 7], + [10, 13, 16], [19, 22, 25]] + kj_plane2 = [[2, 5, 8], + [11, 14, 17], [20, 23, 26]] + kj_plane3 = [[3, 6, 9], + [12, 15, 18], [21, 24, 27]] + ij_plane1 = [[1, 4, 7], + [2, 5, 8], + [3, 6, 9]] + ij_plane2 = [[10, 13, 16], + [11, 14, 17], + [12, 15, 18]] + ij_plane3 = [[19, 22, 25], + [20, 23, 26], + [21, 24, 27]] + ik_plane1 = [[1, 10, 19], + [2, 11, 20], + [3, 12, 21]] + ik_plane2 = [[4, 13, 22], + [5, 14, 23], + [6, 15, 24]] + ik_plane3 = [[7, 16, 25], + [8, 17, 26], + [9, 18, 27]] + ijk_space = [jk_plane1, jk_plane2, jk_plane3] + ikj_space = [kj_plane1, kj_plane2, kj_plane3] + jik_space = [ik_plane1, ik_plane2, ik_plane3] + jki_space = [ki_plane1, ki_plane2, ki_plane3] + kij_space = [ij_plane1, ij_plane2, ij_plane3] + x = array([plane1, plane2, plane3]) + + assert_array_almost_equal(fftn(x), + fftn(x, axes=(-3, -2, -1))) # kji_space + assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2))) + assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1))) + y = fftn(x, axes=(2, 1, 0)) # ijk_space + assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space)) + y = fftn(x, axes=(2, 0, 1)) # ikj_space + assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2), + fftn(ikj_space)) + y = fftn(x, axes=(1, 2, 0)) # jik_space + assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2), + fftn(jik_space)) + y = fftn(x, axes=(1, 0, 2)) # jki_space + assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space)) + y = fftn(x, axes=(0, 2, 1)) # kij_space + assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space)) + + y = fftn(x, axes=(-2, -1)) # ji_plane + assert_array_almost_equal(fftn(plane1), y[0]) + assert_array_almost_equal(fftn(plane2), y[1]) + assert_array_almost_equal(fftn(plane3), y[2]) + + y = fftn(x, axes=(1, 2)) # ji_plane + assert_array_almost_equal(fftn(plane1), y[0]) + assert_array_almost_equal(fftn(plane2), y[1]) + assert_array_almost_equal(fftn(plane3), y[2]) + + y = fftn(x, axes=(-3, -2)) # kj_plane + assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0]) + assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1]) + assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2]) + + y = fftn(x, axes=(-3, -1)) # ki_plane + assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :]) + assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :]) + assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :]) + + y = fftn(x, axes=(-1, -2)) # ij_plane + assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1)) + assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1)) + assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1)) + + y = fftn(x, axes=(-1, -3)) # ik_plane + assert_array_almost_equal(fftn(ik_plane1), + swapaxes(y[:, 0, :], -1, -2)) + assert_array_almost_equal(fftn(ik_plane2), + swapaxes(y[:, 1, :], -1, -2)) + assert_array_almost_equal(fftn(ik_plane3), + swapaxes(y[:, 2, :], -1, -2)) + + y = fftn(x, axes=(-2, -3)) # jk_plane + assert_array_almost_equal(fftn(jk_plane1), + swapaxes(y[:, :, 0], -1, -2)) + assert_array_almost_equal(fftn(jk_plane2), + swapaxes(y[:, :, 1], -1, -2)) + assert_array_almost_equal(fftn(jk_plane3), + swapaxes(y[:, :, 2], -1, -2)) + + y = fftn(x, axes=(-1,)) # i_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :]) + y = fftn(x, axes=(-2,)) # j_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j]) + y = fftn(x, axes=(0,)) # k_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j]) + + y = fftn(x, axes=()) # point + assert_array_almost_equal(y, x) + + def test_shape_argument(self): + small_x = [[1, 2, 3], + [4, 5, 6]] + large_x1 = [[1, 2, 3, 0], + [4, 5, 6, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]] + + y = fftn(small_x, shape=(4, 4)) + assert_array_almost_equal(y, fftn(large_x1)) + + y = fftn(small_x, shape=(3, 4)) + assert_array_almost_equal(y, fftn(large_x1[:-1])) + + def test_shape_axes_argument(self): + small_x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + large_x1 = array([[1, 2, 3, 0], + [4, 5, 6, 0], + [7, 8, 9, 0], + [0, 0, 0, 0]]) + y = fftn(small_x, shape=(4, 4), axes=(-2, -1)) + assert_array_almost_equal(y, fftn(large_x1)) + y = fftn(small_x, shape=(4, 4), axes=(-1, -2)) + + assert_array_almost_equal(y, swapaxes( + fftn(swapaxes(large_x1, -1, -2)), -1, -2)) + + def test_shape_axes_argument2(self): + # Change shape of the last axis + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-1,), shape=(8,)) + assert_array_almost_equal(y, fft(x, axis=-1, n=8)) + + # Change shape of an arbitrary axis which is not the last one + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-2,), shape=(8,)) + assert_array_almost_equal(y, fft(x, axis=-2, n=8)) + + # Change shape of axes: cf #244, where shape and axes were mixed up + x = numpy.random.random((4, 4, 2)) + y = fftn(x, axes=(-3, -2), shape=(8, 8)) + assert_array_almost_equal(y, + numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8))) + + def test_shape_argument_more(self): + x = zeros((4, 4, 2)) + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fftn(x, shape=(8, 8, 2, 1)) + + def test_invalid_sizes(self): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + fftn([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + fftn([[1, 1], [2, 2]], (4, -3)) + + +class TestIfftn: + dtype = None + cdtype = None + + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.parametrize('dtype,cdtype,maxnlp', + [(np.float64, np.complex128, 2000), + (np.float32, np.complex64, 3500)]) + def test_definition(self, dtype, cdtype, maxnlp): + rng = np.random.default_rng(1234) + x = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], dtype=dtype) + y = ifftn(x) + assert_equal(y.dtype, cdtype) + assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp) + + x = rng.random((20, 26)) + assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp) + + x = rng.random((5, 4, 3, 20)) + assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp) + + @pytest.mark.parametrize('maxnlp', [2000, 3500]) + @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92]) + def test_random_complex(self, maxnlp, size): + rng = np.random.default_rng(1234) + x = rng.random([size, size]) + 1j * rng.random([size, size]) + assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp) + assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp) + + def test_invalid_sizes(self): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + ifftn([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + ifftn([[1, 1], [2, 2]], (4, -3)) + + +class FakeArray: + def __init__(self, data): + self._data = data + self.__array_interface__ = data.__array_interface__ + + +class FakeArray2: + def __init__(self, data): + self._data = data + + def __array__(self, dtype=None, copy=None): + return self._data + + +class TestOverwrite: + """Check input overwrite behavior of the FFT functions.""" + + real_dtypes = (np.float32, np.float64) + dtypes = real_dtypes + (np.complex64, np.complex128) + fftsizes = [8, 16, 32] + + def _check(self, x, routine, fftsize, axis, overwrite_x): + x2 = x.copy() + for fake in [lambda x: x, FakeArray, FakeArray2]: + routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x) + + sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, " + f"axis={axis!r}, overwrite_x={overwrite_x!r})") + if not overwrite_x: + assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}") + + def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes, + fftsize, overwrite_x): + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + data = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + data = np.random.randn(*shape) + data = data.astype(dtype) + + self._check(data, routine, fftsize, axis, + overwrite_x=overwrite_x) + + @pytest.mark.parametrize('dtype', dtypes) + @pytest.mark.parametrize('fftsize', fftsizes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), -1), + ((16, 2), 0), + ((2, 16), 1)]) + def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes): + overwritable = (np.complex128, np.complex64) + self._check_1d(fft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + self._check_1d(ifft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + + @pytest.mark.parametrize('dtype', real_dtypes) + @pytest.mark.parametrize('fftsize', fftsizes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), -1), + ((16, 2), 0), + ((2, 16), 1)]) + def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes): + overwritable = self.real_dtypes + self._check_1d(irfft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + self._check_1d(rfft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + + def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes, + overwrite_x): + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + data = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + data = np.random.randn(*shape) + data = data.astype(dtype) + + def fftshape_iter(shp): + if len(shp) <= 0: + yield () + else: + for j in (shp[0]//2, shp[0], shp[0]*2): + for rest in fftshape_iter(shp[1:]): + yield (j,) + rest + + if axes is None: + part_shape = shape + else: + part_shape = tuple(np.take(shape, axes)) + + for fftshape in fftshape_iter(part_shape): + self._check(data, routine, fftshape, axes, + overwrite_x=overwrite_x) + if data.ndim > 1: + self._check(data.T, routine, fftshape, axes, + overwrite_x=overwrite_x) + + @pytest.mark.parametrize('dtype', dtypes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), None), + ((16,), (0,)), + ((16, 2), (0,)), + ((2, 16), (1,)), + ((8, 16), None), + ((8, 16), (0, 1)), + ((8, 16, 2), (0, 1)), + ((8, 16, 2), (1, 2)), + ((8, 16, 2), (0,)), + ((8, 16, 2), (1,)), + ((8, 16, 2), (2,)), + ((8, 16, 2), None), + ((8, 16, 2), (0, 1, 2))]) + def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes): + overwritable = (np.complex128, np.complex64) + self._check_nd_one(fftn, dtype, shape, axes, overwritable, + overwrite_x) + self._check_nd_one(ifftn, dtype, shape, axes, overwritable, + overwrite_x) + + +@pytest.mark.parametrize('func', [fftn, ifftn, fft2]) +def test_shape_axes_ndarray(func): + # Test fftn and ifftn work with NumPy arrays for shape and axes arguments + # Regression test for gh-13342 + a = np.random.rand(10, 10) + + expect = func(a, shape=(5, 5)) + actual = func(a, shape=np.array([5, 5])) + assert_equal(expect, actual) + + expect = func(a, axes=(-1,)) + actual = func(a, axes=np.array([-1,])) + assert_equal(expect, actual) + + expect = func(a, shape=(4, 7), axes=(1, 0)) + actual = func(a, shape=np.array([4, 7]), axes=np.array([1, 0])) + assert_equal(expect, actual) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_helper.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..8ede3120ed3e434bb8019148e5689fdc168e4bc5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_helper.py @@ -0,0 +1,54 @@ +# Created by Pearu Peterson, September 2002 + +__usage__ = """ +Build fftpack: + python setup_fftpack.py build +Run tests if scipy is installed: + python -c 'import scipy;scipy.fftpack.test()' +Run tests if fftpack is not installed: + python tests/test_helper.py [] +""" + +from numpy.testing import assert_array_almost_equal +from scipy.fftpack import fftshift, ifftshift, fftfreq, rfftfreq + +from numpy import pi, random + +class TestFFTShift: + + def test_definition(self): + x = [0,1,2,3,4,-4,-3,-2,-1] + y = [-4,-3,-2,-1,0,1,2,3,4] + assert_array_almost_equal(fftshift(x),y) + assert_array_almost_equal(ifftshift(y),x) + x = [0,1,2,3,4,-5,-4,-3,-2,-1] + y = [-5,-4,-3,-2,-1,0,1,2,3,4] + assert_array_almost_equal(fftshift(x),y) + assert_array_almost_equal(ifftshift(y),x) + + def test_inverse(self): + for n in [1,4,9,100,211]: + x = random.random((n,)) + assert_array_almost_equal(ifftshift(fftshift(x)),x) + + +class TestFFTFreq: + + def test_definition(self): + x = [0,1,2,3,4,-4,-3,-2,-1] + assert_array_almost_equal(9*fftfreq(9),x) + assert_array_almost_equal(9*pi*fftfreq(9,pi),x) + x = [0,1,2,3,4,-5,-4,-3,-2,-1] + assert_array_almost_equal(10*fftfreq(10),x) + assert_array_almost_equal(10*pi*fftfreq(10,pi),x) + + +class TestRFFTFreq: + + def test_definition(self): + x = [0,1,1,2,2,3,3,4,4] + assert_array_almost_equal(9*rfftfreq(9),x) + assert_array_almost_equal(9*pi*rfftfreq(9,pi),x) + x = [0,1,1,2,2,3,3,4,4,5] + assert_array_almost_equal(10*rfftfreq(10),x) + assert_array_almost_equal(10*pi*rfftfreq(10,pi),x) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_import.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_import.py new file mode 100644 index 0000000000000000000000000000000000000000..3d2166b1f2e3eff94a82d103c6caa8b881522c84 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_import.py @@ -0,0 +1,33 @@ +"""Test possibility of patching fftpack with pyfftw. + +No module source outside of scipy.fftpack should contain an import of +the form `from scipy.fftpack import ...`, so that a simple replacement +of scipy.fftpack by the corresponding fftw interface completely swaps +the two FFT implementations. + +Because this simply inspects source files, we only need to run the test +on one version of Python. +""" + + +from pathlib import Path +import re +import tokenize +import pytest +from numpy.testing import assert_ +import scipy + +class TestFFTPackImport: + @pytest.mark.slow + def test_fftpack_import(self): + base = Path(scipy.__file__).parent + regexp = r"\s*from.+\.fftpack import .*\n" + for path in base.rglob("*.py"): + if base / "fftpack" in path.parents: + continue + # use tokenize to auto-detect encoding on systems where no + # default encoding is defined (e.g., LANG='C') + with tokenize.open(str(path)) as file: + assert_(all(not re.fullmatch(regexp, line) + for line in file), + f"{path} contains an import from fftpack") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py new file mode 100644 index 0000000000000000000000000000000000000000..b462663eff3d127715915e8167498974f3c00405 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py @@ -0,0 +1,388 @@ +# Created by Pearu Peterson, September 2002 + +__usage__ = """ +Build fftpack: + python setup_fftpack.py build +Run tests if scipy is installed: + python -c 'import scipy;scipy.fftpack.test()' +Run tests if fftpack is not installed: + python tests/test_pseudo_diffs.py [] +""" + +from numpy.testing import (assert_equal, assert_almost_equal, + assert_array_almost_equal) +from scipy.fftpack import (diff, fft, ifft, tilbert, itilbert, hilbert, + ihilbert, shift, fftfreq, cs_diff, sc_diff, + ss_diff, cc_diff) + +import numpy as np +from numpy import arange, sin, cos, pi, exp, tanh, sum, sign +from numpy.random import random + + +def direct_diff(x,k=1,period=None): + fx = fft(x) + n = len(fx) + if period is None: + period = 2*pi + w = fftfreq(n)*2j*pi/period*n + if k < 0: + w = 1 / w**k + w[0] = 0.0 + else: + w = w**k + if n > 2000: + w[250:n-250] = 0.0 + return ifft(w*fx).real + + +def direct_tilbert(x,h=1,period=None): + fx = fft(x) + n = len(fx) + if period is None: + period = 2*pi + w = fftfreq(n)*h*2*pi/period*n + w[0] = 1 + w = 1j/tanh(w) + w[0] = 0j + return ifft(w*fx) + + +def direct_itilbert(x,h=1,period=None): + fx = fft(x) + n = len(fx) + if period is None: + period = 2*pi + w = fftfreq(n)*h*2*pi/period*n + w = -1j*tanh(w) + return ifft(w*fx) + + +def direct_hilbert(x): + fx = fft(x) + n = len(fx) + w = fftfreq(n)*n + w = 1j*sign(w) + return ifft(w*fx) + + +def direct_ihilbert(x): + return -direct_hilbert(x) + + +def direct_shift(x,a,period=None): + n = len(x) + if period is None: + k = fftfreq(n)*1j*n + else: + k = fftfreq(n)*2j*pi/period*n + return ifft(fft(x)*exp(k*a)).real + + +class TestDiff: + + def test_definition(self): + for n in [16,17,64,127,32]: + x = arange(n)*2*pi/n + assert_array_almost_equal(diff(sin(x)),direct_diff(sin(x))) + assert_array_almost_equal(diff(sin(x),2),direct_diff(sin(x),2)) + assert_array_almost_equal(diff(sin(x),3),direct_diff(sin(x),3)) + assert_array_almost_equal(diff(sin(x),4),direct_diff(sin(x),4)) + assert_array_almost_equal(diff(sin(x),5),direct_diff(sin(x),5)) + assert_array_almost_equal(diff(sin(2*x),3),direct_diff(sin(2*x),3)) + assert_array_almost_equal(diff(sin(2*x),4),direct_diff(sin(2*x),4)) + assert_array_almost_equal(diff(cos(x)),direct_diff(cos(x))) + assert_array_almost_equal(diff(cos(x),2),direct_diff(cos(x),2)) + assert_array_almost_equal(diff(cos(x),3),direct_diff(cos(x),3)) + assert_array_almost_equal(diff(cos(x),4),direct_diff(cos(x),4)) + assert_array_almost_equal(diff(cos(2*x)),direct_diff(cos(2*x))) + assert_array_almost_equal(diff(sin(x*n/8)),direct_diff(sin(x*n/8))) + assert_array_almost_equal(diff(cos(x*n/8)),direct_diff(cos(x*n/8))) + for k in range(5): + assert_array_almost_equal(diff(sin(4*x),k),direct_diff(sin(4*x),k)) + assert_array_almost_equal(diff(cos(4*x),k),direct_diff(cos(4*x),k)) + + def test_period(self): + for n in [17,64]: + x = arange(n)/float(n) + assert_array_almost_equal(diff(sin(2*pi*x),period=1), + 2*pi*cos(2*pi*x)) + assert_array_almost_equal(diff(sin(2*pi*x),3,period=1), + -(2*pi)**3*cos(2*pi*x)) + + def test_sin(self): + for n in [32,64,77]: + x = arange(n)*2*pi/n + assert_array_almost_equal(diff(sin(x)),cos(x)) + assert_array_almost_equal(diff(cos(x)),-sin(x)) + assert_array_almost_equal(diff(sin(x),2),-sin(x)) + assert_array_almost_equal(diff(sin(x),4),sin(x)) + assert_array_almost_equal(diff(sin(4*x)),4*cos(4*x)) + assert_array_almost_equal(diff(sin(sin(x))),cos(x)*cos(sin(x))) + + def test_expr(self): + for n in [64,77,100,128,256,512,1024,2048,4096,8192][:5]: + x = arange(n)*2*pi/n + f = sin(x)*cos(4*x)+exp(sin(3*x)) + df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x)) + ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\ + - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x)) + d1 = diff(f) + assert_array_almost_equal(d1,df) + assert_array_almost_equal(diff(df),ddf) + assert_array_almost_equal(diff(f,2),ddf) + assert_array_almost_equal(diff(ddf,-1),df) + + def test_expr_large(self): + for n in [2048,4096]: + x = arange(n)*2*pi/n + f = sin(x)*cos(4*x)+exp(sin(3*x)) + df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x)) + ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\ + - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x)) + assert_array_almost_equal(diff(f),df) + assert_array_almost_equal(diff(df),ddf) + assert_array_almost_equal(diff(ddf,-1),df) + assert_array_almost_equal(diff(f,2),ddf) + + def test_int(self): + n = 64 + x = arange(n)*2*pi/n + assert_array_almost_equal(diff(sin(x),-1),-cos(x)) + assert_array_almost_equal(diff(sin(x),-2),-sin(x)) + assert_array_almost_equal(diff(sin(x),-4),sin(x)) + assert_array_almost_equal(diff(2*cos(2*x),-1),sin(2*x)) + + def test_random_even(self): + rng = np.random.default_rng(1234) + for k in [0,2,4,6]: + for n in [60,32,64,56,55]: + f = rng.random((n,)) + af = sum(f,axis=0)/n + f = f-af + # zeroing Nyquist mode: + f = diff(diff(f,1),-1) + assert_almost_equal(sum(f,axis=0),0.0) + assert_array_almost_equal(diff(diff(f,k),-k),f) + assert_array_almost_equal(diff(diff(f,-k),k),f) + + def test_random_odd(self): + rng = np.random.default_rng(1234) + for k in [0,1,2,3,4,5,6]: + for n in [33,65,55]: + f = rng.random((n,)) + af = sum(f,axis=0)/n + f = f-af + assert_almost_equal(sum(f,axis=0),0.0) + assert_array_almost_equal(diff(diff(f,k),-k),f) + assert_array_almost_equal(diff(diff(f,-k),k),f) + + def test_zero_nyquist(self): + rng = np.random.default_rng(1234) + for k in [0,1,2,3,4,5,6]: + for n in [32,33,64,56,55]: + f = rng.random((n,)) + af = sum(f,axis=0)/n + f = f-af + # zeroing Nyquist mode: + f = diff(diff(f,1),-1) + assert_almost_equal(sum(f,axis=0),0.0) + assert_array_almost_equal(diff(diff(f,k),-k),f) + assert_array_almost_equal(diff(diff(f,-k),k),f) + + +class TestTilbert: + + def test_definition(self): + for h in [0.1,0.5,1,5.5,10]: + for n in [16,17,64,127]: + x = arange(n)*2*pi/n + y = tilbert(sin(x),h) + y1 = direct_tilbert(sin(x),h) + assert_array_almost_equal(y,y1) + assert_array_almost_equal(tilbert(sin(x),h), + direct_tilbert(sin(x),h)) + assert_array_almost_equal(tilbert(sin(2*x),h), + direct_tilbert(sin(2*x),h)) + + def test_random_even(self): + for h in [0.1,0.5,1,5.5,10]: + for n in [32,64,56]: + f = random((n,)) + af = sum(f,axis=0)/n + f = f-af + assert_almost_equal(sum(f,axis=0),0.0) + assert_array_almost_equal(direct_tilbert(direct_itilbert(f,h),h),f) + + def test_random_odd(self): + rng = np.random.default_rng(1234) + for h in [0.1,0.5,1,5.5,10]: + for n in [33,65,55]: + f = rng.random((n,)) + af = sum(f,axis=0)/n + f = f-af + assert_almost_equal(sum(f,axis=0),0.0) + assert_array_almost_equal(itilbert(tilbert(f,h),h),f) + assert_array_almost_equal(tilbert(itilbert(f,h),h),f) + + +class TestITilbert: + + def test_definition(self): + for h in [0.1,0.5,1,5.5,10]: + for n in [16,17,64,127]: + x = arange(n)*2*pi/n + y = itilbert(sin(x),h) + y1 = direct_itilbert(sin(x),h) + assert_array_almost_equal(y,y1) + assert_array_almost_equal(itilbert(sin(x),h), + direct_itilbert(sin(x),h)) + assert_array_almost_equal(itilbert(sin(2*x),h), + direct_itilbert(sin(2*x),h)) + + +class TestHilbert: + + def test_definition(self): + for n in [16,17,64,127]: + x = arange(n)*2*pi/n + y = hilbert(sin(x)) + y1 = direct_hilbert(sin(x)) + assert_array_almost_equal(y,y1) + assert_array_almost_equal(hilbert(sin(2*x)), + direct_hilbert(sin(2*x))) + + def test_tilbert_relation(self): + for n in [16,17,64,127]: + x = arange(n)*2*pi/n + f = sin(x)+cos(2*x)*sin(x) + y = hilbert(f) + y1 = direct_hilbert(f) + assert_array_almost_equal(y,y1) + y2 = tilbert(f,h=10) + assert_array_almost_equal(y,y2) + + def test_random_odd(self): + rng = np.random.default_rng(1234) + for n in [33,65,55]: + f = rng.random((n,)) + af = sum(f,axis=0)/n + f = f-af + assert_almost_equal(sum(f,axis=0),0.0) + assert_array_almost_equal(ihilbert(hilbert(f)),f) + assert_array_almost_equal(hilbert(ihilbert(f)),f) + + def test_random_even(self): + rng = np.random.default_rng(1234) + for n in [32,64,56]: + f = rng.random((n,)) + af = sum(f,axis=0)/n + f = f-af + # zeroing Nyquist mode: + f = diff(diff(f,1),-1) + assert_almost_equal(sum(f,axis=0),0.0) + assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f) + assert_array_almost_equal(hilbert(ihilbert(f)),f) + + +class TestIHilbert: + + def test_definition(self): + for n in [16,17,64,127]: + x = arange(n)*2*pi/n + y = ihilbert(sin(x)) + y1 = direct_ihilbert(sin(x)) + assert_array_almost_equal(y,y1) + assert_array_almost_equal(ihilbert(sin(2*x)), + direct_ihilbert(sin(2*x))) + + def test_itilbert_relation(self): + for n in [16,17,64,127]: + x = arange(n)*2*pi/n + f = sin(x)+cos(2*x)*sin(x) + y = ihilbert(f) + y1 = direct_ihilbert(f) + assert_array_almost_equal(y,y1) + y2 = itilbert(f,h=10) + assert_array_almost_equal(y,y2) + + +class TestShift: + + def test_definition(self): + for n in [18,17,64,127,32,2048,256]: + x = arange(n)*2*pi/n + for a in [0.1,3]: + assert_array_almost_equal(shift(sin(x),a),direct_shift(sin(x),a)) + assert_array_almost_equal(shift(sin(x),a),sin(x+a)) + assert_array_almost_equal(shift(cos(x),a),cos(x+a)) + assert_array_almost_equal(shift(cos(2*x)+sin(x),a), + cos(2*(x+a))+sin(x+a)) + assert_array_almost_equal(shift(exp(sin(x)),a),exp(sin(x+a))) + assert_array_almost_equal(shift(sin(x),2*pi),sin(x)) + assert_array_almost_equal(shift(sin(x),pi),-sin(x)) + assert_array_almost_equal(shift(sin(x),pi/2),cos(x)) + + +class TestOverwrite: + """Check input overwrite behavior """ + + real_dtypes = (np.float32, np.float64) + dtypes = real_dtypes + (np.complex64, np.complex128) + + def _check(self, x, routine, *args, **kwargs): + x2 = x.copy() + routine(x2, *args, **kwargs) + sig = routine.__name__ + if args: + sig += repr(args) + if kwargs: + sig += repr(kwargs) + assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}") + + def _check_1d(self, routine, dtype, shape, *args, **kwargs): + # rng = np.random.default_rng(1234) + rng = np.random.RandomState(1234) + # np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + data = rng.randn(*shape) + 1j*rng.randn(*shape) + else: + data = rng.randn(*shape) + data = data.astype(dtype) + self._check(data, routine, *args, **kwargs) + + def test_diff(self): + for dtype in self.dtypes: + self._check_1d(diff, dtype, (16,)) + + def test_tilbert(self): + for dtype in self.dtypes: + self._check_1d(tilbert, dtype, (16,), 1.6) + + def test_itilbert(self): + for dtype in self.dtypes: + self._check_1d(itilbert, dtype, (16,), 1.6) + + def test_hilbert(self): + for dtype in self.dtypes: + self._check_1d(hilbert, dtype, (16,)) + + def test_cs_diff(self): + for dtype in self.dtypes: + self._check_1d(cs_diff, dtype, (16,), 1.0, 4.0) + + def test_sc_diff(self): + for dtype in self.dtypes: + self._check_1d(sc_diff, dtype, (16,), 1.0, 4.0) + + def test_ss_diff(self): + for dtype in self.dtypes: + self._check_1d(ss_diff, dtype, (16,), 1.0, 4.0) + + def test_cc_diff(self): + for dtype in self.dtypes: + self._check_1d(cc_diff, dtype, (16,), 1.0, 4.0) + + def test_shift(self): + for dtype in self.dtypes: + self._check_1d(shift, dtype, (16,), 1.0) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_real_transforms.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_real_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..08ab63d033ab98c470f66e00d43dbfc10a521744 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/fftpack/tests/test_real_transforms.py @@ -0,0 +1,836 @@ +from os.path import join, dirname +import threading + +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_equal +import pytest +from pytest import raises as assert_raises + +from scipy.fftpack._realtransforms import ( + dct, idct, dst, idst, dctn, idctn, dstn, idstn) + +# Matlab reference data +MDATA = np.load(join(dirname(__file__), 'test.npz')) +X = [MDATA[f'x{i}'] for i in range(8)] +Y = [MDATA[f'y{i}'] for i in range(8)] + +# FFTW reference data: the data are organized as follows: +# * SIZES is an array containing all available sizes +# * for every type (1, 2, 3, 4) and every size, the array dct_type_size +# contains the output of the DCT applied to the input np.linspace(0, size-1, +# size) +FFTWDATA_DOUBLE = np.load(join(dirname(__file__), 'fftw_double_ref.npz')) +FFTWDATA_SINGLE = np.load(join(dirname(__file__), 'fftw_single_ref.npz')) +FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes'] + + +def fftw_dct_ref(type, size, dt): + x = np.linspace(0, size-1, size).astype(dt) + dt = np.result_type(np.float32, dt) + if dt == np.float64: + data = FFTWDATA_DOUBLE + elif dt == np.float32: + data = FFTWDATA_SINGLE + else: + raise ValueError() + y = (data[f'dct_{type}_{size}']).astype(dt) + return x, y, dt + + +def fftw_dst_ref(type, size, dt): + x = np.linspace(0, size-1, size).astype(dt) + dt = np.result_type(np.float32, dt) + if dt == np.float64: + data = FFTWDATA_DOUBLE + elif dt == np.float32: + data = FFTWDATA_SINGLE + else: + raise ValueError() + y = (data[f'dst_{type}_{size}']).astype(dt) + return x, y, dt + + +def dct_2d_ref(x, **kwargs): + """Calculate reference values for testing dct2.""" + x = np.array(x, copy=True) + for row in range(x.shape[0]): + x[row, :] = dct(x[row, :], **kwargs) + for col in range(x.shape[1]): + x[:, col] = dct(x[:, col], **kwargs) + return x + + +def idct_2d_ref(x, **kwargs): + """Calculate reference values for testing idct2.""" + x = np.array(x, copy=True) + for row in range(x.shape[0]): + x[row, :] = idct(x[row, :], **kwargs) + for col in range(x.shape[1]): + x[:, col] = idct(x[:, col], **kwargs) + return x + + +def dst_2d_ref(x, **kwargs): + """Calculate reference values for testing dst2.""" + x = np.array(x, copy=True) + for row in range(x.shape[0]): + x[row, :] = dst(x[row, :], **kwargs) + for col in range(x.shape[1]): + x[:, col] = dst(x[:, col], **kwargs) + return x + + +def idst_2d_ref(x, **kwargs): + """Calculate reference values for testing idst2.""" + x = np.array(x, copy=True) + for row in range(x.shape[0]): + x[row, :] = idst(x[row, :], **kwargs) + for col in range(x.shape[1]): + x[:, col] = idst(x[:, col], **kwargs) + return x + + +def naive_dct1(x, norm=None): + """Calculate textbook definition version of DCT-I.""" + x = np.array(x, copy=True) + N = len(x) + M = N-1 + y = np.zeros(N) + m0, m = 1, 2 + if norm == 'ortho': + m0 = np.sqrt(1.0/M) + m = np.sqrt(2.0/M) + for k in range(N): + for n in range(1, N-1): + y[k] += m*x[n]*np.cos(np.pi*n*k/M) + y[k] += m0 * x[0] + y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1) + if norm == 'ortho': + y[0] *= 1/np.sqrt(2) + y[N-1] *= 1/np.sqrt(2) + return y + + +def naive_dst1(x, norm=None): + """Calculate textbook definition version of DST-I.""" + x = np.array(x, copy=True) + N = len(x) + M = N+1 + y = np.zeros(N) + for k in range(N): + for n in range(N): + y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M) + if norm == 'ortho': + y *= np.sqrt(0.5/M) + return y + + +def naive_dct4(x, norm=None): + """Calculate textbook definition version of DCT-IV.""" + x = np.array(x, copy=True) + N = len(x) + y = np.zeros(N) + for k in range(N): + for n in range(N): + y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N)) + if norm == 'ortho': + y *= np.sqrt(2.0/N) + else: + y *= 2 + return y + + +def naive_dst4(x, norm=None): + """Calculate textbook definition version of DST-IV.""" + x = np.array(x, copy=True) + N = len(x) + y = np.zeros(N) + for k in range(N): + for n in range(N): + y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N)) + if norm == 'ortho': + y *= np.sqrt(2.0/N) + else: + y *= 2 + return y + + +class TestComplex: + def test_dct_complex64(self): + y = dct(1j*np.arange(5, dtype=np.complex64)) + x = 1j*dct(np.arange(5)) + assert_array_almost_equal(x, y) + + def test_dct_complex(self): + y = dct(np.arange(5)*1j) + x = 1j*dct(np.arange(5)) + assert_array_almost_equal(x, y) + + def test_idct_complex(self): + y = idct(np.arange(5)*1j) + x = 1j*idct(np.arange(5)) + assert_array_almost_equal(x, y) + + def test_dst_complex64(self): + y = dst(np.arange(5, dtype=np.complex64)*1j) + x = 1j*dst(np.arange(5)) + assert_array_almost_equal(x, y) + + def test_dst_complex(self): + y = dst(np.arange(5)*1j) + x = 1j*dst(np.arange(5)) + assert_array_almost_equal(x, y) + + def test_idst_complex(self): + y = idst(np.arange(5)*1j) + x = 1j*idst(np.arange(5)) + assert_array_almost_equal(x, y) + + +class _TestDCTBase: + def setup_method(self): + self.rdt = None + self.dec = 14 + self.type = None + + @pytest.fixture + def dct_lock(self): + return threading.Lock() + + def test_definition(self, dct_lock): + for i in FFTWDATA_SIZES: + with dct_lock: + x, yr, dt = fftw_dct_ref(self.type, i, self.rdt) + y = dct(x, type=self.type) + assert_equal(y.dtype, dt) + # XXX: we divide by np.max(y) because the tests fail otherwise. We + # should really use something like assert_array_approx_equal. The + # difference is due to fftw using a better algorithm w.r.t error + # propagation compared to the ones from fftpack. + assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec, + err_msg=f"Size {i} failed") + + def test_axis(self): + nt = 2 + rng = np.random.RandomState(1234) + for i in [7, 8, 9, 16, 32, 64]: + x = rng.randn(nt, i) + y = dct(x, type=self.type) + for j in range(nt): + assert_array_almost_equal(y[j], dct(x[j], type=self.type), + decimal=self.dec) + + x = x.T + y = dct(x, axis=0, type=self.type) + for j in range(nt): + assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type), + decimal=self.dec) + + +class _TestDCTIBase(_TestDCTBase): + def test_definition_ortho(self): + # Test orthornomal mode. + dt = np.result_type(np.float32, self.rdt) + for xr in X: + x = np.array(xr, dtype=self.rdt) + y = dct(x, norm='ortho', type=1) + y2 = naive_dct1(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec) + +class _TestDCTIIBase(_TestDCTBase): + def test_definition_matlab(self): + # Test correspondence with MATLAB (orthornomal mode). + dt = np.result_type(np.float32, self.rdt) + for xr, yr in zip(X, Y): + x = np.array(xr, dtype=dt) + y = dct(x, norm="ortho", type=2) + assert_equal(y.dtype, dt) + assert_array_almost_equal(y, yr, decimal=self.dec) + + +class _TestDCTIIIBase(_TestDCTBase): + def test_definition_ortho(self): + # Test orthornomal mode. + dt = np.result_type(np.float32, self.rdt) + for xr in X: + x = np.array(xr, dtype=self.rdt) + y = dct(x, norm='ortho', type=2) + xi = dct(y, norm="ortho", type=3) + assert_equal(xi.dtype, dt) + assert_array_almost_equal(xi, x, decimal=self.dec) + +class _TestDCTIVBase(_TestDCTBase): + def test_definition_ortho(self): + # Test orthornomal mode. + dt = np.result_type(np.float32, self.rdt) + for xr in X: + x = np.array(xr, dtype=self.rdt) + y = dct(x, norm='ortho', type=4) + y2 = naive_dct4(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec) + + +class TestDCTIDouble(_TestDCTIBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 10 + self.type = 1 + + +class TestDCTIFloat(_TestDCTIBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 4 + self.type = 1 + + +class TestDCTIInt(_TestDCTIBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 1 + + +class TestDCTIIDouble(_TestDCTIIBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 10 + self.type = 2 + + +class TestDCTIIFloat(_TestDCTIIBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 5 + self.type = 2 + + +class TestDCTIIInt(_TestDCTIIBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 2 + + +class TestDCTIIIDouble(_TestDCTIIIBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 14 + self.type = 3 + + +class TestDCTIIIFloat(_TestDCTIIIBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 5 + self.type = 3 + + +class TestDCTIIIInt(_TestDCTIIIBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 3 + + +class TestDCTIVDouble(_TestDCTIVBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 12 + self.type = 3 + + +class TestDCTIVFloat(_TestDCTIVBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 5 + self.type = 3 + + +class TestDCTIVInt(_TestDCTIVBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 3 + + +class _TestIDCTBase: + def setup_method(self): + self.rdt = None + self.dec = 14 + self.type = None + + @pytest.fixture + def idct_lock(self): + return threading.Lock() + + def test_definition(self, idct_lock): + for i in FFTWDATA_SIZES: + with idct_lock: + xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt) + x = idct(yr, type=self.type) + if self.type == 1: + x /= 2 * (i-1) + else: + x /= 2 * i + assert_equal(x.dtype, dt) + # XXX: we divide by np.max(y) because the tests fail otherwise. We + # should really use something like assert_array_approx_equal. The + # difference is due to fftw using a better algorithm w.r.t error + # propagation compared to the ones from fftpack. + assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec, + err_msg=f"Size {i} failed") + +class TestIDCTIDouble(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 10 + self.type = 1 + + +class TestIDCTIFloat(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 4 + self.type = 1 + + +class TestIDCTIInt(_TestIDCTBase): + def setup_method(self): + self.rdt = int + self.dec = 4 + self.type = 1 + + +class TestIDCTIIDouble(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 10 + self.type = 2 + + +class TestIDCTIIFloat(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 5 + self.type = 2 + + +class TestIDCTIIInt(_TestIDCTBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 2 + + +class TestIDCTIIIDouble(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 14 + self.type = 3 + + +class TestIDCTIIIFloat(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 5 + self.type = 3 + + +class TestIDCTIIIInt(_TestIDCTBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 3 + +class TestIDCTIVDouble(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 12 + self.type = 4 + + +class TestIDCTIVFloat(_TestIDCTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 5 + self.type = 4 + + +class TestIDCTIVInt(_TestIDCTBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 4 + +class _TestDSTBase: + def setup_method(self): + self.rdt = None # dtype + self.dec = None # number of decimals to match + self.type = None # dst type + + @pytest.fixture + def dst_lock(self): + return threading.Lock() + + def test_definition(self, dst_lock): + for i in FFTWDATA_SIZES: + with dst_lock: + xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt) + y = dst(xr, type=self.type) + assert_equal(y.dtype, dt) + # XXX: we divide by np.max(y) because the tests fail otherwise. We + # should really use something like assert_array_approx_equal. The + # difference is due to fftw using a better algorithm w.r.t error + # propagation compared to the ones from fftpack. + assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec, + err_msg=f"Size {i} failed") + + +class _TestDSTIBase(_TestDSTBase): + def test_definition_ortho(self): + # Test orthornomal mode. + dt = np.result_type(np.float32, self.rdt) + for xr in X: + x = np.array(xr, dtype=self.rdt) + y = dst(x, norm='ortho', type=1) + y2 = naive_dst1(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec) + +class _TestDSTIVBase(_TestDSTBase): + def test_definition_ortho(self): + # Test orthornomal mode. + dt = np.result_type(np.float32, self.rdt) + for xr in X: + x = np.array(xr, dtype=self.rdt) + y = dst(x, norm='ortho', type=4) + y2 = naive_dst4(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_array_almost_equal(y, y2, decimal=self.dec) + +class TestDSTIDouble(_TestDSTIBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 12 + self.type = 1 + + +class TestDSTIFloat(_TestDSTIBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 4 + self.type = 1 + + +class TestDSTIInt(_TestDSTIBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 1 + + +class TestDSTIIDouble(_TestDSTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 14 + self.type = 2 + + +class TestDSTIIFloat(_TestDSTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 6 + self.type = 2 + + +class TestDSTIIInt(_TestDSTBase): + def setup_method(self): + self.rdt = int + self.dec = 6 + self.type = 2 + + +class TestDSTIIIDouble(_TestDSTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 14 + self.type = 3 + + +class TestDSTIIIFloat(_TestDSTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 7 + self.type = 3 + + +class TestDSTIIIInt(_TestDSTBase): + def setup_method(self): + self.rdt = int + self.dec = 7 + self.type = 3 + + +class TestDSTIVDouble(_TestDSTIVBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 12 + self.type = 4 + + +class TestDSTIVFloat(_TestDSTIVBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 4 + self.type = 4 + + +class TestDSTIVInt(_TestDSTIVBase): + def setup_method(self): + self.rdt = int + self.dec = 5 + self.type = 4 + + +class _TestIDSTBase: + def setup_method(self): + self.rdt = None + self.dec = None + self.type = None + + @pytest.fixture + def idst_lock(self): + return threading.Lock() + + def test_definition(self, idst_lock): + for i in FFTWDATA_SIZES: + with idst_lock: + xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt) + x = idst(yr, type=self.type) + if self.type == 1: + x /= 2 * (i+1) + else: + x /= 2 * i + assert_equal(x.dtype, dt) + # XXX: we divide by np.max(x) because the tests fail otherwise. We + # should really use something like assert_array_approx_equal. The + # difference is due to fftw using a better algorithm w.r.t error + # propagation compared to the ones from fftpack. + assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec, + err_msg=f"Size {i} failed") + + +class TestIDSTIDouble(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 12 + self.type = 1 + + +class TestIDSTIFloat(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 4 + self.type = 1 + + +class TestIDSTIInt(_TestIDSTBase): + def setup_method(self): + self.rdt = int + self.dec = 4 + self.type = 1 + + +class TestIDSTIIDouble(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 14 + self.type = 2 + + +class TestIDSTIIFloat(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 6 + self.type = 2 + + +class TestIDSTIIInt(_TestIDSTBase): + def setup_method(self): + self.rdt = int + self.dec = 6 + self.type = 2 + + +class TestIDSTIIIDouble(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 14 + self.type = 3 + + +class TestIDSTIIIFloat(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 6 + self.type = 3 + + +class TestIDSTIIIInt(_TestIDSTBase): + def setup_method(self): + self.rdt = int + self.dec = 6 + self.type = 3 + + +class TestIDSTIVDouble(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float64 + self.dec = 12 + self.type = 4 + + +class TestIDSTIVFloat(_TestIDSTBase): + def setup_method(self): + self.rdt = np.float32 + self.dec = 6 + self.type = 4 + + +class TestIDSTIVnt(_TestIDSTBase): + def setup_method(self): + self.rdt = int + self.dec = 6 + self.type = 4 + + +class TestOverwrite: + """Check input overwrite behavior.""" + + real_dtypes = [np.float32, np.float64] + + def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw): + x2 = x.copy() + routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x) + + sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, " + f"axis={axis!r}, overwrite_x={overwrite_x!r})") + if not overwrite_x: + assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}") + + def _check_1d(self, routine, dtype, shape, axis): + rng = np.random.RandomState(1234) + if np.issubdtype(dtype, np.complexfloating): + data = rng.randn(*shape) + 1j*rng.randn(*shape) + else: + data = rng.randn(*shape) + data = data.astype(dtype) + + for type in [1, 2, 3, 4]: + for overwrite_x in [True, False]: + for norm in [None, 'ortho']: + self._check(data, routine, type, None, axis, norm, + overwrite_x) + + def test_dct(self): + for dtype in self.real_dtypes: + self._check_1d(dct, dtype, (16,), -1) + self._check_1d(dct, dtype, (16, 2), 0) + self._check_1d(dct, dtype, (2, 16), 1) + + def test_idct(self): + for dtype in self.real_dtypes: + self._check_1d(idct, dtype, (16,), -1) + self._check_1d(idct, dtype, (16, 2), 0) + self._check_1d(idct, dtype, (2, 16), 1) + + def test_dst(self): + for dtype in self.real_dtypes: + self._check_1d(dst, dtype, (16,), -1) + self._check_1d(dst, dtype, (16, 2), 0) + self._check_1d(dst, dtype, (2, 16), 1) + + def test_idst(self): + for dtype in self.real_dtypes: + self._check_1d(idst, dtype, (16,), -1) + self._check_1d(idst, dtype, (16, 2), 0) + self._check_1d(idst, dtype, (2, 16), 1) + + +class Test_DCTN_IDCTN: + dec = 14 + dct_type = [1, 2, 3, 4] + norms = [None, 'ortho'] + rstate = np.random.RandomState(1234) + shape = (32, 16) + data = rstate.randn(*shape) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + @pytest.mark.parametrize('axes', [None, + 1, (1,), [1], + 0, (0,), [0], + (0, 1), [0, 1], + (-2, -1), [-2, -1]]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', ['ortho']) + def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm): + tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm) + tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm) + assert_array_almost_equal(self.data, tmp, decimal=12) + + @pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref), + (dstn, dst_2d_ref)]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', norms) + def test_dctn_vs_2d_reference(self, fforward, fforward_ref, + dct_type, norm): + y1 = fforward(self.data, type=dct_type, axes=None, norm=norm) + y2 = fforward_ref(self.data, type=dct_type, norm=norm) + assert_array_almost_equal(y1, y2, decimal=11) + + @pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref), + (idstn, idst_2d_ref)]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', [None, 'ortho']) + def test_idctn_vs_2d_reference(self, finverse, finverse_ref, + dct_type, norm): + fdata = dctn(self.data, type=dct_type, norm=norm) + y1 = finverse(fdata, type=dct_type, norm=norm) + y2 = finverse_ref(fdata, type=dct_type, norm=norm) + assert_array_almost_equal(y1, y2, decimal=11) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + def test_axes_and_shape(self, fforward, finverse): + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fforward(self.data, shape=self.data.shape[0], axes=(0, 1)) + + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fforward(self.data, shape=self.data.shape[0], axes=None) + + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fforward(self.data, shape=self.data.shape, axes=0) + + @pytest.mark.parametrize('fforward', [dctn, dstn]) + def test_shape(self, fforward): + tmp = fforward(self.data, shape=(128, 128), axes=None) + assert_equal(tmp.shape, (128, 128)) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + @pytest.mark.parametrize('axes', [1, (1,), [1], + 0, (0,), [0]]) + def test_shape_is_none_with_axes(self, fforward, finverse, axes): + tmp = fforward(self.data, shape=None, axes=axes, norm='ortho') + tmp = finverse(tmp, shape=None, axes=axes, norm='ortho') + assert_array_almost_equal(self.data, tmp, decimal=self.dec) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a627781819964d53f2238f965aeabfb07c8b14d7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_bvp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_bvp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24a48ff04a5a95399634e513f698d37c57d50824 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_bvp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_cubature.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_cubature.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d1a285b0a2b639af247779569401bfdd4eaeb76 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_cubature.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_ode.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_ode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d8822ac89afec8a7bdc1993b6efce94843156b9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_ode.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd4a32b74da00d5f91841cf032d4c6253ca47059 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd6cbd5ea1aab768bcb74aa201c80fae0169229d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..600b092b7a33e36fa96218dd381dcd54c1ab95c4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb3e8728054fb256f665b0d48ecdaafef6a47e72 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecf834f272ee8c863c45de4211d0c953cafb8fbb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/dop.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/dop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daf0ba0620dfd310105a3dbc605b045332c5679d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/dop.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/lsoda.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/lsoda.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..732ad91e07315c7430c921101924893a572c704d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/lsoda.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/odepack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/odepack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e29fd68652a7c6592bff3231600bc3be7c21ddd1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/odepack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/quadpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/quadpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d01bd6ef3bff97a38f8b913908bdcc007029cfc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/quadpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/vode.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/vode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d89878ed96cfe15c8cbef49e2455bbd65048a32a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/__pycache__/vode.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75fadc9ceb2c14e32d9db6c61aa940c66b49d62d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__init__.py @@ -0,0 +1,8 @@ +"""Suite of ODE solvers implemented in Python.""" +from .ivp import solve_ivp +from .rk import RK23, RK45, DOP853 +from .radau import Radau +from .bdf import BDF +from .lsoda import LSODA +from .common import OdeSolution +from .base import DenseOutput, OdeSolver diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..799f9142a25e28052c0692bacee999bc1b36e3a5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84f0640ef4e544128befb0af66550881e3401a43 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a5f9b651f54e472e49edaaf35ac9f91ed69ca00 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14d327a03ce4127eb1ef8b1bacb8b1663e79df23 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc3a59ad748954f30a1b09d7cf1e53975031779b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17bb9ab0c6e0b071d4b8d57bc7bb4948ee5ddd52 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f95030db6e48465bc3e9ddfaf33ecb9c98610c82 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97a8077c9e61e4f63ae9b5cf3b0ef87953d715d0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddd91590513900c40a45c28a08af2f7a50fbea1b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ce54bc4f2aa895a2f0dbb6a07a64c6cf399e2bda --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/base.py @@ -0,0 +1,298 @@ +from types import GenericAlias +import numpy as np + + +def check_arguments(fun, y0, support_complex): + """Helper function for checking arguments common to all solvers.""" + y0 = np.asarray(y0) + if np.issubdtype(y0.dtype, np.complexfloating): + if not support_complex: + raise ValueError("`y0` is complex, but the chosen solver does " + "not support integration in a complex domain.") + dtype = complex + else: + dtype = float + y0 = y0.astype(dtype, copy=False) + + if y0.ndim != 1: + raise ValueError("`y0` must be 1-dimensional.") + + if not np.isfinite(y0).all(): + raise ValueError("All components of the initial state `y0` must be finite.") + + def fun_wrapped(t, y): + return np.asarray(fun(t, y), dtype=dtype) + + return fun_wrapped, y0 + + +class OdeSolver: + """Base class for ODE solvers. + + In order to implement a new solver you need to follow the guidelines: + + 1. A constructor must accept parameters presented in the base class + (listed below) along with any other parameters specific to a solver. + 2. A constructor must accept arbitrary extraneous arguments + ``**extraneous``, but warn that these arguments are irrelevant + using `common.warn_extraneous` function. Do not pass these + arguments to the base class. + 3. A solver must implement a private method `_step_impl(self)` which + propagates a solver one step further. It must return tuple + ``(success, message)``, where ``success`` is a boolean indicating + whether a step was successful, and ``message`` is a string + containing description of a failure if a step failed or None + otherwise. + 4. A solver must implement a private method `_dense_output_impl(self)`, + which returns a `DenseOutput` object covering the last successful + step. + 5. A solver must have attributes listed below in Attributes section. + Note that ``t_old`` and ``step_size`` are updated automatically. + 6. Use `fun(self, t, y)` method for the system rhs evaluation, this + way the number of function evaluations (`nfev`) will be tracked + automatically. + 7. For convenience, a base class provides `fun_single(self, t, y)` and + `fun_vectorized(self, t, y)` for evaluating the rhs in + non-vectorized and vectorized fashions respectively (regardless of + how `fun` from the constructor is implemented). These calls don't + increment `nfev`. + 8. If a solver uses a Jacobian matrix and LU decompositions, it should + track the number of Jacobian evaluations (`njev`) and the number of + LU decompositions (`nlu`). + 9. By convention, the function evaluations used to compute a finite + difference approximation of the Jacobian should not be counted in + `nfev`, thus use `fun_single(self, t, y)` or + `fun_vectorized(self, t, y)` when computing a finite difference + approximation of the Jacobian. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time --- the integration won't continue beyond it. It also + determines the direction of the integration. + vectorized : bool + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for other methods. It can also + result in slower overall execution for 'Radau' and 'BDF' in some + circumstances (e.g. small ``len(y0)``). + support_complex : bool, optional + Whether integration in a complex domain should be supported. + Generally determined by a derived solver class capabilities. + Default is False. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number of the system's rhs evaluations. + njev : int + Number of the Jacobian evaluations. + nlu : int + Number of LU decompositions. + """ + TOO_SMALL_STEP = "Required step size is less than spacing between numbers." + + # generic type compatibility with scipy-stubs + __class_getitem__ = classmethod(GenericAlias) + + def __init__(self, fun, t0, y0, t_bound, vectorized, + support_complex=False): + self.t_old = None + self.t = t0 + self._fun, self.y = check_arguments(fun, y0, support_complex) + self.t_bound = t_bound + self.vectorized = vectorized + + if vectorized: + def fun_single(t, y): + return self._fun(t, y[:, None]).ravel() + fun_vectorized = self._fun + else: + fun_single = self._fun + + def fun_vectorized(t, y): + f = np.empty_like(y) + for i, yi in enumerate(y.T): + f[:, i] = self._fun(t, yi) + return f + + def fun(t, y): + self.nfev += 1 + return self.fun_single(t, y) + + self.fun = fun + self.fun_single = fun_single + self.fun_vectorized = fun_vectorized + + self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1 + self.n = self.y.size + self.status = 'running' + + self.nfev = 0 + self.njev = 0 + self.nlu = 0 + + @property + def step_size(self): + if self.t_old is None: + return None + else: + return np.abs(self.t - self.t_old) + + def step(self): + """Perform one integration step. + + Returns + ------- + message : string or None + Report from the solver. Typically a reason for a failure if + `self.status` is 'failed' after the step was taken or None + otherwise. + """ + if self.status != 'running': + raise RuntimeError("Attempt to step on a failed or finished " + "solver.") + + if self.n == 0 or self.t == self.t_bound: + # Handle corner cases of empty solver or no integration. + self.t_old = self.t + self.t = self.t_bound + message = None + self.status = 'finished' + else: + t = self.t + success, message = self._step_impl() + + if not success: + self.status = 'failed' + else: + self.t_old = t + if self.direction * (self.t - self.t_bound) >= 0: + self.status = 'finished' + + return message + + def dense_output(self): + """Compute a local interpolant over the last successful step. + + Returns + ------- + sol : `DenseOutput` + Local interpolant over the last successful step. + """ + if self.t_old is None: + raise RuntimeError("Dense output is available after a successful " + "step was made.") + + if self.n == 0 or self.t == self.t_old: + # Handle corner cases of empty solver and no integration. + return ConstantDenseOutput(self.t_old, self.t, self.y) + else: + return self._dense_output_impl() + + def _step_impl(self): + raise NotImplementedError + + def _dense_output_impl(self): + raise NotImplementedError + + +class DenseOutput: + """Base class for local interpolant over step made by an ODE solver. + + It interpolates between `t_min` and `t_max` (see Attributes below). + Evaluation outside this interval is not forbidden, but the accuracy is not + guaranteed. + + Attributes + ---------- + t_min, t_max : float + Time range of the interpolation. + """ + + # generic type compatibility with scipy-stubs + __class_getitem__ = classmethod(GenericAlias) + + def __init__(self, t_old, t): + self.t_old = t_old + self.t = t + self.t_min = min(t, t_old) + self.t_max = max(t, t_old) + + def __call__(self, t): + """Evaluate the interpolant. + + Parameters + ---------- + t : float or array_like with shape (n_points,) + Points to evaluate the solution at. + + Returns + ------- + y : ndarray, shape (n,) or (n, n_points) + Computed values. Shape depends on whether `t` was a scalar or a + 1-D array. + """ + t = np.asarray(t) + if t.ndim > 1: + raise ValueError("`t` must be a float or a 1-D array.") + return self._call_impl(t) + + def _call_impl(self, t): + raise NotImplementedError + + +class ConstantDenseOutput(DenseOutput): + """Constant value interpolator. + + This class used for degenerate integration cases: equal integration limits + or a system with 0 equations. + """ + def __init__(self, t_old, t, value): + super().__init__(t_old, t) + self.value = value + + def _call_impl(self, t): + if t.ndim == 0: + return self.value + else: + ret = np.empty((self.value.shape[0], t.shape[0])) + ret[:] = self.value[:, None] + return ret diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/bdf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/bdf.py new file mode 100644 index 0000000000000000000000000000000000000000..31fa5c47e9e92d67111acefb0f4dcebd03dc2d50 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/bdf.py @@ -0,0 +1,479 @@ +import numpy as np +from scipy.linalg import lu_factor, lu_solve +from scipy.sparse import issparse, csc_matrix, eye +from scipy.sparse.linalg import splu +from scipy.optimize._numdiff import group_columns +from .common import (validate_max_step, validate_tol, select_initial_step, + norm, EPS, num_jac, validate_first_step, + warn_extraneous) +from .base import OdeSolver, DenseOutput + + +MAX_ORDER = 5 +NEWTON_MAXITER = 4 +MIN_FACTOR = 0.2 +MAX_FACTOR = 10 + + +def compute_R(order, factor): + """Compute the matrix for changing the differences array.""" + I = np.arange(1, order + 1)[:, None] + J = np.arange(1, order + 1) + M = np.zeros((order + 1, order + 1)) + M[1:, 1:] = (I - 1 - factor * J) / I + M[0] = 1 + return np.cumprod(M, axis=0) + + +def change_D(D, order, factor): + """Change differences array in-place when step size is changed.""" + R = compute_R(order, factor) + U = compute_R(order, 1) + RU = R.dot(U) + D[:order + 1] = np.dot(RU.T, D[:order + 1]) + + +def solve_bdf_system(fun, t_new, y_predict, c, psi, LU, solve_lu, scale, tol): + """Solve the algebraic system resulting from BDF method.""" + d = 0 + y = y_predict.copy() + dy_norm_old = None + converged = False + for k in range(NEWTON_MAXITER): + f = fun(t_new, y) + if not np.all(np.isfinite(f)): + break + + dy = solve_lu(LU, c * f - psi - d) + dy_norm = norm(dy / scale) + + if dy_norm_old is None: + rate = None + else: + rate = dy_norm / dy_norm_old + + if (rate is not None and (rate >= 1 or + rate ** (NEWTON_MAXITER - k) / (1 - rate) * dy_norm > tol)): + break + + y += dy + d += dy + + if (dy_norm == 0 or + rate is not None and rate / (1 - rate) * dy_norm < tol): + converged = True + break + + dy_norm_old = dy_norm + + return converged, k + 1, y, d + + +class BDF(OdeSolver): + """Implicit method based on backward-differentiation formulas. + + This is a variable order method with the order varying automatically from + 1 to 5. The general framework of the BDF algorithm is described in [1]_. + This class implements a quasi-constant step size as explained in [2]_. + The error estimation strategy for the constant-step BDF is derived in [3]_. + An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : {None, array_like, sparse_matrix, callable}, optional + Jacobian matrix of the right-hand side of the system with respect to y, + required by this method. The Jacobian matrix has shape (n, n) and its + element (i, j) is equal to ``d f_i / d y_j``. + There are three ways to define the Jacobian: + + * If array_like or sparse_matrix, the Jacobian is assumed to + be constant. + * If callable, the Jacobian is assumed to depend on both + t and y; it will be called as ``jac(t, y)`` as necessary. + For the 'Radau' and 'BDF' methods, the return value might be a + sparse matrix. + * If None (default), the Jacobian will be approximated by + finite differences. + + It is generally recommended to provide the Jacobian rather than + relying on a finite-difference approximation. + jac_sparsity : {None, array_like, sparse matrix}, optional + Defines a sparsity structure of the Jacobian matrix for a + finite-difference approximation. Its shape must be (n, n). This argument + is ignored if `jac` is not `None`. If the Jacobian has only few non-zero + elements in *each* row, providing the sparsity structure will greatly + speed up the computations [4]_. A zero entry means that a corresponding + element in the Jacobian is always zero. If None (default), the Jacobian + is assumed to be dense. + vectorized : bool, optional + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by this method, but may result in slower + execution overall in some circumstances (e.g. small ``len(y0)``). + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + nlu : int + Number of LU decompositions. + + References + ---------- + .. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical + Solution of Ordinary Differential Equations", ACM Transactions on + Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975. + .. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI. + COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997. + .. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I: + Nonstiff Problems", Sec. III.2. + .. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13, pp. 117-120, 1974. + """ + + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None, + vectorized=False, first_step=None, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized, + support_complex=True) + self.max_step = validate_max_step(max_step) + self.rtol, self.atol = validate_tol(rtol, atol, self.n) + f = self.fun(self.t, self.y) + if first_step is None: + self.h_abs = select_initial_step(self.fun, self.t, self.y, + t_bound, max_step, f, + self.direction, 1, + self.rtol, self.atol) + else: + self.h_abs = validate_first_step(first_step, t0, t_bound) + self.h_abs_old = None + self.error_norm_old = None + + self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5)) + + self.jac_factor = None + self.jac, self.J = self._validate_jac(jac, jac_sparsity) + if issparse(self.J): + def lu(A): + self.nlu += 1 + return splu(A) + + def solve_lu(LU, b): + return LU.solve(b) + + I = eye(self.n, format='csc', dtype=self.y.dtype) + else: + def lu(A): + self.nlu += 1 + return lu_factor(A, overwrite_a=True) + + def solve_lu(LU, b): + return lu_solve(LU, b, overwrite_b=True) + + I = np.identity(self.n, dtype=self.y.dtype) + + self.lu = lu + self.solve_lu = solve_lu + self.I = I + + kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0]) + self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1)))) + self.alpha = (1 - kappa) * self.gamma + self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2) + + D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype) + D[0] = self.y + D[1] = f * self.h_abs * self.direction + self.D = D + + self.order = 1 + self.n_equal_steps = 0 + self.LU = None + + def _validate_jac(self, jac, sparsity): + t0 = self.t + y0 = self.y + + if jac is None: + if sparsity is not None: + if issparse(sparsity): + sparsity = csc_matrix(sparsity) + groups = group_columns(sparsity) + sparsity = (sparsity, groups) + + def jac_wrapped(t, y): + self.njev += 1 + f = self.fun_single(t, y) + J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f, + self.atol, self.jac_factor, + sparsity) + return J + J = jac_wrapped(t0, y0) + elif callable(jac): + J = jac(t0, y0) + self.njev += 1 + if issparse(J): + J = csc_matrix(J, dtype=y0.dtype) + + def jac_wrapped(t, y): + self.njev += 1 + return csc_matrix(jac(t, y), dtype=y0.dtype) + else: + J = np.asarray(J, dtype=y0.dtype) + + def jac_wrapped(t, y): + self.njev += 1 + return np.asarray(jac(t, y), dtype=y0.dtype) + + if J.shape != (self.n, self.n): + raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)}," + f" but actually has {J.shape}.") + else: + if issparse(jac): + J = csc_matrix(jac, dtype=y0.dtype) + else: + J = np.asarray(jac, dtype=y0.dtype) + + if J.shape != (self.n, self.n): + raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)}," + f" but actually has {J.shape}.") + jac_wrapped = None + + return jac_wrapped, J + + def _step_impl(self): + t = self.t + D = self.D + + max_step = self.max_step + min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t) + if self.h_abs > max_step: + h_abs = max_step + change_D(D, self.order, max_step / self.h_abs) + self.n_equal_steps = 0 + elif self.h_abs < min_step: + h_abs = min_step + change_D(D, self.order, min_step / self.h_abs) + self.n_equal_steps = 0 + else: + h_abs = self.h_abs + + atol = self.atol + rtol = self.rtol + order = self.order + + alpha = self.alpha + gamma = self.gamma + error_const = self.error_const + + J = self.J + LU = self.LU + current_jac = self.jac is None + + step_accepted = False + while not step_accepted: + if h_abs < min_step: + return False, self.TOO_SMALL_STEP + + h = h_abs * self.direction + t_new = t + h + + if self.direction * (t_new - self.t_bound) > 0: + t_new = self.t_bound + change_D(D, order, np.abs(t_new - t) / h_abs) + self.n_equal_steps = 0 + LU = None + + h = t_new - t + h_abs = np.abs(h) + + y_predict = np.sum(D[:order + 1], axis=0) + + scale = atol + rtol * np.abs(y_predict) + psi = np.dot(D[1: order + 1].T, gamma[1: order + 1]) / alpha[order] + + converged = False + c = h / alpha[order] + while not converged: + if LU is None: + LU = self.lu(self.I - c * J) + + converged, n_iter, y_new, d = solve_bdf_system( + self.fun, t_new, y_predict, c, psi, LU, self.solve_lu, + scale, self.newton_tol) + + if not converged: + if current_jac: + break + J = self.jac(t_new, y_predict) + LU = None + current_jac = True + + if not converged: + factor = 0.5 + h_abs *= factor + change_D(D, order, factor) + self.n_equal_steps = 0 + LU = None + continue + + safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER + + n_iter) + + scale = atol + rtol * np.abs(y_new) + error = error_const[order] * d + error_norm = norm(error / scale) + + if error_norm > 1: + factor = max(MIN_FACTOR, + safety * error_norm ** (-1 / (order + 1))) + h_abs *= factor + change_D(D, order, factor) + self.n_equal_steps = 0 + # As we didn't have problems with convergence, we don't + # reset LU here. + else: + step_accepted = True + + self.n_equal_steps += 1 + + self.t = t_new + self.y = y_new + + self.h_abs = h_abs + self.J = J + self.LU = LU + + # Update differences. The principal relation here is + # D^{j + 1} y_n = D^{j} y_n - D^{j} y_{n - 1}. Keep in mind that D + # contained difference for previous interpolating polynomial and + # d = D^{k + 1} y_n. Thus this elegant code follows. + D[order + 2] = d - D[order + 1] + D[order + 1] = d + for i in reversed(range(order + 1)): + D[i] += D[i + 1] + + if self.n_equal_steps < order + 1: + return True, None + + if order > 1: + error_m = error_const[order - 1] * D[order] + error_m_norm = norm(error_m / scale) + else: + error_m_norm = np.inf + + if order < MAX_ORDER: + error_p = error_const[order + 1] * D[order + 2] + error_p_norm = norm(error_p / scale) + else: + error_p_norm = np.inf + + error_norms = np.array([error_m_norm, error_norm, error_p_norm]) + with np.errstate(divide='ignore'): + factors = error_norms ** (-1 / np.arange(order, order + 3)) + + delta_order = np.argmax(factors) - 1 + order += delta_order + self.order = order + + factor = min(MAX_FACTOR, safety * np.max(factors)) + self.h_abs *= factor + change_D(D, order, factor) + self.n_equal_steps = 0 + self.LU = None + + return True, None + + def _dense_output_impl(self): + return BdfDenseOutput(self.t_old, self.t, self.h_abs * self.direction, + self.order, self.D[:self.order + 1].copy()) + + +class BdfDenseOutput(DenseOutput): + def __init__(self, t_old, t, h, order, D): + super().__init__(t_old, t) + self.order = order + self.t_shift = self.t - h * np.arange(self.order) + self.denom = h * (1 + np.arange(self.order)) + self.D = D + + def _call_impl(self, t): + if t.ndim == 0: + x = (t - self.t_shift) / self.denom + p = np.cumprod(x) + else: + x = (t - self.t_shift[:, None]) / self.denom[:, None] + p = np.cumprod(x, axis=0) + + y = np.dot(self.D[1:].T, p) + if y.ndim == 1: + y += self.D[0] + else: + y += self.D[0, :, None] + + return y diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/common.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/common.py new file mode 100644 index 0000000000000000000000000000000000000000..282f2a7b8ce55743f8612eb0b5ae55d6391dcdbb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/common.py @@ -0,0 +1,451 @@ +from itertools import groupby +from warnings import warn +import numpy as np +from scipy.sparse import find, coo_matrix + + +EPS = np.finfo(float).eps + + +def validate_first_step(first_step, t0, t_bound): + """Assert that first_step is valid and return it.""" + if first_step <= 0: + raise ValueError("`first_step` must be positive.") + if first_step > np.abs(t_bound - t0): + raise ValueError("`first_step` exceeds bounds.") + return first_step + + +def validate_max_step(max_step): + """Assert that max_Step is valid and return it.""" + if max_step <= 0: + raise ValueError("`max_step` must be positive.") + return max_step + + +def warn_extraneous(extraneous): + """Display a warning for extraneous keyword arguments. + + The initializer of each solver class is expected to collect keyword + arguments that it doesn't understand and warn about them. This function + prints a warning for each key in the supplied dictionary. + + Parameters + ---------- + extraneous : dict + Extraneous keyword arguments + """ + if extraneous: + warn("The following arguments have no effect for a chosen solver: " + f"{', '.join(f'`{x}`' for x in extraneous)}.", + stacklevel=3) + + +def validate_tol(rtol, atol, n): + """Validate tolerance values.""" + + if np.any(rtol < 100 * EPS): + warn("At least one element of `rtol` is too small. " + f"Setting `rtol = np.maximum(rtol, {100 * EPS})`.", + stacklevel=3) + rtol = np.maximum(rtol, 100 * EPS) + + atol = np.asarray(atol) + if atol.ndim > 0 and atol.shape != (n,): + raise ValueError("`atol` has wrong shape.") + + if np.any(atol < 0): + raise ValueError("`atol` must be positive.") + + return rtol, atol + + +def norm(x): + """Compute RMS norm.""" + return np.linalg.norm(x) / x.size ** 0.5 + + +def select_initial_step(fun, t0, y0, t_bound, + max_step, f0, direction, order, rtol, atol): + """Empirically select a good initial step. + + The algorithm is described in [1]_. + + Parameters + ---------- + fun : callable + Right-hand side of the system. + t0 : float + Initial value of the independent variable. + y0 : ndarray, shape (n,) + Initial value of the dependent variable. + t_bound : float + End-point of integration interval; used to ensure that t0+step<=tbound + and that fun is only evaluated in the interval [t0,tbound] + max_step : float + Maximum allowable step size. + f0 : ndarray, shape (n,) + Initial value of the derivative, i.e., ``fun(t0, y0)``. + direction : float + Integration direction. + order : float + Error estimator order. It means that the error controlled by the + algorithm is proportional to ``step_size ** (order + 1)`. + rtol : float + Desired relative tolerance. + atol : float + Desired absolute tolerance. + + Returns + ------- + h_abs : float + Absolute value of the suggested initial step. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II.4. + """ + if y0.size == 0: + return np.inf + + interval_length = abs(t_bound - t0) + if interval_length == 0.0: + return 0.0 + + scale = atol + np.abs(y0) * rtol + d0 = norm(y0 / scale) + d1 = norm(f0 / scale) + if d0 < 1e-5 or d1 < 1e-5: + h0 = 1e-6 + else: + h0 = 0.01 * d0 / d1 + # Check t0+h0*direction doesn't take us beyond t_bound + h0 = min(h0, interval_length) + y1 = y0 + h0 * direction * f0 + f1 = fun(t0 + h0 * direction, y1) + d2 = norm((f1 - f0) / scale) / h0 + + if d1 <= 1e-15 and d2 <= 1e-15: + h1 = max(1e-6, h0 * 1e-3) + else: + h1 = (0.01 / max(d1, d2)) ** (1 / (order + 1)) + + return min(100 * h0, h1, interval_length, max_step) + + +class OdeSolution: + """Continuous ODE solution. + + It is organized as a collection of `DenseOutput` objects which represent + local interpolants. It provides an algorithm to select a right interpolant + for each given point. + + The interpolants cover the range between `t_min` and `t_max` (see + Attributes below). Evaluation outside this interval is not forbidden, but + the accuracy is not guaranteed. + + When evaluating at a breakpoint (one of the values in `ts`) a segment with + the lower index is selected. + + Parameters + ---------- + ts : array_like, shape (n_segments + 1,) + Time instants between which local interpolants are defined. Must + be strictly increasing or decreasing (zero segment with two points is + also allowed). + interpolants : list of DenseOutput with n_segments elements + Local interpolants. An i-th interpolant is assumed to be defined + between ``ts[i]`` and ``ts[i + 1]``. + alt_segment : boolean + Requests the alternative interpolant segment selection scheme. At each + solver integration point, two interpolant segments are available. The + default (False) and alternative (True) behaviours select the segment + for which the requested time corresponded to ``t`` and ``t_old``, + respectively. This functionality is only relevant for testing the + interpolants' accuracy: different integrators use different + construction strategies. + + Attributes + ---------- + t_min, t_max : float + Time range of the interpolation. + """ + def __init__(self, ts, interpolants, alt_segment=False): + ts = np.asarray(ts) + d = np.diff(ts) + # The first case covers integration on zero segment. + if not ((ts.size == 2 and ts[0] == ts[-1]) + or np.all(d > 0) or np.all(d < 0)): + raise ValueError("`ts` must be strictly increasing or decreasing.") + + self.n_segments = len(interpolants) + if ts.shape != (self.n_segments + 1,): + raise ValueError("Numbers of time stamps and interpolants " + "don't match.") + + self.ts = ts + self.interpolants = interpolants + if ts[-1] >= ts[0]: + self.t_min = ts[0] + self.t_max = ts[-1] + self.ascending = True + self.side = "right" if alt_segment else "left" + self.ts_sorted = ts + else: + self.t_min = ts[-1] + self.t_max = ts[0] + self.ascending = False + self.side = "left" if alt_segment else "right" + self.ts_sorted = ts[::-1] + + def _call_single(self, t): + # Here we preserve a certain symmetry that when t is in self.ts, + # if alt_segment=False, then we prioritize a segment with a lower + # index. + ind = np.searchsorted(self.ts_sorted, t, side=self.side) + + segment = min(max(ind - 1, 0), self.n_segments - 1) + if not self.ascending: + segment = self.n_segments - 1 - segment + + return self.interpolants[segment](t) + + def __call__(self, t): + """Evaluate the solution. + + Parameters + ---------- + t : float or array_like with shape (n_points,) + Points to evaluate at. + + Returns + ------- + y : ndarray, shape (n_states,) or (n_states, n_points) + Computed values. Shape depends on whether `t` is a scalar or a + 1-D array. + """ + t = np.asarray(t) + + if t.ndim == 0: + return self._call_single(t) + + order = np.argsort(t) + reverse = np.empty_like(order) + reverse[order] = np.arange(order.shape[0]) + t_sorted = t[order] + + # See comment in self._call_single. + segments = np.searchsorted(self.ts_sorted, t_sorted, side=self.side) + segments -= 1 + segments[segments < 0] = 0 + segments[segments > self.n_segments - 1] = self.n_segments - 1 + if not self.ascending: + segments = self.n_segments - 1 - segments + + ys = [] + group_start = 0 + for segment, group in groupby(segments): + group_end = group_start + len(list(group)) + y = self.interpolants[segment](t_sorted[group_start:group_end]) + ys.append(y) + group_start = group_end + + ys = np.hstack(ys) + ys = ys[:, reverse] + + return ys + + +NUM_JAC_DIFF_REJECT = EPS ** 0.875 +NUM_JAC_DIFF_SMALL = EPS ** 0.75 +NUM_JAC_DIFF_BIG = EPS ** 0.25 +NUM_JAC_MIN_FACTOR = 1e3 * EPS +NUM_JAC_FACTOR_INCREASE = 10 +NUM_JAC_FACTOR_DECREASE = 0.1 + + +def num_jac(fun, t, y, f, threshold, factor, sparsity=None): + """Finite differences Jacobian approximation tailored for ODE solvers. + + This function computes finite difference approximation to the Jacobian + matrix of `fun` with respect to `y` using forward differences. + The Jacobian matrix has shape (n, n) and its element (i, j) is equal to + ``d f_i / d y_j``. + + A special feature of this function is the ability to correct the step + size from iteration to iteration. The main idea is to keep the finite + difference significantly separated from its round-off error which + approximately equals ``EPS * np.abs(f)``. It reduces a possibility of a + huge error and assures that the estimated derivative are reasonably close + to the true values (i.e., the finite difference approximation is at least + qualitatively reflects the structure of the true Jacobian). + + Parameters + ---------- + fun : callable + Right-hand side of the system implemented in a vectorized fashion. + t : float + Current time. + y : ndarray, shape (n,) + Current state. + f : ndarray, shape (n,) + Value of the right hand side at (t, y). + threshold : float + Threshold for `y` value used for computing the step size as + ``factor * np.maximum(np.abs(y), threshold)``. Typically, the value of + absolute tolerance (atol) for a solver should be passed as `threshold`. + factor : ndarray with shape (n,) or None + Factor to use for computing the step size. Pass None for the very + evaluation, then use the value returned from this function. + sparsity : tuple (structure, groups) or None + Sparsity structure of the Jacobian, `structure` must be csc_matrix. + + Returns + ------- + J : ndarray or csc_matrix, shape (n, n) + Jacobian matrix. + factor : ndarray, shape (n,) + Suggested `factor` for the next evaluation. + """ + y = np.asarray(y) + n = y.shape[0] + if n == 0: + return np.empty((0, 0)), factor + + if factor is None: + factor = np.full(n, EPS ** 0.5) + else: + factor = factor.copy() + + # Direct the step as ODE dictates, hoping that such a step won't lead to + # a problematic region. For complex ODEs it makes sense to use the real + # part of f as we use steps along real axis. + f_sign = 2 * (np.real(f) >= 0).astype(float) - 1 + y_scale = f_sign * np.maximum(threshold, np.abs(y)) + h = (y + factor * y_scale) - y + + # Make sure that the step is not 0 to start with. Not likely it will be + # executed often. + for i in np.nonzero(h == 0)[0]: + while h[i] == 0: + factor[i] *= 10 + h[i] = (y[i] + factor[i] * y_scale[i]) - y[i] + + if sparsity is None: + return _dense_num_jac(fun, t, y, f, h, factor, y_scale) + else: + structure, groups = sparsity + return _sparse_num_jac(fun, t, y, f, h, factor, y_scale, + structure, groups) + + +def _dense_num_jac(fun, t, y, f, h, factor, y_scale): + n = y.shape[0] + h_vecs = np.diag(h) + f_new = fun(t, y[:, None] + h_vecs) + diff = f_new - f[:, None] + max_ind = np.argmax(np.abs(diff), axis=0) + r = np.arange(n) + max_diff = np.abs(diff[max_ind, r]) + scale = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r])) + + diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale + if np.any(diff_too_small): + ind, = np.nonzero(diff_too_small) + new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind] + h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind] + h_vecs[ind, ind] = h_new + f_new = fun(t, y[:, None] + h_vecs[:, ind]) + diff_new = f_new - f[:, None] + max_ind = np.argmax(np.abs(diff_new), axis=0) + r = np.arange(ind.shape[0]) + max_diff_new = np.abs(diff_new[max_ind, r]) + scale_new = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r])) + + update = max_diff[ind] * scale_new < max_diff_new * scale[ind] + if np.any(update): + update, = np.nonzero(update) + update_ind = ind[update] + factor[update_ind] = new_factor[update] + h[update_ind] = h_new[update] + diff[:, update_ind] = diff_new[:, update] + scale[update_ind] = scale_new[update] + max_diff[update_ind] = max_diff_new[update] + + diff /= h + + factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE + factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE + factor = np.maximum(factor, NUM_JAC_MIN_FACTOR) + + return diff, factor + + +def _sparse_num_jac(fun, t, y, f, h, factor, y_scale, structure, groups): + n = y.shape[0] + n_groups = np.max(groups) + 1 + h_vecs = np.empty((n_groups, n)) + for group in range(n_groups): + e = np.equal(group, groups) + h_vecs[group] = h * e + h_vecs = h_vecs.T + + f_new = fun(t, y[:, None] + h_vecs) + df = f_new - f[:, None] + + i, j, _ = find(structure) + diff = coo_matrix((df[i, groups[j]], (i, j)), shape=(n, n)).tocsc() + max_ind = np.array(abs(diff).argmax(axis=0)).ravel() + r = np.arange(n) + max_diff = np.asarray(np.abs(diff[max_ind, r])).ravel() + scale = np.maximum(np.abs(f[max_ind]), + np.abs(f_new[max_ind, groups[r]])) + + diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale + if np.any(diff_too_small): + ind, = np.nonzero(diff_too_small) + new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind] + h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind] + h_new_all = np.zeros(n) + h_new_all[ind] = h_new + + groups_unique = np.unique(groups[ind]) + groups_map = np.empty(n_groups, dtype=int) + h_vecs = np.empty((groups_unique.shape[0], n)) + for k, group in enumerate(groups_unique): + e = np.equal(group, groups) + h_vecs[k] = h_new_all * e + groups_map[group] = k + h_vecs = h_vecs.T + + f_new = fun(t, y[:, None] + h_vecs) + df = f_new - f[:, None] + i, j, _ = find(structure[:, ind]) + diff_new = coo_matrix((df[i, groups_map[groups[ind[j]]]], + (i, j)), shape=(n, ind.shape[0])).tocsc() + + max_ind_new = np.array(abs(diff_new).argmax(axis=0)).ravel() + r = np.arange(ind.shape[0]) + max_diff_new = np.asarray(np.abs(diff_new[max_ind_new, r])).ravel() + scale_new = np.maximum( + np.abs(f[max_ind_new]), + np.abs(f_new[max_ind_new, groups_map[groups[ind]]])) + + update = max_diff[ind] * scale_new < max_diff_new * scale[ind] + if np.any(update): + update, = np.nonzero(update) + update_ind = ind[update] + factor[update_ind] = new_factor[update] + h[update_ind] = h_new[update] + diff[:, update_ind] = diff_new[:, update] + scale[update_ind] = scale_new[update] + max_diff[update_ind] = max_diff_new[update] + + diff.data /= np.repeat(h, np.diff(diff.indptr)) + + factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE + factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE + factor = np.maximum(factor, NUM_JAC_MIN_FACTOR) + + return diff, factor diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/dop853_coefficients.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/dop853_coefficients.py new file mode 100644 index 0000000000000000000000000000000000000000..8e734c930f49f0065396e7fa46b80e53692385b5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/dop853_coefficients.py @@ -0,0 +1,193 @@ +import numpy as np + +N_STAGES = 12 +N_STAGES_EXTENDED = 16 +INTERPOLATOR_POWER = 7 + +C = np.array([0.0, + 0.526001519587677318785587544488e-01, + 0.789002279381515978178381316732e-01, + 0.118350341907227396726757197510, + 0.281649658092772603273242802490, + 0.333333333333333333333333333333, + 0.25, + 0.307692307692307692307692307692, + 0.651282051282051282051282051282, + 0.6, + 0.857142857142857142857142857142, + 1.0, + 1.0, + 0.1, + 0.2, + 0.777777777777777777777777777778]) + +A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED)) +A[1, 0] = 5.26001519587677318785587544488e-2 + +A[2, 0] = 1.97250569845378994544595329183e-2 +A[2, 1] = 5.91751709536136983633785987549e-2 + +A[3, 0] = 2.95875854768068491816892993775e-2 +A[3, 2] = 8.87627564304205475450678981324e-2 + +A[4, 0] = 2.41365134159266685502369798665e-1 +A[4, 2] = -8.84549479328286085344864962717e-1 +A[4, 3] = 9.24834003261792003115737966543e-1 + +A[5, 0] = 3.7037037037037037037037037037e-2 +A[5, 3] = 1.70828608729473871279604482173e-1 +A[5, 4] = 1.25467687566822425016691814123e-1 + +A[6, 0] = 3.7109375e-2 +A[6, 3] = 1.70252211019544039314978060272e-1 +A[6, 4] = 6.02165389804559606850219397283e-2 +A[6, 5] = -1.7578125e-2 + +A[7, 0] = 3.70920001185047927108779319836e-2 +A[7, 3] = 1.70383925712239993810214054705e-1 +A[7, 4] = 1.07262030446373284651809199168e-1 +A[7, 5] = -1.53194377486244017527936158236e-2 +A[7, 6] = 8.27378916381402288758473766002e-3 + +A[8, 0] = 6.24110958716075717114429577812e-1 +A[8, 3] = -3.36089262944694129406857109825 +A[8, 4] = -8.68219346841726006818189891453e-1 +A[8, 5] = 2.75920996994467083049415600797e1 +A[8, 6] = 2.01540675504778934086186788979e1 +A[8, 7] = -4.34898841810699588477366255144e1 + +A[9, 0] = 4.77662536438264365890433908527e-1 +A[9, 3] = -2.48811461997166764192642586468 +A[9, 4] = -5.90290826836842996371446475743e-1 +A[9, 5] = 2.12300514481811942347288949897e1 +A[9, 6] = 1.52792336328824235832596922938e1 +A[9, 7] = -3.32882109689848629194453265587e1 +A[9, 8] = -2.03312017085086261358222928593e-2 + +A[10, 0] = -9.3714243008598732571704021658e-1 +A[10, 3] = 5.18637242884406370830023853209 +A[10, 4] = 1.09143734899672957818500254654 +A[10, 5] = -8.14978701074692612513997267357 +A[10, 6] = -1.85200656599969598641566180701e1 +A[10, 7] = 2.27394870993505042818970056734e1 +A[10, 8] = 2.49360555267965238987089396762 +A[10, 9] = -3.0467644718982195003823669022 + +A[11, 0] = 2.27331014751653820792359768449 +A[11, 3] = -1.05344954667372501984066689879e1 +A[11, 4] = -2.00087205822486249909675718444 +A[11, 5] = -1.79589318631187989172765950534e1 +A[11, 6] = 2.79488845294199600508499808837e1 +A[11, 7] = -2.85899827713502369474065508674 +A[11, 8] = -8.87285693353062954433549289258 +A[11, 9] = 1.23605671757943030647266201528e1 +A[11, 10] = 6.43392746015763530355970484046e-1 + +A[12, 0] = 5.42937341165687622380535766363e-2 +A[12, 5] = 4.45031289275240888144113950566 +A[12, 6] = 1.89151789931450038304281599044 +A[12, 7] = -5.8012039600105847814672114227 +A[12, 8] = 3.1116436695781989440891606237e-1 +A[12, 9] = -1.52160949662516078556178806805e-1 +A[12, 10] = 2.01365400804030348374776537501e-1 +A[12, 11] = 4.47106157277725905176885569043e-2 + +A[13, 0] = 5.61675022830479523392909219681e-2 +A[13, 6] = 2.53500210216624811088794765333e-1 +A[13, 7] = -2.46239037470802489917441475441e-1 +A[13, 8] = -1.24191423263816360469010140626e-1 +A[13, 9] = 1.5329179827876569731206322685e-1 +A[13, 10] = 8.20105229563468988491666602057e-3 +A[13, 11] = 7.56789766054569976138603589584e-3 +A[13, 12] = -8.298e-3 + +A[14, 0] = 3.18346481635021405060768473261e-2 +A[14, 5] = 2.83009096723667755288322961402e-2 +A[14, 6] = 5.35419883074385676223797384372e-2 +A[14, 7] = -5.49237485713909884646569340306e-2 +A[14, 10] = -1.08347328697249322858509316994e-4 +A[14, 11] = 3.82571090835658412954920192323e-4 +A[14, 12] = -3.40465008687404560802977114492e-4 +A[14, 13] = 1.41312443674632500278074618366e-1 + +A[15, 0] = -4.28896301583791923408573538692e-1 +A[15, 5] = -4.69762141536116384314449447206 +A[15, 6] = 7.68342119606259904184240953878 +A[15, 7] = 4.06898981839711007970213554331 +A[15, 8] = 3.56727187455281109270669543021e-1 +A[15, 12] = -1.39902416515901462129418009734e-3 +A[15, 13] = 2.9475147891527723389556272149 +A[15, 14] = -9.15095847217987001081870187138 + + +B = A[N_STAGES, :N_STAGES] + +E3 = np.zeros(N_STAGES + 1) +E3[:-1] = B.copy() +E3[0] -= 0.244094488188976377952755905512 +E3[8] -= 0.733846688281611857341361741547 +E3[11] -= 0.220588235294117647058823529412e-1 + +E5 = np.zeros(N_STAGES + 1) +E5[0] = 0.1312004499419488073250102996e-1 +E5[5] = -0.1225156446376204440720569753e+1 +E5[6] = -0.4957589496572501915214079952 +E5[7] = 0.1664377182454986536961530415e+1 +E5[8] = -0.3503288487499736816886487290 +E5[9] = 0.3341791187130174790297318841 +E5[10] = 0.8192320648511571246570742613e-1 +E5[11] = -0.2235530786388629525884427845e-1 + +# First 3 coefficients are computed separately. +D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED)) +D[0, 0] = -0.84289382761090128651353491142e+1 +D[0, 5] = 0.56671495351937776962531783590 +D[0, 6] = -0.30689499459498916912797304727e+1 +D[0, 7] = 0.23846676565120698287728149680e+1 +D[0, 8] = 0.21170345824450282767155149946e+1 +D[0, 9] = -0.87139158377797299206789907490 +D[0, 10] = 0.22404374302607882758541771650e+1 +D[0, 11] = 0.63157877876946881815570249290 +D[0, 12] = -0.88990336451333310820698117400e-1 +D[0, 13] = 0.18148505520854727256656404962e+2 +D[0, 14] = -0.91946323924783554000451984436e+1 +D[0, 15] = -0.44360363875948939664310572000e+1 + +D[1, 0] = 0.10427508642579134603413151009e+2 +D[1, 5] = 0.24228349177525818288430175319e+3 +D[1, 6] = 0.16520045171727028198505394887e+3 +D[1, 7] = -0.37454675472269020279518312152e+3 +D[1, 8] = -0.22113666853125306036270938578e+2 +D[1, 9] = 0.77334326684722638389603898808e+1 +D[1, 10] = -0.30674084731089398182061213626e+2 +D[1, 11] = -0.93321305264302278729567221706e+1 +D[1, 12] = 0.15697238121770843886131091075e+2 +D[1, 13] = -0.31139403219565177677282850411e+2 +D[1, 14] = -0.93529243588444783865713862664e+1 +D[1, 15] = 0.35816841486394083752465898540e+2 + +D[2, 0] = 0.19985053242002433820987653617e+2 +D[2, 5] = -0.38703730874935176555105901742e+3 +D[2, 6] = -0.18917813819516756882830838328e+3 +D[2, 7] = 0.52780815920542364900561016686e+3 +D[2, 8] = -0.11573902539959630126141871134e+2 +D[2, 9] = 0.68812326946963000169666922661e+1 +D[2, 10] = -0.10006050966910838403183860980e+1 +D[2, 11] = 0.77771377980534432092869265740 +D[2, 12] = -0.27782057523535084065932004339e+1 +D[2, 13] = -0.60196695231264120758267380846e+2 +D[2, 14] = 0.84320405506677161018159903784e+2 +D[2, 15] = 0.11992291136182789328035130030e+2 + +D[3, 0] = -0.25693933462703749003312586129e+2 +D[3, 5] = -0.15418974869023643374053993627e+3 +D[3, 6] = -0.23152937917604549567536039109e+3 +D[3, 7] = 0.35763911791061412378285349910e+3 +D[3, 8] = 0.93405324183624310003907691704e+2 +D[3, 9] = -0.37458323136451633156875139351e+2 +D[3, 10] = 0.10409964950896230045147246184e+3 +D[3, 11] = 0.29840293426660503123344363579e+2 +D[3, 12] = -0.43533456590011143754432175058e+2 +D[3, 13] = 0.96324553959188282948394950600e+2 +D[3, 14] = -0.39177261675615439165231486172e+2 +D[3, 15] = -0.14972683625798562581422125276e+3 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/ivp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/ivp.py new file mode 100644 index 0000000000000000000000000000000000000000..65a9339807933e9b38634207687e1f2e94ed03a0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/ivp.py @@ -0,0 +1,757 @@ +import inspect +import numpy as np +from .bdf import BDF +from .radau import Radau +from .rk import RK23, RK45, DOP853 +from .lsoda import LSODA +from scipy.optimize import OptimizeResult +from .common import EPS, OdeSolution +from .base import OdeSolver +from scipy._lib._array_api import xp_capabilities + + +METHODS = {'RK23': RK23, + 'RK45': RK45, + 'DOP853': DOP853, + 'Radau': Radau, + 'BDF': BDF, + 'LSODA': LSODA} + + +MESSAGES = {0: "The solver successfully reached the end of the integration interval.", + 1: "A termination event occurred."} + + +class OdeResult(OptimizeResult): + pass + + +def prepare_events(events): + """Standardize event functions and extract attributes.""" + if callable(events): + events = (events,) + + max_events = np.empty(len(events)) + direction = np.empty(len(events)) + for i, event in enumerate(events): + terminal = getattr(event, 'terminal', None) + direction[i] = getattr(event, 'direction', 0) + + message = ('The `terminal` attribute of each event ' + 'must be a boolean or positive integer.') + if terminal is None or terminal == 0: + max_events[i] = np.inf + elif int(terminal) == terminal and terminal > 0: + max_events[i] = terminal + else: + raise ValueError(message) + + return events, max_events, direction + + +def solve_event_equation(event, sol, t_old, t): + """Solve an equation corresponding to an ODE event. + + The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an + ODE solver using some sort of interpolation. It is solved by + `scipy.optimize.brentq` with xtol=atol=4*EPS. + + Parameters + ---------- + event : callable + Function ``event(t, y)``. + sol : callable + Function ``sol(t)`` which evaluates an ODE solution between `t_old` + and `t`. + t_old, t : float + Previous and new values of time. They will be used as a bracketing + interval. + + Returns + ------- + root : float + Found solution. + """ + from scipy.optimize import brentq + return brentq(lambda t: event(t, sol(t)), t_old, t, + xtol=4 * EPS, rtol=4 * EPS) + + +def handle_events(sol, events, active_events, event_count, max_events, + t_old, t): + """Helper function to handle events. + + Parameters + ---------- + sol : DenseOutput + Function ``sol(t)`` which evaluates an ODE solution between `t_old` + and `t`. + events : list of callables, length n_events + Event functions with signatures ``event(t, y)``. + active_events : ndarray + Indices of events which occurred. + event_count : ndarray + Current number of occurrences for each event. + max_events : ndarray, shape (n_events,) + Number of occurrences allowed for each event before integration + termination is issued. + t_old, t : float + Previous and new values of time. + + Returns + ------- + root_indices : ndarray + Indices of events which take zero between `t_old` and `t` and before + a possible termination. + roots : ndarray + Values of t at which events occurred. + terminate : bool + Whether a terminal event occurred. + """ + roots = [solve_event_equation(events[event_index], sol, t_old, t) + for event_index in active_events] + + roots = np.asarray(roots) + + if np.any(event_count[active_events] >= max_events[active_events]): + if t > t_old: + order = np.argsort(roots) + else: + order = np.argsort(-roots) + active_events = active_events[order] + roots = roots[order] + t = np.nonzero(event_count[active_events] + >= max_events[active_events])[0][0] + active_events = active_events[:t + 1] + roots = roots[:t + 1] + terminate = True + else: + terminate = False + + return active_events, roots, terminate + + +def find_active_events(g, g_new, direction): + """Find which event occurred during an integration step. + + Parameters + ---------- + g, g_new : array_like, shape (n_events,) + Values of event functions at a current and next points. + direction : ndarray, shape (n_events,) + Event "direction" according to the definition in `solve_ivp`. + + Returns + ------- + active_events : ndarray + Indices of events which occurred during the step. + """ + g, g_new = np.asarray(g), np.asarray(g_new) + up = (g <= 0) & (g_new >= 0) + down = (g >= 0) & (g_new <= 0) + either = up | down + mask = (up & (direction > 0) | + down & (direction < 0) | + either & (direction == 0)) + + return np.nonzero(mask)[0] + + +@xp_capabilities(np_only=True) +def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, + events=None, vectorized=False, args=None, **options): + """Solve an initial value problem for a system of ODEs. + + This function numerically integrates a system of ordinary differential + equations given an initial value:: + + dy / dt = f(t, y) + y(t0) = y0 + + Here t is a 1-D independent variable (time), y(t) is an + N-D vector-valued function (state), and an N-D + vector-valued function f(t, y) determines the differential equations. + The goal is to find y(t) approximately satisfying the differential + equations, given an initial value y(t0)=y0. + + Some of the solvers support integration in the complex domain, but note + that for stiff ODE solvers, the right-hand side must be + complex-differentiable (satisfy Cauchy-Riemann equations [11]_). + To solve a problem in the complex domain, pass y0 with a complex data type. + Another option always available is to rewrite your problem for real and + imaginary parts separately. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional + arguments need to be passed if ``args`` is used (see documentation of + ``args`` argument). ``fun`` must return an array of the same shape as + ``y``. See `vectorized` for more information. + t_span : 2-member sequence + Interval of integration (t0, tf). The solver starts with t=t0 and + integrates until it reaches t=tf. Both t0 and tf must be floats + or values interpretable by the float conversion function. + y0 : array_like, shape (n,) + Initial state. For problems in the complex domain, pass `y0` with a + complex data type (even if the initial value is purely real). + method : string or `OdeSolver`, optional + Integration method to use: + + * 'RK45' (default): Explicit Runge-Kutta method of order 5(4) [1]_. + The error is controlled assuming accuracy of the fourth-order + method, but steps are taken using the fifth-order accurate + formula (local extrapolation is done). A quartic interpolation + polynomial is used for the dense output [2]_. Can be applied in + the complex domain. + * 'RK23': Explicit Runge-Kutta method of order 3(2) [3]_. The error + is controlled assuming accuracy of the second-order method, but + steps are taken using the third-order accurate formula (local + extrapolation is done). A cubic Hermite polynomial is used for the + dense output. Can be applied in the complex domain. + * 'DOP853': Explicit Runge-Kutta method of order 8 [13]_. + Python implementation of the "DOP853" algorithm originally + written in Fortran [14]_. A 7-th order interpolation polynomial + accurate to 7-th order is used for the dense output. + Can be applied in the complex domain. + * 'Radau': Implicit Runge-Kutta method of the Radau IIA family of + order 5 [4]_. The error is controlled with a third-order accurate + embedded formula. A cubic polynomial which satisfies the + collocation conditions is used for the dense output. + * 'BDF': Implicit multi-step variable-order (1 to 5) method based + on a backward differentiation formula for the derivative + approximation [5]_. The implementation follows the one described + in [6]_. A quasi-constant step scheme is used and accuracy is + enhanced using the NDF modification. Can be applied in the + complex domain. + * 'LSODA': Adams/BDF method with automatic stiffness detection and + switching [7]_, [8]_. This is a wrapper of the Fortran solver + from ODEPACK. + + Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used + for non-stiff problems and implicit methods ('Radau', 'BDF') for + stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended + for solving with high precision (low values of `rtol` and `atol`). + + If not sure, first try to run 'RK45'. If it makes unusually many + iterations, diverges, or fails, your problem is likely to be stiff and + you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal + choice, but it might be somewhat less convenient to work with as it + wraps old Fortran code. + + You can also pass an arbitrary class derived from `OdeSolver` which + implements the solver. + t_eval : array_like or None, optional + Times at which to store the computed solution, must be sorted and lie + within `t_span`. If None (default), use points selected by the solver. + dense_output : bool, optional + Whether to compute a continuous solution. Default is False. + events : callable, or list of callables, optional + Events to track. If None (default), no events will be tracked. + Each event occurs at the zeros of a continuous function of time and + state. Each function must have the signature ``event(t, y)`` where + additional argument have to be passed if ``args`` is used (see + documentation of ``args`` argument). Each function must return a + float. The solver will find an accurate value of `t` at which + ``event(t, y(t)) = 0`` using a root-finding algorithm. By default, + all zeros will be found. The solver looks for a sign change over + each step, so if multiple zero crossings occur within one step, + events may be missed. Additionally each `event` function might + have the following attributes: + + terminal: bool or int, optional + When boolean, whether to terminate integration if this event occurs. + When integral, termination occurs after the specified the number of + occurrences of this event. + Implicitly False if not assigned. + direction: float, optional + Direction of a zero crossing. If `direction` is positive, + `event` will only trigger when going from negative to positive, + and vice versa if `direction` is negative. If 0, then either + direction will trigger event. Implicitly 0 if not assigned. + + You can assign attributes like ``event.terminal = True`` to any + function in Python. + vectorized : bool, optional + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for other methods and for 'Radau' and + 'BDF' in some circumstances (e.g. small ``len(y0)``). + args : tuple, optional + Additional arguments to pass to the user-defined functions. If given, + the additional arguments are passed to all user-defined functions. + So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``, + then `jac` (if given) and any event functions must have the same + signature, and `args` must be a tuple of length 3. + **options + Options passed to a chosen solver. All options available for already + implemented solvers are listed below. + first_step : float or None, optional + Initial step size. Default is `None` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float or array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : array_like, sparse_matrix, callable or None, optional + Jacobian matrix of the right-hand side of the system with respect + to y, required by the 'Radau', 'BDF' and 'LSODA' method. The + Jacobian matrix has shape (n, n) and its element (i, j) is equal to + ``d f_i / d y_j``. There are three ways to define the Jacobian: + + * If array_like or sparse_matrix, the Jacobian is assumed to + be constant. Not supported by 'LSODA'. + * If callable, the Jacobian is assumed to depend on both + t and y; it will be called as ``jac(t, y)``, as necessary. + Additional arguments have to be passed if ``args`` is + used (see documentation of ``args`` argument). + For 'Radau' and 'BDF' methods, the return value might be a + sparse matrix. + * If None (default), the Jacobian will be approximated by + finite differences. + + It is generally recommended to provide the Jacobian rather than + relying on a finite-difference approximation. + jac_sparsity : array_like, sparse matrix or None, optional + Defines a sparsity structure of the Jacobian matrix for a finite- + difference approximation. Its shape must be (n, n). This argument + is ignored if `jac` is not `None`. If the Jacobian has only few + non-zero elements in *each* row, providing the sparsity structure + will greatly speed up the computations [10]_. A zero entry means that + a corresponding element in the Jacobian is always zero. If None + (default), the Jacobian is assumed to be dense. + Not supported by 'LSODA', see `lband` and `uband` instead. + lband, uband : int or None, optional + Parameters defining the bandwidth of the Jacobian for the 'LSODA' + method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. + Default is None. Setting these requires your jac routine to return the + Jacobian in the packed format: the returned array must have ``n`` + columns and ``uband + lband + 1`` rows in which Jacobian diagonals are + written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``. + The same format is used in `scipy.linalg.solve_banded` (check for an + illustration). These parameters can be also used with ``jac=None`` to + reduce the number of Jacobian elements estimated by finite differences. + min_step : float, optional + The minimum allowed step size for 'LSODA' method. + By default `min_step` is zero. + + Returns + ------- + Bunch object with the following fields defined: + t : ndarray, shape (n_points,) + Time points. + y : ndarray, shape (n, n_points) + Values of the solution at `t`. + sol : `OdeSolution` or None + Found solution as `OdeSolution` instance; None if `dense_output` was + set to False. + t_events : list of ndarray or None + Contains for each event type a list of arrays at which an event of + that type event was detected. None if `events` was None. + y_events : list of ndarray or None + For each value of `t_events`, the corresponding value of the solution. + None if `events` was None. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + nlu : int + Number of LU decompositions. + status : int + Reason for algorithm termination: + + * -1: Integration step failed. + * 0: The solver successfully reached the end of `tspan`. + * 1: A termination event occurred. + + message : string + Human-readable description of the termination reason. + success : bool + True if the solver reached the interval end or a termination event + occurred (``status >= 0``). + + References + ---------- + .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta + formulae", Journal of Computational and Applied Mathematics, Vol. 6, + No. 1, pp. 19-26, 1980. + .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics + of Computation,, Vol. 46, No. 173, pp. 135-150, 1986. + .. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas", + Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989. + .. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II: + Stiff and Differential-Algebraic Problems", Sec. IV.8. + .. [5] `Backward Differentiation Formula + `_ + on Wikipedia. + .. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI. + COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997. + .. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE + Solvers," IMACS Transactions on Scientific Computation, Vol 1., + pp. 55-64, 1983. + .. [8] L. Petzold, "Automatic selection of methods for solving stiff and + nonstiff systems of ordinary differential equations", SIAM Journal + on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148, + 1983. + .. [9] `Stiff equation `_ on + Wikipedia. + .. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13, pp. 117-120, 1974. + .. [11] `Cauchy-Riemann equations + `_ on + Wikipedia. + .. [12] `Lotka-Volterra equations + `_ + on Wikipedia. + .. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II. + .. [14] `Page with original Fortran code of DOP853 + `_. + + Examples + -------- + Basic exponential decay showing automatically chosen time points. + + >>> import numpy as np + >>> from scipy.integrate import solve_ivp + >>> def exponential_decay(t, y): return -0.5 * y + >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8]) + >>> print(sol.t) + [ 0. 0.11487653 1.26364188 3.06061781 4.81611105 6.57445806 + 8.33328988 10. ] + >>> print(sol.y) + [[2. 1.88836035 1.06327177 0.43319312 0.18017253 0.07483045 + 0.03107158 0.01350781] + [4. 3.7767207 2.12654355 0.86638624 0.36034507 0.14966091 + 0.06214316 0.02701561] + [8. 7.5534414 4.25308709 1.73277247 0.72069014 0.29932181 + 0.12428631 0.05403123]] + + Specifying points where the solution is desired. + + >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8], + ... t_eval=[0, 1, 2, 4, 10]) + >>> print(sol.t) + [ 0 1 2 4 10] + >>> print(sol.y) + [[2. 1.21305369 0.73534021 0.27066736 0.01350938] + [4. 2.42610739 1.47068043 0.54133472 0.02701876] + [8. 4.85221478 2.94136085 1.08266944 0.05403753]] + + Cannon fired upward with terminal event upon impact. The ``terminal`` and + ``direction`` fields of an event are applied by monkey patching a function. + Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts + at position 0 with velocity +10. Note that the integration never reaches + t=100 because the event is terminal. + + >>> def upward_cannon(t, y): return [y[1], -0.5] + >>> def hit_ground(t, y): return y[0] + >>> hit_ground.terminal = True + >>> hit_ground.direction = -1 + >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground) + >>> print(sol.t_events) + [array([40.])] + >>> print(sol.t) + [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02 + 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01] + + Use `dense_output` and `events` to find position, which is 100, at the apex + of the cannonball's trajectory. Apex is not defined as terminal, so both + apex and hit_ground are found. There is no information at t=20, so the sol + attribute is used to evaluate the solution. The sol attribute is returned + by setting ``dense_output=True``. Alternatively, the `y_events` attribute + can be used to access the solution at the time of the event. + + >>> def apex(t, y): return y[1] + >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], + ... events=(hit_ground, apex), dense_output=True) + >>> print(sol.t_events) + [array([40.]), array([20.])] + >>> print(sol.t) + [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02 + 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01] + >>> print(sol.sol(sol.t_events[1][0])) + [100. 0.] + >>> print(sol.y_events) + [array([[-5.68434189e-14, -1.00000000e+01]]), + array([[1.00000000e+02, 1.77635684e-15]])] + + As an example of a system with additional parameters, we'll implement + the Lotka-Volterra equations [12]_. + + >>> def lotkavolterra(t, z, a, b, c, d): + ... x, y = z + ... return [a*x - b*x*y, -c*y + d*x*y] + ... + + We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args` + argument. + + >>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1), + ... dense_output=True) + + Compute a dense solution and plot it. + + >>> t = np.linspace(0, 15, 300) + >>> z = sol.sol(t) + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, z.T) + >>> plt.xlabel('t') + >>> plt.legend(['x', 'y'], shadow=True) + >>> plt.title('Lotka-Volterra System') + >>> plt.show() + + A couple examples of using solve_ivp to solve the differential + equation ``y' = Ay`` with complex matrix ``A``. + + >>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j], + ... [0.25 + 0.58j, -0.2 + 0.14j, 0], + ... [0, 0.2 + 0.4j, -0.1 + 0.97j]]) + + Solving an IVP with ``A`` from above and ``y`` as 3x1 vector: + + >>> def deriv_vec(t, y): + ... return A @ y + >>> result = solve_ivp(deriv_vec, [0, 25], + ... np.array([10 + 0j, 20 + 0j, 30 + 0j]), + ... t_eval=np.linspace(0, 25, 101)) + >>> print(result.y[:, 0]) + [10.+0.j 20.+0.j 30.+0.j] + >>> print(result.y[:, -1]) + [18.46291039+45.25653651j 10.01569306+36.23293216j + -4.98662741+80.07360388j] + + Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix : + + >>> def deriv_mat(t, y): + ... return (A @ y.reshape(3, 3)).flatten() + >>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j], + ... [5 + 0j, 6 + 0j, 7 + 0j], + ... [9 + 0j, 34 + 0j, 78 + 0j]]) + + >>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(), + ... t_eval=np.linspace(0, 25, 101)) + >>> print(result.y[:, 0].reshape(3, 3)) + [[ 2.+0.j 3.+0.j 4.+0.j] + [ 5.+0.j 6.+0.j 7.+0.j] + [ 9.+0.j 34.+0.j 78.+0.j]] + >>> print(result.y[:, -1].reshape(3, 3)) + [[ 5.67451179 +12.07938445j 17.2888073 +31.03278837j + 37.83405768 +63.25138759j] + [ 3.39949503 +11.82123994j 21.32530996 +44.88668871j + 53.17531184+103.80400411j] + [ -2.26105874 +22.19277664j -15.1255713 +70.19616341j + -38.34616845+153.29039931j]] + + + """ + if method not in METHODS and not ( + inspect.isclass(method) and issubclass(method, OdeSolver)): + raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.") + + t0, tf = map(float, t_span) + + if args is not None: + # Wrap the user's fun (and jac, if given) in lambdas to hide the + # additional parameters. Pass in the original fun as a keyword + # argument to keep it in the scope of the lambda. + try: + _ = [*(args)] + except TypeError as exp: + suggestion_tuple = ( + "Supplied 'args' cannot be unpacked. Please supply `args`" + f" as a tuple (e.g. `args=({args},)`)" + ) + raise TypeError(suggestion_tuple) from exp + + def fun(t, x, fun=fun): + return fun(t, x, *args) + jac = options.get('jac') + if callable(jac): + options['jac'] = lambda t, x: jac(t, x, *args) + + if t_eval is not None: + t_eval = np.asarray(t_eval) + if t_eval.ndim != 1: + raise ValueError("`t_eval` must be 1-dimensional.") + + if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)): + raise ValueError("Values in `t_eval` are not within `t_span`.") + + d = np.diff(t_eval) + if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0): + raise ValueError("Values in `t_eval` are not properly sorted.") + + if tf > t0: + t_eval_i = 0 + else: + # Make order of t_eval decreasing to use np.searchsorted. + t_eval = t_eval[::-1] + # This will be an upper bound for slices. + t_eval_i = t_eval.shape[0] + + if method in METHODS: + method = METHODS[method] + + solver = method(fun, t0, y0, tf, vectorized=vectorized, **options) + + if t_eval is None: + ts = [t0] + ys = [y0] + elif t_eval is not None and dense_output: + ts = [] + ti = [t0] + ys = [] + else: + ts = [] + ys = [] + + interpolants = [] + + if events is not None: + events, max_events, event_dir = prepare_events(events) + event_count = np.zeros(len(events)) + if args is not None: + # Wrap user functions in lambdas to hide the additional parameters. + # The original event function is passed as a keyword argument to the + # lambda to keep the original function in scope (i.e., avoid the + # late binding closure "gotcha"). + events = [lambda t, x, event=event: event(t, x, *args) + for event in events] + g = [event(t0, y0) for event in events] + t_events = [[] for _ in range(len(events))] + y_events = [[] for _ in range(len(events))] + else: + t_events = None + y_events = None + + status = None + while status is None: + message = solver.step() + + if solver.status == 'finished': + status = 0 + elif solver.status == 'failed': + status = -1 + break + + t_old = solver.t_old + t = solver.t + y = solver.y + + if dense_output: + sol = solver.dense_output() + interpolants.append(sol) + else: + sol = None + + if events is not None: + g_new = [event(t, y) for event in events] + active_events = find_active_events(g, g_new, event_dir) + if active_events.size > 0: + if sol is None: + sol = solver.dense_output() + + event_count[active_events] += 1 + root_indices, roots, terminate = handle_events( + sol, events, active_events, event_count, max_events, + t_old, t) + + for e, te in zip(root_indices, roots): + t_events[e].append(te) + y_events[e].append(sol(te)) + + if terminate: + status = 1 + t = roots[-1] + y = sol(t) + + g = g_new + + if t_eval is None: + donot_append = (len(ts) > 1 and + ts[-1] == t and + dense_output) + if not donot_append: + ts.append(t) + ys.append(y) + else: + if len(interpolants) > 0: + interpolants.pop() + else: + # The value in t_eval equal to t will be included. + if solver.direction > 0: + t_eval_i_new = np.searchsorted(t_eval, t, side='right') + t_eval_step = t_eval[t_eval_i:t_eval_i_new] + else: + t_eval_i_new = np.searchsorted(t_eval, t, side='left') + # It has to be done with two slice operations, because + # you can't slice to 0th element inclusive using backward + # slicing. + t_eval_step = t_eval[t_eval_i_new:t_eval_i][::-1] + + if t_eval_step.size > 0: + if sol is None: + sol = solver.dense_output() + ts.append(t_eval_step) + ys.append(sol(t_eval_step)) + t_eval_i = t_eval_i_new + + if t_eval is not None and dense_output: + ti.append(t) + + message = MESSAGES.get(status, message) + + if t_events is not None: + t_events = [np.asarray(te) for te in t_events] + y_events = [np.asarray(ye) for ye in y_events] + + if t_eval is None: + ts = np.array(ts) + ys = np.vstack(ys).T + elif ts: + ts = np.hstack(ts) + ys = np.hstack(ys) + + if dense_output: + if t_eval is None: + sol = OdeSolution( + ts, interpolants, alt_segment=True if method in [BDF, LSODA] else False + ) + else: + sol = OdeSolution( + ti, interpolants, alt_segment=True if method in [BDF, LSODA] else False + ) + else: + sol = None + + return OdeResult(t=ts, y=ys, sol=sol, t_events=t_events, y_events=y_events, + nfev=solver.nfev, njev=solver.njev, nlu=solver.nlu, + status=status, message=message, success=status >= 0) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/lsoda.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/lsoda.py new file mode 100644 index 0000000000000000000000000000000000000000..a49fb7b7fd23a72a1dc8354b292e9e3b28693e4b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/lsoda.py @@ -0,0 +1,227 @@ +import numpy as np +from scipy.integrate import ode +from .common import validate_tol, validate_first_step, warn_extraneous +from .base import OdeSolver, DenseOutput + + +class LSODA(OdeSolver): + """Adams/BDF method with automatic stiffness detection and switching. + + This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches + automatically between the nonstiff Adams method and the stiff BDF method. + The method was originally detailed in [2]_. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + min_step : float, optional + Minimum allowed step size. Default is 0.0, i.e., the step size is not + bounded and determined solely by the solver. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : None or callable, optional + Jacobian matrix of the right-hand side of the system with respect to + ``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is + equal to ``d f_i / d y_j``. The function will be called as + ``jac(t, y)``. If None (default), the Jacobian will be + approximated by finite differences. It is generally recommended to + provide the Jacobian rather than relying on a finite-difference + approximation. + lband, uband : int or None + Parameters defining the bandwidth of the Jacobian, + i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting + these requires your jac routine to return the Jacobian in the packed format: + the returned array must have ``n`` columns and ``uband + lband + 1`` + rows in which Jacobian diagonals are written. Specifically + ``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used + in `scipy.linalg.solve_banded` (check for an illustration). + These parameters can be also used with ``jac=None`` to reduce the + number of Jacobian elements estimated by finite differences. + vectorized : bool, optional + Whether `fun` may be called in a vectorized fashion. False (default) + is recommended for this solver. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for this solver. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + + References + ---------- + .. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE + Solvers," IMACS Transactions on Scientific Computation, Vol 1., + pp. 55-64, 1983. + .. [2] L. Petzold, "Automatic selection of methods for solving stiff and + nonstiff systems of ordinary differential equations", SIAM Journal + on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148, + 1983. + """ + def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0, + max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None, + uband=None, vectorized=False, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized) + + if first_step is None: + first_step = 0 # LSODA value for automatic selection. + else: + first_step = validate_first_step(first_step, t0, t_bound) + + first_step *= self.direction + + if max_step == np.inf: + max_step = 0 # LSODA value for infinity. + elif max_step <= 0: + raise ValueError("`max_step` must be positive.") + + if min_step < 0: + raise ValueError("`min_step` must be nonnegative.") + + rtol, atol = validate_tol(rtol, atol, self.n) + + solver = ode(self.fun, jac) + solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step, + min_step=min_step, first_step=first_step, + lband=lband, uband=uband) + solver.set_initial_value(y0, t0) + + # Inject t_bound into rwork array as needed for itask=5. + solver._integrator.rwork[0] = self.t_bound + solver._integrator.call_args[4] = solver._integrator.rwork + + self._lsoda_solver = solver + + def _step_impl(self): + solver = self._lsoda_solver + integrator = solver._integrator + + # From lsoda.step and lsoda.integrate itask=5 means take a single + # step and do not go past t_bound. + itask = integrator.call_args[2] + integrator.call_args[2] = 5 + solver._y, solver.t = integrator.run( + solver.f, solver.jac or (lambda: None), solver._y, solver.t, + self.t_bound, solver.f_params, solver.jac_params) + integrator.call_args[2] = itask + + if solver.successful(): + self.t = solver.t + # IMPORTANT: Must copy solver._y because the C code reuses the same + # array object across calls (for in-place modification). Without copy, + # solve_ivp would store references to the same array. + self.y = solver._y.copy() + # From LSODA Fortran source njev is equal to nlu. + self.njev = integrator.iwork[12] + self.nlu = integrator.iwork[12] + return True, None + else: + return False, 'Unexpected istate in LSODA.' + + def _dense_output_impl(self): + iwork = self._lsoda_solver._integrator.iwork + rwork = self._lsoda_solver._integrator.rwork + + # We want to produce the Nordsieck history array, yh, up to the order + # used in the last successful iteration. The step size is unimportant + # because it will be scaled out in LsodaDenseOutput. Some additional + # work may be required because ODEPACK's LSODA implementation produces + # the Nordsieck history in the state needed for the next iteration. + + # iwork[13] contains order from last successful iteration, while + # iwork[14] contains order to be attempted next. + order = iwork[13] + + # rwork[11] contains the step size to be attempted next, while + # rwork[10] contains step size from last successful iteration. + h = rwork[11] + + # rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the + # Nordsieck array in state needed for next iteration. We want + # the entries up to order for the last successful step so use the + # following. + yh = np.reshape(rwork[20:20 + (order + 1) * self.n], + (self.n, order + 1), order='F').copy() + if iwork[14] < order: + # If the order is set to decrease then the final column of yh + # has not been updated within ODEPACK's LSODA + # implementation because this column will not be used in the + # next iteration. We must rescale this column to make the + # associated step size consistent with the other columns. + yh[:, -1] *= (h / rwork[10]) ** order + + return LsodaDenseOutput(self.t_old, self.t, h, order, yh) + + +class LsodaDenseOutput(DenseOutput): + def __init__(self, t_old, t, h, order, yh): + super().__init__(t_old, t) + self.h = h + self.yh = yh + self.p = np.arange(order + 1) + + def _call_impl(self, t): + if t.ndim == 0: + x = ((t - self.t) / self.h) ** self.p + else: + x = ((t - self.t) / self.h) ** self.p[:, None] + + return np.dot(self.yh, x) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/radau.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/radau.py new file mode 100644 index 0000000000000000000000000000000000000000..2f42243a169d135302f8547217fbfefda0648e18 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/radau.py @@ -0,0 +1,572 @@ +import numpy as np +from scipy.linalg import lu_factor, lu_solve +from scipy.sparse import csc_matrix, issparse, eye +from scipy.sparse.linalg import splu +from scipy.optimize._numdiff import group_columns +from .common import (validate_max_step, validate_tol, select_initial_step, + norm, num_jac, EPS, warn_extraneous, + validate_first_step) +from .base import OdeSolver, DenseOutput + +S6 = 6 ** 0.5 + +# Butcher tableau. A is not used directly, see below. +C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1]) +E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3 + +# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue +# and a complex conjugate pair. They are written below. +MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3) +MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3)) + - 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6))) + +# These are transformation matrices. +T = np.array([ + [0.09443876248897524, -0.14125529502095421, 0.03002919410514742], + [0.25021312296533332, 0.20412935229379994, -0.38294211275726192], + [1, 1, 0]]) +TI = np.array([ + [4.17871859155190428, 0.32768282076106237, 0.52337644549944951], + [-4.17871859155190428, -0.32768282076106237, 0.47662355450055044], + [0.50287263494578682, -2.57192694985560522, 0.59603920482822492]]) +# These linear combinations are used in the algorithm. +TI_REAL = TI[0] +TI_COMPLEX = TI[1] + 1j * TI[2] + +# Interpolator coefficients. +P = np.array([ + [13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6], + [13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6], + [1/3, -8/3, 10/3]]) + + +NEWTON_MAXITER = 6 # Maximum number of Newton iterations. +MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size. +MAX_FACTOR = 10 # Maximum allowed increase in a step size. + + +def solve_collocation_system(fun, t, y, h, Z0, scale, tol, + LU_real, LU_complex, solve_lu): + """Solve the collocation system. + + Parameters + ---------- + fun : callable + Right-hand side of the system. + t : float + Current time. + y : ndarray, shape (n,) + Current state. + h : float + Step to try. + Z0 : ndarray, shape (3, n) + Initial guess for the solution. It determines new values of `y` at + ``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants. + scale : ndarray, shape (n) + Problem tolerance scale, i.e. ``rtol * abs(y) + atol``. + tol : float + Tolerance to which solve the system. This value is compared with + the normalized by `scale` error. + LU_real, LU_complex + LU decompositions of the system Jacobians. + solve_lu : callable + Callable which solves a linear system given a LU decomposition. The + signature is ``solve_lu(LU, b)``. + + Returns + ------- + converged : bool + Whether iterations converged. + n_iter : int + Number of completed iterations. + Z : ndarray, shape (3, n) + Found solution. + rate : float + The rate of convergence. + """ + n = y.shape[0] + M_real = MU_REAL / h + M_complex = MU_COMPLEX / h + + W = TI.dot(Z0) + Z = Z0 + + F = np.empty((3, n)) + ch = h * C + + dW_norm_old = None + dW = np.empty_like(W) + converged = False + rate = None + for k in range(NEWTON_MAXITER): + for i in range(3): + F[i] = fun(t + ch[i], y + Z[i]) + + if not np.all(np.isfinite(F)): + break + + f_real = F.T.dot(TI_REAL) - M_real * W[0] + f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2]) + + dW_real = solve_lu(LU_real, f_real) + dW_complex = solve_lu(LU_complex, f_complex) + + dW[0] = dW_real + dW[1] = dW_complex.real + dW[2] = dW_complex.imag + + dW_norm = norm(dW / scale) + if dW_norm_old is not None: + rate = dW_norm / dW_norm_old + + if (rate is not None and (rate >= 1 or + rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)): + break + + W += dW + Z = T.dot(W) + + if (dW_norm == 0 or + rate is not None and rate / (1 - rate) * dW_norm < tol): + converged = True + break + + dW_norm_old = dW_norm + + return converged, k + 1, Z, rate + + +def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old): + """Predict by which factor to increase/decrease the step size. + + The algorithm is described in [1]_. + + Parameters + ---------- + h_abs, h_abs_old : float + Current and previous values of the step size, `h_abs_old` can be None + (see Notes). + error_norm, error_norm_old : float + Current and previous values of the error norm, `error_norm_old` can + be None (see Notes). + + Returns + ------- + factor : float + Predicted factor. + + Notes + ----- + If `h_abs_old` and `error_norm_old` are both not None then a two-step + algorithm is used, otherwise a one-step algorithm is used. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8. + """ + if error_norm_old is None or h_abs_old is None or error_norm == 0: + multiplier = 1 + else: + multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25 + + with np.errstate(divide='ignore'): + factor = min(1, multiplier) * error_norm ** -0.25 + + return factor + + +class Radau(OdeSolver): + """Implicit Runge-Kutta method of Radau IIA family of order 5. + + The implementation follows [1]_. The error is controlled with a + third-order accurate embedded formula. A cubic polynomial which satisfies + the collocation conditions is used for the dense output. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : {None, array_like, sparse_matrix, callable}, optional + Jacobian matrix of the right-hand side of the system with respect to + y, required by this method. The Jacobian matrix has shape (n, n) and + its element (i, j) is equal to ``d f_i / d y_j``. + There are three ways to define the Jacobian: + + * If array_like or sparse_matrix, the Jacobian is assumed to + be constant. + * If callable, the Jacobian is assumed to depend on both + t and y; it will be called as ``jac(t, y)`` as necessary. + For the 'Radau' and 'BDF' methods, the return value might be a + sparse matrix. + * If None (default), the Jacobian will be approximated by + finite differences. + + It is generally recommended to provide the Jacobian rather than + relying on a finite-difference approximation. + jac_sparsity : {None, array_like, sparse matrix}, optional + Defines a sparsity structure of the Jacobian matrix for a + finite-difference approximation. Its shape must be (n, n). This argument + is ignored if `jac` is not `None`. If the Jacobian has only few non-zero + elements in *each* row, providing the sparsity structure will greatly + speed up the computations [2]_. A zero entry means that a corresponding + element in the Jacobian is always zero. If None (default), the Jacobian + is assumed to be dense. + vectorized : bool, optional + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by this method, but may result in slower + execution overall in some circumstances (e.g. small ``len(y0)``). + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + nlu : int + Number of LU decompositions. + + References + ---------- + .. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II: + Stiff and Differential-Algebraic Problems", Sec. IV.8. + .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13, pp. 117-120, 1974. + """ + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None, + vectorized=False, first_step=None, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized) + self.y_old = None + self.max_step = validate_max_step(max_step) + self.rtol, self.atol = validate_tol(rtol, atol, self.n) + self.f = self.fun(self.t, self.y) + # Select initial step assuming the same order which is used to control + # the error. + if first_step is None: + self.h_abs = select_initial_step( + self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction, + 3, self.rtol, self.atol) + else: + self.h_abs = validate_first_step(first_step, t0, t_bound) + self.h_abs_old = None + self.error_norm_old = None + + self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5)) + self.sol = None + + self.jac_factor = None + self.jac, self.J = self._validate_jac(jac, jac_sparsity) + if issparse(self.J): + def lu(A): + self.nlu += 1 + return splu(A) + + def solve_lu(LU, b): + return LU.solve(b) + + I = eye(self.n, format='csc') + else: + def lu(A): + self.nlu += 1 + return lu_factor(A, overwrite_a=True) + + def solve_lu(LU, b): + return lu_solve(LU, b, overwrite_b=True) + + I = np.identity(self.n) + + self.lu = lu + self.solve_lu = solve_lu + self.I = I + + self.current_jac = True + self.LU_real = None + self.LU_complex = None + self.Z = None + + def _validate_jac(self, jac, sparsity): + t0 = self.t + y0 = self.y + + if jac is None: + if sparsity is not None: + if issparse(sparsity): + sparsity = csc_matrix(sparsity) + groups = group_columns(sparsity) + sparsity = (sparsity, groups) + + def jac_wrapped(t, y, f): + self.njev += 1 + J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f, + self.atol, self.jac_factor, + sparsity) + return J + J = jac_wrapped(t0, y0, self.f) + elif callable(jac): + J = jac(t0, y0) + self.njev = 1 + if issparse(J): + J = csc_matrix(J) + + def jac_wrapped(t, y, _=None): + self.njev += 1 + return csc_matrix(jac(t, y), dtype=float) + + else: + J = np.asarray(J, dtype=float) + + def jac_wrapped(t, y, _=None): + self.njev += 1 + return np.asarray(jac(t, y), dtype=float) + + if J.shape != (self.n, self.n): + raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)}," + f" but actually has {J.shape}.") + else: + if issparse(jac): + J = csc_matrix(jac) + else: + J = np.asarray(jac, dtype=float) + + if J.shape != (self.n, self.n): + raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)}," + f" but actually has {J.shape}.") + jac_wrapped = None + + return jac_wrapped, J + + def _step_impl(self): + t = self.t + y = self.y + f = self.f + + max_step = self.max_step + atol = self.atol + rtol = self.rtol + + min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t) + if self.h_abs > max_step: + h_abs = max_step + h_abs_old = None + error_norm_old = None + elif self.h_abs < min_step: + h_abs = min_step + h_abs_old = None + error_norm_old = None + else: + h_abs = self.h_abs + h_abs_old = self.h_abs_old + error_norm_old = self.error_norm_old + + J = self.J + LU_real = self.LU_real + LU_complex = self.LU_complex + + current_jac = self.current_jac + jac = self.jac + + rejected = False + step_accepted = False + message = None + while not step_accepted: + if h_abs < min_step: + return False, self.TOO_SMALL_STEP + + h = h_abs * self.direction + t_new = t + h + + if self.direction * (t_new - self.t_bound) > 0: + t_new = self.t_bound + + h = t_new - t + h_abs = np.abs(h) + + if self.sol is None: + Z0 = np.zeros((3, y.shape[0])) + else: + Z0 = self.sol(t + h * C).T - y + + scale = atol + np.abs(y) * rtol + + converged = False + while not converged: + if LU_real is None or LU_complex is None: + LU_real = self.lu(MU_REAL / h * self.I - J) + LU_complex = self.lu(MU_COMPLEX / h * self.I - J) + + converged, n_iter, Z, rate = solve_collocation_system( + self.fun, t, y, h, Z0, scale, self.newton_tol, + LU_real, LU_complex, self.solve_lu) + + if not converged: + if current_jac: + break + + J = self.jac(t, y, f) + current_jac = True + LU_real = None + LU_complex = None + + if not converged: + h_abs *= 0.5 + LU_real = None + LU_complex = None + continue + + y_new = y + Z[-1] + ZE = Z.T.dot(E) / h + error = self.solve_lu(LU_real, f + ZE) + scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol + error_norm = norm(error / scale) + safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER + + n_iter) + + if rejected and error_norm > 1: + error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE) + error_norm = norm(error / scale) + + if error_norm > 1: + factor = predict_factor(h_abs, h_abs_old, + error_norm, error_norm_old) + h_abs *= max(MIN_FACTOR, safety * factor) + + LU_real = None + LU_complex = None + rejected = True + else: + step_accepted = True + + recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3 + + factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old) + factor = min(MAX_FACTOR, safety * factor) + + if not recompute_jac and factor < 1.2: + factor = 1 + else: + LU_real = None + LU_complex = None + + f_new = self.fun(t_new, y_new) + if recompute_jac: + J = jac(t_new, y_new, f_new) + current_jac = True + elif jac is not None: + current_jac = False + + self.h_abs_old = self.h_abs + self.error_norm_old = error_norm + + self.h_abs = h_abs * factor + + self.y_old = y + + self.t = t_new + self.y = y_new + self.f = f_new + + self.Z = Z + + self.LU_real = LU_real + self.LU_complex = LU_complex + self.current_jac = current_jac + self.J = J + + self.t_old = t + self.sol = self._compute_dense_output() + + return step_accepted, message + + def _compute_dense_output(self): + Q = np.dot(self.Z.T, P) + return RadauDenseOutput(self.t_old, self.t, self.y_old, Q) + + def _dense_output_impl(self): + return self.sol + + +class RadauDenseOutput(DenseOutput): + def __init__(self, t_old, t, y_old, Q): + super().__init__(t_old, t) + self.h = t - t_old + self.Q = Q + self.order = Q.shape[1] - 1 + self.y_old = y_old + + def _call_impl(self, t): + x = (t - self.t_old) / self.h + if t.ndim == 0: + p = np.tile(x, self.order + 1) + p = np.cumprod(p) + else: + p = np.tile(x, (self.order + 1, 1)) + p = np.cumprod(p, axis=0) + # Here we don't multiply by h, not a mistake. + y = np.dot(self.Q, p) + if y.ndim == 2: + y += self.y_old[:, None] + else: + y += self.y_old + + return y diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/rk.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/rk.py new file mode 100644 index 0000000000000000000000000000000000000000..1810b5623159cb898435702cf5d4100646109d34 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/rk.py @@ -0,0 +1,601 @@ +import numpy as np +from .base import OdeSolver, DenseOutput +from .common import (validate_max_step, validate_tol, select_initial_step, + norm, warn_extraneous, validate_first_step) +from . import dop853_coefficients + +# Multiply steps computed from asymptotic behaviour of errors by this. +SAFETY = 0.9 + +MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size. +MAX_FACTOR = 10 # Maximum allowed increase in a step size. + + +def rk_step(fun, t, y, f, h, A, B, C, K): + """Perform a single Runge-Kutta step. + + This function computes a prediction of an explicit Runge-Kutta method and + also estimates the error of a less accurate method. + + Notation for Butcher tableau is as in [1]_. + + Parameters + ---------- + fun : callable + Right-hand side of the system. + t : float + Current time. + y : ndarray, shape (n,) + Current state. + f : ndarray, shape (n,) + Current value of the derivative, i.e., ``fun(x, y)``. + h : float + Step to use. + A : ndarray, shape (n_stages, n_stages) + Coefficients for combining previous RK stages to compute the next + stage. For explicit methods the coefficients at and above the main + diagonal are zeros. + B : ndarray, shape (n_stages,) + Coefficients for combining RK stages for computing the final + prediction. + C : ndarray, shape (n_stages,) + Coefficients for incrementing time for consecutive RK stages. + The value for the first stage is always zero. + K : ndarray, shape (n_stages + 1, n) + Storage array for putting RK stages here. Stages are stored in rows. + The last row is a linear combination of the previous rows with + coefficients + + Returns + ------- + y_new : ndarray, shape (n,) + Solution at t + h computed with a higher accuracy. + f_new : ndarray, shape (n,) + Derivative ``fun(t + h, y_new)``. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II.4. + """ + K[0] = f + for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1): + dy = np.dot(K[:s].T, a[:s]) * h + K[s] = fun(t + c * h, y + dy) + + y_new = y + h * np.dot(K[:-1].T, B) + f_new = fun(t + h, y_new) + + K[-1] = f_new + + return y_new, f_new + + +class RungeKutta(OdeSolver): + """Base class for explicit Runge-Kutta methods.""" + C: np.ndarray = NotImplemented + A: np.ndarray = NotImplemented + B: np.ndarray = NotImplemented + E: np.ndarray = NotImplemented + P: np.ndarray = NotImplemented + order: int = NotImplemented + error_estimator_order: int = NotImplemented + n_stages: int = NotImplemented + + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, vectorized=False, + first_step=None, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized, + support_complex=True) + self.y_old = None + self.max_step = validate_max_step(max_step) + self.rtol, self.atol = validate_tol(rtol, atol, self.n) + self.f = self.fun(self.t, self.y) + if first_step is None: + self.h_abs = select_initial_step( + self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction, + self.error_estimator_order, self.rtol, self.atol) + else: + self.h_abs = validate_first_step(first_step, t0, t_bound) + self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype) + self.error_exponent = -1 / (self.error_estimator_order + 1) + self.h_previous = None + + def _estimate_error(self, K, h): + return np.dot(K.T, self.E) * h + + def _estimate_error_norm(self, K, h, scale): + return norm(self._estimate_error(K, h) / scale) + + def _step_impl(self): + t = self.t + y = self.y + + max_step = self.max_step + rtol = self.rtol + atol = self.atol + + min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t) + + if self.h_abs > max_step: + h_abs = max_step + elif self.h_abs < min_step: + h_abs = min_step + else: + h_abs = self.h_abs + + step_accepted = False + step_rejected = False + + while not step_accepted: + if h_abs < min_step: + return False, self.TOO_SMALL_STEP + + h = h_abs * self.direction + t_new = t + h + + if self.direction * (t_new - self.t_bound) > 0: + t_new = self.t_bound + + h = t_new - t + h_abs = np.abs(h) + + y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A, + self.B, self.C, self.K) + scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol + error_norm = self._estimate_error_norm(self.K, h, scale) + + if error_norm < 1: + if error_norm == 0: + factor = MAX_FACTOR + else: + factor = min(MAX_FACTOR, + SAFETY * error_norm ** self.error_exponent) + + if step_rejected: + factor = min(1, factor) + + h_abs *= factor + + step_accepted = True + else: + h_abs *= max(MIN_FACTOR, + SAFETY * error_norm ** self.error_exponent) + step_rejected = True + + self.h_previous = h + self.y_old = y + + self.t = t_new + self.y = y_new + + self.h_abs = h_abs + self.f = f_new + + return True, None + + def _dense_output_impl(self): + Q = self.K.T.dot(self.P) + return RkDenseOutput(self.t_old, self.t, self.y_old, Q) + + +class RK23(RungeKutta): + """Explicit Runge-Kutta method of order 3(2). + + This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled + assuming accuracy of the second-order method, but steps are taken using the + third-order accurate formula (local extrapolation is done). A cubic Hermite + polynomial is used for the dense output. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + vectorized : bool, optional + Whether `fun` may be called in a vectorized fashion. False (default) + is recommended for this solver. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for this solver. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number evaluations of the system's right-hand side. + njev : int + Number of evaluations of the Jacobian. + Is always 0 for this solver as it does not use the Jacobian. + nlu : int + Number of LU decompositions. Is always 0 for this solver. + + References + ---------- + .. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas", + Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989. + """ + order = 3 + error_estimator_order = 2 + n_stages = 3 + C = np.array([0, 1/2, 3/4]) + A = np.array([ + [0, 0, 0], + [1/2, 0, 0], + [0, 3/4, 0] + ]) + B = np.array([2/9, 1/3, 4/9]) + E = np.array([5/72, -1/12, -1/9, 1/8]) + P = np.array([[1, -4 / 3, 5 / 9], + [0, 1, -2/3], + [0, 4/3, -8/9], + [0, -1, 1]]) + + +class RK45(RungeKutta): + """Explicit Runge-Kutta method of order 5(4). + + This uses the Dormand-Prince pair of formulas [1]_. The error is controlled + assuming accuracy of the fourth-order method accuracy, but steps are taken + using the fifth-order accurate formula (local extrapolation is done). + A quartic interpolation polynomial is used for the dense output [2]_. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system. The calling signature is ``fun(t, y)``. + Here ``t`` is a scalar, and there are two options for the ndarray ``y``: + It can either have shape (n,); then ``fun`` must return array_like with + shape (n,). Alternatively it can have shape (n, k); then ``fun`` + must return an array_like with shape (n, k), i.e., each column + corresponds to a single column in ``y``. The choice between the two + options is determined by `vectorized` argument (see below). + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + vectorized : bool, optional + Whether `fun` is implemented in a vectorized fashion. Default is False. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number evaluations of the system's right-hand side. + njev : int + Number of evaluations of the Jacobian. + Is always 0 for this solver as it does not use the Jacobian. + nlu : int + Number of LU decompositions. Is always 0 for this solver. + + References + ---------- + .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta + formulae", Journal of Computational and Applied Mathematics, Vol. 6, + No. 1, pp. 19-26, 1980. + .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics + of Computation,, Vol. 46, No. 173, pp. 135-150, 1986. + """ + order = 5 + error_estimator_order = 4 + n_stages = 6 + C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1]) + A = np.array([ + [0, 0, 0, 0, 0], + [1/5, 0, 0, 0, 0], + [3/40, 9/40, 0, 0, 0], + [44/45, -56/15, 32/9, 0, 0], + [19372/6561, -25360/2187, 64448/6561, -212/729, 0], + [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656] + ]) + B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84]) + E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525, + 1/40]) + # Corresponds to the optimum value of c_6 from [2]_. + P = np.array([ + [1, -8048581381/2820520608, 8663915743/2820520608, + -12715105075/11282082432], + [0, 0, 0, 0], + [0, 131558114200/32700410799, -68118460800/10900136933, + 87487479700/32700410799], + [0, -1754552775/470086768, 14199869525/1410260304, + -10690763975/1880347072], + [0, 127303824393/49829197408, -318862633887/49829197408, + 701980252875 / 199316789632], + [0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844], + [0, 40617522/29380423, -110615467/29380423, 69997945/29380423]]) + + +class DOP853(RungeKutta): + """Explicit Runge-Kutta method of order 8. + + This is a Python implementation of "DOP853" algorithm originally written + in Fortran [1]_, [2]_. Note that this is not a literal translation, but + the algorithmic core and coefficients are the same. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system. The calling signature is ``fun(t, y)``. + Here, ``t`` is a scalar, and there are two options for the ndarray ``y``: + It can either have shape (n,); then ``fun`` must return array_like with + shape (n,). Alternatively it can have shape (n, k); then ``fun`` + must return an array_like with shape (n, k), i.e. each column + corresponds to a single column in ``y``. The choice between the two + options is determined by `vectorized` argument (see below). + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e. the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + vectorized : bool, optional + Whether `fun` is implemented in a vectorized fashion. Default is False. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number evaluations of the system's right-hand side. + njev : int + Number of evaluations of the Jacobian. Is always 0 for this solver + as it does not use the Jacobian. + nlu : int + Number of LU decompositions. Is always 0 for this solver. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II. + .. [2] `Page with original Fortran code of DOP853 + `_. + """ + n_stages = dop853_coefficients.N_STAGES + order = 8 + error_estimator_order = 7 + A = dop853_coefficients.A[:n_stages, :n_stages] + B = dop853_coefficients.B + C = dop853_coefficients.C[:n_stages] + E3 = dop853_coefficients.E3 + E5 = dop853_coefficients.E5 + D = dop853_coefficients.D + + A_EXTRA = dop853_coefficients.A[n_stages + 1:] + C_EXTRA = dop853_coefficients.C[n_stages + 1:] + + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, vectorized=False, + first_step=None, **extraneous): + super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol, + vectorized, first_step, **extraneous) + self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED, + self.n), dtype=self.y.dtype) + self.K = self.K_extended[:self.n_stages + 1] + + def _estimate_error(self, K, h): # Left for testing purposes. + err5 = np.dot(K.T, self.E5) + err3 = np.dot(K.T, self.E3) + denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3)) + correction_factor = np.ones_like(err5) + mask = denom > 0 + correction_factor[mask] = np.abs(err5[mask]) / denom[mask] + return h * err5 * correction_factor + + def _estimate_error_norm(self, K, h, scale): + err5 = np.dot(K.T, self.E5) / scale + err3 = np.dot(K.T, self.E3) / scale + err5_norm_2 = np.linalg.norm(err5)**2 + err3_norm_2 = np.linalg.norm(err3)**2 + if err5_norm_2 == 0 and err3_norm_2 == 0: + return 0.0 + denom = err5_norm_2 + 0.01 * err3_norm_2 + return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale)) + + def _dense_output_impl(self): + K = self.K_extended + h = self.h_previous + for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA), + start=self.n_stages + 1): + dy = np.dot(K[:s].T, a[:s]) * h + K[s] = self.fun(self.t_old + c * h, self.y_old + dy) + + F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n), + dtype=self.y_old.dtype) + + f_old = K[0] + delta_y = self.y - self.y_old + + F[0] = delta_y + F[1] = h * f_old - delta_y + F[2] = 2 * delta_y - h * (self.f + f_old) + F[3:] = h * np.dot(self.D, K) + + return Dop853DenseOutput(self.t_old, self.t, self.y_old, F) + + +class RkDenseOutput(DenseOutput): + def __init__(self, t_old, t, y_old, Q): + super().__init__(t_old, t) + self.h = t - t_old + self.Q = Q + self.order = Q.shape[1] - 1 + self.y_old = y_old + + def _call_impl(self, t): + x = (t - self.t_old) / self.h + if t.ndim == 0: + p = np.tile(x, self.order + 1) + p = np.cumprod(p) + else: + p = np.tile(x, (self.order + 1, 1)) + p = np.cumprod(p, axis=0) + y = self.h * np.dot(self.Q, p) + if y.ndim == 2: + y += self.y_old[:, None] + else: + y += self.y_old + + return y + + +class Dop853DenseOutput(DenseOutput): + def __init__(self, t_old, t, y_old, F): + super().__init__(t_old, t) + self.h = t - t_old + self.F = F + self.y_old = y_old + + def _call_impl(self, t): + x = (t - self.t_old) / self.h + + if t.ndim == 0: + y = np.zeros_like(self.y_old) + else: + x = x[:, None] + y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype) + + for i, f in enumerate(reversed(self.F)): + y += f + if i % 2 == 0: + y *= x + else: + y *= 1 - x + y += self.y_old + + return y.T diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2206d3f9cb98762e520d25d69df9af323f85a886 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c3c56ea0b42c1969451d29fc141be1d984354f0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90cd567807badb86753e9a81585da3aa67c1e235 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/test_ivp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/test_ivp.py new file mode 100644 index 0000000000000000000000000000000000000000..083889615e202d23dcd4c6633604c240cf080b76 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/test_ivp.py @@ -0,0 +1,1295 @@ +import warnings + +from itertools import product + +from numpy.testing import (assert_, assert_allclose, assert_array_less, + assert_equal, assert_no_warnings) +import pytest +from pytest import raises as assert_raises +import numpy as np +from scipy.optimize._numdiff import group_columns +from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA +from scipy.integrate import OdeSolution +from scipy.integrate._ivp.common import num_jac, select_initial_step +from scipy.integrate._ivp.base import ConstantDenseOutput +from scipy.sparse import coo_matrix, csc_matrix + + +def fun_zero(t, y): + return np.zeros_like(y) + + +def fun_linear(t, y): + return np.array([-y[0] - 5 * y[1], y[0] + y[1]]) + + +def jac_linear(): + return np.array([[-1, -5], [1, 1]]) + + +def sol_linear(t): + return np.vstack((-5 * np.sin(2 * t), + 2 * np.cos(2 * t) + np.sin(2 * t))) + + +def fun_rational(t, y): + return np.array([y[1] / t, + y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))]) + + +def fun_rational_vectorized(t, y): + return np.vstack((y[1] / t, + y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1)))) + + +def jac_rational(t, y): + return np.array([ + [0, 1 / t], + [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2), + (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))] + ]) + + +def jac_rational_sparse(t, y): + return csc_matrix([ + [0, 1 / t], + [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2), + (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))] + ]) + + +def sol_rational(t): + return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2)) + + +def fun_medazko(t, y): + n = y.shape[0] // 2 + k = 100 + c = 4 + + phi = 2 if t <= 5 else 0 + y = np.hstack((phi, 0, y, y[-2])) + + d = 1 / n + j = np.arange(n) + 1 + alpha = 2 * (j * d - 1) ** 3 / c ** 2 + beta = (j * d - 1) ** 4 / c ** 2 + + j_2_p1 = 2 * j + 2 + j_2_m3 = 2 * j - 2 + j_2_m1 = 2 * j + j_2 = 2 * j + 1 + + f = np.empty(2 * n) + f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) + + beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 - + k * y[j_2_m1] * y[j_2]) + f[1::2] = -k * y[j_2] * y[j_2_m1] + + return f + + +def medazko_sparsity(n): + cols = [] + rows = [] + + i = np.arange(n) * 2 + + cols.append(i[1:]) + rows.append(i[1:] - 2) + + cols.append(i) + rows.append(i) + + cols.append(i) + rows.append(i + 1) + + cols.append(i[:-1]) + rows.append(i[:-1] + 2) + + i = np.arange(n) * 2 + 1 + + cols.append(i) + rows.append(i) + + cols.append(i) + rows.append(i - 1) + + cols = np.hstack(cols) + rows = np.hstack(rows) + + return coo_matrix((np.ones_like(cols), (cols, rows))) + + +def fun_complex(t, y): + return -y + + +def jac_complex(t, y): + return -np.eye(y.shape[0]) + + +def jac_complex_sparse(t, y): + return csc_matrix(jac_complex(t, y)) + + +def sol_complex(t): + y = (0.5 + 1j) * np.exp(-t) + return y.reshape((1, -1)) + + +def fun_event_dense_output_LSODA(t, y): + return y * (t - 2) + + +def jac_event_dense_output_LSODA(t, y): + return t - 2 + + +def sol_event_dense_output_LSODA(t): + return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6) + + +def compute_error(y, y_true, rtol, atol): + e = (y - y_true) / (atol + rtol * np.abs(y_true)) + return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0]) + +def test_duplicate_timestamps(): + def upward_cannon(t, y): + return [y[1], -9.80665] + + def hit_ground(t, y): + return y[0] + + hit_ground.terminal = True + hit_ground.direction = -1 + + sol = solve_ivp(upward_cannon, [0, np.inf], [0, 0.01], + max_step=0.05 * 0.001 / 9.80665, + events=hit_ground, dense_output=True) + assert_allclose(sol.sol(0.01), np.asarray([-0.00039033, -0.08806632]), + rtol=1e-5, atol=1e-8) + assert_allclose(sol.t_events, np.asarray([[0.00203943]]), rtol=1e-5, atol=1e-8) + assert_allclose(sol.y_events, [np.asarray([[ 0.0, -0.01 ]])], atol=1e-9) + assert sol.success + assert_equal(sol.status, 1) + + +@pytest.mark.thread_unsafe(reason="lsoda solver is not thread-safe") +def test_integration(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + + for vectorized, method, t_span, jac in product( + [False, True], + ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'], + [[5, 9], [5, 1]], + [None, jac_rational, jac_rational_sparse]): + + if vectorized: + fun = fun_rational_vectorized + else: + fun = fun_rational + + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + "The following arguments have no effect for a chosen solver: `jac`", + UserWarning, + ) + res = solve_ivp(fun, t_span, y0, rtol=rtol, + atol=atol, method=method, dense_output=True, + jac=jac, vectorized=vectorized) + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + if method == 'DOP853': + # DOP853 spends more functions evaluation because it doesn't + # have enough time to develop big enough step size. + assert_(res.nfev < 50) + else: + assert_(res.nfev < 40) + + if method in ['RK23', 'RK45', 'DOP853', 'LSODA']: + assert_equal(res.njev, 0) + assert_equal(res.nlu, 0) + else: + assert_(0 < res.njev < 3) + assert_(0 < res.nlu < 10) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = np.linspace(*t_span) + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = (t_span[0] + t_span[-1]) / 2 + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + +def test_integration_complex(): + rtol = 1e-3 + atol = 1e-6 + y0 = [0.5 + 1j] + t_span = [0, 1] + tc = np.linspace(t_span[0], t_span[1]) + for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'], + [None, jac_complex, jac_complex_sparse]): + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + "The following arguments have no effect for a chosen solver: `jac`", + UserWarning, + ) + res = solve_ivp(fun_complex, t_span, y0, method=method, + dense_output=True, rtol=rtol, atol=atol, jac=jac) + + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + if method == 'DOP853': + assert res.nfev < 35 + else: + assert res.nfev < 25 + + if method == 'BDF': + assert_equal(res.njev, 1) + assert res.nlu < 6 + else: + assert res.njev == 0 + assert res.nlu == 0 + + y_true = sol_complex(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert np.all(e < 5) + + yc_true = sol_complex(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, rtol, atol) + + assert np.all(e < 5) + + +@pytest.mark.fail_slow(5) +def test_integration_sparse_difference(): + n = 200 + t_span = [0, 20] + y0 = np.zeros(2 * n) + y0[1::2] = 1 + sparsity = medazko_sparsity(n) + + for method in ['BDF', 'Radau']: + res = solve_ivp(fun_medazko, t_span, y0, method=method, + jac_sparsity=sparsity) + + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2) + assert_allclose(res.y[79, -1], 0, atol=1e-3) + assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2) + assert_allclose(res.y[149, -1], 0, atol=1e-3) + assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2) + assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3) + assert_allclose(res.y[238, -1], 0, atol=1e-3) + assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2) + + +def test_integration_const_jac(): + rtol = 1e-3 + atol = 1e-6 + y0 = [0, 2] + t_span = [0, 2] + J = jac_linear() + J_sparse = csc_matrix(J) + + for method, jac in product(['Radau', 'BDF'], [J, J_sparse]): + res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol, + method=method, dense_output=True, jac=jac) + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + assert_(res.nfev < 100) + assert_equal(res.njev, 0) + assert_(0 < res.nlu < 15) + + y_true = sol_linear(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 10)) + + tc = np.linspace(*t_span) + yc_true = sol_linear(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 15)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14) + + +@pytest.mark.slow +@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA']) +def test_integration_stiff(method, num_parallel_threads): + rtol = 1e-6 + atol = 1e-6 + y0 = [1e4, 0, 0] + tspan = [0, 1e8] + + if method == 'LSODA' and num_parallel_threads > 1: + pytest.skip(reason='LSODA does not allow for concurrent calls') + + def fun_robertson(t, state): + x, y, z = state + return [ + -0.04 * x + 1e4 * y * z, + 0.04 * x - 1e4 * y * z - 3e7 * y * y, + 3e7 * y * y, + ] + + res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol, + atol=atol, method=method) + + # If the stiff mode is not activated correctly, these numbers will be much bigger + assert res.nfev < 5000 + assert res.njev < 200 + + +def test_events(num_parallel_threads): + def event_rational_1(t, y): + return y[0] - y[1] ** 0.7 + + def event_rational_2(t, y): + return y[1] ** 0.6 - y[0] + + def event_rational_3(t, y): + return t - 7.4 + + event_rational_3.terminal = True + + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + if method == 'LSODA' and num_parallel_threads > 1: + continue + + res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_(7.3 < res.t_events[1][0] < 7.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = 1 + event_rational_2.direction = 1 + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 0) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (0,)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + + event_rational_1.direction = -1 + event_rational_2.direction = -1 + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 0) + assert_equal(res.t_events[1].size, 1) + assert_(7.3 < res.t_events[1][0] < 7.7) + assert_equal(res.y_events[0].shape, (0,)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = 0 + event_rational_2.direction = 0 + + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=(event_rational_1, event_rational_2, + event_rational_3), dense_output=True) + assert_equal(res.status, 1) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 0) + assert_equal(res.t_events[2].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_(7.3 < res.t_events[2][0] < 7.5) + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (0,)) + assert_equal(res.y_events[2].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + assert np.isclose( + event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0) + + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=event_rational_1, dense_output=True) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + + # Also test that termination by event doesn't break interpolants. + tc = np.linspace(res.t[0], res.t[-1]) + yc_true = sol_rational(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, 1e-3, 1e-6) + assert_(np.all(e < 5)) + + # Test that the y_event matches solution + assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0], + rtol=1e-3, atol=1e-6) + + # Test in backward direction. + event_rational_1.direction = 0 + event_rational_2.direction = 0 + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + if method == 'LSODA' and num_parallel_threads > 1: + continue + + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_(7.3 < res.t_events[1][0] < 7.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = -1 + event_rational_2.direction = -1 + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 0) + assert_(5.3 < res.t_events[0][0] < 5.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (0,)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + + event_rational_1.direction = 1 + event_rational_2.direction = 1 + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 0) + assert_equal(res.t_events[1].size, 1) + assert_(7.3 < res.t_events[1][0] < 7.7) + + assert_equal(res.y_events[0].shape, (0,)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = 0 + event_rational_2.direction = 0 + + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2, + event_rational_3), dense_output=True) + assert_equal(res.status, 1) + assert_equal(res.t_events[0].size, 0) + assert_equal(res.t_events[1].size, 1) + assert_equal(res.t_events[2].size, 1) + assert_(7.3 < res.t_events[1][0] < 7.7) + assert_(7.3 < res.t_events[2][0] < 7.5) + + assert_equal(res.y_events[0].shape, (0,)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert_equal(res.y_events[2].shape, (1, 2)) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + assert np.isclose( + event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0) + + # Also test that termination by event doesn't break interpolants. + tc = np.linspace(res.t[-1], res.t[0]) + yc_true = sol_rational(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, 1e-3, 1e-6) + assert_(np.all(e < 5)) + + assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0], + rtol=1e-3, atol=1e-6) + assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0], + rtol=1e-3, atol=1e-6) + + +def _get_harmonic_oscillator(): + def f(t, y): + return [y[1], -y[0]] + + def event(t, y): + return y[0] + + return f, event + + +@pytest.mark.parametrize('n_events', [3, 4]) +def test_event_terminal_integer(n_events): + f, event = _get_harmonic_oscillator() + event.terminal = n_events + res = solve_ivp(f, (0, 100), [1, 0], events=event) + assert len(res.t_events[0]) == n_events + assert len(res.y_events[0]) == n_events + assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14) + + +def test_event_terminal_iv(): + f, event = _get_harmonic_oscillator() + args = (f, (0, 100), [1, 0]) + + event.terminal = None + res = solve_ivp(*args, events=event) + event.terminal = 0 + ref = solve_ivp(*args, events=event) + assert_allclose(res.t_events, ref.t_events) + + message = "The `terminal` attribute..." + event.terminal = -1 + with pytest.raises(ValueError, match=message): + solve_ivp(*args, events=event) + event.terminal = 3.5 + with pytest.raises(ValueError, match=message): + solve_ivp(*args, events=event) + + +def test_max_step(num_parallel_threads): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + if method is LSODA and num_parallel_threads > 1: + continue + for t_span in ([5, 9], [5, 1]): + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, + max_step=0.5, atol=atol, method=method, + dense_output=True) + assert_equal(res.t[0], t_span[0]) + assert_equal(res.t[-1], t_span[-1]) + assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15)) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = np.linspace(*t_span) + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + assert_raises(ValueError, method, fun_rational, t_span[0], y0, + t_span[1], max_step=-1) + + if method is not LSODA: + solver = method(fun_rational, t_span[0], y0, t_span[1], + rtol=rtol, atol=atol, max_step=1e-20) + message = solver.step() + message = solver.step() # First step succeeds but second step fails. + assert_equal(solver.status, 'failed') + assert_("step size is less" in message) + assert_raises(RuntimeError, solver.step) + + +def test_first_step(num_parallel_threads): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + first_step = 0.1 + for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + if method is LSODA and num_parallel_threads > 1: + continue + for t_span in ([5, 9], [5, 1]): + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, + max_step=0.5, atol=atol, method=method, + dense_output=True, first_step=first_step) + + assert_equal(res.t[0], t_span[0]) + assert_equal(res.t[-1], t_span[-1]) + assert_allclose(first_step, np.abs(res.t[1] - 5)) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = np.linspace(*t_span) + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + assert_raises(ValueError, method, fun_rational, t_span[0], y0, + t_span[1], first_step=-1) + assert_raises(ValueError, method, fun_rational, t_span[0], y0, + t_span[1], first_step=5) + + +def test_t_eval(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + for t_span in ([5, 9], [5, 1]): + t_eval = np.linspace(t_span[0], t_span[1], 10) + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + t_eval = [5, 5.01, 7, 8, 8.01, 9] + res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1] + res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + t_eval = [5.01, 7, 8, 8.01] + res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + t_eval = [4.99, 3, 1.5, 1.1, 1.01] + res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + t_eval = [4, 6] + assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0, + rtol=rtol, atol=atol, t_eval=t_eval) + + +def test_t_eval_dense_output(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + t_span = [5, 9] + t_eval = np.linspace(t_span[0], t_span[1], 10) + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + t_eval=t_eval) + res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + t_eval=t_eval, dense_output=True) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + assert_equal(res.t, res_d.t) + assert_equal(res.y, res_d.y) + assert_(res_d.t_events is None) + assert_(res_d.success) + assert_equal(res_d.status, 0) + + # if t and y are equal only test values for one case + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + +@pytest.mark.thread_unsafe(reason="lsoda solver is not thread-safe") +def test_t_eval_early_event(): + def early_event(t, y): + return t - 7 + + early_event.terminal = True + + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + t_span = [5, 9] + t_eval = np.linspace(7.5, 9, 16) + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + "The following arguments have no effect for a chosen solver: `jac`", + UserWarning, + ) + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + method=method, t_eval=t_eval, events=early_event, + jac=jac_rational) + assert res.success + assert res.message == 'A termination event occurred.' + assert res.status == 1 + assert not res.t and not res.y + assert len(res.t_events) == 1 + assert res.t_events[0].size == 1 + assert res.t_events[0][0] == 7 + + +def test_event_dense_output_LSODA(num_parallel_threads): + if num_parallel_threads > 1: + pytest.skip('LSODA does not allow for concurrent execution') + + def event_lsoda(t, y): + return y[0] - 2.02e-5 + + rtol = 1e-3 + atol = 1e-6 + y0 = [0.05] + t_span = [-2, 2] + first_step = 1e-3 + res = solve_ivp( + fun_event_dense_output_LSODA, + t_span, + y0, + method="LSODA", + dense_output=True, + events=event_lsoda, + first_step=first_step, + max_step=1, + rtol=rtol, + atol=atol, + jac=jac_event_dense_output_LSODA, + ) + + assert_equal(res.t[0], t_span[0]) + assert_equal(res.t[-1], t_span[-1]) + assert_allclose(first_step, np.abs(res.t[1] - t_span[0])) + assert res.success + assert_equal(res.status, 0) + + y_true = sol_event_dense_output_LSODA(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_array_less(e, 5) + + tc = np.linspace(*t_span) + yc_true = sol_event_dense_output_LSODA(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, rtol, atol) + assert_array_less(e, 5) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + +def test_no_integration(): + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3], + method=method, dense_output=True) + assert_equal(sol.sol(4), [2, 3]) + assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]]) + + +def test_no_integration_class(): + for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0) + solver.step() + assert_equal(solver.status, 'finished') + sol = solver.dense_output() + assert_equal(sol(0.0), [10.0, 0.0]) + assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]]) + + solver = method(lambda t, y: -y, 0.0, [], np.inf) + solver.step() + assert_equal(solver.status, 'finished') + sol = solver.dense_output() + assert_equal(sol(100.0), []) + assert_equal(sol([0, 1, 2]), np.empty((0, 3))) + + +def test_empty(): + def fun(t, y): + return np.zeros((0,)) + + y0 = np.zeros((0,)) + + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0, + method=method, dense_output=True) + assert_equal(sol.sol(10), np.zeros((0,))) + assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3))) + + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0, + method=method, dense_output=True) + assert_equal(sol.sol(10), np.zeros((0,))) + assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3))) + + +def test_ConstantDenseOutput(): + sol = ConstantDenseOutput(0, 1, np.array([1, 2])) + assert_allclose(sol(1.5), [1, 2]) + assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]]) + + sol = ConstantDenseOutput(0, 1, np.array([])) + assert_allclose(sol(1.5), np.empty(0)) + assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3))) + + +def test_classes(): + y0 = [1 / 3, 2 / 9] + for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + solver = cls(fun_rational, 5, y0, np.inf) + assert_equal(solver.n, 2) + assert_equal(solver.status, 'running') + assert_equal(solver.t_bound, np.inf) + assert_equal(solver.direction, 1) + assert_equal(solver.t, 5) + assert_equal(solver.y, y0) + assert_(solver.step_size is None) + if cls is not LSODA: + assert_(solver.nfev > 0) + assert_(solver.njev >= 0) + assert_equal(solver.nlu, 0) + else: + assert_equal(solver.nfev, 0) + assert_equal(solver.njev, 0) + assert_equal(solver.nlu, 0) + + assert_raises(RuntimeError, solver.dense_output) + + message = solver.step() + assert_equal(solver.status, 'running') + assert_equal(message, None) + assert_equal(solver.n, 2) + assert_equal(solver.t_bound, np.inf) + assert_equal(solver.direction, 1) + assert_(solver.t > 5) + assert_(not np.all(np.equal(solver.y, y0))) + assert_(solver.step_size > 0) + assert_(solver.nfev > 0) + assert_(solver.njev >= 0) + assert_(solver.nlu >= 0) + sol = solver.dense_output() + assert_allclose(sol(5), y0, rtol=1e-15, atol=0) + + +def test_OdeSolution(): + ts = np.array([0, 2, 5], dtype=float) + s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1])) + s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1])) + + sol = OdeSolution(ts, [s1, s2]) + + assert_equal(sol(-1), [-1]) + assert_equal(sol(1), [-1]) + assert_equal(sol(2), [-1]) + assert_equal(sol(3), [1]) + assert_equal(sol(5), [1]) + assert_equal(sol(6), [1]) + + assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]), + np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]])) + + ts = np.array([10, 4, -3]) + s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1])) + s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1])) + + sol = OdeSolution(ts, [s1, s2]) + assert_equal(sol(11), [-1]) + assert_equal(sol(10), [-1]) + assert_equal(sol(5), [-1]) + assert_equal(sol(4), [-1]) + assert_equal(sol(0), [1]) + assert_equal(sol(-3), [1]) + assert_equal(sol(-4), [1]) + + assert_equal(sol([12, -5, 10, -3, 6, 1, 4]), + np.array([[-1, 1, -1, 1, -1, 1, -1]])) + + ts = np.array([1, 1]) + s = ConstantDenseOutput(1, 1, np.array([10])) + sol = OdeSolution(ts, [s]) + assert_equal(sol(0), [10]) + assert_equal(sol(1), [10]) + assert_equal(sol(2), [10]) + + assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]])) + + +def test_num_jac(): + def fun(t, y): + return np.vstack([ + -0.04 * y[0] + 1e4 * y[1] * y[2], + 0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2, + 3e7 * y[1] ** 2 + ]) + + def jac(t, y): + return np.array([ + [-0.04, 1e4 * y[2], 1e4 * y[1]], + [0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]], + [0, 6e7 * y[1], 0] + ]) + + t = 1 + y = np.array([1, 0, 0]) + J_true = jac(t, y) + threshold = 1e-5 + f = fun(t, y).ravel() + + J_num, factor = num_jac(fun, t, y, f, threshold, None) + assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5) + + J_num, factor = num_jac(fun, t, y, f, threshold, factor) + assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5) + + +def test_num_jac_sparse(): + def fun(t, y): + e = y[1:]**3 - y[:-1]**2 + z = np.zeros(y.shape[1]) + return np.vstack((z, 3 * e)) + np.vstack((2 * e, z)) + + def structure(n): + A = np.zeros((n, n), dtype=int) + A[0, 0] = 1 + A[0, 1] = 1 + for i in range(1, n - 1): + A[i, i - 1: i + 2] = 1 + A[-1, -1] = 1 + A[-1, -2] = 1 + + return A + + np.random.seed(0) + n = 20 + y = np.random.randn(n) + A = structure(n) + groups = group_columns(A) + + f = fun(0, y[:, None]).ravel() + + # Compare dense and sparse results, assuming that dense implementation + # is correct (as it is straightforward). + J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None, + sparsity=(A, groups)) + J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None) + assert_allclose(J_num_dense, J_num_sparse.toarray(), + rtol=1e-12, atol=1e-14) + assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14) + + # Take small factors to trigger their recomputing inside. + factor = np.random.uniform(0, 1e-12, size=n) + J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor, + sparsity=(A, groups)) + J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor) + + assert_allclose(J_num_dense, J_num_sparse.toarray(), + rtol=1e-12, atol=1e-14) + assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14) + + +def test_args(): + + # sys3 is actually two decoupled systems. (x, y) form a + # linear oscillator, while z is a nonlinear first order + # system with equilibria at z=0 and z=1. If k > 0, z=1 + # is stable and z=0 is unstable. + + def sys3(t, w, omega, k, zfinal): + x, y, z = w + return [-omega*y, omega*x, k*z*(1 - z)] + + def sys3_jac(t, w, omega, k, zfinal): + x, y, z = w + J = np.array([[0, -omega, 0], + [omega, 0, 0], + [0, 0, k*(1 - 2*z)]]) + return J + + def sys3_x0decreasing(t, w, omega, k, zfinal): + x, y, z = w + return x + + def sys3_y0increasing(t, w, omega, k, zfinal): + x, y, z = w + return y + + def sys3_zfinal(t, w, omega, k, zfinal): + x, y, z = w + return z - zfinal + + # Set the event flags for the event functions. + sys3_x0decreasing.direction = -1 + sys3_y0increasing.direction = 1 + sys3_zfinal.terminal = True + + omega = 2 + k = 4 + + tfinal = 5 + zfinal = 0.99 + # Find z0 such that when z(0) = z0, z(tfinal) = zfinal. + # The condition z(tfinal) = zfinal is the terminal event. + z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal)) + + w0 = [0, -1, z0] + + # Provide the jac argument and use the Radau method to ensure that the use + # of the Jacobian function is exercised. + # If event handling is working, the solution will stop at tfinal, not tend. + tend = 2*tfinal + sol = solve_ivp(sys3, [0, tend], w0, + events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal], + dense_output=True, args=(omega, k, zfinal), + method='Radau', jac=sys3_jac, + rtol=1e-10, atol=1e-13) + + # Check that we got the expected events at the expected times. + x0events_t = sol.t_events[0] + y0events_t = sol.t_events[1] + zfinalevents_t = sol.t_events[2] + assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi]) + assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi]) + assert_allclose(zfinalevents_t, [tfinal]) + + # Check that the solution agrees with the known exact solution. + t = np.linspace(0, zfinalevents_t[0], 250) + w = sol.sol(t) + assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12) + assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12) + assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1), + rtol=1e-9, atol=1e-12) + + # Check that the state variables have the expected values at the events. + x0events = sol.sol(x0events_t) + y0events = sol.sol(y0events_t) + zfinalevents = sol.sol(zfinalevents_t) + assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14) + assert_allclose(x0events[1], np.ones_like(x0events[1])) + assert_allclose(y0events[0], np.ones_like(y0events[0])) + assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14) + assert_allclose(zfinalevents[2], [zfinal]) + + +def test_array_rtol(): + # solve_ivp had a bug with array_like `rtol`; see gh-15482 + # check that it's fixed + def f(t, y): + return y[0], y[1] + + # no warning (or error) when `rtol` is array_like + sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1]) + err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1))) + + # warning when an element of `rtol` is too small + with pytest.warns(UserWarning, match="At least one element..."): + sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16]) + err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1))) + + # tighter rtol improves the error + assert err2 < err1 + + +@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']) +def test_integration_zero_rhs(method, num_parallel_threads): + if method == 'LSODA' and num_parallel_threads > 1: + pytest.skip(reason='LSODA does not allow for concurrent execution') + + result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method) + assert_(result.success) + assert_equal(result.status, 0) + assert_allclose(result.y, 1.0, rtol=1e-15) + + +def test_args_single_value(): + def fun_with_arg(t, y, a): + return a*y + + message = "Supplied 'args' cannot be unpacked." + with pytest.raises(TypeError, match=message): + solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1) + + sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,)) + assert_allclose(sol.y[0, -1], np.exp(-0.1)) + + +@pytest.mark.parametrize("f0_fill", [np.nan, np.inf]) +def test_initial_state_finiteness(f0_fill): + # regression test for gh-17846 + msg = "All components of the initial state `y0` must be finite." + with pytest.raises(ValueError, match=msg): + solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill)) + + +@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF']) +def test_zero_interval(method): + # Case where upper and lower limits of integration are the same + # Result of integration should match initial state. + # f[y(t)] = 2y(t) + def f(t, y): + return 2 * y + res = solve_ivp(f, (0.0, 0.0), np.array([1.0]), method=method) + assert res.success + assert_allclose(res.y[0, -1], 1.0) + + +@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF']) +def test_tbound_respected_small_interval(method): + """Regression test for gh-17341""" + SMALL = 1e-4 + + # f[y(t)] = 2y(t) on t in [0,SMALL] + # undefined otherwise + def f(t, y): + if t > SMALL: + raise ValueError("Function was evaluated outside interval") + return 2 * y + res = solve_ivp(f, (0.0, SMALL), np.array([1]), method=method) + assert res.success + + +@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF']) +def test_tbound_respected_larger_interval(method): + """Regression test for gh-8848""" + def V(r): + return -11/r + 10 * r / (0.05 + r**2) + + def func(t, p): + if t < -17 or t > 2: + raise ValueError("Function was evaluated outside interval") + P = p[0] + Q = p[1] + r = np.exp(t) + dPdr = r * Q + dQdr = -2.0 * r * ((-0.2 - V(r)) * P + 1 / r * Q) + return np.array([dPdr, dQdr]) + + result = solve_ivp(func, + (-17, 2), + y0=np.array([1, -11]), + max_step=0.03, + vectorized=False, + t_eval=None, + atol=1e-8, + rtol=1e-5) + assert result.success + + +@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF']) +def test_tbound_respected_oscillator(method): + "Regression test for gh-9198" + def reactions_func(t, y): + if (t > 205): + raise ValueError("Called outside interval") + yprime = np.array([1.73307544e-02, + 6.49376470e-06, + 0.00000000e+00, + 0.00000000e+00]) + return yprime + + def run_sim2(t_end, n_timepoints=10, shortest_delay_line=10000000): + init_state = np.array([134.08298555, 138.82348612, 100., 0.]) + t0 = 100.0 + t1 = 200.0 + return solve_ivp(reactions_func, + (t0, t1), + init_state.copy(), + dense_output=True, + max_step=t1 - t0) + result = run_sim2(1000, 100, 100) + assert result.success + + +def test_inital_maxstep(): + """Verify that select_inital_step respects max_step""" + rtol = 1e-3 + atol = 1e-6 + y0 = np.array([1/3, 2/9]) + for (t0, t_bound) in ((5, 9), (5, 1)): + for method_order in [RK23.error_estimator_order, + RK45.error_estimator_order, + DOP853.error_estimator_order, + 3, #RADAU + 1 #BDF + ]: + step_no_max = select_initial_step(fun_rational, t0, y0, t_bound, + np.inf, + fun_rational(t0,y0), + np.sign(t_bound - t0), + method_order, + rtol, atol) + max_step = step_no_max/2 + step_with_max = select_initial_step(fun_rational, t0, y0, t_bound, + max_step, + fun_rational(t0, y0), + np.sign(t_bound - t0), + method_order, + rtol, atol) + assert_equal(max_step, step_with_max) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/test_rk.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/test_rk.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd196c43b866e7bcbb05a447f67cc7e190fcfbe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_ivp/tests/test_rk.py @@ -0,0 +1,37 @@ +import pytest +from numpy.testing import assert_allclose, assert_ +import numpy as np +from scipy.integrate import RK23, RK45, DOP853 +from scipy.integrate._ivp import dop853_coefficients + + +@pytest.mark.parametrize("solver", [RK23, RK45, DOP853]) +def test_coefficient_properties(solver): + assert_allclose(np.sum(solver.B), 1, rtol=1e-15) + assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14) + + +def test_coefficient_properties_dop853(): + assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15) + assert_allclose(np.sum(dop853_coefficients.A, axis=1), + dop853_coefficients.C, + rtol=1e-14) + + +@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853]) +def test_error_estimation(solver_class): + step = 0.2 + solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step) + solver.step() + error_estimate = solver._estimate_error(solver.K, step) + error = solver.y - np.exp([step]) + assert_(np.abs(error) < np.abs(error_estimate)) + + +@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853]) +def test_error_estimation_complex(solver_class): + h = 0.2 + solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h) + solver.step() + err_norm = solver._estimate_error_norm(solver.K, h, scale=[1]) + assert np.isrealobj(err_norm) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..37521c54486f26fbb76538b74658b5a9f73e54a6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__init__.py @@ -0,0 +1,12 @@ +"""Numerical cubature algorithms""" + +from ._base import ( + Rule, FixedRule, + NestedFixedRule, + ProductNestedFixed, +) +from ._genz_malik import GenzMalikCubature +from ._gauss_kronrod import GaussKronrodQuadrature +from ._gauss_legendre import GaussLegendreQuadrature + +__all__ = [s for s in dir() if not s.startswith('_')] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e489fdb56d0bc259efaeb1eeba8e314802e90c44 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01f81abc37f3942f643f407dcc442c7d4a34d4b8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8d8049037428b8707f4584d85a02a16ccbc5bb3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7e2f0455c5ff3f41ec909eb6fad3bfe8cbf61a1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f090895fc5452e891dddc4b6b2a8ee4996177a0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ba66db146ed671c3a11c7b3c9ad48e9f519d7c0e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_base.py @@ -0,0 +1,518 @@ +from scipy._lib._array_api import array_namespace, xp_size + +from functools import cached_property + + +class Rule: + """ + Base class for numerical integration algorithms (cubatures). + + Finds an estimate for the integral of ``f`` over the region described by two arrays + ``a`` and ``b`` via `estimate`, and find an estimate for the error of this + approximation via `estimate_error`. + + If a subclass does not implement its own `estimate_error`, then it will use a + default error estimate based on the difference between the estimate over the whole + region and the sum of estimates over that region divided into ``2^ndim`` subregions. + + See Also + -------- + FixedRule + + Examples + -------- + In the following, a custom rule is created which uses 3D Genz-Malik cubature for + the estimate of the integral, and the difference between this estimate and a less + accurate estimate using 5-node Gauss-Legendre quadrature as an estimate for the + error. + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import ( + ... Rule, ProductNestedFixed, GenzMalikCubature, GaussLegendreQuadrature + ... ) + >>> def f(x, r, alphas): + ... # f(x) = cos(2*pi*r + alpha @ x) + ... # Need to allow r and alphas to be arbitrary shape + ... npoints, ndim = x.shape[0], x.shape[-1] + ... alphas_reshaped = alphas[np.newaxis, :] + ... x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim) + ... return np.cos(2*np.pi*r + np.sum(alphas_reshaped * x_reshaped, axis=-1)) + >>> genz = GenzMalikCubature(ndim=3) + >>> gauss = GaussKronrodQuadrature(npoints=21) + >>> # Gauss-Kronrod is 1D, so we find the 3D product rule: + >>> gauss_3d = ProductNestedFixed([gauss, gauss, gauss]) + >>> class CustomRule(Rule): + ... def estimate(self, f, a, b, args=()): + ... return genz.estimate(f, a, b, args) + ... def estimate_error(self, f, a, b, args=()): + ... return np.abs( + ... genz.estimate(f, a, b, args) + ... - gauss_3d.estimate(f, a, b, args) + ... ) + >>> rng = np.random.default_rng() + >>> res = cubature( + ... f=f, + ... a=np.array([0, 0, 0]), + ... b=np.array([1, 1, 1]), + ... rule=CustomRule(), + ... args=(rng.random((2,)), rng.random((3, 2, 3))) + ... ) + >>> res.estimate + array([[-0.95179502, 0.12444608], + [-0.96247411, 0.60866385], + [-0.97360014, 0.25515587]]) + """ + + def estimate(self, f, a, b, args=()): + r""" + Calculate estimate of integral of `f` in rectangular region described by + corners `a` and ``b``. + + Parameters + ---------- + f : callable + Function to integrate. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays ``x`` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to ``f``, if any. + + Returns + ------- + est : ndarray + Result of estimation. If `f` returns arrays of shape ``(npoints, + output_dim_1, ..., output_dim_n)``, then `est` will be of shape + ``(output_dim_1, ..., output_dim_n)``. + """ + raise NotImplementedError + + def estimate_error(self, f, a, b, args=()): + r""" + Estimate the error of the approximation for the integral of `f` in rectangular + region described by corners `a` and `b`. + + If a subclass does not override this method, then a default error estimator is + used. This estimates the error as ``|est - refined_est|`` where ``est`` is + ``estimate(f, a, b)`` and ``refined_est`` is the sum of + ``estimate(f, a_k, b_k)`` where ``a_k, b_k`` are the coordinates of each + subregion of the region described by ``a`` and ``b``. In the 1D case, this + is equivalent to comparing the integral over an entire interval ``[a, b]`` to + the sum of the integrals over the left and right subintervals, ``[a, (a+b)/2]`` + and ``[(a+b)/2, b]``. + + Parameters + ---------- + f : callable + Function to estimate error for. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays `x` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to `f`, if any. + + Returns + ------- + err_est : ndarray + Result of error estimation. If `f` returns arrays of shape + ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be + of shape ``(output_dim_1, ..., output_dim_n)``. + """ + + est = self.estimate(f, a, b, args) + refined_est = 0 + + for a_k, b_k in _split_subregion(a, b): + refined_est += self.estimate(f, a_k, b_k, args) + + return self.xp.abs(est - refined_est) + + +class FixedRule(Rule): + """ + A rule implemented as the weighted sum of function evaluations at fixed nodes. + + Attributes + ---------- + nodes_and_weights : (ndarray, ndarray) + A tuple ``(nodes, weights)`` of nodes at which to evaluate ``f`` and the + corresponding weights. ``nodes`` should be of shape ``(num_nodes,)`` for 1D + cubature rules (quadratures) and more generally for N-D cubature rules, it + should be of shape ``(num_nodes, ndim)``. ``weights`` should be of shape + ``(num_nodes,)``. The nodes and weights should be for integrals over + :math:`[-1, 1]^n`. + + See Also + -------- + GaussLegendreQuadrature, GaussKronrodQuadrature, GenzMalikCubature + + Examples + -------- + + Implementing Simpson's 1/3 rule: + + >>> import numpy as np + >>> from scipy.integrate._rules import FixedRule + >>> class SimpsonsQuad(FixedRule): + ... @property + ... def nodes_and_weights(self): + ... nodes = np.array([-1, 0, 1]) + ... weights = np.array([1/3, 4/3, 1/3]) + ... return (nodes, weights) + >>> rule = SimpsonsQuad() + >>> rule.estimate( + ... f=lambda x: x**2, + ... a=np.array([0]), + ... b=np.array([1]), + ... ) + [0.3333333] + """ + + def __init__(self): + self.xp = None + + @property + def nodes_and_weights(self): + raise NotImplementedError + + def estimate(self, f, a, b, args=()): + r""" + Calculate estimate of integral of `f` in rectangular region described by + corners `a` and `b` as ``sum(weights * f(nodes))``. + + Nodes and weights will automatically be adjusted from calculating integrals over + :math:`[-1, 1]^n` to :math:`[a, b]^n`. + + Parameters + ---------- + f : callable + Function to integrate. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays `x` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to `f`, if any. + + Returns + ------- + est : ndarray + Result of estimation. If `f` returns arrays of shape ``(npoints, + output_dim_1, ..., output_dim_n)``, then `est` will be of shape + ``(output_dim_1, ..., output_dim_n)``. + """ + nodes, weights = self.nodes_and_weights + + if self.xp is None: + self.xp = array_namespace(nodes) + + return _apply_fixed_rule(f, a, b, nodes, weights, args, self.xp) + + +class NestedFixedRule(FixedRule): + r""" + A cubature rule with error estimate given by the difference between two underlying + fixed rules. + + If constructed as ``NestedFixedRule(higher, lower)``, this will use:: + + estimate(f, a, b) := higher.estimate(f, a, b) + estimate_error(f, a, b) := \|higher.estimate(f, a, b) - lower.estimate(f, a, b)| + + (where the absolute value is taken elementwise). + + Attributes + ---------- + higher : Rule + Higher accuracy rule. + + lower : Rule + Lower accuracy rule. + + See Also + -------- + GaussKronrodQuadrature + + Examples + -------- + + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import ( + ... GaussLegendreQuadrature, NestedFixedRule, ProductNestedFixed + ... ) + >>> higher = GaussLegendreQuadrature(10) + >>> lower = GaussLegendreQuadrature(5) + >>> rule = NestedFixedRule( + ... higher, + ... lower + ... ) + >>> rule_2d = ProductNestedFixed([rule, rule]) + """ + + def __init__(self, higher, lower): + self.higher = higher + self.lower = lower + self.xp = None + + @property + def nodes_and_weights(self): + if self.higher is not None: + return self.higher.nodes_and_weights + else: + raise NotImplementedError + + @property + def lower_nodes_and_weights(self): + if self.lower is not None: + return self.lower.nodes_and_weights + else: + raise NotImplementedError + + def estimate_error(self, f, a, b, args=()): + r""" + Estimate the error of the approximation for the integral of `f` in rectangular + region described by corners `a` and `b`. + + Parameters + ---------- + f : callable + Function to estimate error for. `f` must have the signature:: + f(x : ndarray, \*args) -> ndarray + + `f` should accept arrays `x` of shape:: + (npoints, ndim) + + and output arrays of shape:: + (npoints, output_dim_1, ..., output_dim_n) + + In this case, `estimate` will return arrays of shape:: + (output_dim_1, ..., output_dim_n) + a, b : ndarray + Lower and upper limits of integration as rank-1 arrays specifying the left + and right endpoints of the intervals being integrated over. Infinite limits + are currently not supported. + args : tuple, optional + Additional positional args passed to `f`, if any. + + Returns + ------- + err_est : ndarray + Result of error estimation. If `f` returns arrays of shape + ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be + of shape ``(output_dim_1, ..., output_dim_n)``. + """ + + nodes, weights = self.nodes_and_weights + lower_nodes, lower_weights = self.lower_nodes_and_weights + + if self.xp is None: + self.xp = array_namespace(nodes) + + error_nodes = self.xp.concat([nodes, lower_nodes], axis=0) + error_weights = self.xp.concat([weights, -lower_weights], axis=0) + + return self.xp.abs( + _apply_fixed_rule(f, a, b, error_nodes, error_weights, args, self.xp) + ) + + +class ProductNestedFixed(NestedFixedRule): + """ + Find the n-dimensional cubature rule constructed from the Cartesian product of 1-D + `NestedFixedRule` quadrature rules. + + Given a list of N 1-dimensional quadrature rules which support error estimation + using NestedFixedRule, this will find the N-dimensional cubature rule obtained by + taking the Cartesian product of their nodes, and estimating the error by taking the + difference with a lower-accuracy N-dimensional cubature rule obtained using the + ``.lower_nodes_and_weights`` rule in each of the base 1-dimensional rules. + + Parameters + ---------- + base_rules : list of NestedFixedRule + List of base 1-dimensional `NestedFixedRule` quadrature rules. + + Attributes + ---------- + base_rules : list of NestedFixedRule + List of base 1-dimensional `NestedFixedRule` qudarature rules. + + Examples + -------- + + Evaluate a 2D integral by taking the product of two 1D rules: + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import ( + ... ProductNestedFixed, GaussKronrodQuadrature + ... ) + >>> def f(x): + ... # f(x) = cos(x_1) + cos(x_2) + ... return np.sum(np.cos(x), axis=-1) + >>> rule = ProductNestedFixed( + ... [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)] + ... ) # Use 15-point Gauss-Kronrod, which implements NestedFixedRule + >>> a, b = np.array([0, 0]), np.array([1, 1]) + >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829 + np.float64(1.682941969615793) + >>> rule.estimate_error(f, a, b) + np.float64(2.220446049250313e-16) + """ + + def __init__(self, base_rules): + for rule in base_rules: + if not isinstance(rule, NestedFixedRule): + raise ValueError("base rules for product need to be instance of" + "NestedFixedRule") + + self.base_rules = base_rules + self.xp = None + + @cached_property + def nodes_and_weights(self): + nodes = _cartesian_product( + [rule.nodes_and_weights[0] for rule in self.base_rules] + ) + + if self.xp is None: + self.xp = array_namespace(nodes) + + weights = self.xp.prod( + _cartesian_product( + [rule.nodes_and_weights[1] for rule in self.base_rules] + ), + axis=-1, + ) + + return nodes, weights + + @cached_property + def lower_nodes_and_weights(self): + nodes = _cartesian_product( + [cubature.lower_nodes_and_weights[0] for cubature in self.base_rules] + ) + + if self.xp is None: + self.xp = array_namespace(nodes) + + weights = self.xp.prod( + _cartesian_product( + [cubature.lower_nodes_and_weights[1] for cubature in self.base_rules] + ), + axis=-1, + ) + + return nodes, weights + + +def _cartesian_product(arrays): + xp = array_namespace(*arrays) + + arrays_ix = xp.meshgrid(*arrays, indexing='ij') + result = xp.reshape(xp.stack(arrays_ix, axis=-1), (-1, len(arrays))) + + return result + + +def _split_subregion(a, b, xp, split_at=None): + """ + Given the coordinates of a region like a=[0, 0] and b=[1, 1], yield the coordinates + of all subregions, which in this case would be:: + + ([0, 0], [1/2, 1/2]), + ([0, 1/2], [1/2, 1]), + ([1/2, 0], [1, 1/2]), + ([1/2, 1/2], [1, 1]) + """ + xp = array_namespace(a, b) + + if split_at is None: + split_at = (a + b) / 2 + + left = [xp.stack((a[i], split_at[i])) for i in range(a.shape[0])] + right = [xp.stack((split_at[i], b[i])) for i in range(b.shape[0])] + + a_sub = _cartesian_product(left) + b_sub = _cartesian_product(right) + + for i in range(a_sub.shape[0]): + yield a_sub[i, ...], b_sub[i, ...] + + +def _apply_fixed_rule(f, a, b, orig_nodes, orig_weights, args, xp): + # Downcast nodes and weights to common dtype of a and b + result_dtype = a.dtype + orig_nodes = xp.astype(orig_nodes, result_dtype) + orig_weights = xp.astype(orig_weights, result_dtype) + + # Ensure orig_nodes are at least 2D, since 1D cubature methods can return arrays of + # shape (npoints,) rather than (npoints, 1) + if orig_nodes.ndim == 1: + orig_nodes = orig_nodes[:, None] + + rule_ndim = orig_nodes.shape[-1] + + a_ndim = xp_size(a) + b_ndim = xp_size(b) + + if rule_ndim != a_ndim or rule_ndim != b_ndim: + raise ValueError(f"rule and function are of incompatible dimension, nodes have" + f"ndim {rule_ndim}, while limit of integration has ndim" + f"a_ndim={a_ndim}, b_ndim={b_ndim}") + + lengths = b - a + + # The underlying rule is for the hypercube [-1, 1]^n. + # + # To handle arbitrary regions of integration, it's necessary to apply a linear + # change of coordinates to map each interval [a[i], b[i]] to [-1, 1]. + nodes = (orig_nodes + 1) * (lengths * 0.5) + a + + # Also need to multiply the weights by a scale factor equal to the determinant + # of the Jacobian for this coordinate change. + weight_scale_factor = xp.prod(lengths, dtype=result_dtype) / 2**rule_ndim + weights = orig_weights * weight_scale_factor + + f_nodes = f(nodes, *args) + weights_reshaped = xp.reshape(weights, (-1, *([1] * (f_nodes.ndim - 1)))) + + # f(nodes) will have shape (num_nodes, output_dim_1, ..., output_dim_n) + # Summing along the first axis means estimate will shape (output_dim_1, ..., + # output_dim_n) + est = xp.sum(weights_reshaped * f_nodes, axis=0, dtype=result_dtype) + + return est diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_gauss_kronrod.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_gauss_kronrod.py new file mode 100644 index 0000000000000000000000000000000000000000..68c319e0b145f78c8d08aec7025da16830a81a64 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_gauss_kronrod.py @@ -0,0 +1,202 @@ +from scipy._lib._array_api import np_compat, array_namespace + +from functools import cached_property + +from ._base import NestedFixedRule +from ._gauss_legendre import GaussLegendreQuadrature + + +class GaussKronrodQuadrature(NestedFixedRule): + """ + Gauss-Kronrod quadrature. + + Gauss-Kronrod rules consist of two quadrature rules, one higher-order and one + lower-order. The higher-order rule is used as the estimate of the integral and the + difference between them is used as an estimate for the error. + + Gauss-Kronrod is a 1D rule. To use it for multidimensional integrals, it will be + necessary to use ProductNestedFixed and multiple Gauss-Kronrod rules. See Examples. + + For n-node Gauss-Kronrod, the lower-order rule has ``n//2`` nodes, which are the + ordinary Gauss-Legendre nodes with corresponding weights. The higher-order rule has + ``n`` nodes, ``n//2`` of which are the same as the lower-order rule and the + remaining nodes are the Kronrod extension of those nodes. + + Parameters + ---------- + npoints : int + Number of nodes for the higher-order rule. + + xp : array_namespace, optional + The namespace for the node and weight arrays. Default is None, where NumPy is + used. + + Attributes + ---------- + lower : Rule + Lower-order rule. + + References + ---------- + .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic + Integration, files: dqk21.f, dqk15.f (1983). + + Examples + -------- + Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the + estimates will also be arrays, despite the fact that this is a 1D problem. + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import GaussKronrodQuadrature + >>> def f(x): + ... return np.cos(x) + >>> rule = GaussKronrodQuadrature(21) # Use 21-point GaussKronrod + >>> a, b = np.array([0]), np.array([1]) + >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147 + array([0.84147098]) + >>> rule.estimate_error(f, a, b) + array([1.11022302e-16]) + + Evaluate a 2D integral. Note that in this example ``f`` returns a float, so the + estimates will also be floats. + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import ( + ... ProductNestedFixed, GaussKronrodQuadrature + ... ) + >>> def f(x): + ... # f(x) = cos(x_1) + cos(x_2) + ... return np.sum(np.cos(x), axis=-1) + >>> rule = ProductNestedFixed( + ... [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)] + ... ) # Use 15-point Gauss-Kronrod + >>> a, b = np.array([0, 0]), np.array([1, 1]) + >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829 + np.float64(1.682941969615793) + >>> rule.estimate_error(f, a, b) + np.float64(2.220446049250313e-16) + """ + + def __init__(self, npoints, xp=None): + # TODO: nodes and weights are currently hard-coded for values 15 and 21, but in + # the future it would be best to compute the Kronrod extension of the lower rule + if npoints != 15 and npoints != 21: + raise NotImplementedError("Gauss-Kronrod quadrature is currently only" + "supported for 15 or 21 nodes") + + self.npoints = npoints + + if xp is None: + xp = np_compat + + self.xp = array_namespace(xp.empty(0)) + + self.gauss = GaussLegendreQuadrature(npoints//2, xp=self.xp) + + @cached_property + def nodes_and_weights(self): + # These values are from QUADPACK's `dqk21.f` and `dqk15.f` (1983). + if self.npoints == 21: + nodes = self.xp.asarray( + [ + 0.995657163025808080735527280689003, + 0.973906528517171720077964012084452, + 0.930157491355708226001207180059508, + 0.865063366688984510732096688423493, + 0.780817726586416897063717578345042, + 0.679409568299024406234327365114874, + 0.562757134668604683339000099272694, + 0.433395394129247190799265943165784, + 0.294392862701460198131126603103866, + 0.148874338981631210884826001129720, + 0, + -0.148874338981631210884826001129720, + -0.294392862701460198131126603103866, + -0.433395394129247190799265943165784, + -0.562757134668604683339000099272694, + -0.679409568299024406234327365114874, + -0.780817726586416897063717578345042, + -0.865063366688984510732096688423493, + -0.930157491355708226001207180059508, + -0.973906528517171720077964012084452, + -0.995657163025808080735527280689003, + ], + dtype=self.xp.float64, + ) + + weights = self.xp.asarray( + [ + 0.011694638867371874278064396062192, + 0.032558162307964727478818972459390, + 0.054755896574351996031381300244580, + 0.075039674810919952767043140916190, + 0.093125454583697605535065465083366, + 0.109387158802297641899210590325805, + 0.123491976262065851077958109831074, + 0.134709217311473325928054001771707, + 0.142775938577060080797094273138717, + 0.147739104901338491374841515972068, + 0.149445554002916905664936468389821, + 0.147739104901338491374841515972068, + 0.142775938577060080797094273138717, + 0.134709217311473325928054001771707, + 0.123491976262065851077958109831074, + 0.109387158802297641899210590325805, + 0.093125454583697605535065465083366, + 0.075039674810919952767043140916190, + 0.054755896574351996031381300244580, + 0.032558162307964727478818972459390, + 0.011694638867371874278064396062192, + ], + dtype=self.xp.float64, + ) + elif self.npoints == 15: + nodes = self.xp.asarray( + [ + 0.991455371120812639206854697526329, + 0.949107912342758524526189684047851, + 0.864864423359769072789712788640926, + 0.741531185599394439863864773280788, + 0.586087235467691130294144838258730, + 0.405845151377397166906606412076961, + 0.207784955007898467600689403773245, + 0.000000000000000000000000000000000, + -0.207784955007898467600689403773245, + -0.405845151377397166906606412076961, + -0.586087235467691130294144838258730, + -0.741531185599394439863864773280788, + -0.864864423359769072789712788640926, + -0.949107912342758524526189684047851, + -0.991455371120812639206854697526329, + ], + dtype=self.xp.float64, + ) + + weights = self.xp.asarray( + [ + 0.022935322010529224963732008058970, + 0.063092092629978553290700663189204, + 0.104790010322250183839876322541518, + 0.140653259715525918745189590510238, + 0.169004726639267902826583426598550, + 0.190350578064785409913256402421014, + 0.204432940075298892414161999234649, + 0.209482141084727828012999174891714, + 0.204432940075298892414161999234649, + 0.190350578064785409913256402421014, + 0.169004726639267902826583426598550, + 0.140653259715525918745189590510238, + 0.104790010322250183839876322541518, + 0.063092092629978553290700663189204, + 0.022935322010529224963732008058970, + ], + dtype=self.xp.float64, + ) + + return nodes, weights + + @property + def lower_nodes_and_weights(self): + return self.gauss.nodes_and_weights diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_gauss_legendre.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_gauss_legendre.py new file mode 100644 index 0000000000000000000000000000000000000000..422cd0e165995f44af0c3a38c927dbd952a1a8a0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_gauss_legendre.py @@ -0,0 +1,62 @@ +from scipy._lib._array_api import array_namespace, np_compat + +from functools import cached_property + +from scipy.special import roots_legendre + +from ._base import FixedRule + + +class GaussLegendreQuadrature(FixedRule): + """ + Gauss-Legendre quadrature. + + Parameters + ---------- + npoints : int + Number of nodes for the higher-order rule. + + xp : array_namespace, optional + The namespace for the node and weight arrays. Default is None, where NumPy is + used. + + Examples + -------- + Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the + estimates will also be arrays. + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import GaussLegendreQuadrature + >>> def f(x): + ... return np.cos(x) + >>> rule = GaussLegendreQuadrature(21) # Use 21-point GaussLegendre + >>> a, b = np.array([0]), np.array([1]) + >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147 + array([0.84147098]) + >>> rule.estimate_error(f, a, b) + array([1.11022302e-16]) + """ + + def __init__(self, npoints, xp=None): + if npoints < 2: + raise ValueError( + "At least 2 nodes required for Gauss-Legendre cubature" + ) + + self.npoints = npoints + + if xp is None: + xp = np_compat + + self.xp = array_namespace(xp.empty(0)) + + @cached_property + def nodes_and_weights(self): + # TODO: current converting to/from numpy + nodes, weights = roots_legendre(self.npoints) + + return ( + self.xp.asarray(nodes, dtype=self.xp.float64), + self.xp.asarray(weights, dtype=self.xp.float64) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_genz_malik.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_genz_malik.py new file mode 100644 index 0000000000000000000000000000000000000000..581de9b97642de7895f0cb8e8b8c04f5f6d383c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/_rules/_genz_malik.py @@ -0,0 +1,210 @@ +import math +import itertools + +from functools import cached_property + +from scipy._lib._array_api import array_namespace, np_compat + +from scipy.integrate._rules import NestedFixedRule + + +class GenzMalikCubature(NestedFixedRule): + """ + Genz-Malik cubature. + + Genz-Malik is only defined for integrals of dimension >= 2. + + Parameters + ---------- + ndim : int + The spatial dimension of the integrand. + + xp : array_namespace, optional + The namespace for the node and weight arrays. Default is None, where NumPy is + used. + + Attributes + ---------- + higher : Cubature + Higher-order rule. + + lower : Cubature + Lower-order rule. + + References + ---------- + .. [1] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for + numerical integration over an N-dimensional rectangular region, Journal of + Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302, + ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X. + + Examples + -------- + Evaluate a 3D integral: + + >>> import numpy as np + >>> from scipy.integrate import cubature + >>> from scipy.integrate._rules import GenzMalikCubature + >>> def f(x): + ... # f(x) = cos(x_1) + cos(x_2) + cos(x_3) + ... return np.sum(np.cos(x), axis=-1) + >>> rule = GenzMalikCubature(3) # Use 3D Genz-Malik + >>> a, b = np.array([0, 0, 0]), np.array([1, 1, 1]) + >>> rule.estimate(f, a, b) # True value 3*sin(1), approximately 2.5244 + np.float64(2.5244129547230862) + >>> rule.estimate_error(f, a, b) + np.float64(1.378269656626685e-06) + """ + + def __init__(self, ndim, degree=7, lower_degree=5, xp=None): + if ndim < 2: + raise ValueError("Genz-Malik cubature is only defined for ndim >= 2") + + if degree != 7 or lower_degree != 5: + raise NotImplementedError("Genz-Malik cubature is currently only supported" + "for degree=7, lower_degree=5") + + self.ndim = ndim + self.degree = degree + self.lower_degree = lower_degree + + if xp is None: + xp = np_compat + + self.xp = array_namespace(xp.empty(0)) + + @cached_property + def nodes_and_weights(self): + # TODO: Currently only support for degree 7 Genz-Malik cubature, should aim to + # support arbitrary degree + l_2 = math.sqrt(9/70) + l_3 = math.sqrt(9/10) + l_4 = math.sqrt(9/10) + l_5 = math.sqrt(9/19) + + its = itertools.chain( + [(0,) * self.ndim], + _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)), + _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)), + _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)), + _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)), + _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)), + _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)), + _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)), + itertools.product((l_5, -l_5), repeat=self.ndim), + ) + + nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim) + 2**self.ndim + + nodes = self.xp.asarray( + list(zip(*its)), + dtype=self.xp.float64, + ) + + nodes = self.xp.reshape(nodes, (self.ndim, nodes_size)) + + # It's convenient to generate the nodes as a sequence of evaluation points + # as an array of shape (npoints, ndim), but nodes needs to have shape + # (ndim, npoints) + nodes = nodes.T + + w_1 = ( + (2**self.ndim) * (12824 - 9120*self.ndim + (400 * self.ndim**2)) / 19683 + ) + w_2 = (2**self.ndim) * 980/6561 + w_3 = (2**self.ndim) * (1820 - 400 * self.ndim) / 19683 + w_4 = (2**self.ndim) * (200 / 19683) + w_5 = 6859 / 19683 + + weights = self.xp.concat([ + self.xp.asarray([w_1] * 1, dtype=self.xp.float64), + self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64), + self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64), + self.xp.asarray( + [w_4] * (2 * (self.ndim - 1) * self.ndim), + dtype=self.xp.float64, + ), + self.xp.asarray([w_5] * (2**self.ndim), dtype=self.xp.float64), + ]) + + return nodes, weights + + @cached_property + def lower_nodes_and_weights(self): + # TODO: Currently only support for the degree 5 lower rule, in the future it + # would be worth supporting arbitrary degree + + # Nodes are almost the same as the full rule, but there are no nodes + # corresponding to l_5. + l_2 = math.sqrt(9/70) + l_3 = math.sqrt(9/10) + l_4 = math.sqrt(9/10) + + its = itertools.chain( + [(0,) * self.ndim], + _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)), + _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)), + _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)), + _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)), + _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)), + _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)), + _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)), + ) + + nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim) + + nodes = self.xp.asarray(list(zip(*its)), dtype=self.xp.float64) + nodes = self.xp.reshape(nodes, (self.ndim, nodes_size)) + nodes = nodes.T + + # Weights are different from those in the full rule. + w_1 = (2**self.ndim) * (729 - 950*self.ndim + 50*self.ndim**2) / 729 + w_2 = (2**self.ndim) * (245 / 486) + w_3 = (2**self.ndim) * (265 - 100*self.ndim) / 1458 + w_4 = (2**self.ndim) * (25 / 729) + + weights = self.xp.concat([ + self.xp.asarray([w_1] * 1, dtype=self.xp.float64), + self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64), + self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64), + self.xp.asarray( + [w_4] * (2 * (self.ndim - 1) * self.ndim), + dtype=self.xp.float64, + ), + ]) + + return nodes, weights + + +def _distinct_permutations(iterable): + """ + Find the number of distinct permutations of elements of `iterable`. + """ + + # Algorithm: https://w.wiki/Qai + + items = sorted(iterable) + size = len(items) + + while True: + # Yield the permutation we have + yield tuple(items) + + # Find the largest index i such that A[i] < A[i + 1] + for i in range(size - 2, -1, -1): + if items[i] < items[i + 1]: + break + + # If no such index exists, this permutation is the last one + else: + return + + # Find the largest index j greater than j such that A[i] < A[j] + for j in range(size - 1, i, -1): + if items[i] < items[j]: + break + + # Swap the value of A[i] with that of A[j], then reverse the + # sequence from A[i + 1] to form the new permutation + items[i], items[j] = items[j], items[i] + items[i+1:] = items[:i-size:-1] # A[i + 1:][::-1] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26f67a01f91763de3044b923b3fd8f3af50ed225 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test__quad_vec.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test__quad_vec.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1cbe1bf43ace68bb417fa9dd5e0caecef80bdb2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test__quad_vec.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_banded_ode_solvers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_banded_ode_solvers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8ba6379c151255e41cc6eed5174004e3274a617 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_banded_ode_solvers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_bvp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_bvp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..246b5467f189e481e24cf49d25f72ae65e94548d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_bvp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_cubature.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_cubature.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7203fcd19097949f4a6d10905a889ed077ff2516 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_cubature.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_integrate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_integrate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14bfb859e5a7782852bd0929715c5c7001c8d086 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_integrate.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_quadpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_quadpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..932282d762965fce3dbd9cb1b7cde375b264fa90 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_quadpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_quadrature.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_quadrature.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e13c69f620e3acf2f361247e906b958603a0d168 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_quadrature.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_tanhsinh.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_tanhsinh.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efb36a44629506bf4a13ebbb6865a48cf1c79f72 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/__pycache__/test_tanhsinh.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test__quad_vec.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test__quad_vec.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc4b5e809a4def7338ababe2e4ee117d27b18b6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test__quad_vec.py @@ -0,0 +1,212 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose + +from scipy.integrate import quad_vec +from scipy._lib._array_api import make_xp_test_case + +from multiprocessing.dummy import Pool + + +quadrature_params = pytest.mark.parametrize( + 'quadrature', [None, "gk15", "gk21", "trapezoid"]) + +def _lorenzian(x): + return 1 / (1 + x**2) + +def _func_with_args(x, a): + return x * (x + a) * np.arange(3) + + +@make_xp_test_case(quad_vec) +class TestQuadVec: + @quadrature_params + def test_quad_vec_simple(self, quadrature): + n = np.arange(10) + def f(x): + return x ** n + for epsabs in [0.1, 1e-3, 1e-6]: + if quadrature == 'trapezoid' and epsabs < 1e-4: + # slow: skip + continue + + kwargs = dict(epsabs=epsabs, quadrature=quadrature) + + exact = 2**(n+1)/(n + 1) + + res, err = quad_vec(f, 0, 2, norm='max', **kwargs) + assert_allclose(res, exact, rtol=0, atol=epsabs) + + res, err = quad_vec(f, 0, 2, norm='2', **kwargs) + assert np.linalg.norm(res - exact) < epsabs + + res, err = quad_vec(f, 0, 2, norm='max', points=(0.5, 1.0), **kwargs) + assert_allclose(res, exact, rtol=0, atol=epsabs) + + res, err, *rest = quad_vec(f, 0, 2, norm='max', + epsrel=1e-8, + full_output=True, + limit=10000, + **kwargs) + assert_allclose(res, exact, rtol=0, atol=epsabs) + + + @quadrature_params + def test_quad_vec_simple_inf(self, quadrature): + def f(x): + return 1 / (1 + np.float64(x) ** 2) + + for epsabs in [0.1, 1e-3, 1e-6]: + if quadrature == 'trapezoid' and epsabs < 1e-4: + # slow: skip + continue + + kwargs = dict(norm='max', epsabs=epsabs, quadrature=quadrature) + + res, err = quad_vec(f, 0, np.inf, **kwargs) + assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, 0, -np.inf, **kwargs) + assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, -np.inf, 0, **kwargs) + assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, np.inf, 0, **kwargs) + assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, -np.inf, np.inf, **kwargs) + assert_allclose(res, np.pi, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, np.inf, -np.inf, **kwargs) + assert_allclose(res, -np.pi, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, np.inf, np.inf, **kwargs) + assert_allclose(res, 0, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, -np.inf, -np.inf, **kwargs) + assert_allclose(res, 0, rtol=0, atol=max(epsabs, err)) + + res, err = quad_vec(f, 0, np.inf, points=(1.0, 2.0), **kwargs) + assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err)) + + def f(x): + return np.sin(x + 2) / (1 + x ** 2) + exact = np.pi / np.e * np.sin(2) + epsabs = 1e-5 + + res, err, info = quad_vec(f, -np.inf, np.inf, limit=1000, norm='max', + epsabs=epsabs, quadrature=quadrature, + full_output=True) + assert info.status == 1 + assert_allclose(res, exact, rtol=0, atol=max(epsabs, 1.5 * err)) + + + def test_quad_vec_args(self): + def f(x, a): + return x * (x + a) * np.arange(3) + a = 2 + exact = np.array([0, 4/3, 8/3]) + + res, err = quad_vec(f, 0, 1, args=(a,)) + assert_allclose(res, exact, rtol=0, atol=1e-4) + + @pytest.mark.fail_slow(10) + def test_quad_vec_pool(self): + f = _lorenzian + res, err = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=4) + assert_allclose(res, np.pi, rtol=0, atol=1e-4) + + with Pool(10) as pool: + def f(x): + return 1 / (1 + x ** 2) + res, _ = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, + workers=pool.map) + assert_allclose(res, np.pi, rtol=0, atol=1e-4) + + @pytest.mark.fail_slow(10) + @pytest.mark.parametrize('extra_args', [2, (2,)]) + @pytest.mark.parametrize( + 'workers', + [1, pytest.param(10, marks=pytest.mark.parallel_threads_limit(4))] + ) + def test_quad_vec_pool_args(self, extra_args, workers): + f = _func_with_args + exact = np.array([0, 4/3, 8/3]) + + res, err = quad_vec(f, 0, 1, args=extra_args, workers=workers) + assert_allclose(res, exact, rtol=0, atol=1e-4) + + with Pool(workers) as pool: + res, err = quad_vec(f, 0, 1, args=extra_args, workers=pool.map) + assert_allclose(res, exact, rtol=0, atol=1e-4) + + @quadrature_params + def test_num_eval(self, quadrature): + def f(x): + count[0] += 1 + return x**5 + + count = [0] + res = quad_vec(f, 0, 1, norm='max', full_output=True, quadrature=quadrature) + assert res[2].neval == count[0] + + def test_info(self): + def f(x): + return np.ones((3, 2, 1)) + + res, err, info = quad_vec(f, 0, 1, norm='max', full_output=True) + + assert info.success is True + assert info.status == 0 + assert info.message == 'Target precision reached.' + assert info.neval > 0 + assert info.intervals.shape[1] == 2 + assert info.integrals.shape == (info.intervals.shape[0], 3, 2, 1) + assert info.errors.shape == (info.intervals.shape[0],) + + def test_nan_inf(self): + def f_nan(x): + return np.nan + + def f_inf(x): + return np.inf if x < 0.1 else 1/x + + res, err, info = quad_vec(f_nan, 0, 1, full_output=True) + assert info.status == 3 + + res, err, info = quad_vec(f_inf, 0, 1, full_output=True) + assert info.status == 3 + + + @pytest.mark.parametrize('a,b', [(0, 1), (0, np.inf), (np.inf, 0), + (-np.inf, np.inf), (np.inf, -np.inf)]) + def test_points(self, a, b): + # Check that initial interval splitting is done according to + # `points`, by checking that consecutive sets of 15 point (for + # gk15) function evaluations lie between `points` + + points = (0, 0.25, 0.5, 0.75, 1.0) + points += tuple(-x for x in points) + + quadrature_points = 15 + interval_sets = [] + count = 0 + + def f(x): + nonlocal count + + if count % quadrature_points == 0: + interval_sets.append(set()) + + count += 1 + interval_sets[-1].add(float(x)) + return 0.0 + + quad_vec(f, a, b, points=points, quadrature='gk15', limit=0) + + # Check that all point sets lie in a single `points` interval + for p in interval_sets: + j = np.searchsorted(sorted(points), tuple(p)) + assert np.all(j == j[0]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a49a4f565f611f355abf1ce7b7b0305ed0f985 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py @@ -0,0 +1,307 @@ +import itertools +import pytest +import numpy as np +from numpy.testing import assert_allclose +from scipy.integrate import ode + + +def _band_count(a): + """Returns ml and mu, the lower and upper band sizes of a.""" + nrows, ncols = a.shape + ml = 0 + for k in range(-nrows+1, 0): + if np.diag(a, k).any(): + ml = -k + break + mu = 0 + for k in range(nrows-1, 0, -1): + if np.diag(a, k).any(): + mu = k + break + return ml, mu + + +def _linear_func(t, y, a): + """Linear system dy/dt = a * y""" + return a.dot(y) + + +def _linear_jac(t, y, a): + """Jacobian of a * y is a.""" + return a + + +def _linear_banded_jac(t, y, a): + """Banded Jacobian.""" + ml, mu = _band_count(a) + bjac = [np.r_[[0] * k, np.diag(a, k)] for k in range(mu, 0, -1)] + bjac.append(np.diag(a)) + for k in range(-1, -ml-1, -1): + bjac.append(np.r_[np.diag(a, k), [0] * (-k)]) + return bjac + + +def _solve_linear_sys(a, y0, tend=1, dt=0.1, + solver=None, method='bdf', use_jac=True, + with_jacobian=False, banded=False): + """Use scipy.integrate.ode to solve a linear system of ODEs. + + a : square ndarray + Matrix of the linear system to be solved. + y0 : ndarray + Initial condition + tend : float + Stop time. + dt : float + Step size of the output. + solver : str + If not None, this must be "vode", "lsoda" or "zvode". + method : str + Either "bdf" or "adams". + use_jac : bool + Determines if the jacobian function is passed to ode(). + with_jacobian : bool + Passed to ode.set_integrator(). + banded : bool + Determines whether a banded or full jacobian is used. + If `banded` is True, `lband` and `uband` are determined by the + values in `a`. + """ + if banded: + lband, uband = _band_count(a) + else: + lband = None + uband = None + + if use_jac: + if banded: + r = ode(_linear_func, _linear_banded_jac) + else: + r = ode(_linear_func, _linear_jac) + else: + r = ode(_linear_func) + + if solver is None: + if np.iscomplexobj(a): + solver = "zvode" + else: + solver = "vode" + + r.set_integrator(solver, + with_jacobian=with_jacobian, + method=method, + lband=lband, uband=uband, + rtol=1e-9, atol=1e-10, + ) + t0 = 0 + r.set_initial_value(y0, t0) + r.set_f_params(a) + r.set_jac_params(a) + + t = [t0] + y = [y0.copy()] + while r.successful() and r.t < tend: + r.integrate(r.t + dt) + t.append(r.t) + y.append(r.y.copy()) + + t = np.array(t) + y = np.array(y) + return t, y + + +def _analytical_solution(a, y0, t): + """ + Analytical solution to the linear differential equations dy/dt = a*y. + + The solution is only valid if `a` is diagonalizable. + + Returns a 2-D array with shape (len(t), len(y0)). + """ + lam, v = np.linalg.eig(a) + c = np.linalg.solve(v, y0) + e = c * np.exp(lam * t.reshape(-1, 1)) + sol = e.dot(v.T) + return sol + + +@pytest.mark.thread_unsafe(reason="vode integrator is not thread-safe") +def test_banded_ode_solvers(): + # Test the "lsoda", "vode" and "zvode" solvers of the `ode` class + # with a system that has a banded Jacobian matrix. + + # This test does not test the Jacobian evaluation (banded or not) + # of "lsoda" due to the nonstiff nature of the equations. + + t_exact = np.linspace(0, 1.0, 5) + + # --- Real arrays for testing the "lsoda" and "vode" solvers --- + + # lband = 2, uband = 1: + a_real = np.array([[-0.6, 0.1, 0.0, 0.0, 0.0], + [0.2, -0.5, 0.9, 0.0, 0.0], + [0.1, 0.1, -0.4, 0.1, 0.0], + [0.0, 0.3, -0.1, -0.9, -0.3], + [0.0, 0.0, 0.1, 0.1, -0.7]]) + + # lband = 0, uband = 1: + a_real_upper = np.triu(a_real) + + # lband = 2, uband = 0: + a_real_lower = np.tril(a_real) + + # lband = 0, uband = 0: + a_real_diag = np.triu(a_real_lower) + + real_matrices = [a_real, a_real_upper, a_real_lower, a_real_diag] + real_solutions = [] + + for a in real_matrices: + y0 = np.arange(1, a.shape[0] + 1) + y_exact = _analytical_solution(a, y0, t_exact) + real_solutions.append((y0, t_exact, y_exact)) + + def check_real(idx, solver, meth, use_jac, with_jac, banded): + a = real_matrices[idx] + y0, t_exact, y_exact = real_solutions[idx] + t, y = _solve_linear_sys(a, y0, + tend=t_exact[-1], + dt=t_exact[1] - t_exact[0], + solver=solver, + method=meth, + use_jac=use_jac, + with_jacobian=with_jac, + banded=banded) + assert_allclose(t, t_exact) + assert_allclose(y, y_exact) + + for idx in range(len(real_matrices)): + p = [['vode', 'lsoda'], # solver + ['bdf', 'adams'], # method + [False, True], # use_jac + [False, True], # with_jacobian + [False, True]] # banded + for solver, meth, use_jac, with_jac, banded in itertools.product(*p): + check_real(idx, solver, meth, use_jac, with_jac, banded) + + # --- Complex arrays for testing the "zvode" solver --- + + # complex, lband = 2, uband = 1: + a_complex = a_real - 0.5j * a_real + + # complex, lband = 0, uband = 0: + a_complex_diag = np.diag(np.diag(a_complex)) + + complex_matrices = [a_complex, a_complex_diag] + complex_solutions = [] + + for a in complex_matrices: + y0 = np.arange(1, a.shape[0] + 1) + 1j + y_exact = _analytical_solution(a, y0, t_exact) + complex_solutions.append((y0, t_exact, y_exact)) + + def check_complex(idx, solver, meth, use_jac, with_jac, banded): + a = complex_matrices[idx] + y0, t_exact, y_exact = complex_solutions[idx] + t, y = _solve_linear_sys(a, y0, + tend=t_exact[-1], + dt=t_exact[1] - t_exact[0], + solver=solver, + method=meth, + use_jac=use_jac, + with_jacobian=with_jac, + banded=banded) + assert_allclose(t, t_exact) + assert_allclose(y, y_exact) + + for idx in range(len(complex_matrices)): + p = [['bdf', 'adams'], # method + [False, True], # use_jac + [False, True], # with_jacobian + [False, True]] # banded + for meth, use_jac, with_jac, banded in itertools.product(*p): + check_complex(idx, "zvode", meth, use_jac, with_jac, banded) + +# lsoda requires a stiffer problem to switch to stiff solver +# Use the Robertson equation with surrounding trivial equations to make banded + +def stiff_f(t, y): + return np.array([ + y[0], + -0.04 * y[1] + 1e4 * y[2] * y[3], + 0.04 * y[1] - 1e4 * y[2] * y[3] - 3e7 * y[2]**2, + 3e7 * y[2]**2, + y[4] + ]) + +def stiff_jac(t, y): + return np.array([ + [1, 0, 0, 0, 0], + [0, -0.04, 1e4*y[3], 1e4*y[2], 0], + [0, 0.04, -1e4 * y[3] - 3e7 * 2 * y[2], -1e4*y[2], 0], + [0, 0, 3e7*2*y[2], 0, 0], + [0, 0, 0, 0, 1] + ]) + +def banded_stiff_jac(t, y): + return np.array([ + [0, 0, 0, 1e4*y[2], 0], + [0, 0, 1e4*y[3], -1e4*y[2], 0], + [1, -0.04, -1e4*y[3]-3e7*2*y[2], 0, 1], + [0, 0.04, 3e7*2*y[2], 0, 0] + ]) + +@pytest.mark.thread_unsafe(reason="lsoda integrator is not thread-safe") +def test_banded_lsoda(): + # expected solution is given by problem with full jacobian + tfull, yfull = _solve_robertson_lsoda(use_jac=True, banded=False) + + for use_jac in [True, False]: + t, y = _solve_robertson_lsoda(use_jac, True) + assert_allclose(t, tfull) + # Small tolerance to account for legitimate floating-point differences + # After fixing tesco and banded Jacobian bugs, max relative error is ~1.5e-7 + assert_allclose(y, yfull, rtol=2e-7) + +def _solve_robertson_lsoda(use_jac, banded): + + if use_jac: + if banded: + jac = banded_stiff_jac + else: + jac = stiff_jac + else: + jac = None + + if banded: + lband = 1 + uband = 2 + else: + lband = None + uband = None + + r = ode(stiff_f, jac) + r.set_integrator('lsoda', + lband=lband, uband=uband, + rtol=1e-9, atol=1e-10, + ) + t0 = 0 + dt = 1 + tend = 10 + y0 = np.array([1.0, 1.0, 0.0, 0.0, 1.0]) + r.set_initial_value(y0, t0) + + t = [t0] + y = [y0.copy()] + while r.successful() and r.t < tend: + r.integrate(r.t + dt) + t.append(r.t) + y.append(r.y.copy()) + + # Ensure that the Jacobian was evaluated + # iwork[12] has the number of Jacobian evaluations. + assert r._integrator.iwork[12] > 0 + + t = np.array(t) + y = np.array(y) + return t, y diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_bvp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_bvp.py new file mode 100644 index 0000000000000000000000000000000000000000..fe516dc94b5a4ed96d870e9f2929c36ed76d2fa9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_bvp.py @@ -0,0 +1,710 @@ +import sys +from io import StringIO + +import numpy as np +from numpy.testing import (assert_, assert_array_equal, assert_allclose, + assert_equal) +from pytest import raises as assert_raises + +from scipy.sparse import coo_matrix +from scipy.special import erf +from scipy.integrate._bvp import (modify_mesh, estimate_fun_jac, + estimate_bc_jac, compute_jac_indices, + construct_global_jac, solve_bvp) + +import pytest + + +def exp_fun(x, y): + return np.vstack((y[1], y[0])) + + +def exp_fun_jac(x, y): + df_dy = np.empty((2, 2, x.shape[0])) + df_dy[0, 0] = 0 + df_dy[0, 1] = 1 + df_dy[1, 0] = 1 + df_dy[1, 1] = 0 + return df_dy + + +def exp_bc(ya, yb): + return np.hstack((ya[0] - 1, yb[0])) + + +def exp_bc_complex(ya, yb): + return np.hstack((ya[0] - 1 - 1j, yb[0])) + + +def exp_bc_jac(ya, yb): + dbc_dya = np.array([ + [1, 0], + [0, 0] + ]) + dbc_dyb = np.array([ + [0, 0], + [1, 0] + ]) + return dbc_dya, dbc_dyb + + +def exp_sol(x): + return (np.exp(-x) - np.exp(x - 2)) / (1 - np.exp(-2)) + + +def sl_fun(x, y, p): + return np.vstack((y[1], -p[0]**2 * y[0])) + + +def sl_fun_jac(x, y, p): + n, m = y.shape + df_dy = np.empty((n, 2, m)) + df_dy[0, 0] = 0 + df_dy[0, 1] = 1 + df_dy[1, 0] = -p[0]**2 + df_dy[1, 1] = 0 + + df_dp = np.empty((n, 1, m)) + df_dp[0, 0] = 0 + df_dp[1, 0] = -2 * p[0] * y[0] + + return df_dy, df_dp + + +def sl_bc(ya, yb, p): + return np.hstack((ya[0], yb[0], ya[1] - p[0])) + + +def sl_bc_jac(ya, yb, p): + dbc_dya = np.zeros((3, 2)) + dbc_dya[0, 0] = 1 + dbc_dya[2, 1] = 1 + + dbc_dyb = np.zeros((3, 2)) + dbc_dyb[1, 0] = 1 + + dbc_dp = np.zeros((3, 1)) + dbc_dp[2, 0] = -1 + + return dbc_dya, dbc_dyb, dbc_dp + + +def sl_sol(x, p): + return np.sin(p[0] * x) + + +def emden_fun(x, y): + return np.vstack((y[1], -y[0]**5)) + + +def emden_fun_jac(x, y): + df_dy = np.empty((2, 2, x.shape[0])) + df_dy[0, 0] = 0 + df_dy[0, 1] = 1 + df_dy[1, 0] = -5 * y[0]**4 + df_dy[1, 1] = 0 + return df_dy + + +def emden_bc(ya, yb): + return np.array([ya[1], yb[0] - (3/4)**0.5]) + + +def emden_bc_jac(ya, yb): + dbc_dya = np.array([ + [0, 1], + [0, 0] + ]) + dbc_dyb = np.array([ + [0, 0], + [1, 0] + ]) + return dbc_dya, dbc_dyb + + +def emden_sol(x): + return (1 + x**2/3)**-0.5 + + +def undefined_fun(x, y): + return np.zeros_like(y) + + +def undefined_bc(ya, yb): + return np.array([ya[0], yb[0] - 1]) + + +def big_fun(x, y): + f = np.zeros_like(y) + f[::2] = y[1::2] + return f + + +def big_bc(ya, yb): + return np.hstack((ya[::2], yb[::2] - 1)) + + +def big_sol(x, n): + y = np.ones((2 * n, x.size)) + y[::2] = x + return x + + +def big_fun_with_parameters(x, y, p): + """ Big version of sl_fun, with two parameters. + + The two differential equations represented by sl_fun are broadcast to the + number of rows of y, rotating between the parameters p[0] and p[1]. + Here are the differential equations: + + dy[0]/dt = y[1] + dy[1]/dt = -p[0]**2 * y[0] + dy[2]/dt = y[3] + dy[3]/dt = -p[1]**2 * y[2] + dy[4]/dt = y[5] + dy[5]/dt = -p[0]**2 * y[4] + dy[6]/dt = y[7] + dy[7]/dt = -p[1]**2 * y[6] + . + . + . + + """ + f = np.zeros_like(y) + f[::2] = y[1::2] + f[1::4] = -p[0]**2 * y[::4] + f[3::4] = -p[1]**2 * y[2::4] + return f + + +def big_fun_with_parameters_jac(x, y, p): + # big version of sl_fun_jac, with two parameters + n, m = y.shape + df_dy = np.zeros((n, n, m)) + df_dy[range(0, n, 2), range(1, n, 2)] = 1 + df_dy[range(1, n, 4), range(0, n, 4)] = -p[0]**2 + df_dy[range(3, n, 4), range(2, n, 4)] = -p[1]**2 + + df_dp = np.zeros((n, 2, m)) + df_dp[range(1, n, 4), 0] = -2 * p[0] * y[range(0, n, 4)] + df_dp[range(3, n, 4), 1] = -2 * p[1] * y[range(2, n, 4)] + + return df_dy, df_dp + + +def big_bc_with_parameters(ya, yb, p): + # big version of sl_bc, with two parameters + return np.hstack((ya[::2], yb[::2], ya[1] - p[0], ya[3] - p[1])) + + +def big_bc_with_parameters_jac(ya, yb, p): + # big version of sl_bc_jac, with two parameters + n = ya.shape[0] + dbc_dya = np.zeros((n + 2, n)) + dbc_dyb = np.zeros((n + 2, n)) + + dbc_dya[range(n // 2), range(0, n, 2)] = 1 + dbc_dyb[range(n // 2, n), range(0, n, 2)] = 1 + + dbc_dp = np.zeros((n + 2, 2)) + dbc_dp[n, 0] = -1 + dbc_dya[n, 1] = 1 + dbc_dp[n + 1, 1] = -1 + dbc_dya[n + 1, 3] = 1 + + return dbc_dya, dbc_dyb, dbc_dp + + +def big_sol_with_parameters(x, p): + # big version of sl_sol, with two parameters + return np.vstack((np.sin(p[0] * x), np.sin(p[1] * x))) + + +def shock_fun(x, y): + eps = 1e-3 + return np.vstack(( + y[1], + -(x * y[1] + eps * np.pi**2 * np.cos(np.pi * x) + + np.pi * x * np.sin(np.pi * x)) / eps + )) + + +def shock_bc(ya, yb): + return np.array([ya[0] + 2, yb[0]]) + + +def shock_sol(x): + eps = 1e-3 + k = np.sqrt(2 * eps) + return np.cos(np.pi * x) + erf(x / k) / erf(1 / k) + + +def nonlin_bc_fun(x, y): + # laplace eq. + return np.stack([y[1], np.zeros_like(x)]) + + +def nonlin_bc_bc(ya, yb): + phiA, phipA = ya + phiC, phipC = yb + + kappa, ioA, ioC, V, f = 1.64, 0.01, 1.0e-4, 0.5, 38.9 + + # Butler-Volmer Kinetics at Anode + hA = 0.0-phiA-0.0 + iA = ioA * (np.exp(f*hA) - np.exp(-f*hA)) + res0 = iA + kappa * phipA + + # Butler-Volmer Kinetics at Cathode + hC = V - phiC - 1.0 + iC = ioC * (np.exp(f*hC) - np.exp(-f*hC)) + res1 = iC - kappa*phipC + + return np.array([res0, res1]) + + +def nonlin_bc_sol(x): + return -0.13426436116763119 - 1.1308709 * x + + +def test_modify_mesh(): + x = np.array([0, 1, 3, 9], dtype=float) + x_new = modify_mesh(x, np.array([0]), np.array([2])) + assert_array_equal(x_new, np.array([0, 0.5, 1, 3, 5, 7, 9])) + + x = np.array([-6, -3, 0, 3, 6], dtype=float) + x_new = modify_mesh(x, np.array([1], dtype=int), np.array([0, 2, 3])) + assert_array_equal(x_new, [-6, -5, -4, -3, -1.5, 0, 1, 2, 3, 4, 5, 6]) + + +def test_compute_fun_jac(): + x = np.linspace(0, 1, 5) + y = np.empty((2, x.shape[0])) + y[0] = 0.01 + y[1] = 0.02 + p = np.array([]) + df_dy, df_dp = estimate_fun_jac(lambda x, y, p: exp_fun(x, y), x, y, p) + df_dy_an = exp_fun_jac(x, y) + assert_allclose(df_dy, df_dy_an) + assert_(df_dp is None) + + x = np.linspace(0, np.pi, 5) + y = np.empty((2, x.shape[0])) + y[0] = np.sin(x) + y[1] = np.cos(x) + p = np.array([1.0]) + df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p) + df_dy_an, df_dp_an = sl_fun_jac(x, y, p) + assert_allclose(df_dy, df_dy_an) + assert_allclose(df_dp, df_dp_an) + + x = np.linspace(0, 1, 10) + y = np.empty((2, x.shape[0])) + y[0] = (3/4)**0.5 + y[1] = 1e-4 + p = np.array([]) + df_dy, df_dp = estimate_fun_jac(lambda x, y, p: emden_fun(x, y), x, y, p) + df_dy_an = emden_fun_jac(x, y) + assert_allclose(df_dy, df_dy_an) + assert_(df_dp is None) + + +def test_compute_bc_jac(): + ya = np.array([-1.0, 2]) + yb = np.array([0.5, 3]) + p = np.array([]) + dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac( + lambda ya, yb, p: exp_bc(ya, yb), ya, yb, p) + dbc_dya_an, dbc_dyb_an = exp_bc_jac(ya, yb) + assert_allclose(dbc_dya, dbc_dya_an) + assert_allclose(dbc_dyb, dbc_dyb_an) + assert_(dbc_dp is None) + + ya = np.array([0.0, 1]) + yb = np.array([0.0, -1]) + p = np.array([0.5]) + dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, ya, yb, p) + dbc_dya_an, dbc_dyb_an, dbc_dp_an = sl_bc_jac(ya, yb, p) + assert_allclose(dbc_dya, dbc_dya_an) + assert_allclose(dbc_dyb, dbc_dyb_an) + assert_allclose(dbc_dp, dbc_dp_an) + + ya = np.array([0.5, 100]) + yb = np.array([-1000, 10.5]) + p = np.array([]) + dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac( + lambda ya, yb, p: emden_bc(ya, yb), ya, yb, p) + dbc_dya_an, dbc_dyb_an = emden_bc_jac(ya, yb) + assert_allclose(dbc_dya, dbc_dya_an) + assert_allclose(dbc_dyb, dbc_dyb_an) + assert_(dbc_dp is None) + + +def test_compute_jac_indices(): + n = 2 + m = 4 + k = 2 + i, j = compute_jac_indices(n, m, k) + s = coo_matrix((np.ones_like(i), (i, j))).toarray() + s_true = np.array([ + [1, 1, 1, 1, 0, 0, 0, 0, 1, 1], + [1, 1, 1, 1, 0, 0, 0, 0, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1], + [1, 1, 0, 0, 0, 0, 1, 1, 1, 1], + [1, 1, 0, 0, 0, 0, 1, 1, 1, 1], + [1, 1, 0, 0, 0, 0, 1, 1, 1, 1], + [1, 1, 0, 0, 0, 0, 1, 1, 1, 1], + ]) + assert_array_equal(s, s_true) + + +def test_compute_global_jac(): + n = 2 + m = 5 + k = 1 + i_jac, j_jac = compute_jac_indices(2, 5, 1) + x = np.linspace(0, 1, 5) + h = np.diff(x) + y = np.vstack((np.sin(np.pi * x), np.pi * np.cos(np.pi * x))) + p = np.array([3.0]) + + f = sl_fun(x, y, p) + + x_middle = x[:-1] + 0.5 * h + y_middle = 0.5 * (y[:, :-1] + y[:, 1:]) - h/8 * (f[:, 1:] - f[:, :-1]) + + df_dy, df_dp = sl_fun_jac(x, y, p) + df_dy_middle, df_dp_middle = sl_fun_jac(x_middle, y_middle, p) + dbc_dya, dbc_dyb, dbc_dp = sl_bc_jac(y[:, 0], y[:, -1], p) + + J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, + df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp) + J = J.toarray() + + def J_block(h, p): + return np.array([ + [h**2*p**2/12 - 1, -0.5*h, -h**2*p**2/12 + 1, -0.5*h], + [0.5*h*p**2, h**2*p**2/12 - 1, 0.5*h*p**2, 1 - h**2*p**2/12] + ]) + + J_true = np.zeros((m * n + k, m * n + k)) + for i in range(m - 1): + J_true[i * n: (i + 1) * n, i * n: (i + 2) * n] = J_block(h[i], p[0]) + + J_true[:(m - 1) * n:2, -1] = p * h**2/6 * (y[0, :-1] - y[0, 1:]) + J_true[1:(m - 1) * n:2, -1] = p * (h * (y[0, :-1] + y[0, 1:]) + + h**2/6 * (y[1, :-1] - y[1, 1:])) + + J_true[8, 0] = 1 + J_true[9, 8] = 1 + J_true[10, 1] = 1 + J_true[10, 10] = -1 + + assert_allclose(J, J_true, rtol=1e-10) + + df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p) + df_dy_middle, df_dp_middle = estimate_fun_jac(sl_fun, x_middle, y_middle, p) + dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, y[:, 0], y[:, -1], p) + J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, + df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp) + J = J.toarray() + assert_allclose(J, J_true, rtol=2e-8, atol=2e-8) + + +def test_parameter_validation(): + x = [0, 1, 0.5] + y = np.zeros((2, 3)) + assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y) + + x = np.linspace(0, 1, 5) + y = np.zeros((2, 4)) + assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y) + + def fun(x, y, p): + return exp_fun(x, y) + def bc(ya, yb, p): + return exp_bc(ya, yb) + + y = np.zeros((2, x.shape[0])) + assert_raises(ValueError, solve_bvp, fun, bc, x, y, p=[1]) + + def wrong_shape_fun(x, y): + return np.zeros(3) + + assert_raises(ValueError, solve_bvp, wrong_shape_fun, bc, x, y) + + S = np.array([[0, 0]]) + assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y, S=S) + + +def test_no_params(): + x = np.linspace(0, 1, 5) + x_test = np.linspace(0, 1, 100) + y = np.zeros((2, x.shape[0])) + for fun_jac in [None, exp_fun_jac]: + for bc_jac in [None, exp_bc_jac]: + sol = solve_bvp(exp_fun, exp_bc, x, y, fun_jac=fun_jac, + bc_jac=bc_jac) + + assert_equal(sol.status, 0) + assert_(sol.success) + + assert_equal(sol.x.size, 5) + + sol_test = sol.sol(x_test) + + assert_allclose(sol_test[0], exp_sol(x_test), atol=1e-5) + + f_test = exp_fun(x_test, sol_test) + r = sol.sol(x_test, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(rel_res**2, axis=0)**0.5 + assert_(np.all(norm_res < 1e-3)) + + assert_(np.all(sol.rms_residuals < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +def test_with_params(): + x = np.linspace(0, np.pi, 5) + x_test = np.linspace(0, np.pi, 100) + y = np.ones((2, x.shape[0])) + + for fun_jac in [None, sl_fun_jac]: + for bc_jac in [None, sl_bc_jac]: + sol = solve_bvp(sl_fun, sl_bc, x, y, p=[0.5], fun_jac=fun_jac, + bc_jac=bc_jac) + + assert_equal(sol.status, 0) + assert_(sol.success) + + assert_(sol.x.size < 10) + + assert_allclose(sol.p, [1], rtol=1e-4) + + sol_test = sol.sol(x_test) + + assert_allclose(sol_test[0], sl_sol(x_test, [1]), + rtol=1e-4, atol=1e-4) + + f_test = sl_fun(x_test, sol_test, [1]) + r = sol.sol(x_test, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5 + assert_(np.all(norm_res < 1e-3)) + + assert_(np.all(sol.rms_residuals < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +def test_singular_term(): + x = np.linspace(0, 1, 10) + x_test = np.linspace(0.05, 1, 100) + y = np.empty((2, 10)) + y[0] = (3/4)**0.5 + y[1] = 1e-4 + S = np.array([[0, 0], [0, -2]]) + + for fun_jac in [None, emden_fun_jac]: + for bc_jac in [None, emden_bc_jac]: + sol = solve_bvp(emden_fun, emden_bc, x, y, S=S, fun_jac=fun_jac, + bc_jac=bc_jac) + + assert_equal(sol.status, 0) + assert_(sol.success) + + assert_equal(sol.x.size, 10) + + sol_test = sol.sol(x_test) + assert_allclose(sol_test[0], emden_sol(x_test), atol=1e-5) + + f_test = emden_fun(x_test, sol_test) + S.dot(sol_test) / x_test + r = sol.sol(x_test, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5 + + assert_(np.all(norm_res < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +def test_complex(): + # The test is essentially the same as test_no_params, but boundary + # conditions are turned into complex. + x = np.linspace(0, 1, 5) + x_test = np.linspace(0, 1, 100) + y = np.zeros((2, x.shape[0]), dtype=complex) + for fun_jac in [None, exp_fun_jac]: + for bc_jac in [None, exp_bc_jac]: + sol = solve_bvp(exp_fun, exp_bc_complex, x, y, fun_jac=fun_jac, + bc_jac=bc_jac) + + assert_equal(sol.status, 0) + assert_(sol.success) + + sol_test = sol.sol(x_test) + + assert_allclose(sol_test[0].real, exp_sol(x_test), atol=1e-5) + assert_allclose(sol_test[0].imag, exp_sol(x_test), atol=1e-5) + + f_test = exp_fun(x_test, sol_test) + r = sol.sol(x_test, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(np.real(rel_res * np.conj(rel_res)), + axis=0) ** 0.5 + assert_(np.all(norm_res < 1e-3)) + + assert_(np.all(sol.rms_residuals < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +def test_failures(): + x = np.linspace(0, 1, 2) + y = np.zeros((2, x.size)) + res = solve_bvp(exp_fun, exp_bc, x, y, tol=1e-5, max_nodes=5) + assert_equal(res.status, 1) + assert_(not res.success) + + x = np.linspace(0, 1, 5) + y = np.zeros((2, x.size)) + res = solve_bvp(undefined_fun, undefined_bc, x, y) + assert_equal(res.status, 2) + assert_(not res.success) + + +def test_big_problem(): + n = 30 + x = np.linspace(0, 1, 5) + y = np.zeros((2 * n, x.size)) + sol = solve_bvp(big_fun, big_bc, x, y) + + assert_equal(sol.status, 0) + assert_(sol.success) + + sol_test = sol.sol(x) + + assert_allclose(sol_test[0], big_sol(x, n)) + + f_test = big_fun(x, sol_test) + r = sol.sol(x, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(np.real(rel_res * np.conj(rel_res)), axis=0) ** 0.5 + assert_(np.all(norm_res < 1e-3)) + + assert_(np.all(sol.rms_residuals < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +def test_big_problem_with_parameters(): + n = 30 + x = np.linspace(0, np.pi, 5) + x_test = np.linspace(0, np.pi, 100) + y = np.ones((2 * n, x.size)) + + for fun_jac in [None, big_fun_with_parameters_jac]: + for bc_jac in [None, big_bc_with_parameters_jac]: + sol = solve_bvp(big_fun_with_parameters, big_bc_with_parameters, x, + y, p=[0.5, 0.5], fun_jac=fun_jac, bc_jac=bc_jac) + + assert_equal(sol.status, 0) + assert_(sol.success) + + assert_allclose(sol.p, [1, 1], rtol=1e-4) + + sol_test = sol.sol(x_test) + + for isol in range(0, n, 4): + assert_allclose(sol_test[isol], + big_sol_with_parameters(x_test, [1, 1])[0], + rtol=1e-4, atol=1e-4) + assert_allclose(sol_test[isol + 2], + big_sol_with_parameters(x_test, [1, 1])[1], + rtol=1e-4, atol=1e-4) + + f_test = big_fun_with_parameters(x_test, sol_test, [1, 1]) + r = sol.sol(x_test, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5 + assert_(np.all(norm_res < 1e-3)) + + assert_(np.all(sol.rms_residuals < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +def test_shock_layer(): + x = np.linspace(-1, 1, 5) + x_test = np.linspace(-1, 1, 100) + y = np.zeros((2, x.size)) + sol = solve_bvp(shock_fun, shock_bc, x, y) + + assert_equal(sol.status, 0) + assert_(sol.success) + + assert_(sol.x.size < 110) + + sol_test = sol.sol(x_test) + assert_allclose(sol_test[0], shock_sol(x_test), rtol=1e-5, atol=1e-5) + + f_test = shock_fun(x_test, sol_test) + r = sol.sol(x_test, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5 + + assert_(np.all(norm_res < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +def test_nonlin_bc(): + x = np.linspace(0, 0.1, 5) + x_test = x + y = np.zeros([2, x.size]) + sol = solve_bvp(nonlin_bc_fun, nonlin_bc_bc, x, y) + + assert_equal(sol.status, 0) + assert_(sol.success) + + assert_(sol.x.size < 8) + + sol_test = sol.sol(x_test) + assert_allclose(sol_test[0], nonlin_bc_sol(x_test), rtol=1e-5, atol=1e-5) + + f_test = nonlin_bc_fun(x_test, sol_test) + r = sol.sol(x_test, 1) - f_test + rel_res = r / (1 + np.abs(f_test)) + norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5 + + assert_(np.all(norm_res < 1e-3)) + assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10) + assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10) + + +@pytest.mark.thread_unsafe(reason="multithreaded sys.stdout parsing is not thread-safe") +def test_verbose(): + # Smoke test that checks the printing does something and does not crash + x = np.linspace(0, 1, 5) + y = np.zeros((2, x.shape[0])) + for verbose in [0, 1, 2]: + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + sol = solve_bvp(exp_fun, exp_bc, x, y, verbose=verbose) + text = sys.stdout.getvalue() + finally: + sys.stdout = old_stdout + + assert_(sol.success) + if verbose == 0: + assert_(not text, text) + if verbose >= 1: + assert_("Solved in" in text, text) + if verbose >= 2: + assert_("Max residual" in text, text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_cubature.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_cubature.py new file mode 100644 index 0000000000000000000000000000000000000000..ef82f91eccee8f9a505b20872679ed3f29e179c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_cubature.py @@ -0,0 +1,1376 @@ +import math +import scipy +import itertools + +import pytest + +from scipy._lib._array_api import ( + array_namespace, + xp_assert_close, + xp_size, + np_compat, + is_array_api_strict, + make_xp_test_case, +) +from scipy.integrate import cubature +from scipy.integrate._cubature import _InfiniteLimitsTransform +from scipy.integrate._rules import ( + Rule, FixedRule, + NestedFixedRule, + GaussLegendreQuadrature, GaussKronrodQuadrature, + GenzMalikCubature, +) + +skip_xp_backends = pytest.mark.skip_xp_backends +boolean_index_skip_reason = 'JAX/Dask arrays do not support boolean assignment.' + +# The integrands ``genz_malik_1980_*`` come from the paper: +# A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for +# numerical integration over an N-dimensional rectangular region, Journal of +# Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302, +# ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X. + + +def basic_1d_integrand(x, n, xp): + x_reshaped = xp.reshape(x, (-1, 1, 1)) + n_reshaped = xp.reshape(n, (1, -1, 1)) + + return x_reshaped**n_reshaped + + +def basic_1d_integrand_exact(n, xp): + # Exact only for integration over interval [0, 2]. + return xp.reshape(2**(n+1)/(n+1), (-1, 1)) + + +def basic_nd_integrand(x, n, xp): + return xp.reshape(xp.sum(x, axis=-1), (-1, 1))**xp.reshape(n, (1, -1)) + + +def basic_nd_integrand_exact(n, xp): + # Exact only for integration over interval [0, 2]. + return (-2**(3+n) + 4**(2+n))/((1+n)*(2+n)) + + +def genz_malik_1980_f_1(x, r, alphas, xp): + r""" + .. math:: f_1(\mathbf x) = \cos\left(2\pi r + \sum^n_{i = 1}\alpha_i x_i\right) + + .. code-block:: mathematica + + genzMalik1980f1[x_List, r_, alphas_List] := Cos[2*Pi*r + Total[x*alphas]] + """ + + npoints, ndim = x.shape[0], x.shape[-1] + + alphas_reshaped = alphas[None, ...] + x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim)) + + return xp.cos(2*math.pi*r + xp.sum(alphas_reshaped * x_reshaped, axis=-1)) + + +def genz_malik_1980_f_1_exact(a, b, r, alphas, xp): + ndim = xp_size(a) + a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim)) + b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim)) + + return ( + (-2)**ndim + * 1/xp.prod(alphas, axis=-1) + * xp.cos(2*math.pi*r + xp.sum(alphas * (a+b) * 0.5, axis=-1)) + * xp.prod(xp.sin(alphas * (a-b)/2), axis=-1) + ) + + +def genz_malik_1980_f_1_random_args(rng, shape, xp): + r = xp.asarray(rng.random(shape[:-1])) + alphas = xp.asarray(rng.random(shape)) + + difficulty = 9 + normalisation_factors = xp.sum(alphas, axis=-1)[..., None] + alphas = difficulty * alphas / normalisation_factors + + return (r, alphas) + + +def genz_malik_1980_f_2(x, alphas, betas, xp): + r""" + .. math:: f_2(\mathbf x) = \prod^n_{i = 1} (\alpha_i^2 + (x_i - \beta_i)^2)^{-1} + + .. code-block:: mathematica + + genzMalik1980f2[x_List, alphas_List, betas_List] := + 1/Times @@ ((alphas^2 + (x - betas)^2)) + """ + npoints, ndim = x.shape[0], x.shape[-1] + + alphas_reshaped = alphas[None, ...] + betas_reshaped = betas[None, ...] + + x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim)) + + return 1/xp.prod(alphas_reshaped**2 + (x_reshaped-betas_reshaped)**2, axis=-1) + + +def genz_malik_1980_f_2_exact(a, b, alphas, betas, xp): + ndim = xp_size(a) + a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim)) + b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim)) + + return ( + (-1)**ndim * 1/xp.prod(alphas, axis=-1) + * xp.prod( + xp.atan((a - betas)/alphas) - xp.atan((b - betas)/alphas), + axis=-1, + ) + ) + + +def genz_malik_1980_f_2_random_args(rng, shape, xp): + ndim = shape[-1] + alphas = xp.asarray(rng.random(shape)) + betas = xp.asarray(rng.random(shape)) + + difficulty = 25.0 + products = xp.prod(alphas**xp.asarray(-2.0), axis=-1) + normalisation_factors = (products**xp.asarray(1 / (2*ndim)))[..., None] + alphas = alphas * normalisation_factors * math.pow(difficulty, 1 / (2*ndim)) + + # Adjust alphas from distribution used in Genz and Malik 1980 since denominator + # is very small for high dimensions. + alphas *= 10 + + return alphas, betas + + +def genz_malik_1980_f_3(x, alphas, xp): + r""" + .. math:: f_3(\mathbf x) = \exp\left(\sum^n_{i = 1} \alpha_i x_i\right) + + .. code-block:: mathematica + + genzMalik1980f3[x_List, alphas_List] := Exp[Dot[x, alphas]] + """ + + npoints, ndim = x.shape[0], x.shape[-1] + + alphas_reshaped = alphas[None, ...] + x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim)) + + return xp.exp(xp.sum(alphas_reshaped * x_reshaped, axis=-1)) + + +def genz_malik_1980_f_3_exact(a, b, alphas, xp): + ndim = xp_size(a) + a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim)) + b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim)) + + return ( + (-1)**ndim * 1/xp.prod(alphas, axis=-1) + * xp.prod(xp.exp(alphas * a) - xp.exp(alphas * b), axis=-1) + ) + + +def genz_malik_1980_f_3_random_args(rng, shape, xp): + alphas = xp.asarray(rng.random(shape)) + normalisation_factors = xp.sum(alphas, axis=-1)[..., None] + difficulty = 12.0 + alphas = difficulty * alphas / normalisation_factors + + return (alphas,) + + +def genz_malik_1980_f_4(x, alphas, xp): + r""" + .. math:: f_4(\mathbf x) = \left(1 + \sum^n_{i = 1} \alpha_i x_i\right)^{-n-1} + + .. code-block:: mathematica + genzMalik1980f4[x_List, alphas_List] := + (1 + Dot[x, alphas])^(-Length[alphas] - 1) + """ + + npoints, ndim = x.shape[0], x.shape[-1] + + alphas_reshaped = alphas[None, ...] + x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim)) + + return (1 + xp.sum(alphas_reshaped * x_reshaped, axis=-1))**(-ndim-1) + + +def genz_malik_1980_f_4_exact(a, b, alphas, xp): + ndim = xp_size(a) + + def F(x): + x_reshaped = xp.reshape(x, (*([1]*(len(alphas.shape) - 1)), ndim)) + + return ( + (-1)**ndim/xp.prod(alphas, axis=-1) + / math.factorial(ndim) + / (1 + xp.sum(alphas * x_reshaped, axis=-1)) + ) + + return _eval_indefinite_integral(F, a, b, xp) + + +def _eval_indefinite_integral(F, a, b, xp): + """ + Calculates a definite integral from points `a` to `b` by summing up over the corners + of the corresponding hyperrectangle. + """ + + ndim = xp_size(a) + points = xp.stack([a, b], axis=0) + + out = 0 + for ind in itertools.product(range(2), repeat=ndim): + selected_points = xp.asarray( + [float(points[i, j]) for i, j in zip(ind, range(ndim))] + ) + out += pow(-1, sum(ind) + ndim) * F(selected_points) + + return out + + +def genz_malik_1980_f_4_random_args(rng, shape, xp): + ndim = shape[-1] + + alphas = xp.asarray(rng.random(shape)) + normalisation_factors = xp.sum(alphas, axis=-1)[..., None] + difficulty = 14.0 + alphas = (difficulty / ndim) * alphas / normalisation_factors + + return (alphas,) + + +def genz_malik_1980_f_5(x, alphas, betas, xp): + r""" + .. math:: + + f_5(\mathbf x) = \exp\left(-\sum^n_{i = 1} \alpha^2_i (x_i - \beta_i)^2\right) + + .. code-block:: mathematica + + genzMalik1980f5[x_List, alphas_List, betas_List] := + Exp[-Total[alphas^2 * (x - betas)^2]] + """ + + npoints, ndim = x.shape[0], x.shape[-1] + + alphas_reshaped = alphas[None, ...] + betas_reshaped = betas[None, ...] + + x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim)) + + return xp.exp( + -xp.sum(alphas_reshaped**2 * (x_reshaped - betas_reshaped)**2, axis=-1) + ) + + +def genz_malik_1980_f_5_exact(a, b, alphas, betas, xp): + ndim = xp_size(a) + a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim)) + b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim)) + + return ( + (1/2)**ndim + * 1/xp.prod(alphas, axis=-1) + * (math.pi**(ndim/2)) + * xp.prod( + scipy.special.erf(alphas * (betas - a)) + + scipy.special.erf(alphas * (b - betas)), + axis=-1, + ) + ) + + +def genz_malik_1980_f_5_random_args(rng, shape, xp): + alphas = xp.asarray(rng.random(shape)) + betas = xp.asarray(rng.random(shape)) + + difficulty = 21.0 + normalisation_factors = xp.sqrt(xp.sum(alphas**xp.asarray(2.0), axis=-1))[..., None] + alphas = alphas / normalisation_factors * math.sqrt(difficulty) + + return alphas, betas + + +def f_gaussian(x, alphas, xp): + r""" + .. math:: + + f(\mathbf x) = \exp\left(-\sum^n_{i = 1} (\alpha_i x_i)^2 \right) + """ + npoints, ndim = x.shape[0], x.shape[-1] + alphas_reshaped = alphas[None, ...] + x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim)) + + return xp.exp(-xp.sum((alphas_reshaped * x_reshaped)**2, axis=-1)) + + +def f_gaussian_exact(a, b, alphas, xp): + # Exact only when `a` and `b` are one of: + # (-oo, oo), or + # (0, oo), or + # (-oo, 0) + # `alphas` can be arbitrary. + + ndim = xp_size(a) + double_infinite_count = 0 + semi_infinite_count = 0 + + for i in range(ndim): + if xp.isinf(a[i]) and xp.isinf(b[i]): # doubly-infinite + double_infinite_count += 1 + elif xp.isinf(a[i]) != xp.isinf(b[i]): # exclusive or, so semi-infinite + semi_infinite_count += 1 + + return (math.sqrt(math.pi) ** ndim) / ( + 2**semi_infinite_count * xp.prod(alphas, axis=-1) + ) + + +def f_gaussian_random_args(rng, shape, xp): + alphas = xp.asarray(rng.random(shape)) + + # If alphas are very close to 0 this makes the problem very difficult due to large + # values of ``f``. + alphas *= 100 + + return (alphas,) + + +def f_modified_gaussian(x_arr, n, xp): + r""" + .. math:: + + f(x, y, z, w) = x^n \sqrt{y} \exp(-y-z^2-w^2) + """ + x, y, z, w = x_arr[:, 0], x_arr[:, 1], x_arr[:, 2], x_arr[:, 3] + res = (x ** n[:, None]) * xp.sqrt(y) * xp.exp(-y-z**2-w**2) + + return res.T + + +def f_modified_gaussian_exact(a, b, n, xp): + # Exact only for the limits + # a = (0, 0, -oo, -oo) + # b = (1, oo, oo, oo) + # but defined here as a function to match the format of the other integrands. + return 1/(2 + 2*n) * math.pi ** (3/2) + + +def f_with_problematic_points(x_arr, points, xp): + """ + This emulates a function with a list of singularities given by `points`. + + If no `x_arr` are one of the `points`, then this function returns 1. + """ + + for point in points: + if xp.any(x_arr == point): + raise ValueError("called with a problematic point") + + return xp.ones(x_arr.shape[0]) + + +@make_xp_test_case(cubature) +class TestCubature: + """ + Tests related to the interface of `cubature`. + """ + + @pytest.mark.parametrize("rule_str", [ + "gauss-kronrod", + "genz-malik", + "gk21", + "gk15", + ]) + def test_pass_str(self, rule_str, xp): + n = xp.arange(5, dtype=xp.float64) + a = xp.asarray([0, 0], dtype=xp.float64) + b = xp.asarray([2, 2], dtype=xp.float64) + + res = cubature(basic_nd_integrand, a, b, rule=rule_str, args=(n, xp)) + + xp_assert_close( + res.estimate, + basic_nd_integrand_exact(n, xp), + rtol=1e-8, + atol=0, + ) + + def test_pass_array_like_not_array(self): + n = np_compat.arange(5, dtype=np_compat.float64) + a = [0] + b = [2] + + res = cubature( + basic_1d_integrand, + a, + b, + args=(n, np_compat) + ) + + xp_assert_close( + res.estimate, + basic_1d_integrand_exact(n, np_compat), + rtol=1e-8, + atol=0, + ) + + def test_stops_after_max_subdivisions(self, xp): + a = xp.asarray([0]) + b = xp.asarray([1]) + rule = BadErrorRule() + + res = cubature( + basic_1d_integrand, # Any function would suffice + a, + b, + rule=rule, + max_subdivisions=10, + args=(xp.arange(5, dtype=xp.float64), xp), + ) + + assert res.subdivisions == 10 + assert res.status == "not_converged" + + def test_a_and_b_must_be_1d(self, xp): + a = xp.asarray([[0]], dtype=xp.float64) + b = xp.asarray([[1]], dtype=xp.float64) + + with pytest.raises(Exception, match="`a` and `b` must be 1D arrays"): + cubature(basic_1d_integrand, a, b, args=(xp,)) + + def test_a_and_b_must_be_nonempty(self, xp): + a = xp.asarray([]) + b = xp.asarray([]) + + with pytest.raises(Exception, match="`a` and `b` must be nonempty"): + cubature(basic_1d_integrand, a, b, args=(xp,)) + + def test_zero_width_limits(self, xp): + n = xp.arange(5, dtype=xp.float64) + + a = xp.asarray([0], dtype=xp.float64) + b = xp.asarray([0], dtype=xp.float64) + + res = cubature( + basic_1d_integrand, + a, + b, + args=(n, xp), + ) + + xp_assert_close( + res.estimate, + xp.asarray([[0], [0], [0], [0], [0]], dtype=xp.float64), + rtol=1e-8, + atol=0, + ) + + def test_limits_other_way_around(self, xp): + n = xp.arange(5, dtype=xp.float64) + + a = xp.asarray([2], dtype=xp.float64) + b = xp.asarray([0], dtype=xp.float64) + + res = cubature( + basic_1d_integrand, + a, + b, + args=(n, xp), + ) + + xp_assert_close( + res.estimate, + -basic_1d_integrand_exact(n, xp), + rtol=1e-8, + atol=0, + ) + + def test_result_dtype_promoted_correctly(self, xp): + result_dtype = cubature( + basic_1d_integrand, + xp.asarray([0], dtype=xp.float64), + xp.asarray([1], dtype=xp.float64), + points=[], + args=(xp.asarray([1], dtype=xp.float64), xp), + ).estimate.dtype + + assert result_dtype == xp.float64 + + result_dtype = cubature( + basic_1d_integrand, + xp.asarray([0], dtype=xp.float32), + xp.asarray([1], dtype=xp.float32), + points=[], + args=(xp.asarray([1], dtype=xp.float32), xp), + ).estimate.dtype + + assert result_dtype == xp.float32 + + result_dtype = cubature( + basic_1d_integrand, + xp.asarray([0], dtype=xp.float32), + xp.asarray([1], dtype=xp.float64), + points=[], + args=(xp.asarray([1], dtype=xp.float32), xp), + ).estimate.dtype + + assert result_dtype == xp.float64 + + +@make_xp_test_case(cubature) +@pytest.mark.parametrize("rtol", [1e-4]) +@pytest.mark.parametrize("atol", [1e-5]) +@pytest.mark.parametrize("rule", [ + "gk15", + "gk21", + "genz-malik", +]) +class TestCubatureProblems: + """ + Tests that `cubature` gives the correct answer. + """ + + @skip_xp_backends("dask.array", + reason="Dask hangs/takes a long time for some test cases") + @pytest.mark.parametrize("problem", [ + # -- f1 -- + ( + # Function to integrate, like `f(x, *args)` + genz_malik_1980_f_1, + + # Exact solution, like `exact(a, b, *args)` + genz_malik_1980_f_1_exact, + + # Coordinates of `a` + [0], + + # Coordinates of `b` + [10], + + # Arguments to pass to `f` and `exact` + ( + 1/4, + [5], + ) + ), + ( + genz_malik_1980_f_1, + genz_malik_1980_f_1_exact, + [0, 0], + [1, 1], + ( + 1/4, + [2, 4], + ), + ), + ( + genz_malik_1980_f_1, + genz_malik_1980_f_1_exact, + [0, 0], + [5, 5], + ( + 1/2, + [2, 4], + ) + ), + ( + genz_malik_1980_f_1, + genz_malik_1980_f_1_exact, + [0, 0, 0], + [5, 5, 5], + ( + 1/2, + [1, 1, 1], + ) + ), + + # -- f2 -- + ( + genz_malik_1980_f_2, + genz_malik_1980_f_2_exact, + [-1], + [1], + ( + [5], + [4], + ) + ), + ( + genz_malik_1980_f_2, + genz_malik_1980_f_2_exact, + + [0, 0], + [10, 50], + ( + [-3, 3], + [-2, 2], + ), + ), + ( + genz_malik_1980_f_2, + genz_malik_1980_f_2_exact, + [0, 0, 0], + [1, 1, 1], + ( + [1, 1, 1], + [1, 1, 1], + ) + ), + ( + genz_malik_1980_f_2, + genz_malik_1980_f_2_exact, + [0, 0, 0], + [1, 1, 1], + ( + [2, 3, 4], + [2, 3, 4], + ) + ), + ( + genz_malik_1980_f_2, + genz_malik_1980_f_2_exact, + [-1, -1, -1], + [1, 1, 1], + ( + [1, 1, 1], + [2, 2, 2], + ) + ), + ( + genz_malik_1980_f_2, + genz_malik_1980_f_2_exact, + [-1, -1, -1, -1], + [1, 1, 1, 1], + ( + [1, 1, 1, 1], + [1, 1, 1, 1], + ) + ), + + # -- f3 -- + ( + genz_malik_1980_f_3, + genz_malik_1980_f_3_exact, + [-1], + [1], + ( + [1/2], + ), + ), + ( + genz_malik_1980_f_3, + genz_malik_1980_f_3_exact, + [0, -1], + [1, 1], + ( + [5, 5], + ), + ), + ( + genz_malik_1980_f_3, + genz_malik_1980_f_3_exact, + [-1, -1, -1], + [1, 1, 1], + ( + [1, 1, 1], + ), + ), + + # -- f4 -- + ( + genz_malik_1980_f_4, + genz_malik_1980_f_4_exact, + [0], + [2], + ( + [1], + ), + ), + ( + genz_malik_1980_f_4, + genz_malik_1980_f_4_exact, + [0, 0], + [2, 1], + ([1, 1],), + ), + ( + genz_malik_1980_f_4, + genz_malik_1980_f_4_exact, + [0, 0, 0], + [1, 1, 1], + ([1, 1, 1],), + ), + + # -- f5 -- + ( + genz_malik_1980_f_5, + genz_malik_1980_f_5_exact, + [-1], + [1], + ( + [-2], + [2], + ), + ), + ( + genz_malik_1980_f_5, + genz_malik_1980_f_5_exact, + [-1, -1], + [1, 1], + ( + [2, 3], + [4, 5], + ), + ), + ( + genz_malik_1980_f_5, + genz_malik_1980_f_5_exact, + [-1, -1], + [1, 1], + ( + [-1, 1], + [0, 0], + ), + ), + ( + genz_malik_1980_f_5, + genz_malik_1980_f_5_exact, + [-1, -1, -1], + [1, 1, 1], + ( + [1, 1, 1], + [1, 1, 1], + ), + ), + ]) + def test_scalar_output(self, problem, rule, rtol, atol, xp): + f, exact, a, b, args = problem + + a = xp.asarray(a, dtype=xp.float64) + b = xp.asarray(b, dtype=xp.float64) + args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args) + + ndim = xp_size(a) + + if rule == "genz-malik" and ndim < 2: + pytest.skip("Genz-Malik cubature does not support 1D integrals") + + res = cubature( + f, + a, + b, + rule=rule, + rtol=rtol, + atol=atol, + args=(*args, xp), + ) + + assert res.status == "converged" + + est = res.estimate + exact_sol = exact(a, b, *args, xp) + + xp_assert_close( + est, + exact_sol, + rtol=rtol, + atol=atol, + err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}", + ) + + @skip_xp_backends("dask.array", + reason="Dask hangs/takes a long time for some test cases") + @pytest.mark.parametrize("problem", [ + ( + # Function to integrate, like `f(x, *args)` + genz_malik_1980_f_1, + + # Exact solution, like `exact(a, b, *args)` + genz_malik_1980_f_1_exact, + + # Function that generates random args of a certain shape. + genz_malik_1980_f_1_random_args, + ), + ( + genz_malik_1980_f_2, + genz_malik_1980_f_2_exact, + genz_malik_1980_f_2_random_args, + ), + ( + genz_malik_1980_f_3, + genz_malik_1980_f_3_exact, + genz_malik_1980_f_3_random_args + ), + ( + genz_malik_1980_f_4, + genz_malik_1980_f_4_exact, + genz_malik_1980_f_4_random_args + ), + ( + genz_malik_1980_f_5, + genz_malik_1980_f_5_exact, + genz_malik_1980_f_5_random_args, + ), + ]) + @pytest.mark.parametrize("shape", [ + (2,), + (3,), + (4,), + (1, 2), + (1, 3), + (1, 4), + (3, 2), + (3, 4, 2), + (2, 1, 3), + ]) + def test_array_output(self, problem, rule, shape, rtol, atol, xp): + rng = np_compat.random.default_rng(1) + ndim = shape[-1] + + if rule == "genz-malik" and ndim < 2: + pytest.skip("Genz-Malik cubature does not support 1D integrals") + + if rule == "genz-malik" and ndim >= 5: + pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim") + + f, exact, random_args = problem + args = random_args(rng, shape, xp) + + a = xp.asarray([0] * ndim, dtype=xp.float64) + b = xp.asarray([1] * ndim, dtype=xp.float64) + + res = cubature( + f, + a, + b, + rule=rule, + rtol=rtol, + atol=atol, + args=(*args, xp), + ) + + est = res.estimate + exact_sol = exact(a, b, *args, xp) + + xp_assert_close( + est, + exact_sol, + rtol=rtol, + atol=atol, + err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}", + ) + + err_msg = (f"estimate_error={res.error}, " + f"subdivisions= {res.subdivisions}, " + f"true_error={xp.abs(res.estimate - exact_sol)}") + assert res.status == "converged", err_msg + + assert res.estimate.shape == shape[:-1] + + @pytest.mark.parametrize("problem", [ + ( + # Function to integrate + lambda x, xp: x, + + # Exact value + [50.0], + + # Coordinates of `a` + [0], + + # Coordinates of `b` + [10], + + # Points by which to split up the initial region + None, + ), + ( + lambda x, xp: xp.sin(x)/x, + [2.551496047169878], # si(1) + si(2), + [-1], + [2], + [ + [0.0], + ], + ), + ( + lambda x, xp: xp.ones((x.shape[0], 1)), + [1.0], + [0, 0, 0], + [1, 1, 1], + [ + [0.5, 0.5, 0.5], + ], + ), + ( + lambda x, xp: xp.ones((x.shape[0], 1)), + [1.0], + [0, 0, 0], + [1, 1, 1], + [ + [0.25, 0.25, 0.25], + [0.5, 0.5, 0.5], + ], + ), + ( + lambda x, xp: xp.ones((x.shape[0], 1)), + [1.0], + [0, 0, 0], + [1, 1, 1], + [ + [0.1, 0.25, 0.5], + [0.25, 0.25, 0.25], + [0.5, 0.5, 0.5], + ], + ) + ]) + def test_break_points(self, problem, rule, rtol, atol, xp): + f, exact, a, b, points = problem + + a = xp.asarray(a, dtype=xp.float64) + b = xp.asarray(b, dtype=xp.float64) + exact = xp.asarray(exact, dtype=xp.float64) + + if points is not None: + points = [xp.asarray(point, dtype=xp.float64) for point in points] + + ndim = xp_size(a) + + if rule == "genz-malik" and ndim < 2: + pytest.skip("Genz-Malik cubature does not support 1D integrals") + + if rule == "genz-malik" and ndim >= 5: + pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim") + + res = cubature( + f, + a, + b, + rule=rule, + rtol=rtol, + atol=atol, + points=points, + args=(xp,), + ) + + xp_assert_close( + res.estimate, + exact, + rtol=rtol, + atol=atol, + err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}", + check_dtype=False, + ) + + err_msg = (f"estimate_error={res.error}, " + f"subdivisions= {res.subdivisions}, " + f"true_error={xp.abs(res.estimate - exact)}") + assert res.status == "converged", err_msg + + @pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason) + @pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason) + @pytest.mark.parametrize("problem", [ + ( + # Function to integrate + f_gaussian, + + # Exact solution + f_gaussian_exact, + + # Arguments passed to f + f_gaussian_random_args, + (1, 1), + + # Limits, have to match the shape of the arguments + [-math.inf], # a + [math.inf], # b + ), + ( + f_gaussian, + f_gaussian_exact, + f_gaussian_random_args, + (2, 2), + [-math.inf, -math.inf], + [math.inf, math.inf], + ), + ( + f_gaussian, + f_gaussian_exact, + f_gaussian_random_args, + (1, 1), + [0], + [math.inf], + ), + ( + f_gaussian, + f_gaussian_exact, + f_gaussian_random_args, + (1, 1), + [-math.inf], + [0], + ), + ( + f_gaussian, + f_gaussian_exact, + f_gaussian_random_args, + (2, 2), + [0, 0], + [math.inf, math.inf], + ), + ( + f_gaussian, + f_gaussian_exact, + f_gaussian_random_args, + (2, 2), + [0, -math.inf], + [math.inf, math.inf], + ), + ( + f_gaussian, + f_gaussian_exact, + f_gaussian_random_args, + (1, 4), + [0, 0, -math.inf, -math.inf], + [math.inf, math.inf, math.inf, math.inf], + ), + ( + f_gaussian, + f_gaussian_exact, + f_gaussian_random_args, + (1, 4), + [-math.inf, -math.inf, -math.inf, -math.inf], + [0, 0, math.inf, math.inf], + ), + ( + lambda x, xp: 1/xp.prod(x, axis=-1)**2, + + # Exact only for the below limits, not for general `a` and `b`. + lambda a, b, xp: xp.asarray(1/6, dtype=xp.float64), + + # Arguments + lambda rng, shape, xp: tuple(), + tuple(), + + [1, -math.inf, 3], + [math.inf, -2, math.inf], + ), + + # This particular problem can be slow + pytest.param( + ( + # f(x, y, z, w) = x^n * sqrt(y) * exp(-y-z**2-w**2) for n in [0,1,2,3] + f_modified_gaussian, + + # This exact solution is for the below limits, not in general + f_modified_gaussian_exact, + + # Constant arguments + lambda rng, shape, xp: (xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64),), + tuple(), + + [0, 0, -math.inf, -math.inf], + [1, math.inf, math.inf, math.inf] + ), + + marks=pytest.mark.xslow, + ), + ]) + def test_infinite_limits(self, problem, rule, rtol, atol, xp): + rng = np_compat.random.default_rng(1) + f, exact, random_args_func, random_args_shape, a, b = problem + + a = xp.asarray(a, dtype=xp.float64) + b = xp.asarray(b, dtype=xp.float64) + args = random_args_func(rng, random_args_shape, xp) + + ndim = xp_size(a) + + if rule == "genz-malik" and ndim < 2: + pytest.skip("Genz-Malik cubature does not support 1D integrals") + + if rule == "genz-malik" and ndim >= 4: + pytest.mark.slow("Genz-Malik is slow in >= 5 dim") + + if rule == "genz-malik" and ndim >= 4 and is_array_api_strict(xp): + pytest.mark.xslow("Genz-Malik very slow for array_api_strict in >= 4 dim") + + res = cubature( + f, + a, + b, + rule=rule, + rtol=rtol, + atol=atol, + args=(*args, xp), + ) + + assert res.status == "converged" + + xp_assert_close( + res.estimate, + exact(a, b, *args, xp), + rtol=rtol, + atol=atol, + err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}", + check_0d=False, + ) + + @pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason) + @pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason) + @pytest.mark.parametrize("problem", [ + ( + # Function to integrate + lambda x, xp: (xp.sin(x) / x)**8, + + # Exact value + [151/315 * math.pi], + + # Limits + [-math.inf], + [math.inf], + + # Breakpoints + [[0]], + + ), + ( + # Function to integrate + lambda x, xp: (xp.sin(x[:, 0]) / x[:, 0])**8, + + # Exact value + 151/315 * math.pi, + + # Limits + [-math.inf, 0], + [math.inf, 1], + + # Breakpoints + [[0, 0.5]], + + ) + ]) + def test_infinite_limits_and_break_points(self, problem, rule, rtol, atol, xp): + f, exact, a, b, points = problem + + a = xp.asarray(a, dtype=xp.float64) + b = xp.asarray(b, dtype=xp.float64) + exact = xp.asarray(exact, dtype=xp.float64) + + ndim = xp_size(a) + + if rule == "genz-malik" and ndim < 2: + pytest.skip("Genz-Malik cubature does not support 1D integrals") + + if points is not None: + points = [xp.asarray(point, dtype=xp.float64) for point in points] + + res = cubature( + f, + a, + b, + rule=rule, + rtol=rtol, + atol=atol, + points=points, + args=(xp,), + ) + + assert res.status == "converged" + + xp_assert_close( + res.estimate, + exact, + rtol=rtol, + atol=atol, + err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}", + check_0d=False, + ) + + +class TestRules: + """ + Tests related to the general Rule interface (currently private). + """ + + @pytest.mark.parametrize("problem", [ + ( + # 2D problem, 1D rule + [0, 0], + [1, 1], + GaussKronrodQuadrature, + (21,), + ), + ( + # 1D problem, 2D rule + [0], + [1], + GenzMalikCubature, + (2,), + ) + ]) + def test_incompatible_dimension_raises_error(self, problem, xp): + a, b, quadrature, quadrature_args = problem + rule = quadrature(*quadrature_args, xp=xp) + + a = xp.asarray(a, dtype=xp.float64) + b = xp.asarray(b, dtype=xp.float64) + + with pytest.raises(Exception, match="incompatible dimension"): + rule.estimate(basic_1d_integrand, a, b, args=(xp,)) + + def test_estimate_with_base_classes_raise_error(self, xp): + a = xp.asarray([0]) + b = xp.asarray([1]) + + for base_class in [Rule(), FixedRule()]: + with pytest.raises(Exception): + base_class.estimate(basic_1d_integrand, a, b, args=(xp,)) + + +class TestRulesQuadrature: + """ + Tests underlying quadrature rules (ndim == 1). + """ + + @pytest.mark.parametrize(("rule", "rule_args"), [ + (GaussLegendreQuadrature, (3,)), + (GaussLegendreQuadrature, (5,)), + (GaussLegendreQuadrature, (10,)), + (GaussKronrodQuadrature, (15,)), + (GaussKronrodQuadrature, (21,)), + ]) + def test_base_1d_quadratures_simple(self, rule, rule_args, xp): + quadrature = rule(*rule_args, xp=xp) + + n = xp.arange(5, dtype=xp.float64) + + def f(x): + x_reshaped = xp.reshape(x, (-1, 1, 1)) + n_reshaped = xp.reshape(n, (1, -1, 1)) + + return x_reshaped**n_reshaped + + a = xp.asarray([0], dtype=xp.float64) + b = xp.asarray([2], dtype=xp.float64) + + exact = xp.reshape(2**(n+1)/(n+1), (-1, 1)) + estimate = quadrature.estimate(f, a, b) + + xp_assert_close( + estimate, + exact, + rtol=1e-8, + atol=0, + ) + + @pytest.mark.parametrize(("rule_pair", "rule_pair_args"), [ + ((GaussLegendreQuadrature, GaussLegendreQuadrature), (10, 5)), + ]) + def test_base_1d_quadratures_error_from_difference(self, rule_pair, rule_pair_args, + xp): + n = xp.arange(5, dtype=xp.float64) + a = xp.asarray([0], dtype=xp.float64) + b = xp.asarray([2], dtype=xp.float64) + + higher = rule_pair[0](rule_pair_args[0], xp=xp) + lower = rule_pair[1](rule_pair_args[1], xp=xp) + + rule = NestedFixedRule(higher, lower) + res = cubature( + basic_1d_integrand, + a, b, + rule=rule, + rtol=1e-8, + args=(n, xp), + ) + + xp_assert_close( + res.estimate, + basic_1d_integrand_exact(n, xp), + rtol=1e-8, + atol=0, + ) + + @pytest.mark.parametrize("quadrature", [ + GaussLegendreQuadrature + ]) + def test_one_point_fixed_quad_impossible(self, quadrature, xp): + with pytest.raises(Exception): + quadrature(1, xp=xp) + + +class TestRulesCubature: + """ + Tests underlying cubature rules (ndim >= 2). + """ + + @pytest.mark.parametrize("ndim", range(2, 11)) + def test_genz_malik_func_evaluations(self, ndim, xp): + """ + Tests that the number of function evaluations required for Genz-Malik cubature + matches the number in Genz and Malik 1980. + """ + + nodes, _ = GenzMalikCubature(ndim, xp=xp).nodes_and_weights + + assert nodes.shape[0] == (2**ndim) + 2*ndim**2 + 2*ndim + 1 + + def test_genz_malik_1d_raises_error(self, xp): + with pytest.raises(Exception, match="only defined for ndim >= 2"): + GenzMalikCubature(1, xp=xp) + + +@pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason) +@pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason) +class TestTransformations: + @pytest.mark.parametrize(("a", "b", "points"), [ + ( + [0, 1, -math.inf], + [1, math.inf, math.inf], + [ + [1, 1, 1], + [0.5, 10, 10], + ] + ) + ]) + def test_infinite_limits_maintains_points(self, a, b, points, xp): + """ + Test that break points are correctly mapped under the _InfiniteLimitsTransform + transformation. + """ + + points = [xp.asarray(p, dtype=xp.float64) for p in points] + + f_transformed = _InfiniteLimitsTransform( + # Bind `points` and `xp` argument in f + lambda x: f_with_problematic_points(x, points, xp), + xp.asarray(a, dtype=xp.float64), + xp.asarray(b, dtype=xp.float64), + xp=xp, + ) + + for point in points: + transformed_point = f_transformed.inv(xp.reshape(point, (1, -1))) + + with pytest.raises(Exception, match="called with a problematic point"): + f_transformed(transformed_point) + + +class BadErrorRule(Rule): + """ + A rule with fake high error so that cubature will keep on subdividing. + """ + + def estimate(self, f, a, b, args=()): + xp = array_namespace(a, b) + underlying = GaussLegendreQuadrature(10, xp=xp) + + return underlying.estimate(f, a, b, args) + + def estimate_error(self, f, a, b, args=()): + xp = array_namespace(a, b) + return xp.asarray(1e6, dtype=xp.float64) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_integrate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_integrate.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e300fe869abda2255b20fdeb18998b5ebfc949 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_integrate.py @@ -0,0 +1,844 @@ +# Authors: Nils Wagner, Ed Schofield, Pauli Virtanen, John Travers +""" +Tests for numerical integration. +""" +import numpy as np +from numpy import (arange, zeros, array, dot, sqrt, cos, sin, eye, pi, exp, + allclose) + +from numpy.testing import ( + assert_, assert_array_almost_equal, + assert_allclose, assert_array_equal, assert_equal) +import pytest +from pytest import raises as assert_raises +from scipy.integrate import odeint, ode, complex_ode + +#------------------------------------------------------------------------------ +# Test ODE integrators +#------------------------------------------------------------------------------ + + +class TestOdeint: + # Check integrate.odeint + + def _do_problem(self, problem): + t = arange(0.0, problem.stop_t, 0.05) + + # Basic case + z, infodict = odeint(problem.f, problem.z0, t, full_output=True) + assert_(problem.verify(z, t)) + + # Use tfirst=True + z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t, + full_output=True, tfirst=True) + assert_(problem.verify(z, t)) + + if hasattr(problem, 'jac'): + # Use Dfun + z, infodict = odeint(problem.f, problem.z0, t, Dfun=problem.jac, + full_output=True) + assert_(problem.verify(z, t)) + + # Use Dfun and tfirst=True + z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t, + Dfun=lambda t, y: problem.jac(y, t), + full_output=True, tfirst=True) + assert_(problem.verify(z, t)) + + def test_odeint(self): + for problem_cls in PROBLEMS: + problem = problem_cls() + if problem.cmplx: + continue + self._do_problem(problem) + + +class TestODEClass: + + ode_class = None # Set in subclass. + + def _do_problem(self, problem, integrator, method='adams'): + + # ode has callback arguments in different order than odeint + def f(t, z): + return problem.f(z, t) + jac = None + if hasattr(problem, 'jac'): + def jac(t, z): + return problem.jac(z, t) + + integrator_params = {} + if problem.lband is not None or problem.uband is not None: + integrator_params['uband'] = problem.uband + integrator_params['lband'] = problem.lband + + ig = self.ode_class(f, jac) + ig.set_integrator(integrator, + atol=problem.atol/10, + rtol=problem.rtol/10, + method=method, + **integrator_params) + + ig.set_initial_value(problem.z0, t=0.0) + z = ig.integrate(problem.stop_t) + + assert_array_equal(z, ig.y) + assert_(ig.successful(), (problem, method)) + assert_(ig.get_return_code() > 0, (problem, method)) + assert_(problem.verify(array([z]), problem.stop_t), (problem, method)) + + +class TestOde(TestODEClass): + + ode_class = ode + + def test_vode(self): + # Check the vode solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if problem.cmplx: + continue + if not problem.stiff: + self._do_problem(problem, 'vode', 'adams') + self._do_problem(problem, 'vode', 'bdf') + + def test_zvode(self): + # Check the zvode solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if not problem.stiff: + self._do_problem(problem, 'zvode', 'adams') + self._do_problem(problem, 'zvode', 'bdf') + + def test_lsoda(self): + # Check the lsoda solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if problem.cmplx: + continue + self._do_problem(problem, 'lsoda') + + def test_dopri5(self): + # Check the dopri5 solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if problem.cmplx: + continue + if problem.stiff: + continue + if hasattr(problem, 'jac'): + continue + self._do_problem(problem, 'dopri5') + + def test_dop853(self): + # Check the dop853 solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if problem.cmplx: + continue + if problem.stiff: + continue + if hasattr(problem, 'jac'): + continue + self._do_problem(problem, 'dop853') + + def test_concurrent_fail(self): + # Test concurrent usage behavior for different solvers + # All solvers (vode, zvode, lsoda) now support concurrent usage + # with state persistence via explicit state parameters + for sol in ('vode', 'zvode', 'lsoda'): + def f(t, y): + return 1.0 + + r = ode(f).set_integrator(sol) + r.set_initial_value(0, 0) + + r2 = ode(f).set_integrator(sol) + r2.set_initial_value(0, 0) + + r.integrate(r.t + 0.1) + r2.integrate(r2.t + 0.1) + + # With state persistence, r should still work correctly + r.integrate(r.t + 0.1) + assert r.successful() + + def test_concurrent_ok(self, num_parallel_threads): + def f(t, y): + return 1.0 + + for k in range(3): + for sol in ('vode', 'zvode', 'lsoda', 'dopri5', 'dop853'): + if sol in {'vode', 'zvode', 'lsoda'} and num_parallel_threads > 1: + continue + r = ode(f).set_integrator(sol) + r.set_initial_value(0, 0) + + r2 = ode(f).set_integrator(sol) + r2.set_initial_value(0, 0) + + r.integrate(r.t + 0.1) + r2.integrate(r2.t + 0.1) + r2.integrate(r2.t + 0.1) + + assert_allclose(r.y, 0.1) + assert_allclose(r2.y, 0.2) + + for sol in ('dopri5', 'dop853'): + r = ode(f).set_integrator(sol) + r.set_initial_value(0, 0) + + r2 = ode(f).set_integrator(sol) + r2.set_initial_value(0, 0) + + r.integrate(r.t + 0.1) + r.integrate(r.t + 0.1) + r2.integrate(r2.t + 0.1) + r.integrate(r.t + 0.1) + r2.integrate(r2.t + 0.1) + + assert_allclose(r.y, 0.3) + assert_allclose(r2.y, 0.2) + + +class TestComplexOde(TestODEClass): + + ode_class = complex_ode + + def test_vode(self): + # Check the vode solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if not problem.stiff: + self._do_problem(problem, 'vode', 'adams') + else: + self._do_problem(problem, 'vode', 'bdf') + + def test_lsoda(self): + + # Check the lsoda solver + for problem_cls in PROBLEMS: + problem = problem_cls() + self._do_problem(problem, 'lsoda') + + def test_dopri5(self): + # Check the dopri5 solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if problem.stiff: + continue + if hasattr(problem, 'jac'): + continue + self._do_problem(problem, 'dopri5') + + def test_dop853(self): + # Check the dop853 solver + for problem_cls in PROBLEMS: + problem = problem_cls() + if problem.stiff: + continue + if hasattr(problem, 'jac'): + continue + self._do_problem(problem, 'dop853') + + +class TestSolout: + # Check integrate.ode correctly handles solout for dopri5 and dop853 + def _run_solout_test(self, integrator): + # Check correct usage of solout + ts = [] + ys = [] + t0 = 0.0 + tend = 10.0 + y0 = [1.0, 2.0] + + def solout(t, y): + ts.append(t) + ys.append(y.copy()) + + def rhs(t, y): + return [y[0] + y[1], -y[1]**2] + + ig = ode(rhs).set_integrator(integrator) + ig.set_solout(solout) + ig.set_initial_value(y0, t0) + ret = ig.integrate(tend) + assert_array_equal(ys[0], y0) + assert_array_equal(ys[-1], ret) + assert_equal(ts[0], t0) + assert_equal(ts[-1], tend) + + def test_solout(self): + for integrator in ('dopri5', 'dop853'): + self._run_solout_test(integrator) + + def _run_solout_after_initial_test(self, integrator): + # Check if solout works even if it is set after the initial value. + ts = [] + ys = [] + t0 = 0.0 + tend = 10.0 + y0 = [1.0, 2.0] + + def solout(t, y): + ts.append(t) + ys.append(y.copy()) + + def rhs(t, y): + return [y[0] + y[1], -y[1]**2] + + ig = ode(rhs).set_integrator(integrator) + ig.set_initial_value(y0, t0) + ig.set_solout(solout) + ret = ig.integrate(tend) + assert_array_equal(ys[0], y0) + assert_array_equal(ys[-1], ret) + assert_equal(ts[0], t0) + assert_equal(ts[-1], tend) + + def test_solout_after_initial(self): + for integrator in ('dopri5', 'dop853'): + self._run_solout_after_initial_test(integrator) + + def _run_solout_break_test(self, integrator): + # Check correct usage of stopping via solout + ts = [] + ys = [] + t0 = 0.0 + tend = 10.0 + y0 = [1.0, 2.0] + + def solout(t, y): + ts.append(t) + ys.append(y.copy()) + if t > tend/2.0: + return -1 + + def rhs(t, y): + return [y[0] + y[1], -y[1]**2] + + ig = ode(rhs).set_integrator(integrator) + ig.set_solout(solout) + ig.set_initial_value(y0, t0) + ret = ig.integrate(tend) + assert_array_equal(ys[0], y0) + assert_array_equal(ys[-1], ret) + assert_equal(ts[0], t0) + assert_(ts[-1] > tend/2.0) + assert_(ts[-1] < tend) + + def test_solout_break(self): + for integrator in ('dopri5', 'dop853'): + self._run_solout_break_test(integrator) + + +class TestComplexSolout: + # Check integrate.ode correctly handles solout for dopri5 and dop853 + def _run_solout_test(self, integrator): + # Check correct usage of solout + ts = [] + ys = [] + t0 = 0.0 + tend = 20.0 + y0 = [0.0] + + def solout(t, y): + ts.append(t) + ys.append(y.copy()) + + def rhs(t, y): + return [1.0/(t - 10.0 - 1j)] + + ig = complex_ode(rhs).set_integrator(integrator) + ig.set_solout(solout) + ig.set_initial_value(y0, t0) + ret = ig.integrate(tend) + assert_array_equal(ys[0], y0) + assert_array_equal(ys[-1], ret) + assert_equal(ts[0], t0) + assert_equal(ts[-1], tend) + + def test_solout(self): + for integrator in ('dopri5', 'dop853'): + self._run_solout_test(integrator) + + def _run_solout_break_test(self, integrator): + # Check correct usage of stopping via solout + ts = [] + ys = [] + t0 = 0.0 + tend = 20.0 + y0 = [0.0] + + def solout(t, y): + ts.append(t) + ys.append(y.copy()) + if t > tend/2.0: + return -1 + + def rhs(t, y): + return [1.0/(t - 10.0 - 1j)] + + ig = complex_ode(rhs).set_integrator(integrator) + ig.set_solout(solout) + ig.set_initial_value(y0, t0) + ret = ig.integrate(tend) + assert_array_equal(ys[0], y0) + assert_array_equal(ys[-1], ret) + assert_equal(ts[0], t0) + assert_(ts[-1] > tend/2.0) + assert_(ts[-1] < tend) + + def test_solout_break(self): + for integrator in ('dopri5', 'dop853'): + self._run_solout_break_test(integrator) + + +#------------------------------------------------------------------------------ +# Test problems +#------------------------------------------------------------------------------ + + +class ODE: + """ + ODE problem + """ + stiff = False + cmplx = False + stop_t = 1 + z0 = [] + + lband = None + uband = None + + atol = 1e-6 + rtol = 1e-5 + + +class SimpleOscillator(ODE): + r""" + Free vibration of a simple oscillator:: + m \ddot{u} + k u = 0, u(0) = u_0 \dot{u}(0) \dot{u}_0 + Solution:: + u(t) = u_0*cos(sqrt(k/m)*t)+\dot{u}_0*sin(sqrt(k/m)*t)/sqrt(k/m) + """ + stop_t = 1 + 0.09 + z0 = array([1.0, 0.1], float) + + k = 4.0 + m = 1.0 + + def f(self, z, t): + tmp = zeros((2, 2), float) + tmp[0, 1] = 1.0 + tmp[1, 0] = -self.k / self.m + return dot(tmp, z) + + def verify(self, zs, t): + omega = sqrt(self.k / self.m) + u = self.z0[0]*cos(omega*t) + self.z0[1]*sin(omega*t)/omega + return allclose(u, zs[:, 0], atol=self.atol, rtol=self.rtol) + + +class ComplexExp(ODE): + r"""The equation :lm:`\dot u = i u`""" + stop_t = 1.23*pi + z0 = exp([1j, 2j, 3j, 4j, 5j]) + cmplx = True + + def f(self, z, t): + return 1j*z + + def jac(self, z, t): + return 1j*eye(5) + + def verify(self, zs, t): + u = self.z0 * exp(1j*t) + return allclose(u, zs, atol=self.atol, rtol=self.rtol) + + +class Pi(ODE): + r"""Integrate 1/(t + 1j) from t=-10 to t=10""" + stop_t = 20 + z0 = [0] + cmplx = True + + def f(self, z, t): + return array([1./(t - 10 + 1j)]) + + def verify(self, zs, t): + u = -2j * np.arctan(10) + return allclose(u, zs[-1, :], atol=self.atol, rtol=self.rtol) + + +class CoupledDecay(ODE): + r""" + 3 coupled decays suited for banded treatment + (banded mode makes it necessary when N>>3) + """ + + stiff = True + stop_t = 0.5 + z0 = [5.0, 7.0, 13.0] + lband = 1 + uband = 0 + + lmbd = [0.17, 0.23, 0.29] # fictitious decay constants + + def f(self, z, t): + lmbd = self.lmbd + return np.array([-lmbd[0]*z[0], + -lmbd[1]*z[1] + lmbd[0]*z[0], + -lmbd[2]*z[2] + lmbd[1]*z[1]]) + + def jac(self, z, t): + # The full Jacobian is + # + # [-lmbd[0] 0 0 ] + # [ lmbd[0] -lmbd[1] 0 ] + # [ 0 lmbd[1] -lmbd[2]] + # + # The lower and upper bandwidths are lband=1 and uband=0, resp. + # The representation of this array in packed format is + # + # [-lmbd[0] -lmbd[1] -lmbd[2]] + # [ lmbd[0] lmbd[1] 0 ] + + lmbd = self.lmbd + j = np.zeros((self.lband + self.uband + 1, 3), order='F') + + def set_j(ri, ci, val): + j[self.uband + ri - ci, ci] = val + set_j(0, 0, -lmbd[0]) + set_j(1, 0, lmbd[0]) + set_j(1, 1, -lmbd[1]) + set_j(2, 1, lmbd[1]) + set_j(2, 2, -lmbd[2]) + return j + + def verify(self, zs, t): + # Formulae derived by hand + lmbd = np.array(self.lmbd) + d10 = lmbd[1] - lmbd[0] + d21 = lmbd[2] - lmbd[1] + d20 = lmbd[2] - lmbd[0] + e0 = np.exp(-lmbd[0] * t) + e1 = np.exp(-lmbd[1] * t) + e2 = np.exp(-lmbd[2] * t) + u = np.vstack(( + self.z0[0] * e0, + self.z0[1] * e1 + self.z0[0] * lmbd[0] / d10 * (e0 - e1), + self.z0[2] * e2 + self.z0[1] * lmbd[1] / d21 * (e1 - e2) + + lmbd[1] * lmbd[0] * self.z0[0] / d10 * + (1 / d20 * (e0 - e2) - 1 / d21 * (e1 - e2)))).transpose() + return allclose(u, zs, atol=self.atol, rtol=self.rtol) + + +PROBLEMS = [SimpleOscillator, ComplexExp, Pi, CoupledDecay] + +#------------------------------------------------------------------------------ + + +def f(t, x): + dxdt = [x[1], -x[0]] + return dxdt + + +def jac(t, x): + j = array([[0.0, 1.0], + [-1.0, 0.0]]) + return j + + +def f1(t, x, omega): + dxdt = [omega*x[1], -omega*x[0]] + return dxdt + + +def jac1(t, x, omega): + j = array([[0.0, omega], + [-omega, 0.0]]) + return j + + +def f2(t, x, omega1, omega2): + dxdt = [omega1*x[1], -omega2*x[0]] + return dxdt + + +def jac2(t, x, omega1, omega2): + j = array([[0.0, omega1], + [-omega2, 0.0]]) + return j + + +def fv(t, x, omega): + dxdt = [omega[0]*x[1], -omega[1]*x[0]] + return dxdt + + +def jacv(t, x, omega): + j = array([[0.0, omega[0]], + [-omega[1], 0.0]]) + return j + + +class ODECheckParameterUse: + """Call an ode-class solver with several cases of parameter use.""" + + # solver_name must be set before tests can be run with this class. + + # Set these in subclasses. + solver_name = '' + solver_uses_jac = False + + def _get_solver(self, f, jac): + solver = ode(f, jac) + if self.solver_uses_jac: + solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7, + with_jacobian=self.solver_uses_jac) + else: + # XXX Shouldn't set_integrator *always* accept the keyword arg + # 'with_jacobian', and perhaps raise an exception if it is set + # to True if the solver can't actually use it? + solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7) + return solver + + def _check_solver(self, solver): + ic = [1.0, 0.0] + solver.set_initial_value(ic, 0.0) + solver.integrate(pi) + assert_array_almost_equal(solver.y, [-1.0, 0.0]) + + def test_no_params(self): + solver = self._get_solver(f, jac) + self._check_solver(solver) + + def test_one_scalar_param(self): + solver = self._get_solver(f1, jac1) + omega = 1.0 + solver.set_f_params(omega) + if self.solver_uses_jac: + solver.set_jac_params(omega) + self._check_solver(solver) + + def test_two_scalar_params(self): + solver = self._get_solver(f2, jac2) + omega1 = 1.0 + omega2 = 1.0 + solver.set_f_params(omega1, omega2) + if self.solver_uses_jac: + solver.set_jac_params(omega1, omega2) + self._check_solver(solver) + + def test_vector_param(self): + solver = self._get_solver(fv, jacv) + omega = [1.0, 1.0] + solver.set_f_params(omega) + if self.solver_uses_jac: + solver.set_jac_params(omega) + self._check_solver(solver) + + def test_warns_on_failure(self): + # Set nsteps small to ensure failure + solver = self._get_solver(f, jac) + solver.set_integrator(self.solver_name, nsteps=1) + ic = [1.0, 0.0] + solver.set_initial_value(ic, 0.0) + with pytest.warns(UserWarning): + solver.integrate(pi) + + +class TestDOPRI5CheckParameterUse(ODECheckParameterUse): + solver_name = 'dopri5' + solver_uses_jac = False + + +class TestDOP853CheckParameterUse(ODECheckParameterUse): + solver_name = 'dop853' + solver_uses_jac = False + + +class TestVODECheckParameterUse(ODECheckParameterUse): + solver_name = 'vode' + solver_uses_jac = True + + +class TestZVODECheckParameterUse(ODECheckParameterUse): + solver_name = 'zvode' + solver_uses_jac = True + + +class TestLSODACheckParameterUse(ODECheckParameterUse): + solver_name = 'lsoda' + solver_uses_jac = True + + +def test_odeint_trivial_time(): + # Test that odeint succeeds when given a single time point + # and full_output=True. This is a regression test for gh-4282. + y0 = 1 + t = [0] + y, info = odeint(lambda y, t: -y, y0, t, full_output=True) + assert_array_equal(y, np.array([[y0]])) + + +def test_odeint_banded_jacobian(): + # Test the use of the `Dfun`, `ml` and `mu` options of odeint. + + def func(y, t, c): + return c.dot(y) + + def jac(y, t, c): + return c + + def jac_transpose(y, t, c): + return c.T.copy(order='C') + + def bjac_rows(y, t, c): + jac = np.vstack((np.r_[0, np.diag(c, 1)], + np.diag(c), + np.r_[np.diag(c, -1), 0], + np.r_[np.diag(c, -2), 0, 0])) + return jac + + def bjac_cols(y, t, c): + return bjac_rows(y, t, c).T.copy(order='C') + + c = array([[-205, 0.01, 0.00, 0.0], + [0.1, -2.50, 0.02, 0.0], + [1e-3, 0.01, -2.0, 0.01], + [0.00, 0.00, 0.1, -1.0]]) + + y0 = np.ones(4) + t = np.array([0, 5, 10, 100]) + + # Use the full Jacobian. + sol1, info1 = odeint(func, y0, t, args=(c,), full_output=True, + atol=1e-13, rtol=1e-11, mxstep=10000, + Dfun=jac) + + # Use the transposed full Jacobian, with col_deriv=True. + sol2, info2 = odeint(func, y0, t, args=(c,), full_output=True, + atol=1e-13, rtol=1e-11, mxstep=10000, + Dfun=jac_transpose, col_deriv=True) + + # Use the banded Jacobian. + sol3, info3 = odeint(func, y0, t, args=(c,), full_output=True, + atol=1e-13, rtol=1e-11, mxstep=10000, + Dfun=bjac_rows, ml=2, mu=1) + + # Use the transposed banded Jacobian, with col_deriv=True. + sol4, info4 = odeint(func, y0, t, args=(c,), full_output=True, + atol=1e-13, rtol=1e-11, mxstep=10000, + Dfun=bjac_cols, ml=2, mu=1, col_deriv=True) + + assert_allclose(sol1, sol2, err_msg="sol1 != sol2") + assert_allclose(sol1, sol3, atol=1e-12, err_msg="sol1 != sol3") + assert_allclose(sol3, sol4, err_msg="sol3 != sol4") + + # Verify that the number of jacobian evaluations was the same for the + # calls of odeint with a full jacobian and with a banded jacobian. This is + # a regression test--there was a bug in the handling of banded jacobians + # that resulted in an incorrect jacobian matrix being passed to the LSODA + # code. That would cause errors or excessive jacobian evaluations. + assert_array_equal(info1['nje'], info2['nje']) + assert_array_equal(info3['nje'], info4['nje']) + + # Test the use of tfirst + sol1ty, info1ty = odeint(lambda t, y, c: func(y, t, c), y0, t, args=(c,), + full_output=True, atol=1e-13, rtol=1e-11, + mxstep=10000, + Dfun=lambda t, y, c: jac(y, t, c), tfirst=True) + # The code should execute the exact same sequence of floating point + # calculations, so these should be exactly equal. We'll be safe and use + # a small tolerance. + assert_allclose(sol1, sol1ty, rtol=1e-12, err_msg="sol1 != sol1ty") + + +def test_odeint_errors(): + def sys1d(x, t): + return -100*x + + def bad1(x, t): + return 1.0/0 + + def bad2(x, t): + return "foo" + + def bad_jac1(x, t): + return 1.0/0 + + def bad_jac2(x, t): + return [["foo"]] + + def sys2d(x, t): + return [-100*x[0], -0.1*x[1]] + + def sys2d_bad_jac(x, t): + return [[1.0/0, 0], [0, -0.1]] + + assert_raises(ZeroDivisionError, odeint, bad1, 1.0, [0, 1]) + assert_raises(ValueError, odeint, bad2, 1.0, [0, 1]) + + assert_raises(ZeroDivisionError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac1) + assert_raises(ValueError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac2) + + assert_raises(ZeroDivisionError, odeint, sys2d, [1.0, 1.0], [0, 1], + Dfun=sys2d_bad_jac) + + +def test_odeint_bad_shapes(): + # Tests of some errors that can occur with odeint. + + def badrhs(x, t): + return [1, -1] + + def sys1(x, t): + return -100*x + + def badjac(x, t): + return [[0, 0, 0]] + + # y0 must be at most 1-d. + bad_y0 = [[0, 0], [0, 0]] + assert_raises(ValueError, odeint, sys1, bad_y0, [0, 1]) + + # t must be at most 1-d. + bad_t = [[0, 1], [2, 3]] + assert_raises(ValueError, odeint, sys1, [10.0], bad_t) + + # y0 is 10, but badrhs(x, t) returns [1, -1]. + assert_raises(RuntimeError, odeint, badrhs, 10, [0, 1]) + + # shape of array returned by badjac(x, t) is not correct. + assert_raises(RuntimeError, odeint, sys1, [10, 10], [0, 1], Dfun=badjac) + + +def test_repeated_t_values(): + """Regression test for gh-8217.""" + + def func(x, t): + return -0.25*x + + t = np.zeros(10) + sol = odeint(func, [1.], t) + assert_array_equal(sol, np.ones((len(t), 1))) + + tau = 4*np.log(2) + t = [0]*9 + [tau, 2*tau, 2*tau, 3*tau] + sol = odeint(func, [1, 2], t, rtol=1e-12, atol=1e-12) + expected_sol = np.array([[1.0, 2.0]]*9 + + [[0.5, 1.0], + [0.25, 0.5], + [0.25, 0.5], + [0.125, 0.25]]) + assert_allclose(sol, expected_sol) + + # Edge case: empty t sequence. + sol = odeint(func, [1.], []) + assert_array_equal(sol, np.array([], dtype=np.float64).reshape((0, 1))) + + # t values are not monotonic. + assert_raises(ValueError, odeint, func, [1.], [0, 1, 0.5, 0]) + assert_raises(ValueError, odeint, func, [1, 2, 3], [0, -1, -2, 3]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_quadpack.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_quadpack.py new file mode 100644 index 0000000000000000000000000000000000000000..b92c89f30ae22e81b2eb24839745764cc5c0b7d5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_quadpack.py @@ -0,0 +1,723 @@ +import sys +import math +import numpy as np +from numpy import sqrt, cos, sin, arctan, exp, log, pi +from numpy.testing import (assert_, + assert_allclose, assert_array_less, assert_almost_equal, assert_equal) +import pytest + +from scipy.integrate import quad, dblquad, tplquad, nquad +from scipy.special import erf, erfc +from scipy._lib._ccallback import LowLevelCallable +from scipy._lib._array_api import make_xp_test_case + +import ctypes +import ctypes.util +from scipy._lib._ccallback_c import sine_ctypes + +import scipy.integrate._test_multivariate as clib_test + + +def assert_quad(value_and_err, tabled_value, error_tolerance=1.5e-8): + value, err = value_and_err + assert_allclose(value, tabled_value, atol=err, rtol=0) + if error_tolerance is not None: + assert_array_less(err, error_tolerance) + + +def get_clib_test_routine(name, restype, *argtypes): + ptr = getattr(clib_test, name) + return ctypes.cast(ptr, ctypes.CFUNCTYPE(restype, *argtypes)) + + +@make_xp_test_case(quad) +class TestCtypesQuad: + def setup_method(self): + if sys.platform == 'win32': + files = ['api-ms-win-crt-math-l1-1-0.dll'] + elif sys.platform == 'darwin': + files = ['libm.dylib'] + else: + files = ['libm.so', 'libm.so.6'] + + for file in files: + try: + self.lib = ctypes.CDLL(file) + break + except OSError: + pass + else: + # This test doesn't work on some Linux platforms (Fedora for + # example) that put an ld script in libm.so - see gh-5370 + pytest.skip("Ctypes can't import libm.so") + + restype = ctypes.c_double + argtypes = (ctypes.c_double,) + for name in ['sin', 'cos', 'tan']: + func = getattr(self.lib, name) + func.restype = restype + func.argtypes = argtypes + + def test_typical(self): + assert_quad(quad(self.lib.sin, 0, 5), quad(math.sin, 0, 5)[0]) + assert_quad(quad(self.lib.cos, 0, 5), quad(math.cos, 0, 5)[0]) + assert_quad(quad(self.lib.tan, 0, 1), quad(math.tan, 0, 1)[0]) + + def test_ctypes_sine(self): + quad(LowLevelCallable(sine_ctypes), 0, 1) + + def test_ctypes_variants(self): + sin_0 = get_clib_test_routine('_sin_0', ctypes.c_double, + ctypes.c_double, ctypes.c_void_p) + + sin_1 = get_clib_test_routine('_sin_1', ctypes.c_double, + ctypes.c_int, ctypes.POINTER(ctypes.c_double), + ctypes.c_void_p) + + sin_2 = get_clib_test_routine('_sin_2', ctypes.c_double, + ctypes.c_double) + + sin_3 = get_clib_test_routine('_sin_3', ctypes.c_double, + ctypes.c_int, ctypes.POINTER(ctypes.c_double)) + + sin_4 = get_clib_test_routine('_sin_3', ctypes.c_double, + ctypes.c_int, ctypes.c_double) + + all_sigs = [sin_0, sin_1, sin_2, sin_3, sin_4] + legacy_sigs = [sin_2, sin_4] + legacy_only_sigs = [sin_4] + + # LowLevelCallables work for new signatures + for j, func in enumerate(all_sigs): + callback = LowLevelCallable(func) + if func in legacy_only_sigs: + pytest.raises(ValueError, quad, callback, 0, pi) + else: + assert_allclose(quad(callback, 0, pi)[0], 2.0) + + # Plain ctypes items work only for legacy signatures + for j, func in enumerate(legacy_sigs): + if func in legacy_sigs: + assert_allclose(quad(func, 0, pi)[0], 2.0) + else: + pytest.raises(ValueError, quad, func, 0, pi) + + +@make_xp_test_case(quad) +class TestMultivariateCtypesQuad: + def setup_method(self): + restype = ctypes.c_double + argtypes = (ctypes.c_int, ctypes.c_double) + for name in ['_multivariate_typical', '_multivariate_indefinite', + '_multivariate_sin']: + func = get_clib_test_routine(name, restype, *argtypes) + setattr(self, name, func) + + def test_typical(self): + # 1) Typical function with two extra arguments: + assert_quad(quad(self._multivariate_typical, 0, pi, (2, 1.8)), + 0.30614353532540296487) + + def test_indefinite(self): + # 2) Infinite integration limits --- Euler's constant + assert_quad(quad(self._multivariate_indefinite, 0, np.inf), + 0.577215664901532860606512) + + def test_threadsafety(self): + # Ensure multivariate ctypes are threadsafe + def threadsafety(y): + return y + quad(self._multivariate_sin, 0, 1)[0] + assert_quad(quad(threadsafety, 0, 1), 0.9596976941318602) + + +@make_xp_test_case(quad) +class TestQuad: + def test_typical(self): + # 1) Typical function with two extra arguments: + def myfunc(x, n, z): # Bessel function integrand + return cos(n*x-z*sin(x))/pi + assert_quad(quad(myfunc, 0, pi, (2, 1.8)), 0.30614353532540296487) + + def test_indefinite(self): + # 2) Infinite integration limits --- Euler's constant + def myfunc(x): # Euler's constant integrand + return -exp(-x)*log(x) + assert_quad(quad(myfunc, 0, np.inf), 0.577215664901532860606512) + + def test_singular(self): + # 3) Singular points in region of integration. + def myfunc(x): + if 0 < x < 2.5: + return sin(x) + elif 2.5 <= x <= 5.0: + return exp(-x) + else: + return 0.0 + + assert_quad(quad(myfunc, 0, 10, points=[2.5, 5.0]), + 1 - cos(2.5) + exp(-2.5) - exp(-5.0)) + + def test_sine_weighted_finite(self): + # 4) Sine weighted integral (finite limits) + def myfunc(x, a): + return exp(a*(x-1)) + + ome = 2.0**3.4 + assert_quad(quad(myfunc, 0, 1, args=20, weight='sin', wvar=ome), + (20*sin(ome)-ome*cos(ome)+ome*exp(-20))/(20**2 + ome**2)) + + def test_sine_weighted_infinite(self): + # 5) Sine weighted integral (infinite limits) + def myfunc(x, a): + return exp(-x*a) + + a = 4.0 + ome = 3.0 + assert_quad(quad(myfunc, 0, np.inf, args=a, weight='sin', wvar=ome), + ome/(a**2 + ome**2)) + + def test_cosine_weighted_infinite(self): + # 6) Cosine weighted integral (negative infinite limits) + def myfunc(x, a): + return exp(x*a) + + a = 2.5 + ome = 2.3 + assert_quad(quad(myfunc, -np.inf, 0, args=a, weight='cos', wvar=ome), + a/(a**2 + ome**2)) + + def test_algebraic_log_weight(self): + # 6) Algebraic-logarithmic weight. + def myfunc(x, a): + return 1/(1+x+2**(-a)) + + a = 1.5 + assert_quad(quad(myfunc, -1, 1, args=a, weight='alg', + wvar=(-0.5, -0.5)), + pi/sqrt((1+2**(-a))**2 - 1)) + + def test_cauchypv_weight(self): + # 7) Cauchy prinicpal value weighting w(x) = 1/(x-c) + def myfunc(x, a): + return 2.0**(-a)/((x-1)**2+4.0**(-a)) + + a = 0.4 + tabledValue = ((2.0**(-0.4)*log(1.5) - + 2.0**(-1.4)*log((4.0**(-a)+16) / (4.0**(-a)+1)) - + arctan(2.0**(a+2)) - + arctan(2.0**a)) / + (4.0**(-a) + 1)) + assert_quad(quad(myfunc, 0, 5, args=0.4, weight='cauchy', wvar=2.0), + tabledValue, error_tolerance=1.9e-8) + + def test_b_less_than_a(self): + def f(x, p, q): + return p * np.exp(-q*x) + + val_1, err_1 = quad(f, 0, np.inf, args=(2, 3)) + val_2, err_2 = quad(f, np.inf, 0, args=(2, 3)) + assert_allclose(val_1, -val_2, atol=max(err_1, err_2)) + + def test_b_less_than_a_2(self): + def f(x, s): + return np.exp(-x**2 / 2 / s) / np.sqrt(2.*s) + + val_1, err_1 = quad(f, -np.inf, np.inf, args=(2,)) + val_2, err_2 = quad(f, np.inf, -np.inf, args=(2,)) + assert_allclose(val_1, -val_2, atol=max(err_1, err_2)) + + def test_b_less_than_a_3(self): + def f(x): + return 1.0 + + val_1, err_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0)) + val_2, err_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0)) + assert_allclose(val_1, -val_2, atol=max(err_1, err_2)) + + def test_b_less_than_a_full_output(self): + def f(x): + return 1.0 + + res_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0), full_output=True) + res_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0), full_output=True) + err = max(res_1[1], res_2[1]) + assert_allclose(res_1[0], -res_2[0], atol=err) + + @pytest.mark.parametrize("complex_func", [True, False]) + def test_b_equals_a(self, complex_func): + def f(x): + return 1/x + + upper = lower = 0. + limit = 50 + expected_infodict = {"neval": 0, "last": 0, + "alist": np.full(limit, np.nan, dtype=np.float64), + "blist": np.full(limit, np.nan, dtype=np.float64), + "rlist": np.zeros(limit, dtype=np.float64), + "elist": np.zeros(limit, dtype=np.float64), + "iord" : np.zeros(limit, dtype=np.int32)} + + zero, err, infodict = quad(f, lower, upper, full_output=1, + complex_func=complex_func) + assert (zero, err) == (0., 0.) + if complex_func: + assert_equal(infodict, {"real": expected_infodict, + "imag": expected_infodict}) + else: + assert_equal(infodict, expected_infodict) + + def test_complex(self): + def tfunc(x): + return np.exp(1j*x) + + assert np.allclose( + quad(tfunc, 0, np.pi/2, complex_func=True)[0], + 1+1j) + + # We consider a divergent case in order to force quadpack + # to return an error message. The output is compared + # against what is returned by explicit integration + # of the parts. + kwargs = {'a': 0, 'b': np.inf, 'full_output': True, + 'weight': 'cos', 'wvar': 1} + res_c = quad(tfunc, complex_func=True, **kwargs) + res_r = quad(lambda x: np.real(np.exp(1j*x)), + complex_func=False, + **kwargs) + res_i = quad(lambda x: np.imag(np.exp(1j*x)), + complex_func=False, + **kwargs) + + np.testing.assert_equal(res_c[0], res_r[0] + 1j*res_i[0]) + np.testing.assert_equal(res_c[1], res_r[1] + 1j*res_i[1]) + + assert len(res_c[2]['real']) == len(res_r[2:]) == 3 + assert res_c[2]['real'][2] == res_r[4] + assert res_c[2]['real'][1] == res_r[3] + assert res_c[2]['real'][0]['lst'] == res_r[2]['lst'] + + assert len(res_c[2]['imag']) == len(res_i[2:]) == 1 + assert res_c[2]['imag'][0]['lst'] == res_i[2]['lst'] + + +@make_xp_test_case(dblquad) +class TestDblquad: + def test_double_integral(self): + # 8) Double Integral test + def simpfunc(y, x): # Note order of arguments. + return x+y + + a, b = 1.0, 2.0 + assert_quad(dblquad(simpfunc, a, b, lambda x: x, lambda x: 2*x), + 5/6.0 * (b**3.0-a**3.0)) + + def test_double_integral2(self): + def func(x0, x1, t0, t1): + return x0 + x1 + t0 + t1 + def g(x): + return x + def h(x): + return 2 * x + args = 1, 2 + assert_quad(dblquad(func, 1, 2, g, h, args=args),35./6 + 9*.5) + + def test_double_integral3(self): + def func(x0, x1): + return x0 + x1 + 1 + 2 + assert_quad(dblquad(func, 1, 2, 1, 2),6.) + + @pytest.mark.parametrize( + "x_lower, x_upper, y_lower, y_upper, expected", + [ + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-inf, 0] for all n. + (-np.inf, 0, -np.inf, 0, np.pi / 4), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-inf, -1] for each n (one at a time). + (-np.inf, -1, -np.inf, 0, np.pi / 4 * erfc(1)), + (-np.inf, 0, -np.inf, -1, np.pi / 4 * erfc(1)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-inf, -1] for all n. + (-np.inf, -1, -np.inf, -1, np.pi / 4 * (erfc(1) ** 2)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-inf, 1] for each n (one at a time). + (-np.inf, 1, -np.inf, 0, np.pi / 4 * (erf(1) + 1)), + (-np.inf, 0, -np.inf, 1, np.pi / 4 * (erf(1) + 1)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-inf, 1] for all n. + (-np.inf, 1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) ** 2)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain Dx = [-inf, -1] and Dy = [-inf, 1]. + (-np.inf, -1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) * erfc(1))), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain Dx = [-inf, 1] and Dy = [-inf, -1]. + (-np.inf, 1, -np.inf, -1, np.pi / 4 * ((erf(1) + 1) * erfc(1))), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [0, inf] for all n. + (0, np.inf, 0, np.inf, np.pi / 4), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [1, inf] for each n (one at a time). + (1, np.inf, 0, np.inf, np.pi / 4 * erfc(1)), + (0, np.inf, 1, np.inf, np.pi / 4 * erfc(1)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [1, inf] for all n. + (1, np.inf, 1, np.inf, np.pi / 4 * (erfc(1) ** 2)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-1, inf] for each n (one at a time). + (-1, np.inf, 0, np.inf, np.pi / 4 * (erf(1) + 1)), + (0, np.inf, -1, np.inf, np.pi / 4 * (erf(1) + 1)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-1, inf] for all n. + (-1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) ** 2)), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain Dx = [-1, inf] and Dy = [1, inf]. + (-1, np.inf, 1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain Dx = [1, inf] and Dy = [-1, inf]. + (1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [-inf, inf] for all n. + (-np.inf, np.inf, -np.inf, np.inf, np.pi), + # Multiple integration of a function in n = 2 variables: f(x, y, z) + # over domain D = [0, 0] for each n (one at a time). + (0, 0, 0, np.inf, 0.), + (0, np.inf, 0, 0, 0.), + ] + ) + def test_double_integral_improper( + self, x_lower, x_upper, y_lower, y_upper, expected + ): + # The Gaussian Integral. + def f(x, y): + return np.exp(-x ** 2 - y ** 2) + + assert_quad( + dblquad(f, x_lower, x_upper, y_lower, y_upper), + expected, + error_tolerance=3e-8 + ) + + +@make_xp_test_case(tplquad) +class TestTplquad: + def test_triple_integral(self): + # 9) Triple Integral test + def simpfunc(z, y, x, t): # Note order of arguments. + return (x+y+z)*t + + a, b = 1.0, 2.0 + assert_quad(tplquad(simpfunc, a, b, + lambda x: x, lambda x: 2*x, + lambda x, y: x - y, lambda x, y: x + y, + (2.,)), + 2*8/3.0 * (b**4.0 - a**4.0)) + + @pytest.mark.xslow + @pytest.mark.parametrize( + "x_lower, x_upper, y_lower, y_upper, z_lower, z_upper, expected", + [ + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, 0] for all n. + (-np.inf, 0, -np.inf, 0, -np.inf, 0, (np.pi ** (3 / 2)) / 8), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, -1] for each n (one at a time). + (-np.inf, -1, -np.inf, 0, -np.inf, 0, + (np.pi ** (3 / 2)) / 8 * erfc(1)), + (-np.inf, 0, -np.inf, -1, -np.inf, 0, + (np.pi ** (3 / 2)) / 8 * erfc(1)), + (-np.inf, 0, -np.inf, 0, -np.inf, -1, + (np.pi ** (3 / 2)) / 8 * erfc(1)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, -1] for each n (two at a time). + (-np.inf, -1, -np.inf, -1, -np.inf, 0, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)), + (-np.inf, -1, -np.inf, 0, -np.inf, -1, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)), + (-np.inf, 0, -np.inf, -1, -np.inf, -1, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, -1] for all n. + (-np.inf, -1, -np.inf, -1, -np.inf, -1, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = [-inf, -1] and Dy = Dz = [-inf, 1]. + (-np.inf, -1, -np.inf, 1, -np.inf, 1, + (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dy = [-inf, -1] and Dz = [-inf, 1]. + (-np.inf, -1, -np.inf, -1, -np.inf, 1, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dz = [-inf, -1] and Dy = [-inf, 1]. + (-np.inf, -1, -np.inf, 1, -np.inf, -1, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = [-inf, 1] and Dy = Dz = [-inf, -1]. + (-np.inf, 1, -np.inf, -1, -np.inf, -1, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dy = [-inf, 1] and Dz = [-inf, -1]. + (-np.inf, 1, -np.inf, 1, -np.inf, -1, + (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dz = [-inf, 1] and Dy = [-inf, -1]. + (-np.inf, 1, -np.inf, -1, -np.inf, 1, + (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, 1] for each n (one at a time). + (-np.inf, 1, -np.inf, 0, -np.inf, 0, + (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)), + (-np.inf, 0, -np.inf, 1, -np.inf, 0, + (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)), + (-np.inf, 0, -np.inf, 0, -np.inf, 1, + (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, 1] for each n (two at a time). + (-np.inf, 1, -np.inf, 1, -np.inf, 0, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)), + (-np.inf, 1, -np.inf, 0, -np.inf, 1, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)), + (-np.inf, 0, -np.inf, 1, -np.inf, 1, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, 1] for all n. + (-np.inf, 1, -np.inf, 1, -np.inf, 1, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [0, inf] for all n. + (0, np.inf, 0, np.inf, 0, np.inf, (np.pi ** (3 / 2)) / 8), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [1, inf] for each n (one at a time). + (1, np.inf, 0, np.inf, 0, np.inf, + (np.pi ** (3 / 2)) / 8 * erfc(1)), + (0, np.inf, 1, np.inf, 0, np.inf, + (np.pi ** (3 / 2)) / 8 * erfc(1)), + (0, np.inf, 0, np.inf, 1, np.inf, + (np.pi ** (3 / 2)) / 8 * erfc(1)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [1, inf] for each n (two at a time). + (1, np.inf, 1, np.inf, 0, np.inf, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)), + (1, np.inf, 0, np.inf, 1, np.inf, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)), + (0, np.inf, 1, np.inf, 1, np.inf, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [1, inf] for all n. + (1, np.inf, 1, np.inf, 1, np.inf, + (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-1, inf] for each n (one at a time). + (-1, np.inf, 0, np.inf, 0, np.inf, + (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)), + (0, np.inf, -1, np.inf, 0, np.inf, + (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)), + (0, np.inf, 0, np.inf, -1, np.inf, + (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-1, inf] for each n (two at a time). + (-1, np.inf, -1, np.inf, 0, np.inf, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)), + (-1, np.inf, 0, np.inf, -1, np.inf, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)), + (0, np.inf, -1, np.inf, -1, np.inf, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-1, inf] for all n. + (-1, np.inf, -1, np.inf, -1, np.inf, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = [1, inf] and Dy = Dz = [-1, inf]. + (1, np.inf, -1, np.inf, -1, np.inf, + (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dy = [1, inf] and Dz = [-1, inf]. + (1, np.inf, 1, np.inf, -1, np.inf, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dz = [1, inf] and Dy = [-1, inf]. + (1, np.inf, -1, np.inf, 1, np.inf, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = [-1, inf] and Dy = Dz = [1, inf]. + (-1, np.inf, 1, np.inf, 1, np.inf, + (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dy = [-1, inf] and Dz = [1, inf]. + (-1, np.inf, -1, np.inf, 1, np.inf, + (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain Dx = Dz = [-1, inf] and Dy = [1, inf]. + (-1, np.inf, 1, np.inf, -1, np.inf, + (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [-inf, inf] for all n. + (-np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf, + np.pi ** (3 / 2)), + # Multiple integration of a function in n = 3 variables: f(x, y, z) + # over domain D = [0, 0] for each n (one at a time). + (0, 0, 0, np.inf, 0, np.inf, 0), + (0, np.inf, 0, 0, 0, np.inf, 0), + (0, np.inf, 0, np.inf, 0, 0, 0), + ], + ) + def test_triple_integral_improper( + self, + x_lower, + x_upper, + y_lower, + y_upper, + z_lower, + z_upper, + expected + ): + # The Gaussian Integral. + def f(x, y, z): + return np.exp(-x ** 2 - y ** 2 - z ** 2) + + assert_quad( + tplquad(f, x_lower, x_upper, y_lower, y_upper, z_lower, z_upper), + expected, + error_tolerance=6e-8 + ) + + +@make_xp_test_case(nquad) +class TestNQuad: + @pytest.mark.fail_slow(5) + def test_fixed_limits(self): + def func1(x0, x1, x2, x3): + val = (x0**2 + x1*x2 - x3**3 + np.sin(x0) + + (1 if (x0 - 0.2*x3 - 0.5 - 0.25*x1 > 0) else 0)) + return val + + def opts_basic(*args): + return {'points': [0.2*args[2] + 0.5 + 0.25*args[0]]} + + res = nquad(func1, [[0, 1], [-1, 1], [.13, .8], [-.15, 1]], + opts=[opts_basic, {}, {}, {}], full_output=True) + assert_quad(res[:-1], 1.5267454070738635) + assert_(res[-1]['neval'] > 0 and res[-1]['neval'] < 4e5) + + @pytest.mark.fail_slow(5) + def test_variable_limits(self): + scale = .1 + + def func2(x0, x1, x2, x3, t0, t1): + val = (x0*x1*x3**2 + np.sin(x2) + 1 + + (1 if x0 + t1*x1 - t0 > 0 else 0)) + return val + + def lim0(x1, x2, x3, t0, t1): + return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1, + scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1] + + def lim1(x2, x3, t0, t1): + return [scale * (t0*x2 + t1*x3) - 1, + scale * (t0*x2 + t1*x3) + 1] + + def lim2(x3, t0, t1): + return [scale * (x3 + t0**2*t1**3) - 1, + scale * (x3 + t0**2*t1**3) + 1] + + def lim3(t0, t1): + return [scale * (t0 + t1) - 1, scale * (t0 + t1) + 1] + + def opts0(x1, x2, x3, t0, t1): + return {'points': [t0 - t1*x1]} + + def opts1(x2, x3, t0, t1): + return {} + + def opts2(x3, t0, t1): + return {} + + def opts3(t0, t1): + return {} + + res = nquad(func2, [lim0, lim1, lim2, lim3], args=(0, 0), + opts=[opts0, opts1, opts2, opts3]) + assert_quad(res, 25.066666666666663) + + def test_square_separate_ranges_and_opts(self): + def f(y, x): + return 1.0 + + assert_quad(nquad(f, [[-1, 1], [-1, 1]], opts=[{}, {}]), 4.0) + + def test_square_aliased_ranges_and_opts(self): + def f(y, x): + return 1.0 + + r = [-1, 1] + opt = {} + assert_quad(nquad(f, [r, r], opts=[opt, opt]), 4.0) + + def test_square_separate_fn_ranges_and_opts(self): + def f(y, x): + return 1.0 + + def fn_range0(*args): + return (-1, 1) + + def fn_range1(*args): + return (-1, 1) + + def fn_opt0(*args): + return {} + + def fn_opt1(*args): + return {} + + ranges = [fn_range0, fn_range1] + opts = [fn_opt0, fn_opt1] + assert_quad(nquad(f, ranges, opts=opts), 4.0) + + def test_square_aliased_fn_ranges_and_opts(self): + def f(y, x): + return 1.0 + + def fn_range(*args): + return (-1, 1) + + def fn_opt(*args): + return {} + + ranges = [fn_range, fn_range] + opts = [fn_opt, fn_opt] + assert_quad(nquad(f, ranges, opts=opts), 4.0) + + def test_matching_quad(self): + def func(x): + return x**2 + 1 + + res, reserr = quad(func, 0, 4) + res2, reserr2 = nquad(func, ranges=[[0, 4]]) + assert_almost_equal(res, res2) + assert_almost_equal(reserr, reserr2) + + def test_matching_dblquad(self): + def func2d(x0, x1): + return x0**2 + x1**3 - x0 * x1 + 1 + + res, reserr = dblquad(func2d, -2, 2, lambda x: -3, lambda x: 3) + res2, reserr2 = nquad(func2d, [[-3, 3], (-2, 2)]) + assert_almost_equal(res, res2) + assert_almost_equal(reserr, reserr2) + + def test_matching_tplquad(self): + def func3d(x0, x1, x2, c0, c1): + return x0**2 + c0 * x1**3 - x0 * x1 + 1 + c1 * np.sin(x2) + + res = tplquad(func3d, -1, 2, lambda x: -2, lambda x: 2, + lambda x, y: -np.pi, lambda x, y: np.pi, + args=(2, 3)) + res2 = nquad(func3d, [[-np.pi, np.pi], [-2, 2], (-1, 2)], args=(2, 3)) + assert_almost_equal(res, res2) + + def test_dict_as_opts(self): + try: + nquad(lambda x, y: x * y, [[0, 1], [0, 1]], opts={'epsrel': 0.0001}) + except TypeError: + assert False + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_quadrature.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_quadrature.py new file mode 100644 index 0000000000000000000000000000000000000000..ca51e3d1f6a302c186cbcf607d5a6b5fee74e14e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_quadrature.py @@ -0,0 +1,756 @@ +# mypy: disable-error-code="attr-defined" +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_almost_equal, assert_allclose +from hypothesis import given +import hypothesis.strategies as st +import hypothesis.extra.numpy as hyp_num + +from scipy.integrate import (romb, newton_cotes, + cumulative_trapezoid, trapezoid, + quad, simpson, fixed_quad, + qmc_quad, cumulative_simpson) +from scipy.integrate._quadrature import _cumulative_simpson_unequal_intervals + +from scipy import stats, special, integrate +from scipy.conftest import skip_xp_invalid_arg +from scipy._lib._array_api import make_xp_test_case, xp_default_dtype, is_numpy +from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal + +skip_xp_backends = pytest.mark.skip_xp_backends + +@make_xp_test_case(fixed_quad) +class TestFixedQuad: + def test_scalar(self): + n = 4 + expected = 1/(2*n) + got, _ = fixed_quad(lambda x: x**(2*n - 1), 0, 1, n=n) + # quadrature exact for this input + assert_allclose(got, expected, rtol=1e-12) + + def test_vector(self): + n = 4 + p = np.arange(1, 2*n) + expected = 1/(p + 1) + got, _ = fixed_quad(lambda x: x**p[:, None], 0, 1, n=n) + assert_allclose(got, expected, rtol=1e-12) + + +@make_xp_test_case(romb) +class TestRomb: + def test_romb(self, xp): + xp_assert_equal(romb(xp.arange(17.0)), xp.asarray(128.0, dtype=xp.float64)) + + def test_romb_gh_3731(self, xp): + # Check that romb makes maximal use of data points + x = np.arange(2**4+1) + y = np.cos(0.2*x) + val = romb(xp.asarray(y)) + expected, _ = quad(lambda x: np.cos(np.array(0.2*x)), np.min(x), np.max(x)) + xp_assert_close(val, xp.asarray(expected, dtype=xp.float64), rtol=1e-8, atol=0) + + +@make_xp_test_case(newton_cotes) +class TestNewtonCotes: + def test_newton_cotes(self): + """Test the first few degrees, for evenly spaced points.""" + n = 1 + wts, errcoff = newton_cotes(n, 1) + assert_equal(wts, n*np.array([0.5, 0.5])) + assert_almost_equal(errcoff, -n**3/12.0) + + n = 2 + wts, errcoff = newton_cotes(n, 1) + assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0) + assert_almost_equal(errcoff, -n**5/2880.0) + + n = 3 + wts, errcoff = newton_cotes(n, 1) + assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0) + assert_almost_equal(errcoff, -n**5/6480.0) + + n = 4 + wts, errcoff = newton_cotes(n, 1) + assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0) + assert_almost_equal(errcoff, -n**7/1935360.0) + + def test_newton_cotes2(self): + """Test newton_cotes with points that are not evenly spaced.""" + + x = np.array([0.0, 1.5, 2.0]) + y = x**2 + wts, errcoff = newton_cotes(x) + exact_integral = 8.0/3 + numeric_integral = np.dot(wts, y) + assert_almost_equal(numeric_integral, exact_integral) + + x = np.array([0.0, 1.4, 2.1, 3.0]) + y = x**2 + wts, errcoff = newton_cotes(x) + exact_integral = 9.0 + numeric_integral = np.dot(wts, y) + assert_almost_equal(numeric_integral, exact_integral) + + +@make_xp_test_case(simpson) +class TestSimpson: + def test_simpson(self): + y = np.arange(17) + assert_equal(simpson(y), 128) + assert_equal(simpson(y, dx=0.5), 64) + assert_equal(simpson(y, x=np.linspace(0, 4, 17)), 32) + + # integral should be exactly 21 + x = np.linspace(1, 4, 4) + def f(x): + return x**2 + + assert_allclose(simpson(f(x), x=x), 21.0) + + # integral should be exactly 114 + x = np.linspace(1, 7, 4) + assert_allclose(simpson(f(x), dx=2.0), 114) + + # test multi-axis behaviour + a = np.arange(16).reshape(4, 4) + x = np.arange(64.).reshape(4, 4, 4) + y = f(x) + for i in range(3): + r = simpson(y, x=x, axis=i) + it = np.nditer(a, flags=['multi_index']) + for _ in it: + idx = list(it.multi_index) + idx.insert(i, slice(None)) + integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3 + assert_allclose(r[it.multi_index], integral) + + # test when integration axis only has two points + x = np.arange(16).reshape(8, 2) + y = f(x) + r = simpson(y, x=x, axis=-1) + + integral = 0.5 * (y[:, 1] + y[:, 0]) * (x[:, 1] - x[:, 0]) + assert_allclose(r, integral) + + # odd points, test multi-axis behaviour + a = np.arange(25).reshape(5, 5) + x = np.arange(125).reshape(5, 5, 5) + y = f(x) + for i in range(3): + r = simpson(y, x=x, axis=i) + it = np.nditer(a, flags=['multi_index']) + for _ in it: + idx = list(it.multi_index) + idx.insert(i, slice(None)) + integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3 + assert_allclose(r[it.multi_index], integral) + + # Tests for checking base case + x = np.array([3]) + y = np.power(x, 2) + assert_allclose(simpson(y, x=x, axis=0), 0.0) + assert_allclose(simpson(y, x=x, axis=-1), 0.0) + + x = np.array([3, 3, 3, 3]) + y = np.power(x, 2) + assert_allclose(simpson(y, x=x, axis=0), 0.0) + assert_allclose(simpson(y, x=x, axis=-1), 0.0) + + x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 2, 4, 8]]) + y = np.power(x, 2) + zero_axis = [0.0, 0.0, 0.0, 0.0] + default_axis = [170 + 1/3] * 3 # 8**3 / 3 - 1/3 + assert_allclose(simpson(y, x=x, axis=0), zero_axis) + # the following should be exact + assert_allclose(simpson(y, x=x, axis=-1), default_axis) + + x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 8, 16, 32]]) + y = np.power(x, 2) + zero_axis = [0.0, 136.0, 1088.0, 8704.0] + default_axis = [170 + 1/3, 170 + 1/3, 32**3 / 3 - 1/3] + assert_allclose(simpson(y, x=x, axis=0), zero_axis) + assert_allclose(simpson(y, x=x, axis=-1), default_axis) + + + @pytest.mark.parametrize('droplast', [False, True]) + def test_simpson_2d_integer_no_x(self, droplast): + # The inputs are 2d integer arrays. The results should be + # identical to the results when the inputs are floating point. + y = np.array([[2, 2, 4, 4, 8, 8, -4, 5], + [4, 4, 2, -4, 10, 22, -2, 10]]) + if droplast: + y = y[:, :-1] + result = simpson(y, axis=-1) + expected = simpson(np.array(y, dtype=np.float64), axis=-1) + assert_equal(result, expected) + + +@make_xp_test_case(cumulative_trapezoid) +class TestCumulative_trapezoid: + def test_1d(self, xp): + x = xp.linspace(-2, 2, num=5) + y = x + y_int = cumulative_trapezoid(y, x, initial=0) + y_expected = xp.asarray([0., -1.5, -2., -1.5, 0.]) + xp_assert_close(y_int, y_expected) + + y_int = cumulative_trapezoid(y, x, initial=None) + xp_assert_close(y_int, y_expected[1:]) + + def test_y_nd_x_nd(self, xp): + x = xp.reshape(xp.arange(3 * 2 * 4, dtype=xp_default_dtype(xp)), (3, 2, 4)) + y = x + y_int = cumulative_trapezoid(y, x, initial=0) + y_expected = xp.asarray([[[0., 0.5, 2., 4.5], + [0., 4.5, 10., 16.5]], + [[0., 8.5, 18., 28.5], + [0., 12.5, 26., 40.5]], + [[0., 16.5, 34., 52.5], + [0., 20.5, 42., 64.5]]]) + + xp_assert_close(y_int, y_expected) + + # Try with all axes + shapes = [(2, 2, 4), (3, 1, 4), (3, 2, 3)] + for axis, shape in zip([0, 1, 2], shapes): + y_int = cumulative_trapezoid(y, x, initial=0, axis=axis) + assert y_int.shape == (3, 2, 4) + y_int = cumulative_trapezoid(y, x, initial=None, axis=axis) + assert y_int.shape == shape + + def test_y_nd_x_1d(self, xp): + y = xp.reshape(xp.arange(3 * 2 * 4, dtype=xp_default_dtype(xp)), (3, 2, 4)) + x = xp.arange(4, dtype=xp_default_dtype(xp))**2 + # Try with all axes + ys_expected = ( + xp.asarray([[[4., 5., 6., 7.], + [8., 9., 10., 11.]], + [[40., 44., 48., 52.], + [56., 60., 64., 68.]]]), + xp.asarray([[[2., 3., 4., 5.]], + [[10., 11., 12., 13.]], + [[18., 19., 20., 21.]]]), + xp.asarray([[[0.5, 5., 17.5], + [4.5, 21., 53.5]], + [[8.5, 37., 89.5], + [12.5, 53., 125.5]], + [[16.5, 69., 161.5], + [20.5, 85., 197.5]]])) + + for axis, y_expected in zip([0, 1, 2], ys_expected): + y_int = cumulative_trapezoid(y, x=x[:y.shape[axis]], axis=axis, + initial=None) + xp_assert_close(y_int, y_expected) + + def test_x_none(self, xp): + y = xp.linspace(-2, 2, num=5) + + y_int = cumulative_trapezoid(y) + y_expected = xp.asarray([-1.5, -2., -1.5, 0.]) + xp_assert_close(y_int, y_expected) + + y_int = cumulative_trapezoid(y, initial=0) + y_expected = xp.asarray([0, -1.5, -2., -1.5, 0.]) + xp_assert_close(y_int, y_expected) + + y_int = cumulative_trapezoid(y, dx=3) + y_expected = xp.asarray([-4.5, -6., -4.5, 0.]) + xp_assert_close(y_int, y_expected) + + y_int = cumulative_trapezoid(y, dx=3, initial=0) + y_expected = xp.asarray([0, -4.5, -6., -4.5, 0.]) + xp_assert_close(y_int, y_expected) + + @pytest.mark.parametrize( + "initial", [1, 0.5] + ) + def test_initial_error(self, initial, xp): + """If initial is not None or 0, a ValueError is raised.""" + y = xp.linspace(0, 10, num=10) + with pytest.raises(ValueError, match="`initial`"): + cumulative_trapezoid(y, initial=initial) + + def test_zero_len_y(self, xp): + with pytest.raises(ValueError, match="At least one point is required"): + cumulative_trapezoid(y=xp.asarray([])) + + +@make_xp_test_case(trapezoid) +class TestTrapezoid: + def test_simple(self, xp): + x = xp.arange(-10, 10, .1) + r = trapezoid(xp.exp(-.5 * x ** 2) / xp.sqrt(2 * xp.asarray(xp.pi)), dx=0.1) + # check integral of normal equals 1 + xp_assert_close(r, xp.asarray(1.0)) + + def test_ndim(self, xp): + x = xp.linspace(0, 1, 3) + y = xp.linspace(0, 2, 8) + z = xp.linspace(0, 3, 13) + + wx = xp.ones_like(x) * (x[1] - x[0]) + wx[0] /= 2 + wx[-1] /= 2 + wy = xp.ones_like(y) * (y[1] - y[0]) + wy[0] /= 2 + wy[-1] /= 2 + wz = xp.ones_like(z) * (z[1] - z[0]) + wz[0] /= 2 + wz[-1] /= 2 + + q = x[:, None, None] + y[None,:, None] + z[None, None,:] + + qx = xp.sum(q * wx[:, None, None], axis=0) + qy = xp.sum(q * wy[None, :, None], axis=1) + qz = xp.sum(q * wz[None, None, :], axis=2) + + # n-d `x` + r = trapezoid(q, x=x[:, None, None], axis=0) + xp_assert_close(r, qx) + r = trapezoid(q, x=y[None,:, None], axis=1) + xp_assert_close(r, qy) + r = trapezoid(q, x=z[None, None,:], axis=2) + xp_assert_close(r, qz) + + # 1-d `x` + r = trapezoid(q, x=x, axis=0) + xp_assert_close(r, qx) + r = trapezoid(q, x=y, axis=1) + xp_assert_close(r, qy) + r = trapezoid(q, x=z, axis=2) + xp_assert_close(r, qz) + + def test_gh21908(self, xp): + # extended testing for n-dim arrays + x = xp.reshape(xp.linspace(0, 29, 30), (3, 10)) + y = xp.reshape(xp.linspace(0, 29, 30), (3, 10)) + + out0 = xp.linspace(200, 380, 10) + xp_assert_close(trapezoid(y, x=x, axis=0), out0) + xp_assert_close(trapezoid(y, x=xp.asarray([0, 10., 20.]), axis=0), out0) + # x needs to be broadcastable against y + xp_assert_close( + trapezoid(y, x=xp.asarray([0, 10., 20.])[:, None], axis=0), + out0 + ) + with pytest.raises(Exception): + # x is not broadcastable against y + trapezoid(y, x=xp.asarray([0, 10., 20.])[None, :], axis=0) + + out1 = xp.asarray([ 40.5, 130.5, 220.5]) + xp_assert_close(trapezoid(y, x=x, axis=1), out1) + xp_assert_close( + trapezoid(y, x=xp.linspace(0, 9, 10), axis=1), + out1 + ) + + @skip_xp_invalid_arg + def test_masked(self, xp): + # Testing that masked arrays behave as if the function is 0 where + # masked + x = np.arange(5) + y = x * x + mask = x == 2 + ym = np.ma.array(y, mask=mask) + r = 13.0 # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16)) + assert_allclose(trapezoid(ym, x), r) + + xm = np.ma.array(x, mask=mask) + assert_allclose(trapezoid(ym, xm), r) + + xm = np.ma.array(x, mask=mask) + assert_allclose(trapezoid(y, xm), r) + + def test_array_like(self): + x = list(range(5)) + y = [t * t for t in x] + xarr = np.asarray(x, dtype=np.float64) + yarr = np.asarray(y, dtype=np.float64) + res = trapezoid(y, x) + resarr = trapezoid(yarr, xarr) + xp_assert_close(res, resarr) + + +@make_xp_test_case(qmc_quad) +class TestQMCQuad: + def test_input_validation(self, xp): + a = xp.asarray([0., 0.]) + b = xp.asarray([1., 1.]) + + message = "`func` must be callable." + with pytest.raises(TypeError, match=message): + qmc_quad("a duck", a, b) + + message = "`func` must evaluate the integrand at points..." + with pytest.raises(ValueError, match=message): + qmc_quad(lambda: 1, a, b) + + def func(x): + assert x.ndim == 1 + return xp.sum(x) + message = "Exception encountered when attempting vectorized call..." + if is_numpy(xp): + with pytest.warns(UserWarning, match=message): + qmc_quad(func, a, b) + else: + with pytest.raises(ValueError, match=message): + qmc_quad(func, a, b) + + message = "`n_points` must be an integer." + with pytest.raises(TypeError, match=message): + qmc_quad(lambda x: 1, a, b, n_points=1024.5) + + message = "`n_estimates` must be an integer." + with pytest.raises(TypeError, match=message): + qmc_quad(lambda x: 1, a, b, n_estimates=8.5) + + message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine." + with pytest.raises(TypeError, match=message): + qmc_quad(lambda x: 1, a, b, qrng="a duck") + + message = "`qrng` must be initialized with dimensionality equal to " + with pytest.raises(ValueError, match=message): + qmc_quad(lambda x: 1, a, b, qrng=stats.qmc.Sobol(1)) + + message = r"`log` must be boolean \(`True` or `False`\)." + with pytest.raises(TypeError, match=message): + qmc_quad(lambda x: 1, a, b, log=10) + + def basic_test(self, n_points=2**8, n_estimates=8, signs=None, xp=None): + dtype = xp_default_dtype(xp) + if signs is None: + signs = np.ones(2) + ndim = 2 + mean = np.zeros(ndim) + cov = np.eye(ndim) + + def func(x): + # standard multivariate normal PDF in two dimensions + return xp.exp(-0.5 * xp.sum(x*x, axis=0)) / (2 * xp.pi) + + rng = np.random.default_rng(2879434385674690281) + qrng = stats.qmc.Sobol(ndim, seed=rng) + a = np.zeros(ndim) + b = np.ones(ndim) * signs + res = qmc_quad(func, xp.asarray(a, dtype=dtype), xp.asarray(b, dtype=dtype), + n_points=n_points, n_estimates=n_estimates, qrng=qrng) + ref = stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a) + atol = special.stdtrit(n_estimates-1, 0.995) * res.standard_error # 99% CI + xp_assert_close(res.integral, xp.asarray(ref, dtype=dtype), atol=atol) + assert np.prod(signs)*res.integral > 0 + + rng = np.random.default_rng(2879434385674690281) + qrng = stats.qmc.Sobol(ndim, seed=rng) + logres = qmc_quad(lambda *args: xp.log(func(*args)), + xp.asarray(a, dtype=dtype), xp.asarray(b, dtype=dtype), + n_points=n_points, n_estimates=n_estimates, + log=True, qrng=qrng) + rtol = 1e-14 if res.integral.dtype == xp.float64 else 2e-6 + xp_assert_close(xp.real(xp.exp(logres.integral)), res.integral, rtol=rtol) + assert xp.imag(logres.integral + 0j) == (xp.pi if np.prod(signs) < 0 else 0) + xp_assert_close(xp.exp(logres.standard_error), + res.standard_error, rtol=rtol, atol=rtol/100) + + @pytest.mark.parametrize("n_points", [2**8, 2**12]) + @pytest.mark.parametrize("n_estimates", [8, 16]) + def test_basic(self, n_points, n_estimates, xp): + self.basic_test(n_points, n_estimates, xp=xp) + + @pytest.mark.parametrize("signs", [[1., 1.], [-1., -1.], [-1., 1.], [1., -1.]]) + def test_sign(self, signs, xp): + self.basic_test(signs=signs, xp=xp) + + @pytest.mark.parametrize("log", [False, True]) + def test_zero(self, log, xp): + message = "A lower limit was equal to an upper limit, so" + with pytest.warns(UserWarning, match=message): + res = qmc_quad(lambda x: 1, xp.asarray([0, 0]), xp.asarray([0, 1]), log=log) + assert res.integral == (-xp.inf if log else 0) + assert res.standard_error == 0 + + def test_flexible_input(self): + # check that qrng is not required + # also checks that for 1d problems, a and b can be scalars + def func(x): + return stats.norm.pdf(x, scale=2) + + res = qmc_quad(func, 0, 1) + ref = stats.norm.cdf(1, scale=2) - stats.norm.cdf(0, scale=2) + assert_allclose(res.integral, ref, 1e-2) + + +def cumulative_simpson_nd_reference(y, *, x=None, dx=None, initial=None, axis=-1): + # Use cumulative_trapezoid if length of y < 3 + if y.shape[axis] < 3: + if initial is None: + return cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=None) + else: + return initial + cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=0) + + # Ensure that working axis is last axis + y = np.moveaxis(y, axis, -1) + x = np.moveaxis(x, axis, -1) if np.ndim(x) > 1 else x + dx = np.moveaxis(dx, axis, -1) if np.ndim(dx) > 1 else dx + initial = np.moveaxis(initial, axis, -1) if np.ndim(initial) > 1 else initial + + # If `x` is not present, create it from `dx` + n = y.shape[-1] + x = dx * np.arange(n) if dx is not None else x + # Similarly, if `initial` is not present, set it to 0 + initial_was_none = initial is None + initial = 0 if initial_was_none else initial + + # `np.apply_along_axis` accepts only one array, so concatenate arguments + x = np.broadcast_to(x, y.shape) + initial = np.broadcast_to(initial, y.shape[:-1] + (1,)) + z = np.concatenate((y, x, initial), axis=-1) + + # Use `np.apply_along_axis` to compute result + def f(z): + return cumulative_simpson(z[:n], x=z[n:2*n], initial=z[2*n:]) + res = np.apply_along_axis(f, -1, z) + + # Remove `initial` and undo axis move as needed + res = res[..., 1:] if initial_was_none else res + res = np.moveaxis(res, -1, axis) + return res + + +@make_xp_test_case(cumulative_simpson) +class TestCumulativeSimpson: + x0 = np.arange(4) + y0 = x0**2 + + @pytest.mark.parametrize('use_dx', (False, True)) + @pytest.mark.parametrize('use_initial', (False, True)) + def test_1d(self, use_dx, use_initial, xp): + # Test for exact agreement with polynomial of highest + # possible order (3 if `dx` is constant, 2 otherwise). + rng = np.random.default_rng(82456839535679456794) + n = 10 + + # Generate random polynomials and ground truth + # integral of appropriate order + order = 3 if use_dx else 2 + dx = xp.asarray(rng.random()) + if order == 2: + x = xp.asarray(np.sort(rng.random(n))) + else: + x = xp.arange(n, dtype=xp.float64)*dx + xp.asarray(rng.random()) + i = xp.arange(order + 1, dtype=xp.float64)[:, xp.newaxis] + c = xp.asarray(rng.random(order + 1))[:, xp.newaxis] + y = xp.sum(c*x**i, axis=0) + Y = xp.sum(c*x**(i + 1)/(i + 1), axis=0) + ref = Y if use_initial else (Y-Y[0])[1:] + + # Integrate with `cumulative_simpson` + initial = Y[0] if use_initial else None + kwarg = {'dx': dx} if use_dx else {'x': x} + res = cumulative_simpson(y, **kwarg, initial=initial) + + # Compare result against reference + if not use_dx: + xp_assert_close(res, ref, rtol=2e-15) + else: + i0 = 0 if use_initial else 1 + # all terms are "close" + xp_assert_close(res, ref, rtol=0.0025) + # only even-interval terms are "exact" + xp_assert_close(res[i0::2], ref[i0::2], rtol=2e-15) + + @skip_xp_backends(cpu_only=True) # uses np.apply_along_axis + @pytest.mark.parametrize('axis', np.arange(-3, 3)) + @pytest.mark.parametrize('x_ndim', (1, 3)) + @pytest.mark.parametrize('x_len', (1, 2, 7)) + @pytest.mark.parametrize('i_ndim', (None, 0, 3,)) + @pytest.mark.parametrize('dx', (None, True)) + def test_nd(self, axis, x_ndim, x_len, i_ndim, dx, xp): + # Test behavior of `cumulative_simpson` with N-D `y` + rng = np.random.default_rng(82456839535679456794) + + # determine shapes + shape = [5, 6, x_len] + shape[axis], shape[-1] = shape[-1], shape[axis] + shape_len_1 = shape.copy() + shape_len_1[axis] = 1 + i_shape = shape_len_1 if i_ndim == 3 else () + + # initialize arguments + y = xp.asarray(rng.random(size=shape)) + x, dx = None, None + if dx: + dx = rng.random(size=shape_len_1) if x_ndim > 1 else rng.random() + dx = xp.asarray(dx) + else: + x = (np.sort(rng.random(size=shape), axis=axis) if x_ndim > 1 + else np.sort(rng.random(size=shape[axis]))) + x = xp.asarray(x) + initial = None if i_ndim is None else xp.asarray(rng.random(size=i_shape)) + + # compare results + res = cumulative_simpson(y, x=x, dx=dx, initial=initial, axis=axis) + # use np to generate `ref` as `cumulative_simpson_nd_ref` + # uses `apply_along_axis` + ref = cumulative_simpson_nd_reference( + np.asarray(y), x=np.asarray(x), dx=None if dx is None else np.asarray(dx), + initial=None if initial is None else np.asarray(initial), axis=axis + ) + xp_assert_close(res, xp.asarray(ref), rtol=1e-15) + + @pytest.mark.parametrize(('message', 'kwarg_update'), [ + ("x must be strictly increasing", dict(x=[2, 2, 3, 4])), + ("x must be strictly increasing", dict(x=[x0, [2, 2, 4, 8]], y=[y0, y0])), + ("x must be strictly increasing", dict(x=[x0, x0, x0], y=[y0, y0, y0], axis=0)), + ("At least one point is required", dict(x=[], y=[])), + ("`axis=4` is not valid for `y` with `y.ndim=1`", dict(axis=4)), + ("shape of `x` must be the same as `y` or 1-D", dict(x=np.arange(5))), + ("`initial` must either be a scalar or...", dict(initial=np.arange(5))), + ("`dx` must either be a scalar or...", dict(x=None, dx=np.arange(5))), + ]) + def test_simpson_exceptions(self, message, kwarg_update, xp): + kwargs0 = dict(y=xp.asarray(self.y0), x=xp.asarray(self.x0), dx=None, + initial=None, axis=-1) + kwarg_update = {k: xp.asarray(np.asarray(v)) if isinstance(v, list) else v + for k, v in kwarg_update.items()} + with pytest.raises(ValueError, match=message): + cumulative_simpson(**dict(kwargs0, **kwarg_update)) + + def test_special_cases(self, xp): + # Test special cases not checked elsewhere + rng = np.random.default_rng(82456839535679456794) + y = xp.asarray(rng.random(size=10)) + res = cumulative_simpson(y, dx=0.) + xp_assert_equal(res, xp.zeros(9, dtype=xp.float64)) + + # Should add tests of: + # - all elements of `x` identical + # These should work as they do for `simpson` + + def _get_theoretical_diff_between_simps_and_cum_simps(self, y, x): + """`cumulative_simpson` and `simpson` can be tested against other to verify + they give consistent results. `simpson` will iteratively be called with + successively higher upper limits of integration. This function calculates + the theoretical correction required to `simpson` at even intervals to match + with `cumulative_simpson`. + """ + d = np.diff(x, axis=-1) + sub_integrals_h1 = _cumulative_simpson_unequal_intervals(y, d) + sub_integrals_h2 = _cumulative_simpson_unequal_intervals( + y[..., ::-1], d[..., ::-1] + )[..., ::-1] + + # Concatenate to build difference array + zeros_shape = (*y.shape[:-1], 1) + theoretical_difference = np.concatenate( + [ + np.zeros(zeros_shape), + (sub_integrals_h1[..., 1:] - sub_integrals_h2[..., :-1]), + np.zeros(zeros_shape), + ], + axis=-1, + ) + # Differences only expected at even intervals. Odd intervals will + # match exactly so there is no correction + theoretical_difference[..., 1::2] = 0.0 + # Note: the first interval will not match from this correction as + # `simpson` uses the trapezoidal rule + return theoretical_difference + + @pytest.mark.fail_slow(10) + @pytest.mark.slow + @given( + y=hyp_num.arrays( + np.float64, + hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10), + elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7) + ) + ) + def test_cumulative_simpson_against_simpson_with_default_dx( + self, y, xp + ): + """Theoretically, the output of `cumulative_simpson` will be identical + to `simpson` at all even indices and in the last index. The first index + will not match as `simpson` uses the trapezoidal rule when there are only two + data points. Odd indices after the first index are shown to match with + a mathematically-derived correction.""" + def simpson_reference(y): + return np.stack( + [simpson(y[..., :i], dx=1.0) for i in range(2, y.shape[-1]+1)], axis=-1, + ) + + res = cumulative_simpson(xp.asarray(y), dx=1.0) + ref = simpson_reference(y) + theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps( + y, x=np.arange(y.shape[-1]) + ) + xp_assert_close( + res[..., 1:], xp.asarray(ref[..., 1:] + theoretical_difference[..., 1:]), + atol=1e-16 + ) + + @pytest.mark.fail_slow(10) + @pytest.mark.slow + @given( + y=hyp_num.arrays( + np.float64, + hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10), + elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7) + ) + ) + def test_cumulative_simpson_against_simpson( + self, y, xp + ): + """Theoretically, the output of `cumulative_simpson` will be identical + to `simpson` at all even indices and in the last index. The first index + will not match as `simpson` uses the trapezoidal rule when there are only two + data points. Odd indices after the first index are shown to match with + a mathematically-derived correction.""" + interval = 10/(y.shape[-1] - 1) + x = np.linspace(0, 10, num=y.shape[-1]) + x[1:] = x[1:] + 0.2*interval*np.random.uniform(-1, 1, len(x) - 1) + + def simpson_reference(y, x): + return np.stack( + [simpson(y[..., :i], x=x[..., :i]) for i in range(2, y.shape[-1]+1)], + axis=-1, + ) + + res = cumulative_simpson(xp.asarray(y), x=xp.asarray(x)) + ref = simpson_reference(y, x) + theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps( + y, x + ) + xp_assert_close( + res[..., 1:], xp.asarray(ref[..., 1:] + theoretical_difference[..., 1:]) + ) + + +@make_xp_test_case(integrate.lebedev_rule) +class TestLebedev: + def test_input_validation(self): + # only certain rules are available + message = "Order n=-1 not available..." + with pytest.raises(NotImplementedError, match=message): + integrate.lebedev_rule(-1) + + def test_quadrature(self): + # Test points/weights to integrate an example function + + def f(x): + return np.exp(x[0]) + + x, w = integrate.lebedev_rule(15) + res = w @ f(x) + ref = 14.7680137457653 # lebedev_rule reference [3] + assert_allclose(res, ref, rtol=1e-14) + assert_allclose(np.sum(w), 4 * np.pi) + + @pytest.mark.parametrize('order', list(range(3, 32, 2)) + list(range(35, 132, 6))) + def test_properties(self, order): + x, w = integrate.lebedev_rule(order) + # dispersion should be maximal; no clear spherical mean + with np.errstate(divide='ignore', invalid='ignore'): + res = stats.directional_stats(x.T, axis=0) + assert_allclose(res.mean_resultant_length, 0, atol=1e-15) + # weights should sum to 4*pi (surface area of unit sphere) + assert_allclose(np.sum(w), 4*np.pi) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_tanhsinh.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_tanhsinh.py new file mode 100644 index 0000000000000000000000000000000000000000..c05e41238243b99646285fe056193af1dc89c787 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/integrate/tests/test_tanhsinh.py @@ -0,0 +1,1158 @@ +# mypy: disable-error-code="attr-defined" +import os +import pytest +import math + +import numpy as np +from numpy.testing import assert_allclose + +import scipy._lib._elementwise_iterative_method as eim +from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal +from scipy._lib._array_api import (array_namespace, xp_size, xp_ravel, xp_copy, + is_numpy, make_xp_test_case) +from scipy import special, stats +from scipy.integrate import quad_vec, nsum, tanhsinh as _tanhsinh +from scipy.integrate._tanhsinh import _pair_cache +from scipy.special._ufuncs import _gen_harmonic + + +def norm_pdf(x, xp=None): + xp = array_namespace(x) if xp is None else xp + return 1/(2*xp.pi)**0.5 * xp.exp(-x**2/2) + + +def norm_logpdf(x, xp=None): + xp = array_namespace(x) if xp is None else xp + return -0.5*math.log(2*xp.pi) - x**2/2 + + +def _vectorize(xp): + # xp-compatible version of np.vectorize + # assumes arguments are all arrays of the same shape + def decorator(f): + def wrapped(*arg_arrays): + shape = arg_arrays[0].shape + arg_arrays = [xp_ravel(arg_array) for arg_array in arg_arrays] + res = [] + for i in range(math.prod(shape)): + arg_scalars = [arg_array[i] for arg_array in arg_arrays] + res.append(f(*arg_scalars)) + return res + + return wrapped + + return decorator + + +@make_xp_test_case(_tanhsinh) +class TestTanhSinh: + + # Test problems from [1] Section 6 + def f1(self, t): + return t * np.log(1 + t) + + f1.ref = 0.25 + f1.b = 1 + + def f2(self, t): + return t ** 2 * np.arctan(t) + + f2.ref = (np.pi - 2 + 2 * np.log(2)) / 12 + f2.b = 1 + + def f3(self, t): + return np.exp(t) * np.cos(t) + + f3.ref = (np.exp(np.pi / 2) - 1) / 2 + f3.b = np.pi / 2 + + def f4(self, t): + a = np.sqrt(2 + t ** 2) + return np.arctan(a) / ((1 + t ** 2) * a) + + f4.ref = 5 * np.pi ** 2 / 96 + f4.b = 1 + + def f5(self, t): + return np.sqrt(t) * np.log(t) + + f5.ref = -4 / 9 + f5.b = 1 + + def f6(self, t): + return np.sqrt(1 - t ** 2) + + f6.ref = np.pi / 4 + f6.b = 1 + + def f7(self, t): + return np.sqrt(t) / np.sqrt(1 - t ** 2) + + f7.ref = 2 * np.sqrt(np.pi) * special.gamma(3 / 4) / special.gamma(1 / 4) + f7.b = 1 + + def f8(self, t): + return np.log(t) ** 2 + + f8.ref = 2 + f8.b = 1 + + def f9(self, t): + return np.log(np.cos(t)) + + f9.ref = -np.pi * np.log(2) / 2 + f9.b = np.pi / 2 + + def f10(self, t): + return np.sqrt(np.tan(t)) + + f10.ref = np.pi * np.sqrt(2) / 2 + f10.b = np.pi / 2 + + def f11(self, t): + return 1 / (1 + t ** 2) + + f11.ref = np.pi / 2 + f11.b = np.inf + + def f12(self, t): + return np.exp(-t) / np.sqrt(t) + + f12.ref = np.sqrt(np.pi) + f12.b = np.inf + + def f13(self, t): + return np.exp(-t ** 2 / 2) + + f13.ref = np.sqrt(np.pi / 2) + f13.b = np.inf + + def f14(self, t): + return np.exp(-t) * np.cos(t) + + f14.ref = 0.5 + f14.b = np.inf + + def f15(self, t): + return np.sin(t) / t + + f15.ref = np.pi / 2 + f15.b = np.inf + + def error(self, res, ref, log=False, xp=None): + xp = array_namespace(res, ref) if xp is None else xp + err = abs(res - ref) + + if not log: + return err + + with np.errstate(divide='ignore'): + return xp.log10(err) + + def test_input_validation(self, xp): + f = self.f1 + + zero = xp.asarray(0) + f_b = xp.asarray(f.b) + + message = '`f` must be callable.' + with pytest.raises(ValueError, match=message): + _tanhsinh(42, zero, f_b) + + message = '...must be True or False.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, log=2) + + message = '...must be real numbers.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, xp.asarray(1+1j), f_b) + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, atol='ekki') + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, rtol=pytest) + + message = '...must be non-negative and finite.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, rtol=-1) + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, atol=xp.inf) + + message = '...may not be positive infinity.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, rtol=xp.inf, log=True) + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, atol=xp.inf, log=True) + + message = '...must be integers.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, maxlevel=object()) + # with pytest.raises(ValueError, match=message): # unused for now + # _tanhsinh(f, zero, f_b, maxfun=1+1j) + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, minlevel="migratory coconut") + + message = '...must be non-negative.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, maxlevel=-1) + # with pytest.raises(ValueError, match=message): # unused for now + # _tanhsinh(f, zero, f_b, maxfun=-1) + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, minlevel=-1) + + message = '...must be True or False.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, preserve_shape=2) + + message = '...must be callable.' + with pytest.raises(ValueError, match=message): + _tanhsinh(f, zero, f_b, callback='elderberry') + + @pytest.mark.parametrize("limits, ref", [ + [(0, math.inf), 0.5], # b infinite + [(-math.inf, 0), 0.5], # a infinite + [(-math.inf, math.inf), 1.], # a and b infinite + [(math.inf, -math.inf), -1.], # flipped limits + [(1, -1), stats.norm.cdf(-1.) - stats.norm.cdf(1.)], # flipped limits + ]) + def test_integral_transforms(self, limits, ref, xp): + # Check that the integral transforms are behaving for both normal and + # log integration + limits = [xp.asarray(limit) for limit in limits] + dtype = xp.asarray(float(limits[0])).dtype + ref = xp.asarray(ref, dtype=dtype) + + res = _tanhsinh(norm_pdf, *limits) + xp_assert_close(res.integral, ref) + + logres = _tanhsinh(norm_logpdf, *limits, log=True) + xp_assert_close(xp.exp(logres.integral), ref, check_dtype=False) + # Transformation should not make the result complex unnecessarily + assert (xp.isdtype(logres.integral.dtype, "real floating") if ref > 0 + else xp.isdtype(logres.integral.dtype, "complex floating")) + + atol = 2 * xp.finfo(res.error.dtype).eps + xp_assert_close(xp.exp(logres.error), res.error, atol=atol, check_dtype=False) + + # 15 skipped intentionally; it's very difficult numerically + @pytest.mark.skip_xp_backends(np_only=True, + reason='Cumbersome to convert everything.') + @pytest.mark.parametrize('f_number', range(1, 15)) + def test_basic(self, f_number, xp): + f = getattr(self, f"f{f_number}") + rtol = 2e-8 + res = _tanhsinh(f, 0, f.b, rtol=rtol) + assert_allclose(res.integral, f.ref, rtol=rtol) + if f_number not in {7, 12, 14}: # mildly underestimates error here + true_error = abs(self.error(res.integral, f.ref)/res.integral) + assert true_error < res.error + + if f_number in {7, 10, 12}: # succeeds, but doesn't know it + return + + assert res.success + assert res.status == 0 + + @pytest.mark.skip_xp_backends(np_only=True, + reason="Distributions aren't xp-compatible.") + @pytest.mark.parametrize('ref', (0.5, [0.4, 0.6])) + @pytest.mark.parametrize('case', stats._distr_params.distcont) + def test_accuracy(self, ref, case, xp): + distname, params = case + if distname in {'dgamma', 'dweibull', 'laplace', 'kstwo'}: + # should split up interval at first-derivative discontinuity + pytest.skip('tanh-sinh is not great for non-smooth integrands') + if (distname in {'studentized_range', 'levy_stable'} + and not int(os.getenv('SCIPY_XSLOW', 0))): + pytest.skip('This case passes, but it is too slow.') + dist = getattr(stats, distname)(*params) + x = dist.interval(ref) + res = _tanhsinh(dist.pdf, *x) + assert_allclose(res.integral, ref) + + @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) + def test_vectorization(self, shape, xp): + # Test for correct functionality, output shapes, and dtypes for various + # input shapes. + rng = np.random.default_rng(82456839535679456794) + a = xp.asarray(rng.random(shape)) + b = xp.asarray(rng.random(shape)) + p = xp.asarray(rng.random(shape)) + n = math.prod(shape) + + def f(x, p): + f.ncall += 1 + f.feval += 1 if (xp_size(x) == n or x.ndim <= 1) else x.shape[-1] + return x**p + f.ncall = 0 + f.feval = 0 + + @_vectorize(xp) + def _tanhsinh_single(a, b, p): + return _tanhsinh(lambda x: x**p, a, b) + + res = _tanhsinh(f, a, b, args=(p,)) + refs = _tanhsinh_single(a, b, p) + + attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel'] + for attr in attrs: + ref_attr = xp.stack([getattr(ref, attr) for ref in refs]) + res_attr = xp_ravel(getattr(res, attr)) + xp_assert_close(res_attr, ref_attr, rtol=1e-15) + assert getattr(res, attr).shape == shape + + assert xp.isdtype(res.success.dtype, 'bool') + assert xp.isdtype(res.status.dtype, 'integral') + assert xp.isdtype(res.nfev.dtype, 'integral') + assert xp.isdtype(res.maxlevel.dtype, 'integral') + assert xp.max(res.nfev) == f.feval + # maxlevel = 2 -> 3 function calls (2 initialization, 1 work) + assert xp.max(res.maxlevel) >= 2 + assert xp.max(res.maxlevel) == f.ncall + + def test_flags(self, xp): + # Test cases that should produce different status flags; show that all + # can be produced simultaneously. + def f(xs, js): + f.nit += 1 + funcs = [lambda x: xp.exp(-x**2), # converges + lambda x: xp.exp(x), # reaches maxiter due to order=2 + lambda x: xp.full_like(x, xp.nan)] # stops due to NaN + res = [] + for i in range(xp_size(js)): + x = xs[i, ...] + j = int(xp_ravel(js)[i]) + res.append(funcs[j](x)) + return xp.stack(res) + f.nit = 0 + + args = (xp.arange(3, dtype=xp.int64),) + a = xp.asarray([xp.inf]*3) + b = xp.asarray([-xp.inf] * 3) + res = _tanhsinh(f, a, b, maxlevel=5, args=args) + ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32) + xp_assert_equal(res.status, ref_flags) + + def test_flags_preserve_shape(self, xp): + # Same test as above but using `preserve_shape` option to simplify. + def f(x): + res = [xp.exp(-x[0]**2), # converges + xp.exp(x[1]), # reaches maxiter due to order=2 + xp.full_like(x[2], xp.nan)] # stops due to NaN + return xp.stack(res) + + a = xp.asarray([xp.inf] * 3) + b = xp.asarray([-xp.inf] * 3) + res = _tanhsinh(f, a, b, maxlevel=5, preserve_shape=True) + ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32) + xp_assert_equal(res.status, ref_flags) + + def test_preserve_shape(self, xp): + # Test `preserve_shape` option + def f(x, xp): + return xp.stack([xp.stack([x, xp.sin(10 * x)]), + xp.stack([xp.cos(30 * x), x * xp.sin(100 * x)])]) + + ref = quad_vec(lambda x: f(x, np), 0, 1) + res = _tanhsinh(lambda x: f(x, xp), xp.asarray(0), xp.asarray(1), + preserve_shape=True) + dtype = xp.asarray(0.).dtype + xp_assert_close(res.integral, xp.asarray(ref[0], dtype=dtype)) + + def test_convergence(self, xp): + # demonstrate that number of accurate digits doubles each iteration + dtype = xp.float64 # this only works with good precision + def f(t): + return t * xp.log(1 + t) + ref = xp.asarray(0.25, dtype=dtype) + a, b = xp.asarray(0., dtype=dtype), xp.asarray(1., dtype=dtype) + + last_logerr = 0 + for i in range(4): + res = _tanhsinh(f, a, b, minlevel=0, maxlevel=i) + logerr = self.error(res.integral, ref, log=True, xp=xp) + assert (logerr < last_logerr * 2 or logerr < -15.5) + last_logerr = logerr + + def test_options_and_result_attributes(self, xp): + # demonstrate that options are behaving as advertised and status + # messages are as intended + def f(x): + f.calls += 1 + f.feval += xp_size(xp.asarray(x)) + return x**2 * xp.atan(x) + + f.ref = xp.asarray((math.pi - 2 + 2 * math.log(2)) / 12, dtype=xp.float64) + + default_rtol = 1e-12 + default_atol = f.ref * default_rtol # effective default absolute tol + + # Keep things simpler by leaving tolerances fixed rather than + # having to make them dtype-dependent + a = xp.asarray(0., dtype=xp.float64) + b = xp.asarray(1., dtype=xp.float64) + + # Test default options + f.feval, f.calls = 0, 0 + ref = _tanhsinh(f, a, b) + assert self.error(ref.integral, f.ref) < ref.error < default_atol + assert ref.nfev == f.feval + ref.calls = f.calls # reference number of function calls + assert ref.success + assert ref.status == 0 + + # Test `maxlevel` equal to required max level + # We should get all the same results + f.feval, f.calls = 0, 0 + maxlevel = int(ref.maxlevel) + res = _tanhsinh(f, a, b, maxlevel=maxlevel) + res.calls = f.calls + assert res == ref + + # Now reduce the maximum level. We won't meet tolerances. + f.feval, f.calls = 0, 0 + maxlevel -= 1 + assert maxlevel >= 2 # can't compare errors otherwise + res = _tanhsinh(f, a, b, maxlevel=maxlevel) + assert self.error(res.integral, f.ref) < res.error > default_atol + assert res.nfev == f.feval < ref.nfev + assert f.calls == ref.calls - 1 + assert not res.success + assert res.status == eim._ECONVERR + + # `maxfun` is currently not enforced + + # # Test `maxfun` equal to required number of function evaluations + # # We should get all the same results + # f.feval, f.calls = 0, 0 + # maxfun = ref.nfev + # res = _tanhsinh(f, 0, f.b, maxfun = maxfun) + # assert res == ref + # + # # Now reduce `maxfun`. We won't meet tolerances. + # f.feval, f.calls = 0, 0 + # maxfun -= 1 + # res = _tanhsinh(f, 0, f.b, maxfun=maxfun) + # assert self.error(res.integral, f.ref) < res.error > default_atol + # assert res.nfev == f.feval < ref.nfev + # assert f.calls == ref.calls - 1 + # assert not res.success + # assert res.status == 2 + + # Take this result to be the new reference + ref = res + ref.calls = f.calls + + # Test `atol` + f.feval, f.calls = 0, 0 + # With this tolerance, we should get the exact same result as ref + atol = np.nextafter(float(ref.error), np.inf) + res = _tanhsinh(f, a, b, rtol=0, atol=atol) + assert res.integral == ref.integral + assert res.error == ref.error + assert res.nfev == f.feval == ref.nfev + assert f.calls == ref.calls + # Except the result is considered to be successful + assert res.success + assert res.status == 0 + + f.feval, f.calls = 0, 0 + # With a tighter tolerance, we should get a more accurate result + atol = np.nextafter(float(ref.error), -np.inf) + res = _tanhsinh(f, a, b, rtol=0, atol=atol) + assert self.error(res.integral, f.ref) < res.error < atol + assert res.nfev == f.feval > ref.nfev + assert f.calls > ref.calls + assert res.success + assert res.status == 0 + + # Test `rtol` + f.feval, f.calls = 0, 0 + # With this tolerance, we should get the exact same result as ref + rtol = np.nextafter(float(ref.error/ref.integral), np.inf) + res = _tanhsinh(f, a, b, rtol=rtol) + assert res.integral == ref.integral + assert res.error == ref.error + assert res.nfev == f.feval == ref.nfev + assert f.calls == ref.calls + # Except the result is considered to be successful + assert res.success + assert res.status == 0 + + f.feval, f.calls = 0, 0 + # With a tighter tolerance, we should get a more accurate result + rtol = np.nextafter(float(ref.error/ref.integral), -np.inf) + res = _tanhsinh(f, a, b, rtol=rtol) + assert self.error(res.integral, f.ref)/f.ref < res.error/res.integral < rtol + assert res.nfev == f.feval > ref.nfev + assert f.calls > ref.calls + assert res.success + assert res.status == 0 + + @pytest.mark.skip_xp_backends('torch', reason= + 'https://github.com/scipy/scipy/pull/21149#issuecomment-2330477359', + ) + @pytest.mark.parametrize('rtol', [1e-4, 1e-14]) + def test_log(self, rtol, xp): + # Test equivalence of log-integration and regular integration + test_tols = dict(atol=1e-18, rtol=1e-15) + + # Positive integrand (real log-integrand) + a = xp.asarray(-1., dtype=xp.float64) + b = xp.asarray(2., dtype=xp.float64) + res = _tanhsinh(norm_logpdf, a, b, log=True, rtol=math.log(rtol)) + ref = _tanhsinh(norm_pdf, a, b, rtol=rtol) + xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols) + xp_assert_close(xp.exp(res.error), ref.error, **test_tols) + assert res.nfev == ref.nfev + + # Real integrand (complex log-integrand) + def f(x): + return -norm_logpdf(x)*norm_pdf(x) + + def logf(x): + return xp.log(norm_logpdf(x) + 0j) + norm_logpdf(x) + xp.pi * 1j + + a = xp.asarray(-xp.inf, dtype=xp.float64) + b = xp.asarray(xp.inf, dtype=xp.float64) + res = _tanhsinh(logf, a, b, log=True) + ref = _tanhsinh(f, a, b) + # In gh-19173, we saw `invalid` warnings on one CI platform. + # Silencing `all` because I can't reproduce locally and don't want + # to risk the need to run CI again. + with np.errstate(all='ignore'): + xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols, + check_dtype=False) + xp_assert_close(xp.exp(res.error), ref.error, **test_tols, + check_dtype=False) + assert res.nfev == ref.nfev + + def test_complex(self, xp): + # Test integration of complex integrand + # Finite limits + def f(x): + return xp.exp(1j * x) + + a, b = xp.asarray(0.), xp.asarray(xp.pi/4) + res = _tanhsinh(f, a, b) + ref = math.sqrt(2)/2 + (1-math.sqrt(2)/2)*1j + xp_assert_close(res.integral, xp.asarray(ref)) + + # Infinite limits + def f(x): + return norm_pdf(x) + 1j/2*norm_pdf(x/2) + + a, b = xp.asarray(xp.inf), xp.asarray(-xp.inf) + res = _tanhsinh(f, a, b) + xp_assert_close(res.integral, xp.asarray(-(1+1j))) + + @pytest.mark.parametrize("maxlevel", range(4)) + def test_minlevel(self, maxlevel, xp): + # Verify that minlevel does not change the values at which the + # integrand is evaluated or the integral/error estimates, only the + # number of function calls + + def f(x): + f.calls += 1 + f.feval += xp_size(xp.asarray(x)) + f.x = xp.concat((f.x, xp_ravel(x))) + return x**2 * xp.atan(x) + + f.feval, f.calls, f.x = 0, 0, xp.asarray([]) + + a = xp.asarray(0, dtype=xp.float64) + b = xp.asarray(1, dtype=xp.float64) + ref = _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel) + ref_x = xp.sort(f.x) + + for minlevel in range(0, maxlevel + 1): + f.feval, f.calls, f.x = 0, 0, xp.asarray([]) + options = dict(minlevel=minlevel, maxlevel=maxlevel) + res = _tanhsinh(f, a, b, **options) + # Should be very close; all that has changed is the order of values + xp_assert_close(res.integral, ref.integral, rtol=4e-16) + # Difference in absolute errors << magnitude of integral + xp_assert_close(res.error, ref.error, atol=4e-16 * ref.integral) + assert res.nfev == f.feval == f.x.shape[0] + assert f.calls == maxlevel - minlevel + 1 + 1 # 1 validation call + assert res.status == ref.status + xp_assert_equal(ref_x, xp.sort(f.x)) + + def test_improper_integrals(self, xp): + # Test handling of infinite limits of integration (mixed with finite limits) + def f(x): + x[xp.isinf(x)] = xp.nan + return xp.exp(-x**2) + a = xp.asarray([-xp.inf, 0, -xp.inf, xp.inf, -20, -xp.inf, -20]) + b = xp.asarray([xp.inf, xp.inf, 0, -xp.inf, 20, 20, xp.inf]) + ref = math.sqrt(math.pi) + ref = xp.asarray([ref, ref/2, ref/2, -ref, ref, ref, ref]) + res = _tanhsinh(f, a, b) + xp_assert_close(res.integral, ref) + + @pytest.mark.parametrize("limits", ((0, 3), ([-math.inf, 0], [3, 3]))) + @pytest.mark.parametrize("dtype", ('float32', 'float64')) + def test_dtype(self, limits, dtype, xp): + # Test that dtypes are preserved + dtype = getattr(xp, dtype) + a, b = xp.asarray(limits, dtype=dtype) + + def f(x): + assert x.dtype == dtype + return xp.exp(x) + + rtol = 1e-12 if dtype == xp.float64 else 1e-5 + res = _tanhsinh(f, a, b, rtol=rtol) + assert res.integral.dtype == dtype + assert res.error.dtype == dtype + assert xp.all(res.success) + xp_assert_close(res.integral, xp.exp(b)-xp.exp(a)) + + def test_maxiter_callback(self, xp): + # Test behavior of `maxiter` parameter and `callback` interface + a, b = xp.asarray(-xp.inf), xp.asarray(xp.inf) + def f(x): + return xp.exp(-x*x) + + minlevel, maxlevel = 0, 2 + maxiter = maxlevel - minlevel + 1 + kwargs = dict(minlevel=minlevel, maxlevel=maxlevel, rtol=1e-15) + res = _tanhsinh(f, a, b, **kwargs) + assert not res.success + assert res.maxlevel == maxlevel + + def callback(res): + callback.iter += 1 + callback.res = res + assert hasattr(res, 'integral') + assert res.status == 1 + if callback.iter == maxiter: + raise StopIteration + callback.iter = -1 # callback called once before first iteration + callback.res = None + + del kwargs['maxlevel'] + res2 = _tanhsinh(f, a, b, **kwargs, callback=callback) + # terminating with callback is identical to terminating due to maxiter + # (except for `status`) + for key in res.keys(): + if key == 'status': + assert res[key] == -2 + assert res2[key] == -4 + else: + assert res2[key] == callback.res[key] == res[key] + + def test_jumpstart(self, xp): + # The intermediate results at each level i should be the same as the + # final results when jumpstarting at level i; i.e. minlevel=maxlevel=i + a = xp.asarray(-xp.inf, dtype=xp.float64) + b = xp.asarray(xp.inf, dtype=xp.float64) + + def f(x): + return xp.exp(-x*x) + + def callback(res): + callback.integrals.append(xp_copy(res.integral)[()]) + callback.errors.append(xp_copy(res.error)[()]) + callback.integrals = [] + callback.errors = [] + + maxlevel = 4 + _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel, callback=callback) + + for i in range(maxlevel + 1): + res = _tanhsinh(f, a, b, minlevel=i, maxlevel=i) + xp_assert_close(callback.integrals[1+i], res.integral, rtol=1e-15) + xp_assert_close(callback.errors[1+i], res.error, rtol=1e-15, atol=1e-16) + + def test_special_cases(self, xp): + # Test edge cases and other special cases + a, b = xp.asarray(0), xp.asarray(1) + + def f(x): + assert xp.isdtype(x.dtype, "real floating") + return x + + res = _tanhsinh(f, a, b) + assert res.success + xp_assert_close(res.integral, xp.asarray(0.5)) + + # Test levels 0 and 1; error is NaN + res = _tanhsinh(f, a, b, maxlevel=0) + assert res.integral > 0 + xp_assert_equal(res.error, xp.asarray(xp.nan)) + res = _tanhsinh(f, a, b, maxlevel=1) + assert res.integral > 0 + xp_assert_equal(res.error, xp.asarray(xp.nan)) + + # Test equal left and right integration limits + res = _tanhsinh(f, b, b) + assert res.success + assert res.maxlevel == -1 + xp_assert_close(res.integral, xp.asarray(0.)) + + # Test scalar `args` (not in tuple) + def f(x, c): + return x**c + + res = _tanhsinh(f, a, b, args=29) + xp_assert_close(res.integral, xp.asarray(1/30)) + + # Test NaNs + a = xp.asarray([xp.nan, 0, 0, 0]) + b = xp.asarray([1, xp.nan, 1, 1]) + c = xp.asarray([1, 1, xp.nan, 1]) + res = _tanhsinh(f, a, b, args=(c,)) + xp_assert_close(res.integral, xp.asarray([xp.nan, xp.nan, xp.nan, 0.5])) + xp_assert_equal(res.error[:3], xp.full((3,), xp.nan)) + xp_assert_equal(res.status, xp.asarray([-3, -3, -3, 0], dtype=xp.int32)) + xp_assert_equal(res.success, xp.asarray([False, False, False, True])) + xp_assert_equal(res.nfev[:3], xp.full((3,), 1, dtype=xp.int32)) + + # Test complex integral followed by real integral + # Previously, h0 was of the result dtype. If the `dtype` were complex, + # this could lead to complex cached abscissae/weights. If these get + # cast to real dtype for a subsequent real integral, we would get a + # ComplexWarning. Check that this is avoided. + _pair_cache.xjc = xp.empty(0) + _pair_cache.wj = xp.empty(0) + _pair_cache.indices = [0] + _pair_cache.h0 = None + a, b = xp.asarray(0), xp.asarray(1) + res = _tanhsinh(lambda x: xp.asarray(x*1j), a, b) + xp_assert_close(res.integral, xp.asarray(0.5*1j)) + res = _tanhsinh(lambda x: x, a, b) + xp_assert_close(res.integral, xp.asarray(0.5)) + + # Test zero-size + shape = (0, 3) + res = _tanhsinh(lambda x: x, xp.asarray(0), xp.zeros(shape)) + attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel'] + for attr in attrs: + assert res[attr].shape == shape + + @pytest.mark.skip_xp_backends(np_only=True) + def test_compress_nodes_weights_gh21496(self, xp): + # See discussion in: + # https://github.com/scipy/scipy/pull/21496#discussion_r1878681049 + # This would cause "ValueError: attempt to get argmax of an empty sequence" + # Check that this has been resolved. + x = np.full(65, 3) + x[-1] = 1000 + _tanhsinh(np.sin, 1, x) + + def test_gh_22681_finite_error(self, xp): + # gh-22681 noted a case in which the error was NaN on some platforms; + # check that this does in fact fail in CI. + c1 = complex(12, -10) + c2 = complex(12, 39) + def f(t): + return xp.sin(c1 * (1 - t) + c2 * t) + a, b = xp.asarray(0., dtype=xp.float64), xp.asarray(1., dtype=xp.float64) + ref = _tanhsinh(f, a, b, atol=0, rtol=0, maxlevel=10) + assert xp.isfinite(ref.error) + # Previously, tanhsinh would not detect convergence + res = _tanhsinh(f, a, b, rtol=1e-14) + assert res.success + assert res.maxlevel < 5 + xp_assert_close(res.integral, ref.integral, rtol=1e-15) + + +@make_xp_test_case(nsum) +class TestNSum: + rng = np.random.default_rng(5895448232066142650) + p = rng.uniform(1, 10, size=10).tolist() + + def f1(self, k): + # Integers are never passed to `f1`; if they were, we'd get + # integer to negative integer power error + return k**(-2) + + f1.ref = np.pi**2/6 + f1.a = 1 + f1.b = np.inf + f1.args = tuple() + + def f2(self, k, p): + return 1 / k**p + + f2.ref = special.zeta(p, 1) + f2.a = 1. + f2.b = np.inf + f2.args = (p,) + + def f3(self, k, p): + return 1 / k**p + + f3.a = 1 + f3.b = rng.integers(5, 15, size=(3, 1)) + f3.ref = _gen_harmonic(f3.b, p) + f3.args = (p,) + + def test_input_validation(self, xp): + f = self.f1 + a, b = xp.asarray(f.a), xp.asarray(f.b) + + message = '`f` must be callable.' + with pytest.raises(ValueError, match=message): + nsum(42, a, b) + + message = '...must be True or False.' + with pytest.raises(ValueError, match=message): + nsum(f, a, b, log=2) + + message = '...must be real numbers.' + with pytest.raises(ValueError, match=message): + nsum(f, xp.asarray(1+1j), b) + with pytest.raises(ValueError, match=message): + nsum(f, a, xp.asarray(1+1j)) + with pytest.raises(ValueError, match=message): + nsum(f, a, b, step=xp.asarray(1+1j)) + with pytest.raises(ValueError, match=message): + nsum(f, a, b, tolerances=dict(atol='ekki')) + with pytest.raises(ValueError, match=message): + nsum(f, a, b, tolerances=dict(rtol=pytest)) + + with (np.errstate(all='ignore')): + res = nsum(f, xp.asarray([np.nan, np.inf]), xp.asarray(1.)) + assert (res.status[0] == -1) and not res.success[0] + assert xp.isnan(res.sum[0]) and xp.isnan(res.error[0]) + assert (res.status[1] == 0) and res.success[1] + assert res.sum[1] == res.error[1] + assert xp.all(res.nfev[0] == 1) + + res = nsum(f, xp.asarray(10.), xp.asarray([np.nan, 1])) + assert (res.status[0] == -1) and not res.success[0] + assert xp.isnan(res.sum[0]) and xp.isnan(res.error[0]) + assert (res.status[1] == 0) and res.success[1] + assert res.sum[1] == res.error[1] + assert xp.all(res.nfev[0] == 1) + + res = nsum(f, xp.asarray(1.), xp.asarray(10.), + step=xp.asarray([xp.nan, -xp.inf, xp.inf, -1, 0])) + assert xp.all((res.status == -1) & xp.isnan(res.sum) + & xp.isnan(res.error) & ~res.success & res.nfev == 1) + + message = '...must be non-negative and finite.' + with pytest.raises(ValueError, match=message): + nsum(f, a, b, tolerances=dict(rtol=-1)) + with pytest.raises(ValueError, match=message): + nsum(f, a, b, tolerances=dict(atol=np.inf)) + + message = '...may not be positive infinity.' + with pytest.raises(ValueError, match=message): + nsum(f, a, b, tolerances=dict(rtol=np.inf), log=True) + with pytest.raises(ValueError, match=message): + nsum(f, a, b, tolerances=dict(atol=np.inf), log=True) + + message = '...must be a non-negative integer.' + with pytest.raises(ValueError, match=message): + nsum(f, a, b, maxterms=3.5) + with pytest.raises(ValueError, match=message): + nsum(f, a, b, maxterms=-2) + + @pytest.mark.parametrize('f_number', range(1, 4)) + def test_basic(self, f_number, xp): + dtype = xp.asarray(1.).dtype + f = getattr(self, f"f{f_number}") + a, b = xp.asarray(f.a), xp.asarray(f.b), + args = tuple(xp.asarray(arg) for arg in f.args) + ref = xp.asarray(f.ref, dtype=dtype) + res = nsum(f, a, b, args=args) + xp_assert_close(res.sum, ref) + xp_assert_equal(res.status, xp.zeros(ref.shape, dtype=xp.int32)) + xp_assert_equal(res.success, xp.ones(ref.shape, dtype=xp.bool)) + + with np.errstate(divide='ignore'): + logres = nsum(lambda *args: xp.log(f(*args)), + a, b, log=True, args=args) + xp_assert_close(xp.exp(logres.sum), res.sum) + xp_assert_close(xp.exp(logres.error), res.error, atol=1e-15) + xp_assert_equal(logres.status, res.status) + xp_assert_equal(logres.success, res.success) + + @pytest.mark.parametrize('maxterms', [0, 1, 10, 20, 100]) + def test_integral(self, maxterms, xp): + # test precise behavior of integral approximation + f = self.f1 + + def logf(x): + return -2*xp.log(x) + + def F(x): + return -1 / x + + a = xp.asarray([1, 5], dtype=xp.float64)[:, xp.newaxis] + b = xp.asarray([20, 100, xp.inf], dtype=xp.float64)[:, xp.newaxis, xp.newaxis] + step = xp.asarray([0.5, 1, 2], dtype=xp.float64).reshape((-1, 1, 1, 1)) + nsteps = xp.floor((b - a)/step) + b_original = b + b = a + nsteps*step + + k = a + maxterms*step + # partial sum + direct = xp.sum(f(a + xp.arange(maxterms)*step), axis=-1, keepdims=True) + integral = (F(b) - F(k))/step # integral approximation of remainder + low = direct + integral + f(b) # theoretical lower bound + high = direct + integral + f(k) # theoretical upper bound + ref_sum = (low + high)/2 # nsum uses average of the two + ref_err = (high - low)/2 # error (assuming perfect quadrature) + + # correct reference values where number of terms < maxterms + a, b, step = xp.broadcast_arrays(a, b, step) + for i in np.ndindex(a.shape): + ai, bi, stepi = float(a[i]), float(b[i]), float(step[i]) + if (bi - ai)/stepi + 1 <= maxterms: + direct = xp.sum(f(xp.arange(ai, bi+stepi, stepi, dtype=xp.float64))) + ref_sum[i] = direct + ref_err[i] = direct * xp.finfo(direct.dtype).eps + + rtol = 1e-12 + res = nsum(f, a, b_original, step=step, maxterms=maxterms, + tolerances=dict(rtol=rtol)) + xp_assert_close(res.sum, ref_sum, rtol=10*rtol) + xp_assert_close(res.error, ref_err, rtol=100*rtol) + + i = ((b_original - a)/step + 1 <= maxterms) + xp_assert_close(res.sum[i], ref_sum[i], rtol=1e-15) + xp_assert_close(res.error[i], ref_err[i], rtol=1e-15) + + logres = nsum(logf, a, b_original, step=step, log=True, + tolerances=dict(rtol=math.log(rtol)), maxterms=maxterms) + xp_assert_close(xp.exp(logres.sum), res.sum) + xp_assert_close(xp.exp(logres.error), res.error) + + @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) + def test_vectorization(self, shape, xp): + # Test for correct functionality, output shapes, and dtypes for various + # input shapes. + rng = np.random.default_rng(82456839535679456794) + a = rng.integers(1, 10, size=shape) + # when the sum can be computed directly or `maxterms` is large enough + # to meet `atol`, there are slight differences (for good reason) + # between vectorized call and looping. + b = np.inf + p = rng.random(shape) + 1 + n = math.prod(shape) + + def f(x, p): + f.feval += 1 if (x.size == n or x.ndim <= 1) else x.shape[-1] + return 1 / x ** p + + f.feval = 0 + + @np.vectorize + def nsum_single(a, b, p, maxterms): + return nsum(lambda x: 1 / x**p, a, b, maxterms=maxterms) + + res = nsum(f, xp.asarray(a), xp.asarray(b), maxterms=1000, + args=(xp.asarray(p),)) + refs = nsum_single(a, b, p, maxterms=1000).ravel() + + attrs = ['sum', 'error', 'success', 'status', 'nfev'] + for attr in attrs: + ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs] + res_attr = getattr(res, attr) + xp_assert_close(xp_ravel(res_attr), xp.asarray(ref_attr), rtol=1e-15) + assert res_attr.shape == shape + + assert xp.isdtype(res.success.dtype, 'bool') + assert xp.isdtype(res.status.dtype, 'integral') + assert xp.isdtype(res.nfev.dtype, 'integral') + if is_numpy(xp): # other libraries might have different number + assert int(xp.max(res.nfev)) == f.feval + + def test_status(self, xp): + f = self.f2 + + p = [2, 2, 0.9, 1.1, 2, 2] + a = xp.asarray([0, 0, 1, 1, 1, np.nan], dtype=xp.float64) + b = xp.asarray([10, np.inf, np.inf, np.inf, np.inf, np.inf], dtype=xp.float64) + ref = special.zeta(p, 1) + p = xp.asarray(p, dtype=xp.float64) + + with np.errstate(divide='ignore'): # intentionally dividing by zero + res = nsum(f, a, b, args=(p,)) + + ref_success = xp.asarray([False, False, False, False, True, False]) + ref_status = xp.asarray([-3, -3, -2, -4, 0, -1], dtype=xp.int32) + xp_assert_equal(res.success, ref_success) + xp_assert_equal(res.status, ref_status) + xp_assert_close(res.sum[res.success], xp.asarray(ref)[res.success]) + + def test_nfev(self, xp): + def f(x): + f.nfev += xp_size(x) + return 1 / x**2 + + f.nfev = 0 + res = nsum(f, xp.asarray(1), xp.asarray(10)) + assert res.nfev == f.nfev + + f.nfev = 0 + res = nsum(f, xp.asarray(1), xp.asarray(xp.inf), tolerances=dict(atol=1e-6)) + assert res.nfev == f.nfev + + def test_inclusive(self, xp): + # There was an edge case off-by one bug when `_direct` was called with + # `inclusive=True`. Check that this is resolved. + a = xp.asarray([1, 4]) + b = xp.asarray(xp.inf) + res = nsum(lambda k: 1 / k ** 2, a, b, + maxterms=500, tolerances=dict(atol=0.1)) + ref = nsum(lambda k: 1 / k ** 2, a, b) + assert xp.all(res.sum > (ref.sum - res.error)) + assert xp.all(res.sum < (ref.sum + res.error)) + + @pytest.mark.parametrize('log', [True, False]) + def test_infinite_bounds(self, log, xp): + a = xp.asarray([1, -np.inf, -np.inf]) + b = xp.asarray([np.inf, -1, np.inf]) + c = xp.asarray([1, 2, 3]) + + def f(x, a): + return (xp.log(xp.tanh(a / 2)) - a*xp.abs(x) if log + else xp.tanh(a/2) * xp.exp(-a*xp.abs(x))) + + res = nsum(f, a, b, args=(c,), log=log) + ref = xp.asarray([stats.dlaplace.sf(0, 1), stats.dlaplace.sf(0, 2), 1]) + ref = xp.log(ref) if log else ref + atol = (1e-10 if a.dtype==xp.float64 else 1e-5) if log else 0 + xp_assert_close(res.sum, xp.asarray(ref, dtype=a.dtype), atol=atol) + + # # Make sure the sign of `x` passed into `f` is correct. + def f(x, c): + return -3*xp.log(c*x) if log else 1 / (c*x)**3 + + a = xp.asarray([1, -np.inf]) + b = xp.asarray([np.inf, -1]) + arg = xp.asarray([1, -1]) + res = nsum(f, a, b, args=(arg,), log=log) + ref = np.log(special.zeta(3)) if log else special.zeta(3) + xp_assert_close(res.sum, xp.full(a.shape, ref, dtype=a.dtype)) + + def test_decreasing_check(self, xp): + # Test accuracy when we start sum on an uphill slope. + # Without the decreasing check, the terms would look small enough to + # use the integral approximation. Because the function is not decreasing, + # the error is not bounded by the magnitude of the last term of the + # partial sum. In this case, the error would be ~1e-4, causing the test + # to fail. + def f(x): + return xp.exp(-x ** 2) + + a, b = xp.asarray(-25, dtype=xp.float64), xp.asarray(np.inf, dtype=xp.float64) + res = nsum(f, a, b) + + # Reference computed with mpmath: + # from mpmath import mp + # mp.dps = 50 + # def fmp(x): return mp.exp(-x**2) + # ref = mp.nsum(fmp, (-25, 0)) + mp.nsum(fmp, (1, mp.inf)) + ref = xp.asarray(1.772637204826652, dtype=xp.float64) + + xp_assert_close(res.sum, ref, rtol=1e-15) + + def test_special_case(self, xp): + # test equal lower/upper limit + f = self.f1 + a = b = xp.asarray(2) + res = nsum(f, a, b) + xp_assert_equal(res.sum, xp.asarray(f(2))) + + # Test scalar `args` (not in tuple) + res = nsum(self.f2, xp.asarray(1), xp.asarray(np.inf), args=xp.asarray(2)) + xp_assert_close(res.sum, xp.asarray(self.f1.ref)) # f1.ref is correct w/ args=2 + + # Test 0 size input + a = xp.empty((3, 1, 1)) # arbitrary broadcastable shapes + b = xp.empty((0, 1)) # could use Hypothesis + p = xp.empty(4) # but it's overkill + shape = np.broadcast_shapes(a.shape, b.shape, p.shape) + res = nsum(self.f2, a, b, args=(p,)) + assert res.sum.shape == shape + assert res.status.shape == shape + assert res.nfev.shape == shape + + # Test maxterms=0 + def f(x): + with np.errstate(divide='ignore'): + return 1 / x + + res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=0) + assert xp.isinf(res.sum) + assert xp.isinf(res.error) + assert res.status == -2 + + res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=1) + assert xp.isnan(res.sum) + assert xp.isnan(res.error) + assert res.status == -3 + + # Test NaNs + # should skip both direct and integral methods if there are NaNs + a = xp.asarray([xp.nan, 1, 1, 1]) + b = xp.asarray([xp.inf, xp.nan, xp.inf, xp.inf]) + p = xp.asarray([2, 2, xp.nan, 2]) + res = nsum(self.f2, a, b, args=(p,)) + xp_assert_close(res.sum, xp.asarray([xp.nan, xp.nan, xp.nan, self.f1.ref])) + xp_assert_close(res.error[:3], xp.full((3,), xp.nan)) + xp_assert_equal(res.status, xp.asarray([-1, -1, -3, 0], dtype=xp.int32)) + xp_assert_equal(res.success, xp.asarray([False, False, False, True])) + # Ideally res.nfev[2] would be 1, but `tanhsinh` has some function evals + xp_assert_equal(res.nfev[:2], xp.full((2,), 1, dtype=xp.int32)) + + @pytest.mark.parametrize('dtype', ['float32', 'float64']) + def test_dtype(self, dtype, xp): + dtype = getattr(xp, dtype) + + def f(k): + assert k.dtype == dtype + return 1 / k ** xp.asarray(2, dtype=dtype) + + a = xp.asarray(1, dtype=dtype) + b = xp.asarray([10, xp.inf], dtype=dtype) + res = nsum(f, a, b) + assert res.sum.dtype == dtype + assert res.error.dtype == dtype + + rtol = 1e-12 if dtype == xp.float64 else 1e-6 + ref = [_gen_harmonic(10, 2), special.zeta(2, 1)] + xp_assert_close(res.sum, xp.asarray(ref, dtype=dtype), rtol=rtol) + + @pytest.mark.parametrize('case', [(10, 100), (100, 10)]) + def test_nondivisible_interval(self, case, xp): + # When the limits of the sum are such that (b - a)/step + # is not exactly integral, check that only floor((b - a)/step) + # terms are included. + n, maxterms = case + + def f(k): + return 1 / k ** 2 + + a = np.e + step = 1 / 3 + b0 = a + n * step + i = np.arange(-2, 3) + b = b0 + i * np.spacing(b0) + ns = np.floor((b - a) / step) + assert len(set(ns)) == 2 + + a, b = xp.asarray(a, dtype=xp.float64), xp.asarray(b, dtype=xp.float64) + step, ns = xp.asarray(step, dtype=xp.float64), xp.asarray(ns, dtype=xp.float64) + res = nsum(f, a, b, step=step, maxterms=maxterms) + xp_assert_equal(xp.diff(ns) > 0, xp.diff(res.sum) > 0) + xp_assert_close(res.sum[-1], res.sum[0] + f(b0)) + + @pytest.mark.skip_xp_backends(np_only=True, reason='Needs beta function.') + def test_logser_kurtosis_gh20648(self, xp): + # Some functions return NaN at infinity rather than 0 like they should. + # Check that this is accounted for. + ref = stats.yulesimon.moment(4, 5) + def f(x): + return stats.yulesimon._pmf(x, 5) * x**4 + + with np.errstate(invalid='ignore'): + assert np.isnan(f(np.inf)) + + res = nsum(f, 1, np.inf) + assert_allclose(res.sum, ref) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37bdb02e8bc3af270b48e1eb72cbe25511ff15c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9bb26a5d15367467564c6d04591b59700dd7690 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9029a249e18dbd10d96716311927778c2c260bb8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7d56fa257a6065afea8f1739fe39f21e853443d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..943a57b93e1c562cb99794b7e0e96b5edd4a3e14 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8065a417cf984d9f58da706e6589cbc0f4ab5589 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76fac2374cf2a736a3dbcf8a9d2921ea6a6469bb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5428e77ba8201cb8f4ce7db5aab76dcca996983c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_pade.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_pade.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0db86362ba173376ff16e1b7377ed9e91bd1412c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_pade.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a33f2af1417aaee3819a46e3d6940c883fa7024 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf63f56589b96035d5a24ca8c6f9fa404c7bb866 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c44d880a667c793059f82c6ebe9f5b555c35f669 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f3ab8d0fde5a0f7f4064725bf01b7b2ed233269 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_np.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_np.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55388d00affaecf641b327361c8ac79de9413b33 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_np.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_xp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_xp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69797a817931c68bb500c6dbc0be0e2fb32f43f7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rbfinterp_xp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4ea034e707e6f8a35763e3f42a84f449fbe3f20 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/dfitpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/dfitpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..756584149d9d80eef924ed3a1f6f1493f6f89d10 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/dfitpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbf2da4b061d8228532fce7111e24662a1d5869f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fb1dbe0b7f60d1df46e5466315cd3d4c75288f0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60d0810cd5657fcdc353de919a59a0abfd9f5514 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92b7d4bf2ac3a7239b78e2308e6f0d474862be1d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c00664cdb155074cd7db0fcd41d21ce99395910 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/polyint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/polyint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e006852cb415f816b96f653ad8775ff760e05858 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/polyint.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/rbf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/rbf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70dd3f11b4d10e204cbe144a78d97ed8087f16ea Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/__pycache__/rbf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb38b71c7392a4fdfb4fc01d6a0e9202eeed0d87 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_bary_rational.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_bary_rational.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e44b23c5370805d8b9a7c7a5a7c03b1f2177edcb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_bary_rational.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_fitpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_fitpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab87458a77ba1f2bfaf10bed80c8ed1a7050edea Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_fitpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_gil.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_gil.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2aa0033afc2c4676b5e766c72a0103bcbf77b482 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_gil.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_interpnd.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_interpnd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c717c1f30502cfde448e23f5f946dd1ce89845c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_interpnd.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_ndgriddata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_ndgriddata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a2bf27a4008542d01c0f5ff3e2e2b8b200c9741 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_ndgriddata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_pade.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_pade.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1166d2d0401bcba093ab08c341f0e0e59928452 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_pade.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_polyint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_polyint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75f850bb7647060875a8aad8ecdb7466ec7ad5b6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_polyint.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rbf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rbf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2149bc07279cabd8730f7bbebb4c698b25ef61f4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rbf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rbfinterp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rbfinterp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..402d4140c1855334b7401f88ff26fca7ebc719cf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rbfinterp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rgi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rgi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f38d67564c5e30414a43136972842ea146c2fe29 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/__pycache__/test_rgi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_bary_rational.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_bary_rational.py new file mode 100644 index 0000000000000000000000000000000000000000..8d116ca977319cccece8938775259210b5d56142 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_bary_rational.py @@ -0,0 +1,411 @@ +# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University +# of Oxford, and the Chebfun Developers. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the University of Oxford nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from math import factorial + +import numpy as np +from numpy.testing import assert_allclose, assert_equal, assert_array_less +import pytest +import scipy +from scipy.interpolate import AAA, FloaterHormannInterpolator, BarycentricInterpolator + +TOL = 1e4 * np.finfo(np.float64).eps +UNIT_INTERVAL = np.linspace(-1, 1, num=1000) +PTS = np.logspace(-15, 0, base=10, num=500) +PTS = np.concatenate([-PTS[::-1], [0], PTS]) + + +@pytest.mark.parametrize("method", [AAA, FloaterHormannInterpolator]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.complex64, np.complex128]) +def test_dtype_preservation(method, dtype): + rtol = np.finfo(dtype).eps ** 0.75 * 100 + if method is FloaterHormannInterpolator: + rtol *= 100 + rng = np.random.default_rng(59846294526092468) + + z = np.linspace(-1, 1, dtype=dtype) + r = method(z, np.sin(z)) + + z2 = rng.uniform(-1, 1, size=100).astype(dtype) + assert_allclose(r(z2), np.sin(z2), rtol=rtol) + assert r(z2).dtype == dtype + + if method is AAA: + assert r.support_points.dtype == dtype + assert r.support_values.dtype == dtype + assert r.errors.dtype == z.real.dtype + assert r.weights.dtype == dtype + assert r.poles().dtype == np.result_type(dtype, 1j) + assert r.residues().dtype == np.result_type(dtype, 1j) + assert r.roots().dtype == np.result_type(dtype, 1j) + + +@pytest.mark.parametrize("method", [AAA, FloaterHormannInterpolator]) +@pytest.mark.parametrize("dtype", [np.int16, np.int32, np.int64]) +def test_integer_promotion(method, dtype): + z = np.arange(10, dtype=dtype) + r = method(z, z) + assert r.weights.dtype == np.result_type(dtype, 1.0) + if method is AAA: + assert r.support_points.dtype == np.result_type(dtype, 1.0) + assert r.support_values.dtype == np.result_type(dtype, 1.0) + assert r.errors.dtype == np.result_type(dtype, 1.0) + assert r.poles().dtype == np.result_type(dtype, 1j) + assert r.residues().dtype == np.result_type(dtype, 1j) + assert r.roots().dtype == np.result_type(dtype, 1j) + + assert r(z).dtype == np.result_type(dtype, 1.0) + + +class TestAAA: + def test_input_validation(self): + with pytest.raises(ValueError, match="`x` be of size 2 but got size 1."): + AAA([0], [1, 1]) + with pytest.raises(ValueError, match="1-D"): + AAA([[0], [0]], [[1], [1]]) + with pytest.raises(ValueError, match="finite"): + AAA([np.inf], [1]) + with pytest.raises(TypeError): + AAA([1], [1], max_terms=1.0) + with pytest.raises(ValueError, match="greater"): + AAA([1], [1], max_terms=-1) + + def test_convergence_error(self): + with pytest.warns(RuntimeWarning, match="AAA failed"): + AAA(UNIT_INTERVAL, np.exp(UNIT_INTERVAL), max_terms=1) + + # The following tests are based on: + # https://github.com/chebfun/chebfun/blob/master/tests/chebfun/test_aaa.m + def test_exp(self): + f = np.exp(UNIT_INTERVAL) + r = AAA(UNIT_INTERVAL, f) + + assert_allclose(r(UNIT_INTERVAL), f, atol=TOL) + assert_equal(r(np.nan), np.nan) + assert np.isfinite(r(np.inf)) + + m1 = r.support_points.size + r = AAA(UNIT_INTERVAL, f, rtol=1e-3) + assert r.support_points.size < m1 + + def test_tan(self): + f = np.tan(np.pi * UNIT_INTERVAL) + r = AAA(UNIT_INTERVAL, f) + + assert_allclose(r(UNIT_INTERVAL), f, atol=10 * TOL, rtol=1.4e-7) + assert_allclose(np.min(np.abs(r.roots())), 0, atol=3e-10) + assert_allclose(np.min(np.abs(r.poles() - 0.5)), 0, atol=TOL) + # Test for spurious poles (poles with tiny residue are likely spurious) + assert np.min(np.abs(r.residues())) > 1e-13 + + def test_short_cases(self): + # Computed using Chebfun: + # >> format long + # >> [r, pol, res, zer, zj, fj, wj, errvec] = aaa([1 2], [0 1]) + z = np.array([0, 1]) + f = np.array([1, 2]) + r = AAA(z, f, rtol=1e-13) + assert_allclose(r(z), f, atol=TOL) + assert_allclose(r.poles(), 0.5) + assert_allclose(r.residues(), 0.25) + assert_allclose(r.roots(), 1/3) + assert_equal(r.support_points, z) + assert_equal(r.support_values, f) + assert_allclose(r.weights, [0.707106781186547, 0.707106781186547]) + assert_equal(r.errors, [1, 0]) + + # >> format long + # >> [r, pol, res, zer, zj, fj, wj, errvec] = aaa([1 0 0], [0 1 2]) + z = np.array([0, 1, 2]) + f = np.array([1, 0, 0]) + r = AAA(z, f, rtol=1e-13) + assert_allclose(r(z), f, atol=TOL) + assert_allclose(np.sort(r.poles()), + np.sort([1.577350269189626, 0.422649730810374])) + assert_allclose(np.sort(r.residues()), + np.sort([-0.070441621801729, -0.262891711531604])) + assert_allclose(np.sort(r.roots()), np.sort([2, 1])) + assert_equal(r.support_points, z) + assert_equal(r.support_values, f) + assert_allclose(r.weights, [0.577350269189626, 0.577350269189626, + 0.577350269189626]) + assert_equal(r.errors, [1, 1, 0]) + + def test_scale_invariance(self): + z = np.linspace(0.3, 1.5) + f = np.exp(z) / (1 + 1j) + r1 = AAA(z, f) + r2 = AAA(z, (2**311 * f).astype(np.complex128)) + r3 = AAA(z, (2**-311 * f).astype(np.complex128)) + assert_equal(r1(0.2j), 2**-311 * r2(0.2j)) + assert_equal(r1(1.4), 2**311 * r3(1.4)) + + def test_log_func(self): + rng = np.random.default_rng(1749382759832758297) + z = rng.standard_normal(10000) + 3j * rng.standard_normal(10000) + + def f(z): + return np.log(5 - z) / (1 + z**2) + + r = AAA(z, f(z)) + assert_allclose(r(0), f(0), atol=TOL) + + def test_infinite_data(self): + z = np.linspace(-1, 1) + r = AAA(z, scipy.special.gamma(z)) + assert_allclose(r(0.63), scipy.special.gamma(0.63), atol=1e-15) + + def test_nan(self): + x = np.linspace(0, 20) + with np.errstate(invalid="ignore"): + f = np.sin(x) / x + r = AAA(x, f) + assert_allclose(r(2), np.sin(2) / 2, atol=1e-15) + + def test_residues(self): + x = np.linspace(-1.337, 2, num=537) + r = AAA(x, np.exp(x) / x) + ii = np.flatnonzero(np.abs(r.poles()) < 1e-8) + assert_allclose(r.residues()[ii], 1, atol=1e-15) + + r = AAA(x, (1 + 1j) * scipy.special.gamma(x)) + ii = np.flatnonzero(abs(r.poles() - (-1)) < 1e-8) + assert_allclose(r.residues()[ii], -1 - 1j, atol=1e-15) + + # The following tests are based on: + # https://github.com/complexvariables/RationalFunctionApproximation.jl/blob/main/test/interval.jl + @pytest.mark.parametrize("func,atol,rtol", + [(lambda x: np.abs(x + 0.5 + 0.01j), 5e-13, 1e-7), + (lambda x: np.sin(1/(1.05 - x)), 2e-13, 1e-7), + (lambda x: np.exp(-1/(x**2)), 3.5e-11, 0), + (lambda x: np.exp(-100*x**2), 2e-12, 0), + (lambda x: np.exp(-10/(1.2 - x)), 1e-14, 0), + (lambda x: 1/(1+np.exp(100*(x + 0.5))), 2e-13, 1e-7), + (lambda x: np.abs(x - 0.95), 1e-6, 1e-7)]) + def test_basic_functions(self, func, atol, rtol): + with np.errstate(divide="ignore"): + f = func(PTS) + assert_allclose(AAA(UNIT_INTERVAL, func(UNIT_INTERVAL))(PTS), + f, atol=atol, rtol=rtol) + + def test_poles_zeros_residues(self): + def f(z): + return (z+1) * (z+2) / ((z+3) * (z+4)) + r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL)) + assert_allclose(np.sum(r.poles() + r.roots()), -10, atol=1e-12) + + def f(z): + return 2/(3 + z) + 5/(z - 2j) + r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL)) + assert_allclose(r.residues().prod(), 10, atol=1e-8) + + r = AAA(UNIT_INTERVAL, np.sin(10*np.pi*UNIT_INTERVAL)) + assert_allclose(np.sort(np.abs(r.roots()))[18], 0.9, atol=1e-12) + + def f(z): + return (z - (3 + 3j))/(z + 2) + r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL)) + assert_allclose(r.poles()[0]*r.roots()[0], -6-6j, atol=1e-12) + + @pytest.mark.parametrize("func", + [lambda z: np.zeros_like(z), lambda z: z, lambda z: 1j*z, + lambda z: z**2 + z, lambda z: z**3 + z, + lambda z: 1/(1.1 + z), lambda z: 1/(1 + 1j*z), + lambda z: 1/(3 + z + z**2), lambda z: 1/(1.01 + z**3)]) + def test_polynomials_and_reciprocals(self, func): + assert_allclose(AAA(UNIT_INTERVAL, func(UNIT_INTERVAL))(PTS), + func(PTS), atol=2e-13) + + # The following tests are taken from: + # https://github.com/macd/BaryRational.jl/blob/main/test/test_aaa.jl + def test_spiral(self): + z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, num=1000)) + r = AAA(z, np.tan(np.pi*z/2)) + assert_allclose(np.sort(np.abs(r.poles()))[:4], [1, 1, 3, 3], rtol=9e-7) + + def test_spiral_cleanup(self): + z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, num=1000)) + # here we set `rtol=0` to force froissart doublets, without cleanup there + # are many spurious poles + with pytest.warns(RuntimeWarning): + r = AAA(z, np.tan(np.pi*z/2), rtol=0, max_terms=60, clean_up=False) + n_spurious = np.sum(np.abs(r.residues()) < 1e-14) + with pytest.warns(RuntimeWarning): + assert r.clean_up() >= 1 + # check there are less potentially spurious poles than before + assert np.sum(np.abs(r.residues()) < 1e-14) < n_spurious + # check accuracy + assert_allclose(r(z), np.tan(np.pi*z/2), atol=6e-12, rtol=3e-12) + + def test_diag_scaling(self): + # fails without diag scaling + z = np.logspace(-15, 0, 300) + f = np.sqrt(z) + r = AAA(z, f) + + zz = np.logspace(-15, 0, 500) + assert_allclose(r(zz), np.sqrt(zz), rtol=9e-6) + + +class BatchFloaterHormann: + # FloaterHormann class with reference batch behaviour + def __init__(self, x, y, axis): + y = np.moveaxis(y, axis, -1) + self._batch_shape = y.shape[:-1] + self._interps = [FloaterHormannInterpolator(x, yi,) + for yi in y.reshape(-1, y.shape[-1])] + self._axis = axis + + def __call__(self, x): + y = [interp(x) for interp in self._interps] + y = np.reshape(y, self._batch_shape + x.shape) + return np.moveaxis(y, -1, self._axis) if x.shape else y + + +class TestFloaterHormann: + def runge(self, z): + return 1/(1 + z**2) + + def scale(self, n, d): + return (-1)**(np.arange(n) + d) * factorial(d) + + def test_iv(self): + with pytest.raises(ValueError, match="`x`"): + FloaterHormannInterpolator([[0]], [0], d=0) + with pytest.raises(ValueError, match="`y`"): + FloaterHormannInterpolator([0], 0, d=0) + with pytest.raises(ValueError, match="`x` be of size 2 but got size 1."): + FloaterHormannInterpolator([0], [[1, 1], [1, 1]], d=0) + with pytest.raises(ValueError, match="finite"): + FloaterHormannInterpolator([np.inf], [1], d=0) + with pytest.raises(ValueError, match="`d`"): + FloaterHormannInterpolator([0], [0], d=-1) + with pytest.raises(ValueError, match="`d`"): + FloaterHormannInterpolator([0], [0], d=10) + with pytest.raises(TypeError): + FloaterHormannInterpolator([0], [0], d=0.0) + + # reference values from Floater and Hormann 2007 page 8. + @pytest.mark.parametrize("d,expected", [ + (0, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + (1, [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]), + (2, [1, 3, 4, 4, 4, 4, 4, 4, 4, 3, 1]), + (3, [1, 4, 7, 8, 8, 8, 8, 8, 7, 4, 1]), + (4, [1, 5, 11, 15, 16, 16, 16, 15, 11, 5, 1]) + ]) + def test_uniform_grid(self, d, expected): + # Check against explicit results on an uniform grid + x = np.arange(11) + r = FloaterHormannInterpolator(x, 0.0*x, d=d) + assert_allclose(r.weights.ravel()*self.scale(x.size, d), expected, + rtol=1e-15, atol=1e-15) + + @pytest.mark.parametrize("d", range(10)) + def test_runge(self, d): + x = np.linspace(0, 1, 51) + rng = np.random.default_rng(802754237598370893) + xx = rng.uniform(0, 1, size=1000) + y = self.runge(x) + h = x[1] - x[0] + + r = FloaterHormannInterpolator(x, y, d=d) + + tol = 10*h**(d+1) + assert_allclose(r(xx), self.runge(xx), atol=1e-10, rtol=tol) + # check interpolation property + assert_equal(r(x), self.runge(x)) + + def test_complex(self): + x = np.linspace(-1, 1) + z = x + x*1j + r = FloaterHormannInterpolator(z, np.sin(z), d=12) + xx = np.linspace(-1, 1, num=1000) + zz = xx + xx*1j + assert_allclose(r(zz), np.sin(zz), rtol=1e-12) + + def test_polyinterp(self): + # check that when d=n-1 FH gives a polynomial interpolant + x = np.linspace(0, 1, 11) + xx = np.linspace(0, 1, 1001) + y = np.sin(x) + r = FloaterHormannInterpolator(x, y, d=x.size-1) + p = BarycentricInterpolator(x, y) + assert_allclose(r(xx), p(xx), rtol=1e-12, atol=1e-12) + + @pytest.mark.parametrize("y_shape", [(2,), (2, 3, 1), (1, 5, 6, 4)]) + @pytest.mark.parametrize("xx_shape", [(100), (10, 10)]) + def test_trailing_dim(self, y_shape, xx_shape): + x = np.linspace(0, 1) + y = np.broadcast_to( + np.expand_dims(np.sin(x), tuple(range(1, len(y_shape) + 1))), + x.shape + y_shape + ) + + r = FloaterHormannInterpolator(x, y) + + rng = np.random.default_rng(897138947238097528091759187597) + xx = rng.random(xx_shape) + yy = np.broadcast_to( + np.expand_dims(np.sin(xx), tuple(range(xx.ndim, len(y_shape) + xx.ndim))), + xx.shape + y_shape + ) + rr = r(xx) + assert rr.shape == xx.shape + y_shape + assert_allclose(rr, yy, rtol=1e-6) + + + def test_zeros(self): + x = np.linspace(0, 10, num=100) + r = FloaterHormannInterpolator(x, np.sin(np.pi*x)) + + err = np.abs(np.subtract.outer(r.roots(), np.arange(11))).min(axis=0) + assert_array_less(err, 1e-5) + + def test_no_poles(self): + x = np.linspace(-1, 1) + r = FloaterHormannInterpolator(x, 1/x**2) + p = r.poles() + mask = (p.real >= -1) & (p.real <= 1) & (np.abs(p.imag) < 1.e-12) + assert np.sum(mask) == 0 + + @pytest.mark.parametrize('eval_shape', [(), (1,), (3,)]) + @pytest.mark.parametrize('axis', [-1, 0, 1]) + def test_batch(self, eval_shape, axis): + rng = np.random.default_rng(4329872134985134) + n = 10 + shape = (2, 3, 4, n) + domain = (0, 10) + + x = np.linspace(*domain, n) + y = np.moveaxis(rng.random(shape), -1, axis) + + res = FloaterHormannInterpolator(x, y, axis=axis) + ref = BatchFloaterHormann(x, y, axis=axis) + + x = rng.uniform(*domain, size=eval_shape) + assert_allclose(res(x), ref(x)) + + pytest.raises(NotImplementedError, res.roots) + pytest.raises(NotImplementedError, res.residues) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_bsplines.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..ca4df48560e9705c16ce8cee09d47bbc27052aed --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_bsplines.py @@ -0,0 +1,4330 @@ +import os +import operator +import itertools +import math +import cmath +import threading +import copy +import warnings +import sys + +import numpy as np +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, xp_default_dtype, concat_1d, make_xp_test_case, + xp_ravel +) +import scipy._lib.array_api_extra as xpx +from pytest import raises as assert_raises +import pytest + +from scipy.interpolate import ( + BSpline, BPoly, PPoly, make_interp_spline, make_lsq_spline, + splev, splrep, splprep, splder, splantider, sproot, splint, insert, + CubicSpline, NdBSpline, make_smoothing_spline, RegularGridInterpolator, +) +import scipy.linalg as sl +import scipy.sparse.linalg as ssl + +from scipy.interpolate._bsplines import (_not_a_knot, _augknt, + _woodbury_algorithm, _periodic_knots, + _make_interp_per_full_matr) +from scipy.interpolate._fitpack_repro import Fperiodic, root_rati + +from scipy.interpolate import generate_knots, make_splrep, make_splprep + +import scipy.interpolate._fitpack_impl as _impl +from scipy._lib._util import AxisError +from scipy._lib._testutils import _run_concurrent_barrier + +# XXX: move to the interpolate namespace +from scipy.interpolate._ndbspline import make_ndbspl + +from scipy.interpolate import _dfitpack as dfitpack +from scipy.interpolate import _bsplines as _b +from scipy.interpolate import _dierckx + +skip_xp_backends = pytest.mark.skip_xp_backends + + +@make_xp_test_case(BSpline) +class TestBSpline: + + def test_ctor(self, xp): + # knots should be an ordered 1-D array of finite real numbers + assert_raises((TypeError, ValueError), BSpline, + **dict(t=[1, 1.j], c=[1.], k=0)) + with np.errstate(invalid='ignore'): + assert_raises(ValueError, BSpline, **dict(t=[1, np.nan], c=[1.], k=0)) + assert_raises(ValueError, BSpline, **dict(t=[1, np.inf], c=[1.], k=0)) + assert_raises(ValueError, BSpline, **dict(t=[1, -1], c=[1.], k=0)) + assert_raises(ValueError, BSpline, **dict(t=[[1], [1]], c=[1.], k=0)) + + # for n+k+1 knots and degree k need at least n coefficients + assert_raises(ValueError, BSpline, **dict(t=[0, 1, 2], c=[1], k=0)) + assert_raises(ValueError, BSpline, + **dict(t=[0, 1, 2, 3, 4], c=[1., 1.], k=2)) + + # non-integer orders + assert_raises(TypeError, BSpline, + **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k="cubic")) + assert_raises(TypeError, BSpline, + **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k=2.5)) + + # basic interval cannot have measure zero (here: [1..1]) + assert_raises(ValueError, BSpline, + **dict(t=[0., 0, 1, 1, 2, 3], c=[1., 1, 1], k=2)) + + # tck vs self.tck + n, k = 11, 3 + t = xp.arange(n+k+1, dtype=xp.float64) + c = xp.asarray(np.random.random(n)) + b = BSpline(t, c, k) + + xp_assert_close(t, b.t) + xp_assert_close(c, b.c) + assert k == b.k + + def test_tck(self): + b = _make_random_spline() + tck = b.tck + + xp_assert_close(b.t, tck[0], atol=1e-15, rtol=1e-15) + xp_assert_close(b.c, tck[1], atol=1e-15, rtol=1e-15) + assert b.k == tck[2] + + # b.tck is read-only + with pytest.raises(AttributeError): + b.tck = 'foo' + + def test_call_namespace(self, xp): + # similar to test_degree_0 below, only parametrized with xp + # (test_degree_0 tests array-like inputs, which resolve to numpy) + b = BSpline(t=xp.asarray([0, 1., 2]), c=xp.asarray([3., 4]), k=0) + xx = xp.linspace(0, 2, 10) + + expected = xp.where(xx < 1., xp.asarray(3., dtype=xp.float64), 4.0) + xp_assert_close(b(xx), expected) + + def test_degree_0(self): + xx = np.linspace(0, 1, 10) + + b = BSpline(t=[0, 1], c=[3.], k=0) + xp_assert_close(b(xx), np.ones_like(xx) * 3.0) + + b = BSpline(t=[0, 0.35, 1], c=[3, 4], k=0) + xp_assert_close(b(xx), np.where(xx < 0.35, 3.0, 4.0)) + + def test_degree_1(self, xp): + t = xp.asarray([0, 1, 2, 3, 4]) + c = xp.asarray([1.0, 2, 3]) + k = 1 + b = BSpline(t, c, k) + + x = xp.linspace(1.0, 3.0, 50, dtype=xp.float64) + xp_assert_close( + b(x), + c[0]*B_012(x, xp=xp) + c[1]*B_012(x-1, xp=xp) + c[2]*B_012(x-2, xp=xp), + atol=1e-14 + ) + x_np, t_np, c_np = map(np.asarray, (x, t, c)) + splev_result = splev(x_np, (t_np, c_np, k)) + xp_assert_close(b(x), xp.asarray(splev_result), atol=1e-14) + + def test_bernstein(self, xp): + # a special knot vector: Bernstein polynomials + k = 3 + t = xp.asarray([0]*(k+1) + [1]*(k+1)) + c = xp.asarray([1., 2., 3., 4.]) + bp = BPoly(xp.reshape(c, (-1, 1)), xp.asarray([0, 1])) + bspl = BSpline(t, c, k) + + xx = xp.linspace(-1., 2., 10) + xp_assert_close(bp(xx, extrapolate=True), + bspl(xx, extrapolate=True), atol=1e-14) + + @skip_xp_backends("dask.array", reason="_naive_eval is not dask-compatible") + @skip_xp_backends("jax.numpy", reason="too slow; XXX a slow-if marker?") + @skip_xp_backends("torch", reason="OOB on CI") + def test_rndm_naive_eval(self, xp): + # test random coefficient spline *on the base interval*, + # t[k] <= x < t[-k-1] + b = _make_random_spline(xp=xp) + t, c, k = b.tck + xx = xp.linspace(t[k], t[-k-1], 50) + y_b = b(xx) + y_n = xp.stack([_naive_eval(x, t, c, k, xp=xp) for x in xx]) + xp_assert_close(y_b, y_n, atol=1e-14) + + y_n2 = xp.stack([_naive_eval_2(x, t, c, k, xp=xp) for x in xx]) + xp_assert_close(y_b, y_n2, atol=1e-14) + + def test_rndm_splev(self): + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[k], t[-k-1], 50) + xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14) + + def test_rndm_splrep(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(20)) + y = rng.random(20) + + tck = splrep(x, y) + b = BSpline(*tck) + + t, k = b.t, b.k + xx = np.linspace(t[k], t[-k-1], 80) + xp_assert_close(b(xx), splev(xx, tck), atol=1e-14) + + def test_rndm_unity(self, xp): + b = _make_random_spline(xp=xp) + b.c = xp.ones_like(b.c) + xx = xp.linspace(b.t[b.k], b.t[-b.k-1], 100, dtype=xp.float64) + xp_assert_close(b(xx), xp.ones_like(xx)) + + def test_vectorization(self, xp): + rng = np.random.RandomState(1234) + n, k = 22, 3 + t = np.sort(rng.random(n)) + c = rng.random(size=(n, 6, 7)) + t, c = map(xp.asarray, (t, c)) + b = BSpline(t, c, k) + tm, tp = t[k], t[-k-1] + xx = tm + (tp - tm) * xp.asarray(rng.random((3, 4, 5))) + assert b(xx).shape == (3, 4, 5, 6, 7) + + def test_len_c(self): + # for n+k+1 knots, only first n coefs are used. + # and BTW this is consistent with FITPACK + rng = np.random.RandomState(1234) + n, k = 33, 3 + t = np.sort(rng.random(n+k+1)) + c = rng.random(n) + + # pad coefficients with random garbage + c_pad = np.r_[c, rng.random(k+1)] + + b, b_pad = BSpline(t, c, k), BSpline(t, c_pad, k) + + dt = t[-1] - t[0] + xx = np.linspace(t[0] - dt, t[-1] + dt, 50) + xp_assert_close(b(xx), b_pad(xx), atol=1e-14) + xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14) + xp_assert_close(b(xx), splev(xx, (t, c_pad, k)), atol=1e-14) + + def test_endpoints(self, num_parallel_threads): + # base interval is closed + b = _make_random_spline() + t, _, k = b.tck + tm, tp = t[k], t[-k-1] + # atol = 1e-9 if num_parallel_threads == 1 else 1e-7 + for extrap in (True, False): + xp_assert_close(b([tm, tp], extrap), + b([tm + 1e-10, tp - 1e-10], extrap), atol=1e-9, rtol=1e-7) + + def test_continuity(self, num_parallel_threads): + # assert continuity at internal knots + b = _make_random_spline() + t, _, k = b.tck + xp_assert_close(b(t[k+1:-k-1] - 1e-10), b(t[k+1:-k-1] + 1e-10), + atol=1e-9) + + def test_extrap(self, xp): + b = _make_random_spline(xp=xp) + t, c, k = b.tck + dt = t[-1] - t[0] + xx = xp.linspace(t[k] - dt, t[-k-1] + dt, 50) + mask = (t[k] < xx) & (xx < t[-k-1]) + + # extrap has no effect within the base interval + xp_assert_close(b(xx[mask], extrapolate=True), + b(xx[mask], extrapolate=False)) + + # extrapolated values agree with FITPACK + xx_np, t_np, c_np = map(np.asarray, (xx, t, c)) + splev_result = xp.asarray(splev(xx_np, (t_np, c_np, k), ext=0)) + xp_assert_close(b(xx, extrapolate=True), splev_result) + + def test_default_extrap(self): + # BSpline defaults to extrapolate=True + b = _make_random_spline() + t, _, k = b.tck + xx = [t[0] - 1, t[-1] + 1] + yy = b(xx) + assert not np.all(np.isnan(yy)) + + def test_periodic_extrap(self, xp): + rng = np.random.RandomState(1234) + t = np.sort(rng.random(8)) + c = rng.random(4) + t, c = map(xp.asarray, (t, c)) + k = 3 + b = BSpline(t, c, k, extrapolate='periodic') + n = t.shape[0] - (k + 1) + + dt = t[-1] - t[0] + xx = xp.linspace(t[k] - dt, t[n] + dt, 50) + xy = t[k] + (xx - t[k]) % (t[n] - t[k]) + xy_np, t_np, c_np = map(np.asarray, (xy, t, c)) + atol = 1e-12 if xp_default_dtype(xp) == xp.float64 else 2e-7 + xp_assert_close( + b(xx), xp.asarray(splev(xy_np, (t_np, c_np, k))), atol=atol + ) + + # Direct check + xx = xp.asarray([-1, 0, 0.5, 1]) + xy = t[k] + (xx - t[k]) % (t[n] - t[k]) + xp_assert_close( + b(xx, extrapolate='periodic'), + b(xy, extrapolate=True), + atol=1e-14 if xp_default_dtype(xp) == xp.float64 else 5e-7 + ) + + def test_ppoly(self): + b = _make_random_spline() + t, c, k = b.tck + pp = PPoly.from_spline((t, c, k)) + + xx = np.linspace(t[k], t[-k], 100) + xp_assert_close(b(xx), pp(xx), atol=1e-14, rtol=1e-14) + + def test_derivative_rndm(self): + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[0], t[-1], 50) + xx = np.r_[xx, t] + + for der in range(1, k+1): + yd = splev(xx, (t, c, k), der=der) + xp_assert_close(yd, b(xx, nu=der), atol=1e-14) + + # higher derivatives all vanish + xp_assert_close(b(xx, nu=k+1), np.zeros_like(xx), atol=1e-14) + + def test_derivative_jumps(self): + # example from de Boor, Chap IX, example (24) + # NB: knots augmented & corresp coefs are zeroed out + # in agreement with the convention (29) + k = 2 + t = [-1, -1, 0, 1, 1, 3, 4, 6, 6, 6, 7, 7] + rng = np.random.RandomState(1234) + c = np.r_[0, 0, rng.random(5), 0, 0] + b = BSpline(t, c, k) + + # b is continuous at x != 6 (triple knot) + x = np.asarray([1, 3, 4, 6]) + xp_assert_close(b(x[x != 6] - 1e-10), + b(x[x != 6] + 1e-10)) + assert not np.allclose(b(6.-1e-10), b(6+1e-10)) + + # 1st derivative jumps at double knots, 1 & 6: + x0 = np.asarray([3, 4]) + xp_assert_close(b(x0 - 1e-10, nu=1), + b(x0 + 1e-10, nu=1)) + x1 = np.asarray([1, 6]) + assert not np.allclose(b(x1 - 1e-10, nu=1), b(x1 + 1e-10, nu=1)) + + # 2nd derivative is not guaranteed to be continuous either + assert not np.allclose(b(x - 1e-10, nu=2), b(x + 1e-10, nu=2)) + + def test_basis_element_quadratic(self, xp): + xx = xp.linspace(-1, 4, 20) + b = BSpline.basis_element(t=xp.asarray([0, 1, 2, 3])) + + xx_np, t_np, c_np = map(np.asarray, (xx, b.t, b.c)) + splev_result = xp.asarray(splev(xx_np, (t_np, c_np, b.k))) + xp_assert_close(b(xx), splev_result, atol=1e-14) + + atol=1e-14 if xp_default_dtype(xp) == xp.float64 else 1e-7 + xp_assert_close(b(xx), xp.asarray(B_0123(xx), dtype=xp.float64), atol=atol) + + b = BSpline.basis_element(t=xp.asarray([0, 1, 1, 2])) + xx = xp.linspace(0, 2, 10, dtype=xp.float64) + xp_assert_close(b(xx), + xp.where(xx < 1, xx*xx, (2.-xx)**2), atol=1e-14) + + def test_basis_element_rndm(self): + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[k], t[-k-1], 20) + xp_assert_close(b(xx), _sum_basis_elements(xx, t, c, k), atol=1e-14) + + def test_cmplx(self): + b = _make_random_spline() + t, c, k = b.tck + cc = c * (1. + 3.j) + + b = BSpline(t, cc, k) + b_re = BSpline(t, b.c.real, k) + b_im = BSpline(t, b.c.imag, k) + + xx = np.linspace(t[k], t[-k-1], 20) + xp_assert_close(b(xx).real, b_re(xx), atol=1e-14) + xp_assert_close(b(xx).imag, b_im(xx), atol=1e-14) + + def test_nan(self, xp): + # nan in, nan out. + b = BSpline.basis_element(xp.asarray([0, 1, 1, 2])) + assert xp.isnan(b(xp.nan)) + + def test_derivative_method(self, xp): + b = _make_random_spline(k=5, xp=xp) + t, c, k = b.tck + b0 = BSpline(t, c, k) + xx = xp.linspace(t[k], t[-k-1], 20) + for j in range(1, k): + b = b.derivative() + xp_assert_close(b0(xx, j), b(xx), atol=1e-12, rtol=1e-12) + + def test_antiderivative_method(self, xp): + b = _make_random_spline(xp=xp) + t, c, k = b.tck + xx = xp.linspace(t[k], t[-k-1], 20) + xp_assert_close(b.antiderivative().derivative()(xx), + b(xx), atol=1e-14, rtol=1e-14) + + # repeat with N-D array for c + c = xp.stack((c, c, c), axis=1) + c = xp.stack((c, c), axis=2) + b = BSpline(t, c, k) + xp_assert_close(b.antiderivative().derivative()(xx), + b(xx), atol=1e-14, rtol=1e-14) + + def test_integral(self, xp): + b = BSpline.basis_element(xp.asarray([0, 1, 2])) # x for x < 1 else 2 - x + assert math.isclose(b.integrate(0, 1), 0.5, abs_tol=1e-14) + assert math.isclose(b.integrate(1, 0), -1 * 0.5, abs_tol=1e-14) + assert math.isclose(b.integrate(1, 0), -0.5, abs_tol=1e-14) + + + assert math.isclose(b.integrate(0, 1), 0.5, abs_tol=1e-14) + assert math.isclose(b.integrate(1, 0), -1 * 0.5, abs_tol=1e-14) + assert math.isclose(b.integrate(1, 0), -0.5, abs_tol=1e-14) + + # extrapolate or zeros outside of [0, 2]; default is yes + assert math.isclose(b.integrate(-1, 1), 0.0, abs_tol=1e-14) + assert math.isclose(b.integrate(-1, 1, extrapolate=True), 0.0, abs_tol=1e-14) + assert math.isclose(b.integrate(-1, 1, extrapolate=False), 0.5, abs_tol=1e-14) + assert math.isclose(b.integrate(1, -1, extrapolate=False), -0.5, abs_tol=1e-14) + + # Test ``_fitpack._splint()`` + assert math.isclose(b.integrate(1, -1, extrapolate=False), + _impl.splint(1, -1, b.tck), abs_tol=1e-14) + + # Test ``extrapolate='periodic'``. + b.extrapolate = 'periodic' + i = b.antiderivative() + period_int = xp.asarray(i(2) - i(0), dtype=xp.float64) + + assert math.isclose(b.integrate(0, 2), period_int) + assert math.isclose(b.integrate(2, 0), -1 * period_int) + assert math.isclose(b.integrate(-9, -7), period_int) + assert math.isclose(b.integrate(-8, -4), 2 * period_int) + + xp_assert_close(b.integrate(0.5, 1.5), + xp.asarray(i(1.5) - i(0.5))) + xp_assert_close(b.integrate(1.5, 3), + xp.asarray(i(1) - i(0) + i(2) - i(1.5))) + xp_assert_close(b.integrate(1.5 + 12, 3 + 12), + xp.asarray(i(1) - i(0) + i(2) - i(1.5))) + xp_assert_close(b.integrate(1.5, 3 + 12), + xp.asarray(i(1) - i(0) + i(2) - i(1.5) + 6 * period_int)) + + xp_assert_close(b.integrate(0, -1), xp.asarray(i(0) - i(1))) + xp_assert_close(b.integrate(-9, -10), xp.asarray(i(0) - i(1))) + xp_assert_close(b.integrate(0, -9), + xp.asarray(i(1) - i(2) - 4 * period_int)) + + def test_integrate_ppoly(self): + # test .integrate method to be consistent with PPoly.integrate + x = [0, 1, 2, 3, 4] + b = make_interp_spline(x, x) + b.extrapolate = 'periodic' + p = PPoly.from_spline(b) + + for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]: + xp_assert_close(b.integrate(x0, x1), + p.integrate(x0, x1)) + + def test_integrate_0D_always(self): + # make sure the result is always a 0D array (not a python scalar) + b = BSpline.basis_element([0, 1, 2]) + for extrapolate in (True, False): + res = b.integrate(0, 1, extrapolate=extrapolate) + assert isinstance(res, np.ndarray) + assert res.ndim == 0 + + def test_subclassing(self): + # classmethods should not decay to the base class + class B(BSpline): + pass + + b = B.basis_element([0, 1, 2, 2]) + assert b.__class__ == B + assert b.derivative().__class__ == B + assert b.antiderivative().__class__ == B + + @pytest.mark.parametrize('axis', range(-4, 4)) + def test_axis(self, axis, xp): + n, k = 22, 3 + t = xp.linspace(0, 1, n + k + 1) + sh = [6, 7, 8] + # We need the positive axis for some of the indexing and slices used + # in this test. + pos_axis = axis % 4 + sh.insert(pos_axis, n) # [22, 6, 7, 8] etc + sh = tuple(sh) + rng = np.random.RandomState(1234) + c = xp.asarray(rng.random(size=sh)) + b = BSpline(t, c, k, axis=axis) + assert b.c.shape == (sh[pos_axis],) + sh[:pos_axis] + sh[pos_axis+1:] + + xp = rng.random((3, 4, 5)) + assert b(xp).shape == sh[:pos_axis] + xp.shape + sh[pos_axis+1:] + + # -c.ndim <= axis < c.ndim + for ax in [-c.ndim - 1, c.ndim]: + assert_raises(AxisError, BSpline, + **dict(t=t, c=c, k=k, axis=ax)) + + # derivative, antiderivative keeps the axis + for b1 in [BSpline(t, c, k, axis=axis).derivative(), + BSpline(t, c, k, axis=axis).derivative(2), + BSpline(t, c, k, axis=axis).antiderivative(), + BSpline(t, c, k, axis=axis).antiderivative(2)]: + assert b1.axis == b.axis + + def test_neg_axis(self, xp): + k = 2 + t = xp.asarray([0, 1, 2, 3, 4, 5, 6]) + c = xp.asarray([[-1, 2, 0, -1], [2, 0, -3, 1]]) + + spl = BSpline(t, c, k, axis=-1) + spl0 = BSpline(t, c[0, :], k) + spl1 = BSpline(t, c[1, :], k) + xp_assert_equal(spl(2.5), xp.stack([spl0(2.5), spl1(2.5)])) + + def test_design_matrix_bc_types(self): + ''' + Splines with different boundary conditions are built on different + types of vectors of knots. As far as design matrix depends only on + vector of knots, `k` and `x` it is useful to make tests for different + boundary conditions (and as following different vectors of knots). + ''' + def run_design_matrix_tests(n, k, bc_type): + ''' + To avoid repetition of code the following function is provided. + ''' + rng = np.random.RandomState(1234) + x = np.sort(rng.random_sample(n) * 40 - 20) + y = rng.random_sample(n) * 40 - 20 + if bc_type == "periodic": + y[0] = y[-1] + + bspl = make_interp_spline(x, y, k=k, bc_type=bc_type) + + c = np.eye(len(bspl.t) - k - 1) + des_matr_def = BSpline(bspl.t, c, k)(x) + des_matr_csr = BSpline.design_matrix(x, + bspl.t, + k).toarray() + xp_assert_close(des_matr_csr @ bspl.c, y, atol=1e-14) + xp_assert_close(des_matr_def, des_matr_csr, atol=1e-14) + + # "clamped" and "natural" work only with `k = 3` + n = 11 + k = 3 + for bc in ["clamped", "natural"]: + run_design_matrix_tests(n, k, bc) + + # "not-a-knot" works with odd `k` + for k in range(3, 8, 2): + run_design_matrix_tests(n, k, "not-a-knot") + + # "periodic" works with any `k` (even more than `n`) + n = 5 # smaller `n` to test `k > n` case + for k in range(2, 7): + run_design_matrix_tests(n, k, "periodic") + + @pytest.mark.parametrize('extrapolate', [False, True, 'periodic']) + @pytest.mark.parametrize('degree', range(5)) + def test_design_matrix_same_as_BSpline_call(self, extrapolate, degree): + """Test that design_matrix(x) is equivalent to BSpline(..)(x).""" + rng = np.random.RandomState(1234) + x = rng.random_sample(10 * (degree + 1)) + xmin, xmax = np.amin(x), np.amax(x) + k = degree + t = np.r_[np.linspace(xmin - 2, xmin - 1, degree), + np.linspace(xmin, xmax, 2 * (degree + 1)), + np.linspace(xmax + 1, xmax + 2, degree)] + c = np.eye(len(t) - k - 1) + bspline = BSpline(t, c, k, extrapolate) + xp_assert_close( + bspline(x), BSpline.design_matrix(x, t, k, extrapolate).toarray() + ) + + # extrapolation regime + x = np.array([xmin - 10, xmin - 1, xmax + 1.5, xmax + 10]) + if not extrapolate: + with pytest.raises(ValueError): + BSpline.design_matrix(x, t, k, extrapolate) + else: + xp_assert_close( + bspline(x), + BSpline.design_matrix(x, t, k, extrapolate).toarray() + ) + + def test_design_matrix_x_shapes(self): + # test for different `x` shapes + rng = np.random.RandomState(1234) + n = 10 + k = 3 + x = np.sort(rng.random_sample(n) * 40 - 20) + y = rng.random_sample(n) * 40 - 20 + + bspl = make_interp_spline(x, y, k=k) + for i in range(1, 4): + xc = x[:i] + yc = y[:i] + des_matr_csr = BSpline.design_matrix(xc, + bspl.t, + k).toarray() + xp_assert_close(des_matr_csr @ bspl.c, yc, atol=1e-14) + + def test_design_matrix_t_shapes(self): + # test for minimal possible `t` shape + t = [1., 1., 1., 2., 3., 4., 4., 4.] + des_matr = BSpline.design_matrix(2., t, 3).toarray() + xp_assert_close(des_matr, + [[0.25, 0.58333333, 0.16666667, 0.]], + atol=1e-14) + + def test_design_matrix_asserts(self): + rng = np.random.RandomState(1234) + n = 10 + k = 3 + x = np.sort(rng.random_sample(n) * 40 - 20) + y = rng.random_sample(n) * 40 - 20 + bspl = make_interp_spline(x, y, k=k) + # invalid vector of knots (should be a 1D non-descending array) + # here the actual vector of knots is reversed, so it is invalid + with assert_raises(ValueError): + BSpline.design_matrix(x, bspl.t[::-1], k) + k = 2 + t = [0., 1., 2., 3., 4., 5.] + x = [1., 2., 3., 4.] + # out of bounds + with assert_raises(ValueError): + BSpline.design_matrix(x, t, k) + + @pytest.mark.parametrize('bc_type', ['natural', 'clamped', + 'periodic', 'not-a-knot']) + def test_from_power_basis(self, bc_type): + # TODO: convert CubicSpline + rng = np.random.RandomState(1234) + x = np.sort(rng.random(20)) + y = rng.random(20) + if bc_type == 'periodic': + y[-1] = y[0] + cb = CubicSpline(x, y, bc_type=bc_type) + bspl = BSpline.from_power_basis(cb, bc_type=bc_type) + xx = np.linspace(0, 1, 20) + xp_assert_close(cb(xx), bspl(xx), atol=1e-15) + bspl_new = make_interp_spline(x, y, bc_type=bc_type) + xp_assert_close(bspl.c, bspl_new.c, atol=1e-15) + + @pytest.mark.parametrize('bc_type', ['natural', 'clamped', + 'periodic', 'not-a-knot']) + def test_from_power_basis_complex(self, bc_type): + # TODO: convert CubicSpline + rng = np.random.RandomState(1234) + x = np.sort(rng.random(20)) + y = rng.random(20) + rng.random(20) * 1j + if bc_type == 'periodic': + y[-1] = y[0] + cb = CubicSpline(x, y, bc_type=bc_type) + bspl = BSpline.from_power_basis(cb, bc_type=bc_type) + bspl_new_real = make_interp_spline(x, y.real, bc_type=bc_type) + bspl_new_imag = make_interp_spline(x, y.imag, bc_type=bc_type) + xp_assert_close(bspl.c, bspl_new_real.c + 1j * bspl_new_imag.c, atol=1e-15) + + def test_from_power_basis_exmp(self): + ''' + For x = [0, 1, 2, 3, 4] and y = [1, 1, 1, 1, 1] + the coefficients of Cubic Spline in the power basis: + + $[[0, 0, 0, 0, 0],\\$ + $[0, 0, 0, 0, 0],\\$ + $[0, 0, 0, 0, 0],\\$ + $[1, 1, 1, 1, 1]]$ + + It could be shown explicitly that coefficients of the interpolating + function in B-spline basis are c = [1, 1, 1, 1, 1, 1, 1] + ''' + x = np.array([0, 1, 2, 3, 4]) + y = np.array([1, 1, 1, 1, 1]) + bspl = BSpline.from_power_basis(CubicSpline(x, y, bc_type='natural'), + bc_type='natural') + xp_assert_close(bspl.c, [1.0, 1, 1, 1, 1, 1, 1], atol=1e-15) + + def test_read_only(self): + # BSpline must work on read-only knots and coefficients. + t = np.array([0, 1]) + c = np.array([3.0]) + t.setflags(write=False) + c.setflags(write=False) + + xx = np.linspace(0, 1, 10) + xx.setflags(write=False) + + b = BSpline(t=t, c=c, k=0) + xp_assert_close(b(xx), np.ones_like(xx) * 3.0) + + def test_concurrency(self, xp): + # Check that no segfaults appear with concurrent access to BSpline + b = _make_random_spline(xp=xp) + + def worker_fn(_, b): + t, _, k = b.tck + xx = xp.linspace(t[k], t[-k-1], 10000) + b(xx) + + _run_concurrent_barrier(10, worker_fn, b) + + + @pytest.mark.xfail( + sys.platform == "cygwin", + reason="threading.get_native_id not implemented", + raises=AttributeError + ) + def test_memmap(self, tmpdir): + # Make sure that memmaps can be used as t and c atrributes after the + # spline has been constructed. This is similar to what happens in a + # scikit-learn context, where joblib can create read-only memmap to + # share objects between workers. For more details, see + # https://github.com/scipy/scipy/issues/22143 + b = _make_random_spline() + xx = np.linspace(0, 1, 10) + + expected = b(xx) + + tid = threading.get_native_id() + t_mm = np.memmap(str(tmpdir.join(f't{tid}.dat')), mode='w+', + dtype=b.t.dtype, shape=b.t.shape) + t_mm[:] = b.t + c_mm = np.memmap(str(tmpdir.join(f'c{tid}.dat')), mode='w+', + dtype=b.c.dtype, shape=b.c.shape) + c_mm[:] = b.c + b.t = t_mm + b.c = c_mm + + xp_assert_close(b(xx), expected) + + +@make_xp_test_case(BSpline) +class TestInsert: + + @pytest.mark.parametrize('xval', [0.0, 1.0, 2.5, 4, 6.5, 7.0]) + def test_insert(self, xval, xp): + # insert a knot, incl edges (0.0, 7.0) and exactly at an existing knot (4.0) + x = xp.arange(8, dtype=xp.float64) + y = xp.sin(x)**3 + spl = make_interp_spline(x, y, k=3) + + tck = (spl._t, spl._c, spl.k) + spl_1f = BSpline(*insert(xval, tck)) # FITPACK + spl_1 = spl.insert_knot(xval) + + xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15) + xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15) + + # knot insertion preserves values, unless multiplicity >= k+1 + xx = x if xval != x[-1] else x[:-1] + xx = xp.concat((xx, 0.5*(x[1:] + x[:-1]))) + xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) + + # ... repeat with ndim > 1 + y1 = xp.cos(x)**3 + spl_y1 = make_interp_spline(x, y1, k=3) + spl_yy = make_interp_spline(x, xp.stack((y, y1), axis=1), k=3) + spl_yy1 = spl_yy.insert_knot(xval) + + xp_assert_close(spl_yy1.t, spl_1.t, atol=1e-15) + xp_assert_close( + spl_yy1.c, + xp.stack((spl.insert_knot(xval).c, spl_y1.insert_knot(xval).c), axis=1), + atol=1e-15 + ) + + xx = x if xval != x[-1] else x[:-1] + xx = xp.concat((xx, 0.5*(x[1:] + x[:-1]))) + xp_assert_close(spl_yy(xx), spl_yy1(xx), atol=1e-15) + + + @pytest.mark.parametrize( + 'xval, m', [(0.0, 2), (1.0, 3), (1.5, 5), (4, 2), (7.0, 2)] + ) + def test_insert_multi(self, xval, m, xp): + x = xp.arange(8, dtype=xp.float64) + y = xp.sin(x)**3 + spl = make_interp_spline(x, y, k=3) + + spl_1f = BSpline(*insert(xval, (spl._t, spl._c, spl.k), m=m)) + spl_1 = spl.insert_knot(xval, m) + + xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15) + xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15) + + xx = x if xval != x[-1] else x[:-1] + xx = xp.concat((xx, 0.5*(x[1:] + x[:-1]))) + xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) + + def test_insert_random(self, xp): + rng = np.random.default_rng(12345) + n, k = 11, 3 + + t = xp.asarray(np.sort(rng.uniform(size=n+k+1))) + c = xp.asarray(rng.uniform(size=(n, 3, 2))) + spl = BSpline(t, c, k) + + xv = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1])) + spl_1 = spl.insert_knot(xv) + + xx = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1], size=33)) + xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) + + @pytest.mark.parametrize('xv', [0, 0.1, 2.0, 4.0, 4.5, # l.h. edge + 5.5, 6.0, 6.1, 7.0] # r.h. edge + ) + def test_insert_periodic(self, xv, xp): + x = xp.arange(8, dtype=xp.float64) + y = xp.sin(x)**3 + t, c, k = splrep(x, y, k=3) + t, c = map(xp.asarray, (t, c)) + spl = BSpline(t, c, k, extrapolate="periodic") + + spl_1 = spl.insert_knot(xv) + tf, cf, k = insert(xv, spl.tck, per=True) + + xp_assert_close(spl_1.t, xp.asarray(tf), atol=1e-15) + xp_assert_close(spl_1.c[:-k-1], xp.asarray(cf[:-k-1]), atol=1e-15) + + xx_np = np.random.default_rng(1234).uniform(low=0, high=7, size=41) + xx = xp.asarray(xx_np) + xp_assert_close(spl_1(xx), xp.asarray(splev(xx_np, (tf, cf, k))), atol=1e-15) + + @pytest.mark.parametrize('extrapolate', [None, 'periodic']) + def test_complex(self, extrapolate, xp): + x = xp.arange(8, dtype=xp.float64) * 2 * np.pi + y_re, y_im = xp.sin(x), xp.cos(x) + + spl = make_interp_spline(x, y_re + 1j*y_im, k=3) + spl.extrapolate = extrapolate + + spl_re = make_interp_spline(x, y_re, k=3) + spl_re.extrapolate = extrapolate + + spl_im = make_interp_spline(x, y_im, k=3) + spl_im.extrapolate = extrapolate + + xv = 3.5 + spl_1 = spl.insert_knot(xv) + spl_1re = spl_re.insert_knot(xv) + spl_1im = spl_im.insert_knot(xv) + + xp_assert_close(spl_1.t, spl_1re.t, atol=1e-15) + xp_assert_close(spl_1.t, spl_1im.t, atol=1e-15) + xp_assert_close(spl_1.c, spl_1re.c + 1j*spl_1im.c, atol=1e-15) + + def test_insert_periodic_too_few_internal_knots(self): + # both FITPACK and spl.insert_knot raise when there's not enough + # internal knots to make a periodic extension. + # Below the internal knots are 2, 3, , 4, 5 + # ^ + # 2, 3, 3.5, 4, 5 + # so two knots from each side from the new one, while need at least + # from either left or right. + xv = 3.5 + k = 3 + t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1)) + c = np.ones(len(t) - k - 1) + spl = BSpline(t, c, k, extrapolate="periodic") + + with assert_raises(ValueError): + insert(xv, (t, c, k), per=True) + + with assert_raises(ValueError): + spl.insert_knot(xv) + + def test_insert_no_extrap(self): + k = 3 + t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1)) + c = np.ones(len(t) - k - 1) + spl = BSpline(t, c, k) + + with assert_raises(ValueError): + spl.insert_knot(-1) + + with assert_raises(ValueError): + spl.insert_knot(8) + + with assert_raises(ValueError): + spl.insert_knot(3, m=0) + + +def test_knots_multiplicity(): + # Take a spline w/ random coefficients, throw in knots of varying + # multiplicity. + + def check_splev(b, j, der=0, atol=1e-14, rtol=1e-14): + # check evaluations against FITPACK, incl extrapolations + t, c, k = b.tck + x = np.unique(t) + x = np.r_[t[0]-0.1, 0.5*(x[1:] + x[:1]), t[-1]+0.1] + xp_assert_close(splev(x, (t, c, k), der), b(x, der), + atol=atol, rtol=rtol, err_msg=f'der = {der} k = {b.k}') + + # test loop itself + # [the index `j` is for interpreting the traceback in case of a failure] + for k in [1, 2, 3, 4, 5]: + b = _make_random_spline(k=k) + for j, b1 in enumerate(_make_multiples(b)): + check_splev(b1, j) + for der in range(1, k+1): + check_splev(b1, j, der, 1e-12, 1e-12) + + +def _naive_B(x, k, i, t): + """ + Naive way to compute B-spline basis functions. Useful only for testing! + computes B(x; t[i],..., t[i+k+1]) + """ + if k == 0: + return 1.0 if t[i] <= x < t[i+1] else 0.0 + if t[i+k] == t[i]: + c1 = 0.0 + else: + c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t) + if t[i+k+1] == t[i+1]: + c2 = 0.0 + else: + c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t) + return (c1 + c2) + + +def _naive_eval(x, t, c, k, *, xp): + """ + Naive B-spline evaluation. Useful only for testing! + """ + if x == t[k]: + i = k + else: + i = xp.searchsorted(t, x) - 1 + + assert t[i] <= x <= t[i+1] + assert i >= k and i < t.shape[0] - k + return sum(c[i-j] * _naive_B(x, k, i-j, t) for j in range(0, k+1)) + + +def _naive_eval_2(x, t, c, k, *, xp): + """Naive B-spline evaluation, another way.""" + n = t.shape[0] - (k+1) + assert n >= k+1 + assert c.shape[0] >= n + assert t[k] <= x <= t[n] + return sum(c[i] * _naive_B(x, k, i, t) for i in range(n)) + + +def _sum_basis_elements(x, t, c, k): + n = len(t) - (k+1) + assert n >= k+1 + assert c.shape[0] >= n + s = 0. + for i in range(n): + b = BSpline.basis_element(t[i:i+k+2], extrapolate=False)(x) + s += c[i] * np.nan_to_num(b) # zero out out-of-bounds elements + return s + + +def B_012(x, xp=np): + """ A linear B-spline function B(x | 0, 1, 2).""" + x = np.atleast_1d(x) + result = np.piecewise(x, [(x < 0) | (x > 2), + (x >= 0) & (x < 1), + (x >= 1) & (x <= 2)], + [lambda x: 0., lambda x: x, lambda x: 2.-x]) + return xp.asarray(result) + + +def B_0123(x, der=0): + """A quadratic B-spline function B(x | 0, 1, 2, 3).""" + x = np.atleast_1d(x) + conds = [x < 1, (x > 1) & (x < 2), x > 2] + if der == 0: + funcs = [lambda x: x*x/2., + lambda x: 3./4 - (x-3./2)**2, + lambda x: (3.-x)**2 / 2] + elif der == 2: + funcs = [lambda x: 1., + lambda x: -2., + lambda x: 1.] + else: + raise ValueError(f'never be here: der={der}') + pieces = np.piecewise(x, conds, funcs) + return pieces + + +def _make_random_spline(n=35, k=3, xp=np): + rng = np.random.RandomState(123) + t = np.sort(rng.random(n+k+1)) + c = rng.random(n) + t, c = xp.asarray(t), xp.asarray(c) + return BSpline.construct_fast(t, c, k) + + +def _make_multiples(b): + """Increase knot multiplicity.""" + c, k = b.c, b.k + + t1 = b.t.copy() + t1[17:19] = t1[17] + t1[22] = t1[21] + yield BSpline(t1, c, k) + + t1 = b.t.copy() + t1[:k+1] = t1[0] + yield BSpline(t1, c, k) + + t1 = b.t.copy() + t1[-k-1:] = t1[-1] + yield BSpline(t1, c, k) + + +class TestInterop: + # + # Test that FITPACK-based spl* functions can deal with BSpline objects + # + def setup_method(self): + xx = np.linspace(0, 4.*np.pi, 41) + yy = np.cos(xx) + b = make_interp_spline(xx, yy) + self.tck = (b.t, b.c, b.k) + self.xx, self.yy, self.b = xx, yy, b + + self.xnew = np.linspace(0, 4.*np.pi, 21) + + c2 = np.c_[b.c, b.c, b.c] + self.c2 = np.dstack((c2, c2)) + self.b2 = BSpline(b.t, self.c2, b.k) + + def test_splev(self): + xnew, b, b2 = self.xnew, self.b, self.b2 + + # check that splev works with 1-D array of coefficients + # for array and scalar `x` + xp_assert_close(splev(xnew, b), + b(xnew), atol=1e-15, rtol=1e-15) + xp_assert_close(splev(xnew, b.tck), + b(xnew), atol=1e-15, rtol=1e-15) + xp_assert_close(np.asarray([splev(x, b) for x in xnew]), + b(xnew), atol=1e-15, rtol=1e-15) + + # With N-D coefficients, there's a quirck: + # splev(x, BSpline) is equivalent to BSpline(x) + with assert_raises(ValueError, match="Calling splev.. with BSpline"): + splev(xnew, b2) + + # However, splev(x, BSpline.tck) needs some transposes. This is because + # BSpline interpolates along the first axis, while the legacy FITPACK + # wrapper does list(map(...)) which effectively interpolates along the + # last axis. Like so: + sh = tuple(range(1, b2.c.ndim)) + (0,) # sh = (1, 2, 0) + cc = b2.c.transpose(sh) + tck = (b2.t, cc, b2.k) + xp_assert_close(np.asarray(splev(xnew, tck)), + b2(xnew).transpose(sh), atol=1e-15, rtol=1e-15) + + def test_splrep(self): + x, y = self.xx, self.yy + # test that "new" splrep is equivalent to _impl.splrep + tck = splrep(x, y) + t, c, k = _impl.splrep(x, y) + xp_assert_close(tck[0], t, atol=1e-15) + xp_assert_close(tck[1], c, atol=1e-15) + assert tck[2] == k + + # also cover the `full_output=True` branch + tck_f, _, _, _ = splrep(x, y, full_output=True) + xp_assert_close(tck_f[0], t, atol=1e-15) + xp_assert_close(tck_f[1], c, atol=1e-15) + assert tck_f[2] == k + + # test that the result of splrep roundtrips with splev: + # evaluate the spline on the original `x` points + yy = splev(x, tck) + xp_assert_close(y, yy, atol=1e-15) + + # ... and also it roundtrips if wrapped in a BSpline + b = BSpline(*tck) + xp_assert_close(y, b(x), atol=1e-15) + + def test_splrep_errors(self): + # test that both "old" and "new" splrep raise for an N-D ``y`` array + # with n > 1 + x, y = self.xx, self.yy + y2 = np.c_[y, y] + with assert_raises(ValueError): + splrep(x, y2) + with assert_raises(ValueError): + _impl.splrep(x, y2) + + # input below minimum size + with assert_raises(TypeError, match="m > k must hold"): + splrep(x[:3], y[:3]) + with assert_raises(TypeError, match="m > k must hold"): + _impl.splrep(x[:3], y[:3]) + + def test_splprep(self): + x = np.arange(15, dtype=np.float64).reshape((3, 5)) + b, u = splprep(x) + tck, u1 = _impl.splprep(x) + + # test the roundtrip with splev for both "old" and "new" output + xp_assert_close(u, u1, atol=1e-15) + xp_assert_close(np.asarray(splev(u, b)), x, atol=1e-15) + xp_assert_close(np.asarray(splev(u, tck)), x, atol=1e-15) + + # cover the ``full_output=True`` branch + (b_f, u_f), _, _, _ = splprep(x, s=0, full_output=True) + xp_assert_close(u, u_f, atol=1e-15) + xp_assert_close(np.asarray(splev(u_f, b_f)), x, atol=1e-15) + + def test_splprep_errors(self): + # test that both "old" and "new" code paths raise for x.ndim > 2 + x = np.arange(3*4*5).reshape((3, 4, 5)) + with assert_raises(ValueError, match="too many values to unpack"): + splprep(x) + with assert_raises(ValueError, match="too many values to unpack"): + _impl.splprep(x) + + # input below minimum size + x = np.linspace(0, 40, num=3) + with assert_raises(TypeError, match="m > k must hold"): + splprep([x]) + with assert_raises(TypeError, match="m > k must hold"): + _impl.splprep([x]) + + # automatically calculated parameters are non-increasing + # see gh-7589 + x = [-50.49072266, -50.49072266, -54.49072266, -54.49072266] + with assert_raises(ValueError, match="Invalid inputs"): + splprep([x]) + with assert_raises(ValueError, match="Invalid inputs"): + _impl.splprep([x]) + + # given non-increasing parameter values u + x = [1, 3, 2, 4] + u = [0, 0.3, 0.2, 1] + with assert_raises(ValueError, match="Invalid inputs"): + splprep(*[[x], None, u]) + + def test_sproot(self): + b, b2 = self.b, self.b2 + roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi + # sproot accepts a BSpline obj w/ 1-D coef array + xp_assert_close(sproot(b), roots, atol=1e-7, rtol=1e-7) + xp_assert_close(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7) + + # ... and deals with trailing dimensions if coef array is N-D + with assert_raises(ValueError, match="Calling sproot.. with BSpline"): + sproot(b2, mest=50) + + # and legacy behavior is preserved for a tck tuple w/ N-D coef + c2r = b2.c.transpose(1, 2, 0) + rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50)) + assert rr.shape == (3, 2, 4) + xp_assert_close(rr - roots, np.zeros_like(rr), atol=1e-12) + + def test_splint(self): + # test that splint accepts BSpline objects + b, b2 = self.b, self.b2 + + xp_assert_close(splint(0, 1, b), + splint(0, 1, b.tck), atol=1e-14, check_0d=False) + xp_assert_close(splint(0, 1, b), + b.integrate(0, 1), atol=1e-14, check_0d=False) + + # ... and deals with N-D arrays of coefficients + with assert_raises(ValueError, match="Calling splint.. with BSpline"): + splint(0, 1, b2) + + # and the legacy behavior is preserved for a tck tuple w/ N-D coef + c2r = b2.c.transpose(1, 2, 0) + integr = np.asarray(splint(0, 1, (b2.t, c2r, b2.k))) + assert integr.shape == (3, 2) + xp_assert_close(integr, + splint(0, 1, b), atol=1e-14, check_shape=False) + + def test_splder(self): + for b in [self.b, self.b2]: + # pad the c array (FITPACK convention) + ct = len(b.t) - len(b.c) + b_c = b.c.copy() + if ct > 0: + b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])] + + for n in [1, 2, 3]: + bd = splder(b) + tck_d = _impl.splder((b.t.copy(), b_c, b.k)) + xp_assert_close(bd.t, tck_d[0], atol=1e-15) + xp_assert_close(bd.c, tck_d[1], atol=1e-15) + assert bd.k == tck_d[2] + assert isinstance(bd, BSpline) + assert isinstance(tck_d, tuple) # back-compat: tck in and out + + def test_splantider(self): + for b in [self.b, self.b2]: + # pad the c array (FITPACK convention) + ct = len(b.t) - len(b.c) + b_c = b.c.copy() + if ct > 0: + b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])] + + for n in [1, 2, 3]: + bd = splantider(b) + tck_d = _impl.splantider((b.t.copy(), b_c, b.k)) + xp_assert_close(bd.t, tck_d[0], atol=1e-15) + xp_assert_close(bd.c, tck_d[1], atol=1e-15) + assert bd.k == tck_d[2] + assert isinstance(bd, BSpline) + assert isinstance(tck_d, tuple) # back-compat: tck in and out + + def test_insert(self): + b, b2, xx = self.b, self.b2, self.xx + + j = b.t.size // 2 + tn = 0.5*(b.t[j] + b.t[j+1]) + + bn, tck_n = insert(tn, b), insert(tn, (b.t, b.c, b.k)) + xp_assert_close(splev(xx, bn), + splev(xx, tck_n), atol=1e-15) + assert isinstance(bn, BSpline) + assert isinstance(tck_n, tuple) # back-compat: tck in, tck out + + # for N-D array of coefficients, BSpline.c needs to be transposed + # after that, the results are equivalent. + sh = tuple(range(b2.c.ndim)) + c_ = b2.c.transpose(sh[1:] + (0,)) + tck_n2 = insert(tn, (b2.t, c_, b2.k)) + + bn2 = insert(tn, b2) + + # need a transpose for comparing the results, cf test_splev + xp_assert_close(np.asarray(splev(xx, tck_n2)).transpose(2, 0, 1), + bn2(xx), atol=1e-15) + assert isinstance(bn2, BSpline) + assert isinstance(tck_n2, tuple) # back-compat: tck in, tck out + + +@make_xp_test_case(make_interp_spline) +class TestInterp: + # + # Test basic ways of constructing interpolating splines. + # + xx = np.linspace(0., 2.*np.pi) + yy = np.sin(xx) + + def _get_xy(self, xp): + return xp.asarray(self.xx), xp.asarray(self.yy) + + def test_non_int_order(self): + with assert_raises(TypeError): + make_interp_spline(self.xx, self.yy, k=2.5) + + def test_order_0(self, xp): + xx, yy = self._get_xy(xp) + b = make_interp_spline(xx, yy, k=0) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + b = make_interp_spline(xx, yy, k=0, axis=-1) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + def test_linear(self, xp): + xx, yy = self._get_xy(xp) + b = make_interp_spline(xx, yy, k=1) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + b = make_interp_spline(xx, yy, k=1, axis=-1) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + @pytest.mark.parametrize('k', [0, 1, 2, 3]) + def test_incompatible_x_y(self, k): + x = [0, 1, 2, 3, 4, 5] + y = [0, 1, 2, 3, 4, 5, 6, 7] + with assert_raises(ValueError, match="Shapes of x"): + make_interp_spline(x, y, k=k) + + @pytest.mark.parametrize('k', [0, 1, 2, 3]) + def test_broken_x(self, k): + x = [0, 1, 1, 2, 3, 4] # duplicates + y = [0, 1, 2, 3, 4, 5] + with assert_raises(ValueError, match="x to not have duplicates"): + make_interp_spline(x, y, k=k) + + x = [0, 2, 1, 3, 4, 5] # unsorted + with assert_raises(ValueError, match="Expect x to be a 1D strictly"): + make_interp_spline(x, y, k=k) + + x = [0, 1, 2, 3, 4, 5] + x = np.asarray(x).reshape((1, -1)) # 1D + with assert_raises(ValueError, match="Expect x to be a 1D strictly"): + make_interp_spline(x, y, k=k) + + def test_not_a_knot(self, xp): + xx, yy = self._get_xy(xp) + for k in [2, 3, 4, 5, 6, 7]: + b = make_interp_spline(xx, yy, k) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + def test_periodic(self, xp): + xx, yy = self._get_xy(xp) + + # k = 5 here for more derivatives + b = make_interp_spline(xx, yy, k=5, bc_type='periodic') + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + # in periodic case it is expected equality of k-1 first + # derivatives at the boundaries + for i in range(1, 5): + xp_assert_close(b(xx[0], nu=i), b(xx[-1], nu=i), atol=1e-11) + # tests for axis=-1 + b = make_interp_spline(xx, yy, k=5, bc_type='periodic', axis=-1) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + for i in range(1, 5): + xp_assert_close(b(xx[0], nu=i), b(xx[-1], nu=i), atol=1e-11) + + @pytest.mark.parametrize('k', [2, 3, 4, 5, 6, 7]) + def test_periodic_random(self, k, xp): + # tests for both cases (k > n and k <= n) + n = 5 + rng = np.random.RandomState(1234) + x = np.sort(rng.random_sample(n) * 10) + y = rng.random_sample(n) * 100 + y[0] = y[-1] + x, y = xp.asarray(x), xp.asarray(y) + + b = make_interp_spline(x, y, k=k, bc_type='periodic') + xp_assert_close(b(x), y, atol=1e-14) + + def test_periodic_axis(self, xp): + n = self.xx.shape[0] + rng = np.random.RandomState(1234) + x = rng.random_sample(n) * 2 * np.pi + x = np.sort(x) + x[0] = 0. + x[-1] = 2 * np.pi + y = np.zeros((2, n)) + y[0] = np.sin(x) + y[1] = np.cos(x) + x, y = xp.asarray(x), xp.asarray(y) + + b = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1) + for i in range(n): + xp_assert_close(b(x[i]), y[:, i], atol=1e-14) + xp_assert_close(b(x[0]), b(x[-1]), atol=1e-14) + + def test_periodic_points_exception(self): + # first and last points should match when periodic case expected + rng = np.random.RandomState(1234) + k = 5 + n = 8 + x = np.sort(rng.random_sample(n)) + y = rng.random_sample(n) + y[0] = y[-1] - 1 # to be sure that they are not equal + with assert_raises(ValueError): + make_interp_spline(x, y, k=k, bc_type='periodic') + + def test_periodic_knots_exception(self): + # `periodic` case does not work with passed vector of knots + rng = np.random.RandomState(1234) + k = 3 + n = 7 + x = np.sort(rng.random_sample(n)) + y = rng.random_sample(n) + t = np.zeros(n + 2 * k) + with assert_raises(ValueError): + make_interp_spline(x, y, k, t, 'periodic') + + @pytest.mark.parametrize('k', [2, 3, 4, 5]) + def test_periodic_splev(self, k): + # comparison values of periodic b-spline with splev + b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic') + tck = splrep(self.xx, self.yy, per=True, k=k) + spl = splev(self.xx, tck) + xp_assert_close(spl, b(self.xx), atol=1e-14) + + # comparison derivatives of periodic b-spline with splev + for i in range(1, k): + spl = splev(self.xx, tck, der=i) + xp_assert_close(spl, b(self.xx, nu=i), atol=1e-10) + + def test_periodic_cubic(self): + # comparison values of cubic periodic b-spline with CubicSpline + b = make_interp_spline(self.xx, self.yy, k=3, bc_type='periodic') + cub = CubicSpline(self.xx, self.yy, bc_type='periodic') + xp_assert_close(b(self.xx), cub(self.xx), atol=1e-14) + + # edge case: Cubic interpolation on 3 points + rng = np.random.RandomState(1234) + n = 3 + x = np.sort(rng.random_sample(n) * 10) + y = rng.random_sample(n) * 100 + y[0] = y[-1] + b = make_interp_spline(x, y, k=3, bc_type='periodic') + cub = CubicSpline(x, y, bc_type='periodic') + xp_assert_close(b(x), cub(x), atol=1e-14) + + def test_periodic_full_matrix(self): + # comparison values of cubic periodic b-spline with + # solution of the system with full matrix + k = 3 + b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic') + t = _periodic_knots(self.xx, k) + c = _make_interp_per_full_matr(self.xx, self.yy, t, k) + b1 = np.vectorize(lambda x: _naive_eval(x, t, c, k, xp=np)) + xp_assert_close(b(self.xx), b1(self.xx), atol=1e-14) + + def test_quadratic_deriv(self, xp): + xx, yy = self._get_xy(xp) + der = [(1, 8.)] # order, value: f'(x) = 8. + + # derivative at right-hand edge + b = make_interp_spline(xx, yy, k=2, bc_type=(None, der)) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + xp_assert_close( + b(xx[-1], 1), + xp.asarray(der[0][1], dtype=xp.float64), + atol=1e-14, rtol=1e-14, check_0d=False + ) + + # derivative at left-hand edge + b = make_interp_spline(xx, yy, k=2, bc_type=(der, None)) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + xp_assert_close( + b(xx[0], 1), + xp.asarray(der[0][1], dtype=xp.float64), + atol=1e-14, rtol=1e-14, check_0d=False + ) + + def test_cubic_deriv(self, xp): + xx, yy = self._get_xy(xp) + k = 3 + + # first derivatives at left & right edges: + der_l, der_r = [(1, 3.)], [(1, 4.)] + b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r)) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + xp_assert_close( + b(xx[0], 1), + xp.asarray(der_l[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14 + ) + xp_assert_close( + b(xx[-1], 1), + xp.asarray(der_r[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14 + ) + + # 'natural' cubic spline, zero out 2nd derivatives at the boundaries + der_l, der_r = [(2, 0)], [(2, 0)] + b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r)) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + def test_quintic_derivs(self, xp): + k, n = 5, 7 + x = xp.arange(n, dtype=xp.float64) + y = xp.sin(x) + der_l = [(1, -12.), (2, 1)] + der_r = [(1, 8.), (2, 3.)] + b = make_interp_spline(x, y, k=k, bc_type=(der_l, der_r)) + xp_assert_close(b(x), y, atol=1e-14, rtol=1e-14) + xp_assert_close(xp.stack([b(x[0], 1), b(x[0], 2)]), + xp.asarray([val for (nu, val) in der_l], dtype=xp.float64)) + xp_assert_close(xp.stack([b(x[-1], 1), b(x[-1], 2)]), + xp.asarray([val for (nu, val) in der_r], dtype=xp.float64)) + + @pytest.mark.xfail(reason='unstable') + def test_cubic_deriv_unstable(self): + # 1st and 2nd derivative at x[0], no derivative information at x[-1] + # The problem is not that it fails [who would use this anyway], + # the problem is that it fails *silently*, and I've no idea + # how to detect this sort of instability. + # In this particular case: it's OK for len(t) < 20, goes haywire + # at larger `len(t)`. + k = 3 + t = _augknt(self.xx, k) + + der_l = [(1, 3.), (2, 4.)] + b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None)) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + + def test_knots_not_data_sites(self, xp): + # Knots need not coincide with the data sites. + # use a quadratic spline, knots are at data averages, + # two additional constraints are zero 2nd derivatives at edges + k = 2 + xx, yy = self._get_xy(xp) + + t = concat_1d(xp, + xp.ones(k+1) * xx[0], + (xx[1:] + xx[:-1]) / 2., + xp.ones(k+1) * xx[-1] + ) + b = make_interp_spline(xx, yy, k, t, + bc_type=([(2, 0)], [(2, 0)])) + + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + assert math.isclose(b(xx[0], 2), 0.0, abs_tol=1e-14) + assert math.isclose(b(xx[-1], 2), 0.0, abs_tol=1e-14) + + def test_minimum_points_and_deriv(self, xp): + # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and + # f'(0) = 0, f'(1) = 3. + k = 3 + x = xp.asarray([0., 1.]) + y = xp.asarray([0., 1.]) + b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)])) + + xx = xp.linspace(0., 1., 21, dtype=xp.float64) + yy = xx**3 + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + def test_deriv_spec(self): + # If one of the derivatives is omitted, the spline definition is + # incomplete. + x = y = [1.0, 2, 3, 4, 5, 6] + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=([(1, 0.)], None)) + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=(1, 0.)) + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=[(1, 0.)]) + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=42) + + # CubicSpline expects`bc_type=(left_pair, right_pair)`, while + # here we expect `bc_type=(iterable, iterable)`. + l, r = (1, 0.0), (1, 0.0) + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=(l, r)) + + def test_deriv_order_too_large(self, xp): + x = xp.arange(7) + y = x**2 + l, r = [(6, 0)], [(1, 0)] # 6th derivative = 0 at x[0] for k=3 + with assert_raises(ValueError, match="Bad boundary conditions at 0."): + # cannot fix 6th derivative at x[0]: does not segfault + make_interp_spline(x, y, bc_type=(l, r)) + + l, r = [(1, 0)], [(-6, 0)] # derivative order < 0 at x[-1] + with assert_raises(ValueError, match="Bad boundary conditions at 6."): + # does not segfault + make_interp_spline(x, y, bc_type=(l, r)) + + def test_complex(self, xp): + k = 3 + xx, yy = self._get_xy(xp) + yy = yy + 1.j*yy + + # first derivatives at left & right edges: + der_l, der_r = [(1, 3.j)], [(1, 4.+2.j)] + b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r)) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + assert cmath.isclose(b(xx[0], 1), der_l[0][1], abs_tol=1e-14) + assert cmath.isclose(b(xx[-1], 1), der_r[0][1], abs_tol=1e-14) + + # also test zero and first order + for k in (0, 1): + b = make_interp_spline(xx, yy, k=k) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + def test_int_xy(self, xp): + x = xp.arange(10, dtype=xp.int32) + y = xp.arange(10, dtype=xp.int32) + + # Cython chokes on "buffer type mismatch" (construction) or + # "no matching signature found" (evaluation) + for k in (0, 1, 2, 3): + b = make_interp_spline(x, y, k=k) + b(x) + + def test_sliced_input(self, xp): + # Cython code chokes on non C contiguous arrays + xx = xp.linspace(-1, 1, 100) + + x = xx[::5] + y = xx[::5] + + for k in (0, 1, 2, 3): + make_interp_spline(x, y, k=k) + + def test_check_finite(self, xp): + # check_finite defaults to True; nans and such trigger a ValueError + x = xp.arange(10, dtype=xp.float64) + y = x**2 + + for z in [xp.nan, xp.inf, -xp.inf]: + y = xpx.at(y, -1).set(z) + assert_raises(ValueError, make_interp_spline, x, y) + + @pytest.mark.parametrize('k', [1, 2, 3, 5]) + def test_list_input(self, k): + # regression test for gh-8714: TypeError for x, y being lists and k=2 + x = list(range(10)) + y = [a**2 for a in x] + make_interp_spline(x, y, k=k) + + def test_multiple_rhs(self, xp): + xx, yy = self._get_xy(xp) + yy = xp.stack((xx, yy), axis=1) + der_l = [(1, [1., 2.])] + der_r = [(1, [3., 4.])] + + b = make_interp_spline(xx, yy, k=3, bc_type=(der_l, der_r)) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + xp_assert_close( + b(xx[0], 1), + xp.asarray(der_l[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14 + ) + xp_assert_close( + b(xx[-1], 1), + xp.asarray(der_r[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14 + ) + + def test_shapes(self): + rng = np.random.RandomState(1234) + k, n = 3, 22 + x = np.sort(rng.random(size=n)) + y = rng.random(size=(n, 5, 6, 7)) + + b = make_interp_spline(x, y, k) + assert b.c.shape == (n, 5, 6, 7) + + # now throw in some derivatives + d_l = [(1, rng.random((5, 6, 7)))] + d_r = [(1, rng.random((5, 6, 7)))] + b = make_interp_spline(x, y, k, bc_type=(d_l, d_r)) + assert b.c.shape == (n + k - 1, 5, 6, 7) + + def test_string_aliases(self, xp): + xx, yy = self._get_xy(xp) + yy = xp.sin(xx) + + # a single string is duplicated + b1 = make_interp_spline(xx, yy, k=3, bc_type='natural') + b2 = make_interp_spline(xx, yy, k=3, bc_type=([(2, 0)], [(2, 0)])) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # two strings are handled + b1 = make_interp_spline(xx, yy, k=3, + bc_type=('natural', 'clamped')) + b2 = make_interp_spline(xx, yy, k=3, + bc_type=([(2, 0)], [(1, 0)])) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # one-sided BCs are OK + b1 = make_interp_spline(xx, yy, k=2, bc_type=(None, 'clamped')) + b2 = make_interp_spline(xx, yy, k=2, bc_type=(None, [(1, 0.0)])) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # 'not-a-knot' is equivalent to None + b1 = make_interp_spline(xx, yy, k=3, bc_type='not-a-knot') + b2 = make_interp_spline(xx, yy, k=3, bc_type=None) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # unknown strings do not pass + with assert_raises(ValueError): + make_interp_spline(xx, yy, k=3, bc_type='typo') + + # string aliases are handled for 2D values + yy = xp.stack((xp.sin(xx), xp.cos(xx)), axis=1) + der_l = [(1, [0., 0.])] + der_r = [(2, [0., 0.])] + b2 = make_interp_spline(xx, yy, k=3, bc_type=(der_l, der_r)) + b1 = make_interp_spline(xx, yy, k=3, + bc_type=('clamped', 'natural')) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # ... and for N-D values: + rng = np.random.RandomState(1234) + k, n = 3, 22 + x = np.sort(rng.random(size=n)) + y = rng.random(size=(n, 5, 6, 7)) + x, y = xp.asarray(x), xp.asarray(y) + + # now throw in some derivatives + d_l = [(1, xp.zeros((5, 6, 7)))] + d_r = [(1, xp.zeros((5, 6, 7)))] + b1 = make_interp_spline(x, y, k, bc_type=(d_l, d_r)) + b2 = make_interp_spline(x, y, k, bc_type='clamped') + xp_assert_close(b1.c, b2.c, atol=1e-15) + + def test_full_matrix(self, xp): + rng = np.random.RandomState(1234) + k, n = 3, 7 + x_np = np.sort(rng.random(size=n)) + y_np = rng.random(size=n) + t_np = _not_a_knot(x_np, k) + cf = make_interp_full_matr(x_np, y_np, t_np, k) + cf = xp.asarray(cf) + + x, y, t = map(xp.asarray, (x_np, y_np, t_np)) + b = make_interp_spline(x, y, k, t) + xp_assert_close(b.c, cf, atol=1e-14, rtol=1e-14) + + def test_woodbury(self): + ''' + Random elements in diagonal matrix with blocks in the + left lower and right upper corners checking the + implementation of Woodbury algorithm. + ''' + rng = np.random.RandomState(1234) + n = 201 + for k in range(3, 32, 2): + offset = int((k - 1) / 2) + a = np.diagflat(rng.random((1, n))) + for i in range(1, offset + 1): + a[:-i, i:] += np.diagflat(rng.random((1, n - i))) + a[i:, :-i] += np.diagflat(rng.random((1, n - i))) + ur = rng.random((offset, offset)) + a[:offset, -offset:] = ur + ll = rng.random((offset, offset)) + a[-offset:, :offset] = ll + d = np.zeros((k, n)) + for i, j in enumerate(range(offset, -offset - 1, -1)): + if j < 0: + d[i, :j] = np.diagonal(a, offset=j) + else: + d[i, j:] = np.diagonal(a, offset=j) + b = rng.random(n) + xp_assert_close(_woodbury_algorithm(d, ur, ll, b, k), + np.linalg.solve(a, b), atol=1e-14) + + +def make_interp_full_matr(x, y, t, k): + """Assemble an spline order k with knots t to interpolate + y(x) using full matrices. + Not-a-knot BC only. + + This routine is here for testing only (even though it's functional). + """ + assert x.size == y.size + assert t.size == x.size + k + 1 + n = x.size + + A = np.zeros((n, n), dtype=np.float64) + + for j in range(n): + xval = x[j] + if xval == t[k]: + left = k + else: + left = np.searchsorted(t, xval) - 1 + + # fill a row + bb = _dierckx.evaluate_all_bspl(t, k, xval, left) + A[j, left-k:left+1] = bb + + c = sl.solve(A, y) + return c + + +def make_lsq_full_matrix(x, y, t, k=3): + """Make the least-square spline, full matrices.""" + x, y, t = map(np.asarray, (x, y, t)) + m = x.size + n = t.size - k - 1 + + A = np.zeros((m, n), dtype=np.float64) + + for j in range(m): + xval = x[j] + # find interval + if xval == t[k]: + left = k + else: + left = np.searchsorted(t, xval) - 1 + + # fill a row + bb = _dierckx.evaluate_all_bspl(t, k, xval, left) + A[j, left-k:left+1] = bb + + # have observation matrix, can solve the LSQ problem + B = np.dot(A.T, A) + Y = np.dot(A.T, y) + c = sl.solve(B, Y) + + return c, (A, Y) + + +parametrize_lsq_methods = pytest.mark.parametrize("method", ["norm-eq", "qr"]) + + +@make_xp_test_case(make_lsq_spline) +class TestLSQ: + # + # Test make_lsq_spline + # + rng = np.random.RandomState(1234) + n, k = 13, 3 + x = np.sort(rng.random(n)) + y = rng.random(n) + t = _augknt(np.linspace(x[0], x[-1], 7), k) + + @parametrize_lsq_methods + def test_lstsq(self, method): + # check LSQ construction vs a full matrix version + x, y, t, k = self.x, self.y, self.t, self.k + + c0, AY = make_lsq_full_matrix(x, y, t, k) + b = make_lsq_spline(x, y, t, k, method=method) + + xp_assert_close(b.c, c0) + assert b.c.shape == (t.size - k - 1,) + + # also check against numpy.lstsq + aa, yy = AY + c1, _, _, _ = np.linalg.lstsq(aa, y, rcond=-1) + xp_assert_close(b.c, c1) + + @parametrize_lsq_methods + def test_weights(self, method, xp): + # weights = 1 is same as None + x, y, t, k = *map(xp.asarray, (self.x, self.y, self.t)), self.k + w = xp.ones_like(x) + + b = make_lsq_spline(x, y, t, k, method=method) + b_w = make_lsq_spline(x, y, t, k, w=w, method=method) + + xp_assert_close(b.t, b_w.t, atol=1e-14) + xp_assert_close(b.c, b_w.c, atol=1e-14) + assert b.k == b_w.k + + def test_weights_same(self, xp): + # both methods treat weights + x, y, t, k = *map(xp.asarray, (self.x, self.y, self.t)), self.k + w = np.random.default_rng(1234).uniform(size=x.shape[0]) + w = xp.asarray(w) + + b_ne = make_lsq_spline(x, y, t, k, w=w, method="norm-eq") + b_qr = make_lsq_spline(x, y, t, k, w=w, method="qr") + b_no_w = make_lsq_spline(x, y, t, k, method="qr") + + xp_assert_close(b_ne.c, b_qr.c, atol=1e-14) + assert not xp.all(xp.abs(b_no_w.c - b_qr.c) < 1e-14) + + @parametrize_lsq_methods + def test_multiple_rhs(self, method, xp): + x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n + rng = np.random.RandomState(1234) + y = rng.random(size=(n, 5, 6, 7)) + y = xp.asarray(y) + + b = make_lsq_spline(x, y, t, k, method=method) + assert b.c.shape == (t.shape[0] - k - 1, 5, 6, 7) + + @parametrize_lsq_methods + def test_multiple_rhs_2(self, method, xp): + x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n + nrhs = 3 + rng = np.random.RandomState(1234) + y = rng.random(size=(n, nrhs)) + y = xp.asarray(y) + b = make_lsq_spline(x, y, t, k, method=method) + + bb = [make_lsq_spline(x, y[:, i], t, k, method=method) + for i in range(nrhs)] + coefs = xp.stack([bb[i].c for i in range(nrhs)]).T + + xp_assert_close(coefs, b.c, atol=1e-15) + + def test_multiple_rhs_3(self, xp): + x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n + nrhs = 3 + y = np.random.random(size=(n, nrhs)) + y = xp.asarray(y) + b_qr = make_lsq_spline(x, y, t, k, method="qr") + b_neq = make_lsq_spline(x, y, t, k, method="norm-eq") + xp_assert_close(b_qr.c, b_neq.c, atol=1e-15) + + @parametrize_lsq_methods + def test_complex(self, method, xp): + # cmplx-valued `y` + x, t, k = *map(xp.asarray, (self.x, self.t)), self.k + yc = xp.asarray(self.y * (1. + 2.j)) + + b = make_lsq_spline(x, yc, t, k, method=method) + b_re = make_lsq_spline(x, xp.real(yc), t, k, method=method) + b_im = make_lsq_spline(x, xp.imag(yc), t, k, method=method) + + xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15) + + def test_complex_2(self, xp): + # test complex-valued y with y.ndim > 1 + + x, t, k = *map(xp.asarray, (self.x, self.t)), self.k + yc = xp.asarray(self.y * (1. + 2.j)) + yc = xp.stack((yc, yc), axis=1) + + b = make_lsq_spline(x, yc, t, k) + b_re = make_lsq_spline(x, xp.real(yc), t, k) + b_im = make_lsq_spline(x, xp.imag(yc), t, k) + + xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15) + + # repeat with num_trailing_dims > 1 : yc.shape[1:] = (2, 2) + yc = xp.stack((yc, yc), axis=1) + + b = make_lsq_spline(x, yc, t, k) + b_re = make_lsq_spline(x, xp.real(yc), t, k) + b_im = make_lsq_spline(x, xp.imag(yc), t, k) + + xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15) + + @parametrize_lsq_methods + def test_int_xy(self, method): + x = np.arange(10).astype(int) + y = np.arange(10).astype(int) + t = _augknt(x, k=1) + # Cython chokes on "buffer type mismatch" + make_lsq_spline(x, y, t, k=1, method=method) + + @parametrize_lsq_methods + def test_f32_xy(self, method): + x = np.arange(10, dtype=np.float32) + y = np.arange(10, dtype=np.float32) + t = _augknt(x, k=1) + spl_f32 = make_lsq_spline(x, y, t, k=1, method=method) + spl_f64 = make_lsq_spline( + x.astype(float), y.astype(float), t.astype(float), k=1, method=method + ) + + x2 = (x[1:] + x[:-1]) / 2.0 + xp_assert_close(spl_f32(x2), spl_f64(x2), atol=1e-15) + + @parametrize_lsq_methods + def test_sliced_input(self, method): + # Cython code chokes on non C contiguous arrays + xx = np.linspace(-1, 1, 100) + + x = xx[::3] + y = xx[::3] + t = _augknt(x, 1) + make_lsq_spline(x, y, t, k=1, method=method) + + @parametrize_lsq_methods + def test_checkfinite(self, method): + # check_finite defaults to True; nans and such trigger a ValueError + x = np.arange(12).astype(float) + y = x**2 + t = _augknt(x, 3) + + for z in [np.nan, np.inf, -np.inf]: + y[-1] = z + assert_raises(ValueError, make_lsq_spline, x, y, t, method=method) + + @parametrize_lsq_methods + def test_read_only(self, method): + # Check that make_lsq_spline works with read only arrays + x, y, t = self.x, self.y, self.t + x.setflags(write=False) + y.setflags(write=False) + t.setflags(write=False) + make_lsq_spline(x=x, y=y, t=t, method=method) + + @pytest.mark.parametrize('k', list(range(1, 7))) + def test_qr_vs_norm_eq(self, k): + # check that QR and normal eq solutions match + x, y = self.x, self.y + t = _augknt(np.linspace(x[0], x[-1], 7), k) + spl_norm_eq = make_lsq_spline(x, y, t, k=k, method='norm-eq') + spl_qr = make_lsq_spline(x, y, t, k=k, method='qr') + + xx = (x[1:] + x[:-1]) / 2.0 + xp_assert_close(spl_norm_eq(xx), spl_qr(xx), atol=1e-15) + + def test_duplicates(self): + # method="qr" can handle duplicated data points + x = np.repeat(self.x, 2) + y = np.repeat(self.y, 2) + spl_1 = make_lsq_spline(self.x, self.y, self.t, k=3, method='qr') + spl_2 = make_lsq_spline(x, y, self.t, k=3, method='qr') + + xx = (x[1:] + x[:-1]) / 2.0 + xp_assert_close(spl_1(xx), spl_2(xx), atol=1e-15) + + +class PackedMatrix: + """A simplified CSR format for when non-zeros in each row are consecutive. + + Assuming that each row of an `(m, nc)` matrix 1) only has `nz` non-zeros, and + 2) these non-zeros are consecutive, we only store an `(m, nz)` matrix of + non-zeros and a 1D array of row offsets. This way, a row `i` of the original + matrix A is ``A[i, offset[i]: offset[i] + nz]``. + + """ + def __init__(self, a, offset, nc): + self.a = a + self.offset = offset + self.nc = nc + + assert a.ndim == 2 + assert offset.ndim == 1 + assert a.shape[0] == offset.shape[0] + + @property + def shape(self): + return self.a.shape[0], self.nc + + def todense(self): + out = np.zeros(self.shape) + nelem = self.a.shape[1] + for i in range(out.shape[0]): + nel = min(self.nc - self.offset[i], nelem) + out[i, self.offset[i]:self.offset[i] + nel] = self.a[i, :nel] + return out + + +def _qr_reduce_py(a_p, y, startrow=1): + """This is a python counterpart of the `_qr_reduce` routine, + declared in interpolate/src/__fitpack.h + """ + from scipy.linalg.lapack import dlartg + + # unpack the packed format + a = a_p.a + offset = a_p.offset + nc = a_p.nc + + m, nz = a.shape + + assert y.shape[0] == m + R = a.copy() + y1 = y.copy() + + for i in range(startrow, m): + oi = offset[i] + for j in range(oi, nc): + # rotate only the lower diagonal + if j >= min(i, nc): + break + + # In dense format: diag a1[j, j] vs a1[i, j] + c, s, r = dlartg(R[j, 0], R[i, 0]) + + # rotate l.h.s. + R[j, 0] = r + for l in range(1, nz): + R[j, l], R[i, l-1] = fprota(c, s, R[j, l], R[i, l]) + R[i, -1] = 0.0 + + # rotate r.h.s. + for l in range(y1.shape[1]): + y1[j, l], y1[i, l] = fprota(c, s, y1[j, l], y1[i, l]) + + # convert to packed + offs = list(range(R.shape[0])) + R_p = PackedMatrix(R, np.array(offs, dtype=np.int64), nc) + + return R_p, y1 + + +def fprota(c, s, a, b): + """Givens rotate [a, b]. + + [aa] = [ c s] @ [a] + [bb] [-s c] [b] + + """ + aa = c*a + s*b + bb = -s*a + c*b + return aa, bb + + +def fpback(R_p, y): + """Backsubsitution solve upper triangular banded `R @ c = y.` + + `R` is in the "packed" format: `R[i, :]` is `a[i, i:i+k+1]` + """ + R = R_p.a + _, nz = R.shape + nc = R_p.nc + assert y.shape[0] == R.shape[0] + + c = np.zeros_like(y[:nc]) + c[nc-1, ...] = y[nc-1] / R[nc-1, 0] + for i in range(nc-2, -1, -1): + nel = min(nz, nc-i) + # NB: broadcast R across trailing dimensions of `c`. + summ = (R[i, 1:nel, None] * c[i+1:i+nel, ...]).sum(axis=0) + c[i, ...] = ( y[i] - summ ) / R[i, 0] + return c + + +class TestGivensQR: + # Test row-by-row QR factorization, used for the LSQ spline construction. + # This is implementation detail; still test it separately. + def _get_xyt(self, n): + k = 3 + x = np.arange(n, dtype=float) + y = x**3 + 1/(1+x) + t = _not_a_knot(x, k) + return x, y, t, k + + def test_vs_full(self): + n = 10 + x, y, t, k = self._get_xyt(n) + + # design matrix + a_csr = BSpline.design_matrix(x, t, k) + + # dense QR + q, r = sl.qr(a_csr.todense()) + qTy = q.T @ y + + # prepare the PackedMatrix to factorize + # convert to "packed" format + m, nc = a_csr.shape + assert nc == t.shape[0] - k - 1 + + offset = a_csr.indices[::(k+1)] + offset = np.ascontiguousarray(offset, dtype=np.int64) + A = a_csr.data.reshape(m, k+1) + + R = PackedMatrix(A, offset, nc) + y_ = y[:, None] # _qr_reduce requires `y` a 2D array + _dierckx.qr_reduce(A, offset, nc, y_) # modifies arguments in-place + + # signs may differ + xp_assert_close(np.minimum(R.todense() + r, + R.todense() - r), np.zeros_like(r), atol=1e-15) + xp_assert_close(np.minimum(abs(qTy - y_[:, 0]), + abs(qTy + y_[:, 0])), np.zeros_like(qTy), atol=2e-13) + + # sign changes are consistent between Q and R: + c_full = sl.solve(r, qTy) + c_banded, _, _ = _dierckx.fpback(R.a, R.nc, x, y_, t, k, np.ones_like(y), y_) + xp_assert_close(c_full, c_banded[:, 0], atol=5e-13) + + def test_py_vs_compiled(self): + # test _qr_reduce vs a python implementation + n = 10 + x, y, t, k = self._get_xyt(n) + + # design matrix + a_csr = BSpline.design_matrix(x, t, k) + m, nc = a_csr.shape + assert nc == t.shape[0] - k - 1 + + offset = a_csr.indices[::(k+1)] + offset = np.ascontiguousarray(offset, dtype=np.int64) + A = a_csr.data.reshape(m, k+1) + + R = PackedMatrix(A, offset, nc) + y_ = y[:, None] + + RR, yy = _qr_reduce_py(R, y_) + _dierckx.qr_reduce(A, offset, nc , y_) # in-place + + xp_assert_close(RR.a, R.a, atol=1e-15) + xp_assert_equal(RR.offset, R.offset, check_dtype=False) + assert RR.nc == R.nc + xp_assert_close(yy, y_, atol=1e-15) + + # Test C-level construction of the design matrix + + def test_data_matrix(self): + n = 10 + x, y, t, k = self._get_xyt(n) + w = np.arange(1, n+1, dtype=float) + + A, offset, nc = _dierckx.data_matrix(x, t, k, w) + + m = x.shape[0] + a_csr = BSpline.design_matrix(x, t, k) + a_w = (a_csr * w[:, None]).tocsr() + A_ = a_w.data.reshape((m, k+1)) + offset_ = a_w.indices[::(k+1)].astype(np.int64) + + xp_assert_close(A, A_, atol=1e-15) + xp_assert_equal(offset, offset_) + assert nc == t.shape[0] - k - 1 + + def test_fpback(self): + n = 10 + x, y, t, k = self._get_xyt(n) + y = np.c_[y, y**2] + A, offset, nc = _dierckx.data_matrix(x, t, k, np.ones_like(x)) + R = PackedMatrix(A, offset, nc) + _dierckx.qr_reduce(A, offset, nc, y) + + c = fpback(R, y) + cc, _, _ = _dierckx.fpback(A, nc, x, y, t, k, np.ones_like(x), y) + + xp_assert_close(cc, c, atol=1e-14) + + def test_evaluate_all_bspl(self): + n = 10 + x, _, t, k = self._get_xyt(n) + zero_array = np.zeros((k + 1,), dtype=float) + for xval in x: + xp_assert_equal( + _dierckx.evaluate_all_bspl(t, k, xval, n, k + 2), zero_array) + xp_assert_equal( + _dierckx.evaluate_all_bspl(t, k, xval, n, 2*k), zero_array) + + +def data_file(basename): + return os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', basename) + + +@make_xp_test_case(make_smoothing_spline) +class TestSmoothingSpline: + # + # test make_smoothing_spline + # + def test_invalid_input(self): + rng = np.random.RandomState(1234) + n = 100 + x = np.sort(rng.random_sample(n) * 4 - 2) + y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n) + + # ``x`` and ``y`` should have same shapes (1-D array) + with assert_raises(ValueError): + make_smoothing_spline(x, y[1:]) + with assert_raises(ValueError): + make_smoothing_spline(x[1:], y) + with assert_raises(ValueError): + make_smoothing_spline(x.reshape(1, n), y) + + # ``x`` should be an ascending array + with assert_raises(ValueError): + make_smoothing_spline(x[::-1], y) + + x_dupl = np.copy(x) + x_dupl[0] = x_dupl[1] + + with assert_raises(ValueError): + make_smoothing_spline(x_dupl, y) + + # x and y length must be >= 5 + x = np.arange(4) + y = np.ones(4) + exception_message = "``x`` and ``y`` length must be at least 5" + with pytest.raises(ValueError, match=exception_message): + make_smoothing_spline(x, y) + + def test_compare_with_GCVSPL(self): + """ + Data is generated in the following way: + >>> np.random.seed(1234) + >>> n = 100 + >>> x = np.sort(np.random.random_sample(n) * 4 - 2) + >>> y = np.sin(x) + np.random.normal(scale=.5, size=n) + >>> np.savetxt('x.csv', x) + >>> np.savetxt('y.csv', y) + + We obtain the result of performing the GCV smoothing splines + package (by Woltring, gcvspl) on the sample data points + using its version for Octave (https://github.com/srkuberski/gcvspl). + In order to use this implementation, one should clone the repository + and open the folder in Octave. + In Octave, we load up ``x`` and ``y`` (generated from Python code + above): + + >>> x = csvread('x.csv'); + >>> y = csvread('y.csv'); + + Then, in order to access the implementation, we compile gcvspl files in + Octave: + + >>> mex gcvsplmex.c gcvspl.c + >>> mex spldermex.c gcvspl.c + + The first function computes the vector of unknowns from the dataset + (x, y) while the second one evaluates the spline in certain points + with known vector of coefficients. + + >>> c = gcvsplmex( x, y, 2 ); + >>> y0 = spldermex( x, c, 2, x, 0 ); + + If we want to compare the results of the gcvspl code, we can save + ``y0`` in csv file: + + >>> csvwrite('y0.csv', y0); + + """ + # load the data sample + with np.load(data_file('gcvspl.npz')) as data: + # data points + x = data['x'] + y = data['y'] + + y_GCVSPL = data['y_GCVSPL'] + y_compr = make_smoothing_spline(x, y)(x) + + # such tolerance is explained by the fact that the spline is built + # using an iterative algorithm for minimizing the GCV criteria. These + # algorithms may vary, so the tolerance should be rather low. + # Not checking dtypes as gcvspl.npz stores little endian arrays, which + # result in conflicting dtypes on big endian systems. + xp_assert_close(y_compr, y_GCVSPL, atol=1e-4, rtol=1e-4, check_dtype=False) + + def test_non_regularized_case(self, xp): + """ + In case the regularization parameter is 0, the resulting spline + is an interpolation spline with natural boundary conditions. + """ + # create data sample + rng = np.random.RandomState(1234) + n = 100 + x = np.sort(rng.random_sample(n) * 4 - 2) + y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n) + + x, y = xp.asarray(x), xp.asarray(y) + + spline_GCV = make_smoothing_spline(x, y, lam=0.) + spline_interp = make_interp_spline(x, y, 3, bc_type='natural') + + grid = xp.linspace(x[0], x[-1], 2 * n) + xp_assert_close(spline_GCV(grid), + spline_interp(grid), + atol=1e-15) + + @pytest.mark.fail_slow(2) + def test_weighted_smoothing_spline(self, xp): + # create data sample + rng = np.random.RandomState(1234) + n = 100 + x = np.sort(rng.random_sample(n) * 4 - 2) + y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n) + + x, y = map(xp.asarray, (x, y)) + + spl = make_smoothing_spline(x, y) + + # in order not to iterate over all of the indices, we select 10 of + # them randomly + for ind in rng.choice(range(100), size=10): + w = xp.ones(n) + xpx.at(w, int(ind)).set(30.) # w[int(ind)] = 30. + spl_w = make_smoothing_spline(x, y, w) + # check that spline with weight in a certain point is closer to the + # original point than the one without weights + orig = abs(spl(x[ind]) - y[ind]) + weighted = abs(spl_w(x[ind]) - y[ind]) + + if orig < weighted: + raise ValueError(f'Spline with weights should be closer to the' + f' points than the original one: {orig:.4} < ' + f'{weighted:.4}') + + +################################ +# NdBSpline tests +def bspline2(xy, t, c, k): + """A naive 2D tensort product spline evaluation.""" + x, y = xy + tx, ty = t + nx = len(tx) - k - 1 + assert (nx >= k+1) + ny = len(ty) - k - 1 + assert (ny >= k+1) + res = sum(c[ix, iy] * B(x, k, ix, tx) * B(y, k, iy, ty) + for ix in range(nx) for iy in range(ny)) + return np.asarray(res) + + +def B(x, k, i, t): + if k == 0: + return 1.0 if t[i] <= x < t[i+1] else 0.0 + if t[i+k] == t[i]: + c1 = 0.0 + else: + c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t) + if t[i+k+1] == t[i+1]: + c2 = 0.0 + else: + c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t) + return c1 + c2 + + +def bspline(x, t, c, k): + n = len(t) - k - 1 + assert (n >= k+1) and (len(c) >= n) + return sum(c[i] * B(x, k, i, t) for i in range(n)) + + +class NdBSpline0: + def __init__(self, t, c, k=3): + """Tensor product spline object. + + c[i1, i2, ..., id] * B(x1, i1) * B(x2, i2) * ... * B(xd, id) + + Parameters + ---------- + c : ndarray, shape (n1, n2, ..., nd, ...) + b-spline coefficients + t : tuple of 1D ndarrays + knot vectors in directions 1, 2, ... d + ``len(t[i]) == n[i] + k + 1`` + k : int or length-d tuple of integers + spline degrees. + """ + ndim = len(t) + assert ndim <= len(c.shape) + + try: + len(k) + except TypeError: + # make k a tuple + k = (k,)*ndim + + self.k = tuple(operator.index(ki) for ki in k) + self.t = tuple(np.asarray(ti, dtype=float) for ti in t) + self.c = c + + def __call__(self, x): + ndim = len(self.t) + # a single evaluation point: `x` is a 1D array_like, shape (ndim,) + assert len(x) == ndim + + # get the indices in an ndim-dimensional vector + i = ['none', ]*ndim + for d in range(ndim): + td, xd = self.t[d], x[d] + k = self.k[d] + + # find the index for x[d] + if xd == td[k]: + i[d] = k + else: + i[d] = np.searchsorted(td, xd) - 1 + assert td[i[d]] <= xd <= td[i[d]+1] + assert i[d] >= k and i[d] < len(td) - k + i = tuple(i) + + # iterate over the dimensions, form linear combinations of + # products B(x_1) * B(x_2) * ... B(x_N) of (k+1)**N b-splines + # which are non-zero at `i = (i_1, i_2, ..., i_N)`. + result = 0 + iters = [range(i[d] - self.k[d], i[d] + 1) for d in range(ndim)] + for idx in itertools.product(*iters): + term = self.c[idx] * np.prod([B(x[d], self.k[d], idx[d], self.t[d]) + for d in range(ndim)]) + result += term + return np.asarray(result) + + +@make_xp_test_case(NdBSpline) +class TestNdBSpline: + + def test_1D(self, xp): + # test ndim=1 agrees with BSpline + rng = np.random.default_rng(12345) + n, k = 11, 3 + n_tr = 7 + t = np.sort(rng.uniform(size=n + k + 1)) + c = rng.uniform(size=(n, n_tr)) + + t = xp.asarray(t) + c = xp.asarray(c) + + b = BSpline(t, c, k) + nb = NdBSpline((t,), c, k) + + xi = rng.uniform(size=21) + xi = xp.asarray(xi) + + # NdBSpline expects xi.shape=(npts, ndim) + xp_assert_close(nb(xi[:, None]), + b(xi), atol=1e-14) + assert nb(xi[:, None]).shape == (xi.shape[0], c.shape[1]) + + def make_2d_case(self, xp=np): + # make a 2D separable spline + x = xp.arange(6) + y = x**3 + spl = make_interp_spline(x, y, k=3) + + y_1 = x**3 + 2*x + spl_1 = make_interp_spline(x, y_1, k=3) + + t2 = (spl.t, spl_1.t) + c2 = spl.c[:, None] * spl_1.c[None, :] + + return t2, c2, 3 + + def make_2d_mixed(self, xp=np): + # make a 2D separable spline w/ kx=3, ky=2 + x = xp.arange(6) + y = x**3 + spl = make_interp_spline(x, y, k=3) + + x = xp.arange(5, dtype=xp.float64) + 1.5 + y_1 = x**2 + 2*x + spl_1 = make_interp_spline(x, y_1, k=2) + + t2 = (spl.t, spl_1.t) + c2 = spl.c[:, None] * spl_1.c[None, :] + + return t2, c2, spl.k, spl_1.k + + def test_2D_separable(self, xp): + xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)] + t2, c2, k = self.make_2d_case(xp=xp) + target = [x**3 * (y**3 + 2*y) for (x, y) in xi] + + # sanity check: bspline2 gives the product as constructed + b2 = [bspline2( + xy, + [np.asarray(_) for _ in t2], + np.asarray(c2), + k + ) for xy in xi + ] + b2 = np.asarray(b2, dtype=np.float64) + xp_assert_close(xp.asarray(b2), + xp.asarray(target, dtype=xp.float64), + check_shape=False, + atol=1e-14) + + # check evaluation on a 2D array: the 1D array of 2D points + bspl2 = NdBSpline(t2, c2, k=3) + assert bspl2(xi).shape == (len(xi), ) + xp_assert_close(bspl2(xi), + xp.asarray(target, dtype=xp.float64), atol=1e-14) + + # test that a nan in -> nan out + xi = np.asarray(xi) + xi[0, 1] = np.nan + xi = xp.asarray(xi) + xp_assert_equal(xp.isnan(bspl2(xi)), xp.asarray([True, False, False])) + + # now check on a multidim xi + rng = np.random.default_rng(12345) + xi = rng.uniform(size=(4, 3, 2)) * 5 + xi = xp.asarray(xi) + result = bspl2(xi) + assert result.shape == (4, 3) + + # also check the values + rrr = xp.reshape(xi, (-1, 2)).T + x, y = rrr[0, ...], rrr[1, ...] + xp_assert_close(xp_ravel(result, xp=xp), + x**3 * (y**3 + 2*y), atol=1e-14) + + def test_2D_separable_2(self, xp): + # test `c` with trailing dimensions, i.e. c.ndim > ndim + ndim = 2 + xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)] + target = [x**3 * (y**3 + 2*y) for (x, y) in xi] + + t2, c2, k = self.make_2d_case(xp=xp) + c2_4 = xp.stack((c2, c2, c2, c2), axis=2) # c22.shape = (6, 6, 4) + + xy = (1.5, 2.5) + bspl2_4 = NdBSpline(t2, c2_4, k=3) + result = bspl2_4(xy) + val_single = NdBSpline(t2, c2, k)(xy) + assert result.shape == (4,) + xp_assert_close(result, + xp.stack([val_single, ]*4), atol=1e-14) + + # now try the array xi : the output.shape is (3, 4) where 3 + # is the number of points in xi and 4 is the trailing dimension of c + assert bspl2_4(xi).shape == np.shape(xi)[:-1] + bspl2_4.c.shape[ndim:] + xp_assert_close(bspl2_4(xi), + xp.asarray(target, dtype=xp.float64)[:, None], + check_shape=False, + atol=5e-14) + + # two trailing dimensions + c2_22 = xp.reshape(c2_4, (6, 6, 2, 2)) + bspl2_22 = NdBSpline(t2, c2_22, k=3) + + result = bspl2_22(xy) + assert result.shape == (2, 2) + target2_22 = xp.ones((2, 2), dtype=xp.float64)*val_single + xp_assert_close(result, target2_22, atol=1e-14) + + # now try the array xi : the output shape is (3, 2, 2) + # for 3 points in xi and c trailing dimensions being (2, 2) + assert (bspl2_22(xi).shape == + np.shape(xi)[:-1] + bspl2_22.c.shape[ndim:]) + xp_assert_close(bspl2_22(xi), + xp.asarray(target, dtype=xp.float64)[:, None, None], + check_shape=False, + atol=5e-14) + + def test_2D_separable_2_complex(self, xp): + # test `c` with c.dtype == complex, with and w/o trailing dims + xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)] + target = [x**3 * (y**3 + 2*y) for (x, y) in xi] + + target = [t + 2j*t for t in target] + + t2, c2, k = self.make_2d_case(xp=xp) + c2 = c2 * (1 + 2j) + c2_4 = xp.stack((c2, c2, c2, c2), axis=2) # c2_4.shape = (6, 6, 4) + + xy = (1.5, 2.5) + bspl2_4 = NdBSpline(t2, c2_4, k=3) + result = bspl2_4(xy) + val_single = NdBSpline(t2, c2, k)(xy) + assert result.shape == (4,) + xp_assert_close(result, + xp.stack([val_single]*4), atol=1e-14) + + def test_2D_random(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size-k-1, ty.size-k-1)) + + spl = NdBSpline((tx, ty), c, k=k) + + xi = (1., 1.) + xp_assert_close(spl(xi), + bspline2(xi, (tx, ty), c, k), atol=1e-14) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1]] + xp_assert_close(spl(xi), + [bspline2(xy, (tx, ty), c, k) for xy in xi], + atol=1e-14) + + def test_2D_mixed(self): + t2, c2, kx, ky = self.make_2d_mixed() + xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)] + target = [x**3 * (y**2 + 2*y) for (x, y) in xi] + bspl2 = NdBSpline(t2, c2, k=(kx, ky)) + assert bspl2(xi).shape == (len(xi), ) + xp_assert_close(bspl2(xi), + target, atol=1e-14) + + def test_2D_derivative(self, xp): + t2, c2, kx, ky = self.make_2d_mixed(xp=xp) + xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)] + bspl2 = NdBSpline(t2, c2, k=(kx, ky)) + + # Derivative orders and expected functions + test_cases = { + (1, 0): lambda x, y: 3 * x**2 * (y**2 + 2*y), + (1, 1): lambda x, y: 3 * x**2 * (2*y + 2), + (0, 0): lambda x, y: x**3 * (y**2 + 2*y), + (2*kx, 1): lambda x, y: 0, + (2*kx, 0): lambda x, y: 0, + (1, 3*ky): lambda x, y: 0, + (0, 3*ky): lambda x, y: 0, + (3*kx, 2*ky): lambda x, y: 0, + } + + for nu, expected_fn in test_cases.items(): + expected_vals = xp.asarray( + [expected_fn(x, y) for x, y in xi], dtype=xp.float64 + ) + + # Evaluate via nu argument + direct = bspl2(xi, nu=nu) + xp_assert_close(direct, expected_vals, atol=1e-14) + + # Evaluate via .derivative() call + via_method = bspl2.derivative(nu)(xi) + xp_assert_close(via_method, expected_vals, atol=1e-14) + + # Error cases + for bad_nu in [(-1, 0), # all(nu >= 0) + (-1, 0, 1)]: # len(nu) == ndim + with assert_raises(ValueError): + bspl2(xi, nu=bad_nu) + with assert_raises(ValueError): + bspl2.derivative(bad_nu) + + def test_2D_mixed_random(self): + rng = np.random.default_rng(12345) + kx, ky = 2, 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size - kx - 1, ty.size - ky - 1)) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1]] + + bspl2 = NdBSpline((tx, ty), c, k=(kx, ky)) + bspl2_0 = NdBSpline0((tx, ty), c, k=(kx, ky)) + + xp_assert_close(bspl2(xi), + [bspl2_0(xp) for xp in xi], atol=1e-14) + + def test_tx_neq_ty(self): + # 2D separable spline w/ len(tx) != len(ty) + x = np.arange(6) + y = np.arange(7) + 1.5 + + spl_x = make_interp_spline(x, x**3, k=3) + spl_y = make_interp_spline(y, y**2 + 2*y, k=3) + cc = spl_x.c[:, None] * spl_y.c[None, :] + bspl = NdBSpline((spl_x.t, spl_y.t), cc, (spl_x.k, spl_y.k)) + + values = (x**3)[:, None] * (y**2 + 2*y)[None, :] + rgi = RegularGridInterpolator((x, y), values) + + xi = [(a, b) for a, b in itertools.product(x, y)] + bxi = bspl(xi) + + assert not np.isnan(bxi).any() + xp_assert_close(bxi, rgi(xi), atol=1e-14) + xp_assert_close(bxi.reshape(values.shape), values, atol=1e-14) + + def make_3d_case(self, xp=np): + # make a 3D separable spline + x = xp.arange(6) + y = x**3 + spl = make_interp_spline(x, y, k=3) + + y_1 = x**3 + 2*x + spl_1 = make_interp_spline(x, y_1, k=3) + + y_2 = x**3 + 3*x + 1 + spl_2 = make_interp_spline(x, y_2, k=3) + + t2 = (spl.t, spl_1.t, spl_2.t) + c2 = (spl.c[:, None, None] * + spl_1.c[None, :, None] * + spl_2.c[None, None, :]) + + return t2, c2, 3 + + def test_3D_separable(self): + rng = np.random.default_rng(12345) + x, y, z = rng.uniform(size=(3, 11)) * 5 + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + xi = [_ for _ in zip(x, y, z)] + result = bspl3(xi) + assert result.shape == (11,) + xp_assert_close(result, target, atol=1e-14) + + def test_3D_derivative(self, xp): + t3, c3, k = self.make_3d_case(xp=xp) + bspl3 = NdBSpline(t3, c3, k=3) + rng = np.random.default_rng(12345) + x, y, z = rng.uniform(size=(3, 11)) * 5 + + xi_np = [_ for _ in zip(x, y, z)] + xi = xp.asarray(xi_np) + + # Derivative orders and their expected expressions + test_cases = { + (1, 0, 0): lambda x, y, z: 3 * x**2 * (y**3 + 2*y) * (z**3 + 3*z + 1), + (2, 0, 0): lambda x, y, z: 6 * x * (y**3 + 2*y) * (z**3 + 3*z + 1), + (2, 1, 0): lambda x, y, z: 6 * x * (3*y**2 + 2) * (z**3 + 3*z + 1), + (2, 1, 3): lambda x, y, z: 6 * x * (3*y**2 + 2) * 6, + (2, 1, 4): lambda x, y, z: 0.0, + } + + for nu, expected_fn in test_cases.items(): + expected_vals = [expected_fn(xi_, yi_, zi_) for xi_, yi_, zi_ in xi_np] + expected_vals = xp.asarray(expected_vals, dtype=xp.float64) + xp_assert_close(bspl3(xi, nu=nu), expected_vals, atol=1e-14) + xp_assert_close(bspl3.derivative(nu)(xi), expected_vals, atol=1e-14) + + def test_3D_random(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) + + spl = NdBSpline((tx, ty, tz), c, k=k) + spl_0 = NdBSpline0((tx, ty, tz), c, k=k) + + xi = (1., 1., 1) + xp_assert_close(spl(xi), spl_0(xi), atol=1e-14) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1], + [0.9, 1.4, 1.9]] + xp_assert_close(spl(xi), [spl_0(xp) for xp in xi], atol=1e-14) + + def test_3D_random_complex(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = (rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) + + rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))*1j) + + spl = NdBSpline((tx, ty, tz), c, k=k) + spl_re = NdBSpline((tx, ty, tz), c.real, k=k) + spl_im = NdBSpline((tx, ty, tz), c.imag, k=k) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1], + [0.9, 1.4, 1.9]] + xp_assert_close(spl(xi), + spl_re(xi) + 1j*spl_im(xi), atol=1e-14) + + @pytest.mark.parametrize('cls_extrap', [None, True]) + @pytest.mark.parametrize('call_extrap', [None, True]) + def test_extrapolate_3D_separable(self, cls_extrap, call_extrap): + # test that extrapolate=True does extrapolate + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap) + + # evaluate out of bounds + x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5] + x, y, z = map(np.asarray, (x, y, z)) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + result = bspl3(xi, extrapolate=call_extrap) + xp_assert_close(result, target, atol=1e-14) + + @pytest.mark.parametrize('extrap', [(False, True), (True, None)]) + def test_extrapolate_3D_separable_2(self, extrap): + # test that call(..., extrapolate=None) defers to self.extrapolate, + # otherwise supersedes self.extrapolate + t3, c3, k = self.make_3d_case() + cls_extrap, call_extrap = extrap + bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap) + + # evaluate out of bounds + x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5] + x, y, z = map(np.asarray, (x, y, z)) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + result = bspl3(xi, extrapolate=call_extrap) + xp_assert_close(result, target, atol=1e-14) + + def test_extrapolate_false_3D_separable(self): + # test that extrapolate=False produces nans for out-of-bounds values + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + # evaluate out of bounds and inside + x, y, z = [-2, 1, 7], [-3, 0.5, 6.5], [-1, 1.5, 7.5] + x, y, z = map(np.asarray, (x, y, z)) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + result = bspl3(xi, extrapolate=False) + assert np.isnan(result[0]) + assert np.isnan(result[-1]) + xp_assert_close(result[1:-1], target[1:-1], atol=1e-14) + + def test_x_nan_3D(self): + # test that spline(nan) is nan + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + # evaluate out of bounds and inside + x = np.asarray([-2, 3, np.nan, 1, 2, 7, np.nan]) + y = np.asarray([-3, 3.5, 1, np.nan, 3, 6.5, 6.5]) + z = np.asarray([-1, 3.5, 2, 3, np.nan, 7.5, 7.5]) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + mask = np.isnan(x) | np.isnan(y) | np.isnan(z) + target[mask] = np.nan + + result = bspl3(xi) + assert np.isnan(result[mask]).all() + xp_assert_close(result, target, atol=1e-14) + + def test_non_c_contiguous(self): + # check that non C-contiguous inputs are OK + rng = np.random.default_rng(12345) + kx, ky = 3, 3 + tx = np.sort(rng.uniform(low=0, high=4, size=16)) + tx = np.r_[(tx[0],)*kx, tx, (tx[-1],)*kx] + ty = np.sort(rng.uniform(low=0, high=4, size=16)) + ty = np.r_[(ty[0],)*ky, ty, (ty[-1],)*ky] + + assert not tx[::2].flags.c_contiguous + assert not ty[::2].flags.c_contiguous + + c = rng.uniform(size=(tx.size//2 - kx - 1, ty.size//2 - ky - 1)) + c = c.T + assert not c.flags.c_contiguous + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1]] + + bspl2 = NdBSpline((tx[::2], ty[::2]), c, k=(kx, ky)) + bspl2_0 = NdBSpline0((tx[::2], ty[::2]), c, k=(kx, ky)) + + xp_assert_close(bspl2(xi), + [bspl2_0(xp) for xp in xi], atol=1e-14) + + def test_readonly(self): + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + for i in range(3): + t3[i].flags.writeable = False + c3.flags.writeable = False + + bspl3_ = NdBSpline(t3, c3, k=3) + + assert bspl3((1, 2, 3)) == bspl3_((1, 2, 3)) + + def test_design_matrix(self): + t3, c3, k = self.make_3d_case() + + xi = np.asarray([[1, 2, 3], [4, 5, 6]]) + dm = NdBSpline(t3, c3, k).design_matrix(xi, t3, k) + dm1 = NdBSpline.design_matrix(xi, t3, [k, k, k]) + assert dm.shape[0] == xi.shape[0] + xp_assert_close(dm.todense(), dm1.todense(), atol=1e-16) + + with assert_raises(ValueError): + NdBSpline.design_matrix([1, 2, 3], t3, [k]*3) + + with assert_raises(ValueError, match="Data and knots*"): + NdBSpline.design_matrix([[1, 2]], t3, [k]*3) + + def test_concurrency(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) + + spl = NdBSpline((tx, ty, tz), c, k=k) + + def worker_fn(_, spl): + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1], + [0.9, 1.4, 1.9]] + spl(xi) + + _run_concurrent_barrier(10, worker_fn, spl) + + +class TestMakeND: + def test_2D_separable_simple(self): + x = np.arange(6) + y = np.arange(6) + 0.5 + values = x[:, None]**3 * (y**3 + 2*y)[None, :] + xi = [(a, b) for a, b in itertools.product(x, y)] + + bspl = make_ndbspl((x, y), values, k=1) + xp_assert_close(bspl(xi), values.ravel(), atol=1e-15) + + # test the coefficients vs outer product of 1D coefficients + spl_x = make_interp_spline(x, x**3, k=1) + spl_y = make_interp_spline(y, y**3 + 2*y, k=1) + cc = spl_x.c[:, None] * spl_y.c[None, :] + xp_assert_close(cc, bspl.c, atol=1e-11, rtol=0) + + # test against RGI + from scipy.interpolate import RegularGridInterpolator as RGI + rgi = RGI((x, y), values, method='linear') + xp_assert_close(rgi(xi), bspl(xi), atol=1e-14) + + def test_2D_separable_trailing_dims(self): + # test `c` with trailing dimensions, i.e. c.ndim > ndim + x = np.arange(6) + y = np.arange(6) + xi = [(a, b) for a, b in itertools.product(x, y)] + + # make values4.shape = (6, 6, 4) + values = x[:, None]**3 * (y**3 + 2*y)[None, :] + values4 = np.dstack((values, values, values, values)) + bspl = make_ndbspl((x, y), values4, k=3, solver=ssl.spsolve) + + result = bspl(xi) + target = np.dstack((values, values, values, values)).astype(float) + assert result.shape == (36, 4) + xp_assert_close(result.reshape(6, 6, 4), + target, atol=1e-14) + + # now two trailing dimensions + values22 = values4.reshape((6, 6, 2, 2)) + bspl = make_ndbspl((x, y), values22, k=3, solver=ssl.spsolve) + + result = bspl(xi) + assert result.shape == (36, 2, 2) + xp_assert_close(result.reshape(6, 6, 2, 2), + target.reshape((6, 6, 2, 2)), atol=1e-14) + + @pytest.mark.parametrize('k', [(3, 3), (1, 1), (3, 1), (1, 3), (3, 5)]) + def test_2D_mixed(self, k): + # make a 2D separable spline w/ len(tx) != len(ty) + x = np.arange(6) + y = np.arange(7) + 1.5 + xi = [(a, b) for a, b in itertools.product(x, y)] + + values = (x**3)[:, None] * (y**2 + 2*y)[None, :] + bspl = make_ndbspl((x, y), values, k=k, solver=ssl.spsolve) + xp_assert_close(bspl(xi), values.ravel(), atol=1e-15) + + def test_2D_nans(self): + x = np.arange(6) + y = np.arange(6) + 0.5 + y[-1] = np.nan + values = x[:, None]**3 * (y**3 + 2*y)[None, :] + + with assert_raises(ValueError): + make_ndbspl((x, y), values, k=1) + + def _get_sample_2d_data(self): + # from test_rgi.py::TestIntepN + x = np.array([.5, 2., 3., 4., 5.5, 6.]) + y = np.array([.5, 2., 3., 4., 5.5, 6.]) + z = np.array( + [ + [1, 2, 1, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 3, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + ] + ) + return x, y, z + + def test_2D_vs_RGI_linear(self): + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=1) + rgi = RegularGridInterpolator((x, y), z, method='linear') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + def test_2D_vs_RGI_cubic(self): + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=3, solver=ssl.spsolve) + rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + @pytest.mark.parametrize('solver', [ssl.gmres, ssl.gcrotmk]) + def test_2D_vs_RGI_cubic_iterative(self, solver): + # same as `test_2D_vs_RGI_cubic`, only with an iterative solver. + # Note the need to add an explicit `rtol` solver_arg to achieve the + # target accuracy of 1e-14. (the relation between solver atol/rtol + # and the accuracy of the final result is not direct and needs experimenting) + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=3, solver=solver, rtol=1e-6) + rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14, rtol=1e-7) + + def test_2D_vs_RGI_quintic(self): + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=5, solver=ssl.spsolve) + rgi = RegularGridInterpolator((x, y), z, method='quintic_legacy') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + @pytest.mark.parametrize( + 'k, meth', [(1, 'linear'), (3, 'cubic_legacy'), (5, 'quintic_legacy')] + ) + def test_3D_random_vs_RGI(self, k, meth): + rndm = np.random.default_rng(123456) + x = np.cumsum(rndm.uniform(size=6)) + y = np.cumsum(rndm.uniform(size=7)) + z = np.cumsum(rndm.uniform(size=8)) + values = rndm.uniform(size=(6, 7, 8)) + + bspl = make_ndbspl((x, y, z), values, k=k, solver=ssl.spsolve) + rgi = RegularGridInterpolator((x, y, z), values, method=meth) + + xi = np.random.uniform(low=0.7, high=2.1, size=(11, 3)) + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + def test_solver_err_not_converged(self): + x, y, z = self._get_sample_2d_data() + solver_args = {'maxiter': 1} + with assert_raises(ValueError, match='solver'): + make_ndbspl((x, y), z, k=3, **solver_args) + + with assert_raises(ValueError, match='solver'): + make_ndbspl((x, y), np.dstack((z, z)), k=3, **solver_args) + + +class TestFpchec: + # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f + + def test_1D_x_t(self): + k = 1 + t = np.arange(12).reshape(2, 6) + x = np.arange(12) + + with pytest.raises(ValueError, match="1D sequence"): + _b.fpcheck(x, t, k) + + with pytest.raises(ValueError, match="1D sequence"): + _b.fpcheck(t, x, k) + + def test_condition_1(self): + # c 1) k+1 <= n-k-1 <= m + k = 3 + n = 2*(k + 1) - 1 # not OK + m = n + 11 # OK + t = np.arange(n) + x = np.arange(m) + + assert dfitpack.fpchec(x, t, k) == 10 + with pytest.raises(ValueError, match="Need k+1*"): + _b.fpcheck(x, t, k) + + n = 2*(k+1) + 1 # OK + m = n - k - 2 # not OK + t = np.arange(n) + x = np.arange(m) + + assert dfitpack.fpchec(x, t, k) == 10 + with pytest.raises(ValueError, match="Need k+1*"): + _b.fpcheck(x, t, k) + + def test_condition_2(self): + # c 2) t(1) <= t(2) <= ... <= t(k+1) + # c t(n-k) <= t(n-k+1) <= ... <= t(n) + k = 3 + t = [0]*(k+1) + [2] + [5]*(k+1) # this is OK + x = [1, 2, 3, 4, 4.5] + + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None # does not raise + + tt = t.copy() + tt[-1] = tt[0] # not OK + assert dfitpack.fpchec(x, tt, k) == 20 + with pytest.raises(ValueError, match="Last k knots*"): + _b.fpcheck(x, tt, k) + + tt = t.copy() + tt[0] = tt[-1] # not OK + assert dfitpack.fpchec(x, tt, k) == 20 + with pytest.raises(ValueError, match="First k knots*"): + _b.fpcheck(x, tt, k) + + def test_condition_3(self): + # c 3) t(k+1) < t(k+2) < ... < t(n-k) + k = 3 + t = [0]*(k+1) + [2, 3] + [5]*(k+1) # this is OK + x = [1, 2, 3, 3.5, 4, 4.5] + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + t = [0]*(k+1) + [2, 2] + [5]*(k+1) # this is not OK + assert dfitpack.fpchec(x, t, k) == 30 + with pytest.raises(ValueError, match="Internal knots*"): + _b.fpcheck(x, t, k) + + def test_condition_4(self): + # c 4) t(k+1) <= x(i) <= t(n-k) + # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow. + k = 3 + t = [0]*(k+1) + [5]*(k+1) + x = [1, 2, 3, 3.5, 4, 4.5] # this is OK + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + xx = x.copy() + xx[0] = t[0] # still OK + assert dfitpack.fpchec(xx, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + xx = x.copy() + xx[0] = t[0] - 1 # not OK + assert dfitpack.fpchec(xx, t, k) == 40 + with pytest.raises(ValueError, match="Out of bounds*"): + _b.fpcheck(xx, t, k) + + xx = x.copy() + xx[-1] = t[-1] + 1 # not OK + assert dfitpack.fpchec(xx, t, k) == 40 + with pytest.raises(ValueError, match="Out of bounds*"): + _b.fpcheck(xx, t, k) + + # ### Test the S-W condition (no 5) + # c 5) the conditions specified by schoenberg and whitney must hold + # c for at least one subset of data points, i.e. there must be a + # c subset of data points y(j) such that + # c t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 + def test_condition_5_x1xm(self): + # x(1).ge.t(k2) .or. x(m).le.t(nk1) + k = 1 + t = [0, 0, 1, 2, 2] + x = [1.1, 1.1, 1.1] + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + x = [0.5, 0.5, 0.5] + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + def test_condition_5_k1(self): + # special case nk3 (== n - k - 2) < 2 + k = 1 + t = [0, 0, 1, 1] + x = [0.5, 0.6] + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + def test_condition_5_1(self): + # basically, there can't be an interval of t[j]..t[j+k+1] with no x + k = 3 + t = [0]*(k+1) + [2] + [5]*(k+1) + x = [3]*5 + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + t = [0]*(k+1) + [2] + [5]*(k+1) + x = [1]*5 + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + def test_condition_5_2(self): + # same as _5_1, only the empty interval is in the middle + k = 3 + t = [0]*(k+1) + [2, 3] + [5]*(k+1) + x = [1.1]*5 + [4] + + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + # and this one is OK + x = [1.1]*4 + [4, 4] + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + def test_condition_5_3(self): + # similar to _5_2, covers a different failure branch + k = 1 + t = [0, 0, 2, 3, 4, 5, 6, 7, 7] + x = [1, 1, 1, 5.2, 5.2, 5.2, 6.5] + + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + +# ### python replicas of generate_knots(...) implementation details, for testing. +# ### see TestGenerateKnots::test_split_and_add_knot +def _split(x, t, k, residuals): + """Split the knot interval into "runs". + """ + ix = np.searchsorted(x, t[k:-k]) + # sum half-open intervals + fparts = [residuals[ix[i]:ix[i+1]].sum() for i in range(len(ix)-1)] + carries = residuals[ix[1:-1]] + + for i in range(len(carries)): # split residuals at internal knots + carry = carries[i] / 2 + fparts[i] += carry + fparts[i+1] -= carry + + fparts[-1] += residuals[-1] # add the contribution of the last knot + + xp_assert_close(sum(fparts), sum(residuals), atol=1e-15) + + return fparts, ix + + +def _add_knot(x, t, k, residuals): + """Insert a new knot given reduals.""" + fparts, ix = _split(x, t, k, residuals) + + # find the interval with max fparts and non-zero number of x values inside + idx_max = -101 + fpart_max = -1e100 + for i in range(len(fparts)): + if ix[i+1] - ix[i] > 1 and fparts[i] > fpart_max: + idx_max = i + fpart_max = fparts[i] + + if idx_max == -101: + raise ValueError("Internal error, please report it to SciPy developers.") + + # round up, like Dierckx does? This is really arbitrary though. + idx_newknot = (ix[idx_max] + ix[idx_max+1] + 1) // 2 + new_knot = x[idx_newknot] + idx_t = np.searchsorted(t, new_knot) + t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]] + return t_new + + +@make_xp_test_case(generate_knots) +class TestGenerateKnots: + def test_split_add_knot(self): + # smoke test implementation details: insert a new knot given residuals + x = np.arange(8, dtype=float) + y = x**3 + 1./(1 + x) + k = 3 + t = np.array([0.]*(k+1) + [7.]*(k+1)) + spl = make_lsq_spline(x, y, k=k, t=t) + residuals = (spl(x) - y)**2 + + from scipy.interpolate import _fitpack_repro as _fr + new_t = _fr.add_knot(x, t, k, residuals) + new_t_py = _add_knot(x, t, k, residuals) + + xp_assert_close(new_t, new_t_py, atol=1e-15) + + # redo with new knots + spl2 = make_lsq_spline(x, y, k=k, t=new_t) + residuals2 = (spl2(x) - y)**2 + + new_t2 = _fr.add_knot(x, new_t, k, residuals2) + new_t2_py = _add_knot(x, new_t, k, residuals2) + + xp_assert_close(new_t2, new_t2_py, atol=1e-15) + + @pytest.mark.parametrize('k', [1, 2, 3, 4, 5]) + def test_s0(self, k, xp): + x = xp.arange(8, dtype=xp.float64) + y = xp.sin(x*xp.pi/8) + t = list(generate_knots(x, y, k=k, s=0))[-1] + + tt = splrep(x, y, k=k, s=0)[0] + tt = xp.asarray(tt, dtype=xp.float64) + xp_assert_close(t, tt, atol=1e-15) + + def test_s0_1(self, xp): + # with these data, naive algorithm tries to insert >= nmax knots + n = 10 + x = xp.arange(n, dtype=xp.float64) + y = x**3 + knots = list(generate_knots(x, y, k=3, s=0)) # does not error out + expected = xp.asarray(_not_a_knot(np.asarray(x), 3)) + xp_assert_close(knots[-1], expected, atol=1e-15) + + def test_s0_n20(self, xp): + n = 20 + x = xp.arange(n) + y = x**3 + knots = list(generate_knots(x, y, k=3, s=0)) + expected = xp.asarray(_not_a_knot(np.asarray(x), 3)) + xp_assert_close(knots[-1], expected, atol=1e-15) + + def test_s0_nest(self): + # s=0 and non-default nest: not implemented, errors out + x = np.arange(10) + y = x**3 + with assert_raises(ValueError): + list(generate_knots(x, y, k=3, s=0, nest=10)) + + def test_s_switch(self, xp): + # test the process switching to interpolating knots when len(t) == m + k + 1 + """ + To generate the `wanted` list below apply the following diff and rerun + the test. The stdout will contain successive iterations of the `t` + array. + +$ git diff scipy/interpolate/fitpack/fpcurf.f +diff --git a/scipy/interpolate/fitpack/fpcurf.f b/scipy/interpolate/fitpack/fpcurf.f +index 1afb1900f1..d817e51ad8 100644 +--- a/scipy/interpolate/fitpack/fpcurf.f ++++ b/scipy/interpolate/fitpack/fpcurf.f +@@ -216,6 +216,9 @@ c t(j+k) <= x(i) <= t(j+k+1) and store it in fpint(j),j=1,2,...nrint. + do 190 l=1,nplus + c add a new knot. + call fpknot(x,m,t,n,fpint,nrdata,nrint,nest,1) ++ print*, l, nest, ': ', t ++ print*, "n, nmax = ", n, nmax ++ + c if n=nmax we locate the knots as for interpolation. + if(n.eq.nmax) go to 10 + c test whether we cannot further increase the number of knots. + """ # NOQA: E501 + x = xp.arange(8, dtype=xp.float64) + y = xp.sin(x*np.pi/8) + k = 3 + + knots = list(generate_knots(x, y, k=k, s=1e-7)) + wanted = [[0., 0., 0., 0., 7., 7., 7., 7.], + [0., 0., 0., 0., 4., 7., 7., 7., 7.], + [0., 0., 0., 0., 2., 4., 7., 7., 7., 7.], + [0., 0., 0., 0., 2., 4., 6., 7., 7., 7., 7.], + [0., 0., 0., 0., 2., 3., 4., 5., 7, 7., 7., 7.] + ] + wanted = [xp.asarray(want, dtype=xp.float64) for want in wanted] + + assert len(knots) == len(wanted) + for t, tt in zip(knots, wanted): + xp_assert_close(t, tt, atol=1e-15) + + # also check that the last knot vector matches FITPACK + t, _, _ = splrep(x, y, k=k, s=1e-7) + xp_assert_close(knots[-1], xp.asarray(t), atol=1e-15) + + def test_list_input(self): + # test that list inputs are accepted + x = list(range(8)) + gen = generate_knots(x, x, s=0.1, k=1) + next(gen) + + def test_nest(self, xp): + # test that nest < nmax stops the process early (and we get 10 knots not 12) + x = xp.arange(8, dtype=xp.float64) + y = xp.sin(x*xp.pi/8) + s = 1e-7 + + knots = list(generate_knots(x, y, k=3, s=s, nest=10)) + xp_assert_close( + knots[-1], + xp.asarray([0., 0., 0., 0., 2., 4., 7., 7., 7., 7.], dtype=xp.float64), + atol=1e-15 + ) + + with assert_raises(ValueError): + # nest < 2*(k+1) + list(generate_knots(x, y, k=3, nest=4)) + + def test_weights(self): + x = np.arange(8) + y = np.sin(x*np.pi/8) + + with assert_raises(ValueError): + list(generate_knots(x, y, w=np.arange(11))) # len(w) != len(x) + + with assert_raises(ValueError): + list(generate_knots(x, y, w=-np.ones(8))) # w < 0 + + @pytest.mark.parametrize("npts", [30, 50, 100]) + @pytest.mark.parametrize("s", [0.1, 1e-2, 0]) + def test_vs_splrep(self, s, npts): + # XXX this test is brittle: differences start apearing for k=3 and s=1e-6, + # also for k != 3. Might be worth investigating at some point. + # I think we do not really guarantee exact agreement with splrep. Instead, + # we guarantee it is the same *in most cases*; otherwise slight differences + # are allowed. There is no theorem, it is al heuristics by P. Dierckx. + # The best we can do it to best-effort reproduce it. + rndm = np.random.RandomState(12345) + x = 10*np.sort(rndm.uniform(size=npts)) + y = np.sin(x*np.pi/10) + np.exp(-(x-6)**2) + + k = 3 + t = splrep(x, y, k=k, s=s)[0] + tt = list(generate_knots(x, y, k=k, s=s))[-1] + + xp_assert_close(tt, t, atol=1e-15) + + def test_s_too_small(self): + n = 14 + x = np.arange(n) + y = x**3 + + # XXX splrep warns that "s too small": ier=2 + knots = list(generate_knots(x, y, k=3, s=1e-50)) + + with pytest.warns(RuntimeWarning) as r: + tck = splrep(x, y, k=3, s=1e-50) + assert len(r) == 1 + xp_assert_equal(knots[-1], tck[0]) + + def test_zero_weights(self): + # regression test for https://github.com/scipy/scipy/issues/23542 + gen = generate_knots([0.,1.,2.,3.], [4.,5.,6.,7.], w=[0.,0.,0.,0.], s=1) + with pytest.raises(ValueError, match="weights are zero"): + list(gen) + + +def disc_naive(t, k): + """Straitforward way to compute the discontinuity matrix. For testing ONLY. + + This routine returns a dense matrix, while `_fitpack_repro.disc` returns + a packed one. + """ + n = t.shape[0] + + delta = t[n - k - 1] - t[k] + nrint = n - 2*k - 1 + + ti = t[k+1:n-k-1] # internal knots + tii = np.repeat(ti, 2) + tii[::2] += 1e-10 + tii[1::2] -= 1e-10 + m = BSpline(t, np.eye(n - k - 1), k)(tii, nu=k) + + matr = np.empty((nrint-1, m.shape[1]), dtype=float) + for i in range(0, m.shape[0], 2): + matr[i//2, :] = m[i, :] - m[i+1, :] + + matr *= (delta/nrint)**k / math.factorial(k) + return matr + + +class F_dense: + """ The r.h.s. of ``f(p) = s``, an analog of _fitpack_repro.F + Uses full matrices, so is for tests only. + """ + def __init__(self, x, y, t, k, s, w=None, extrapolate=True): + self.x = x + self.y = y + self.t = t + self.k = k + self.w = np.ones_like(x, dtype=float) if w is None else w + self.extrapolate = extrapolate + assert self.w.ndim == 1 + + # lhs + a_dense = BSpline(t, np.eye(t.shape[0] - k - 1), k, extrapolate=extrapolate)(x) + self.a_dense = a_dense * self.w[:, None] + + from scipy.interpolate import _fitpack_repro as _fr + self.b_dense = PackedMatrix(*_fr.disc(t, k)).todense() + + # rhs + assert y.ndim == 1 + yy = y * self.w + self.yy = np.r_[yy, np.zeros(self.b_dense.shape[0])] + + self.s = s + + def __call__(self, p): + ab = np.vstack((self.a_dense, self.b_dense / p)) + + # LSQ solution of ab @ c = yy + from scipy.linalg import qr, solve + q, r = qr(ab, mode='economic') + + qy = q.T @ self.yy + + nc = r.shape[1] + c = solve(r[:nc, :nc], qy[:nc]) + + spl = BSpline(self.t, c, self.k, extrapolate=self.extrapolate) + fp = np.sum(self.w**2 * (spl(self.x) - self.y)**2) + + self.spl = spl # store it + + return fp - self.s + + +class _TestMakeSplrepBase: + + bc_type = None + + def _get_xykt(self, xp=np): + if self.bc_type == 'periodic': + x = xp.linspace(0, 2*np.pi, 10) # nodes + y = xp.sin(x) + s = 1.7e-4 + + return x, y, s + else: + x = xp.linspace(0, 5, 11) + y = xp.sin(x*3.14 / 5)**2 + s = 1.7e-4 + + return x, y, s + + def test_input_errors(self): + x = np.linspace(0, 10, 11) + y = np.linspace(0, 10, 12) + with assert_raises(ValueError): + # len(x) != len(y) + make_splrep(x, y, bc_type=self.bc_type) + + with assert_raises(ValueError): + # 0D inputs + make_splrep(1, 2, s=0.1, bc_type=self.bc_type) + + with assert_raises(ValueError): + # y.ndim > 2 + y = np.ones((x.size, 2, 2, 2)) + make_splrep(x, y, s=0.1, bc_type=self.bc_type) + + w = np.ones(12) + with assert_raises(ValueError): + # len(weights) != len(x) + make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type) + + w = -np.ones(12) + with assert_raises(ValueError): + # w < 0 + make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type) + + w = np.ones((x.shape[0], 2)) + with assert_raises(ValueError): + # w.ndim != 1 + make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type) + + with assert_raises(ValueError): + # x not ordered + make_splrep(x[::-1], x**3, s=0.1, bc_type=self.bc_type) + + with assert_raises(TypeError): + # k != int(k) + make_splrep(x, x**3, k=2.5, s=0.1, bc_type=self.bc_type) + + with assert_raises(ValueError): + # s < 0 + make_splrep(x, x**3, s=-1, bc_type=self.bc_type) + + with assert_raises(ValueError): + # nest < 2*k + 2 + make_splrep(x, x**3, k=3, nest=2, s=0.1, bc_type=self.bc_type) + + with assert_raises(ValueError): + # nest not None and s==0 + make_splrep(x, x**3, s=0, nest=11, bc_type=self.bc_type) + + with assert_raises(ValueError): + # len(x) != len(y) + make_splrep(np.arange(8), np.arange(9), s=0.1, bc_type=self.bc_type) + + def _test_with_knots(self, x, y, k, s): + t = list(generate_knots(x, y, k=k, s=s, bc_type=self.bc_type))[-1] + + spl_auto = make_splrep(x, y, k=k, s=s, bc_type=self.bc_type) + spl_t = make_splrep(x, y, t=t, k=k, s=s, bc_type=self.bc_type) + + xp_assert_close(spl_auto.t, spl_t.t, atol=1e-15) + xp_assert_close(spl_auto.c, spl_t.c, atol=1e-15) + assert spl_auto.k == spl_t.k + + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6]) + def test_with_knots(self, k): + x, y, s = self._get_xykt() + + self._test_with_knots(x, y, k, s) + + def _test_default_s(self, x, y, k): + spl = make_splrep(x, y, k=k, bc_type=self.bc_type) + spl_i = make_interp_spline(x, y, k=k, bc_type=self.bc_type) + t = list(generate_knots(x, y, k=k, bc_type=self.bc_type))[-1] + + xp_assert_close(spl.c, spl_i.c, atol=1e-15) + xp_assert_close(spl.t, t, atol=1e-15) + xp_assert_close(spl_i.t, t, atol=1e-15) + + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6]) + def test_default_s(self, k): + x, y, _ = self._get_xykt() + self._test_default_s(x, y, k) + + @pytest.mark.thread_unsafe + def test_s_too_small(self): + # both splrep and make_splrep warn that "s too small": ier=2 + s = 1e-30 + if self.bc_type == 'periodic': + x = np.linspace(0, 2*np.pi, 14) + y = np.sin(x) + else: + x = np.arange(14) + y = x**3 + + with warnings.catch_warnings(): + warnings.simplefilter( + "ignore", + RuntimeWarning + ) + tck = splrep(x, y, k=3, s=s, per=(self.bc_type == 'periodic')) + + with warnings.catch_warnings(): + warnings.simplefilter( + "ignore", + RuntimeWarning + ) + spl = make_splrep(x, y, k=3, s=s, bc_type=self.bc_type) + + xp_assert_close(spl.t, tck[0]) + xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)], + tck[1], atol=5e-13) + + @pytest.mark.parametrize("k", [1, 2, 3]) + def test_shape(self, k): + # make sure coefficients have the right shape (not extra dims) + n = 10 + if self.bc_type == 'periodic': + x = np.linspace(0, 2*np.pi, n) + y = np.cos(x) + else: + x = np.arange(n) + y = x**3 + + spl = make_splrep(x, y, k=k, bc_type=self.bc_type) + spl_1 = make_splrep(x, y, k=k, s=1e-5, bc_type=self.bc_type) + + assert spl.c.ndim == 1 + assert spl_1.c.ndim == 1 + + # force the general code path, not shortcuts + spl_2 = make_splrep(x, y + 1/(1+y), k=k, s=1e-5, bc_type=self.bc_type) + assert spl_2.c.ndim == 1 + + def test_error_on_invalid_bc_type(self): + N = 10 + a, b = 0, 2*np.pi + x = np.linspace(a, b, N + 1) # nodes + y = np.exp(x) + + with assert_raises(ValueError): + make_splrep(x, y, s=1e-8, bc_type="nonsense") + + @pytest.mark.parametrize("bc_type", ["periodic", None]) + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5]) + def test_make_splrep_with_unequal_weights(self, bc_type, k): + # Sample data + x = np.linspace(0, 2*np.pi, 10) + y = np.sin(x) + + w = np.linspace(1, 5, len(x)) + + tck = splrep(x, y, w=w, k=k, s=1e-8, per=(bc_type == 'periodic')) + spl = make_splrep(x, y, w=w, s=1e-8, k=k, bc_type=bc_type) + + xp_assert_close(spl.t, tck[0]) + xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)], + tck[1], atol=1e-8) + + + @pytest.mark.parametrize("bc_type", ["periodic", None]) + def test_make_splrep_with_non_c_contiguous_input(self, bc_type): + # regression test for https://github.com/scipy/scipy/issues/23371 + + def check(spl, tck): + xp_assert_close(spl.t, tck[0]) + xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)], + tck[1], atol=1e-8) + + # Sample data + x = np.linspace(0, 2*np.pi, 10) + y = np.sin(x) + + x1, y1 = np.c_[x, y].T + + # Safety check to make sure inputs + # are actually not C contiguous + assert x1.flags.c_contiguous is False + assert y1.flags.c_contiguous is False + + w = np.linspace(1, 5, len(x)) + w1, _ = np.c_[w, w].T + + # Safety check to make sure inputs + # are actually not C contiguous + assert w1.flags.c_contiguous is False + + tck = splrep(x, y, w=w, k=3, s=1e-8, per=(bc_type == 'periodic')) + + # only x.flags.c_contiguous is False + spl = make_splrep(x1, y, w=w, s=1e-8, k=3, bc_type=bc_type) + check(spl, tck) + + # only x.flags.c_contiguous is False + spl = make_splrep(x, y1, w=w, s=1e-8, k=3, bc_type=bc_type) + check(spl, tck) + + # only w.flags.c_contiguous is False + spl = make_splrep(x, y, w=w1, s=1e-8, k=3, bc_type=bc_type) + check(spl, tck) + + # x, y, z all have c_contiguous False + spl = make_splrep(x1, y1, w=w1, s=1e-8, k=3, + bc_type=bc_type) + check(spl, tck) + + + @pytest.mark.parametrize("bc_type", ["periodic", None]) + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5]) + def test_make_splrep_impl_no_optimization(self, bc_type, k): + # Sample data + x = np.linspace(0, 1, 10) + y = np.sin(2 * np.pi * x) + + xb, xe = x[0], x[-1] + k = 3 # Cubic spline + s = 1e-8 # No smoothing + + # Provide t with only boundary knots -> length = 2*(k+1) + t = np.array([xb] * (k + 1) + [xe] * (k + 1)) + + # Should skip optimization + spl = make_splrep(x, y, xb=xb, xe=xe, k=k, + s=s, t=t, nest=None, bc_type=bc_type) + + assert isinstance(spl, BSpline) + assert spl.t.shape[0] == 2 * (k + 1) + assert spl.k == k + xp_assert_close(spl.t[:k+1], np.asarray([xb] * (k + 1))) + xp_assert_close(spl.t[-(k+1):], np.asarray([xe] * (k + 1))) + + @pytest.mark.parametrize("n", [100, 51, 15, 11]) + @pytest.mark.parametrize("s", [10, 8, 5, 1, 1e-2]) + def test_make_splrep_matches_splrep_periodic(self, n, s): + rng = np.random.default_rng(123) + x = np.r_[0, np.sort(rng.uniform(0, 2 * np.pi, size=n - 2)), 2 * np.pi] + y = np.sin(x) + np.cos(x) + + t, c, k = splrep(x, y, s=s, per=(self.bc_type == "periodic")) + spl = make_splrep(x, y, s=s, bc_type=self.bc_type) + + if not (n == 11 and s == 1 and self.bc_type == "periodic"): + xp_assert_close(spl.t, t, atol=1e-15) + xp_assert_close(spl.c, c[:-k - 1], atol=1e-15) + + @pytest.mark.parametrize("n", [100, 51, 15, 11]) + @pytest.mark.parametrize("s", [10, 8, 5, 1, 1e-2]) + def test_make_splrep_with_splrep_knots(self, n, s): + rng = np.random.default_rng(123) + x = np.r_[0, np.sort(rng.uniform(0, 2 * np.pi, size=n - 2)), 2 * np.pi] + y = np.sin(x) + np.cos(x) + + t, c, k = splrep(x, y, s=s, per=(self.bc_type == "periodic")) + spl = make_splrep(x, y, s=s, bc_type=self.bc_type, t=t) + xp_assert_close(spl.c, c[:-k - 1], atol=1e-15) + + +@make_xp_test_case(make_splrep) +class TestMakeSplrep(_TestMakeSplrepBase): + + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6]) + def test_fitpack_F(self, k): + # test an implementation detail: banded/packed linalg vs full matrices + from scipy.interpolate._fitpack_repro import F + + x, y, s = self._get_xykt() + t = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1)) + f = F(x, y[:, None], t, k, s) # F expects y to be 2D + f_d = F_dense(x, y, t, k, s) + for p in [1, 10, 100]: + xp_assert_close(f(p), f_d(p), atol=1e-15) + + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6]) + def test_fitpack_F_with_weights(self, k): + # repeat test_fitpack_F, with weights + from scipy.interpolate._fitpack_repro import F + + x, y, s = self._get_xykt() + t = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1)) + w = np.arange(x.shape[0], dtype=float) + fw = F(x, y[:, None], t, k, s, w=w) # F expects y to be 2D + fw_d = F_dense(x, y, t, k, s, w=w) + + f_d = F_dense(x, y, t, k, s) # no weights + + for p in [1, 10, 100]: + xp_assert_close(fw(p), fw_d(p), atol=1e-15) + assert not np.allclose(f_d(p), fw_d(p), atol=1e-15) + + def test_disc_matrix(self): + # test an implementation detail: discontinuity matrix + # (jumps of k-th derivative at knots) + import scipy.interpolate._fitpack_repro as _fr + + rng = np.random.default_rng(12345) + t = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7))*5, 5, 5, 5, 5] + + n, k = len(t), 3 + D = PackedMatrix(*_fr.disc(t, k)).todense() + D_dense = disc_naive(t, k) + assert D.shape[0] == n - 2*k - 2 # number of internal knots + xp_assert_close(D, D_dense, atol=1e-15) + + def test_simple_vs_splrep(self, xp): + # XX: Non-periodic splines do not work for all supported degrees + k = 3 + x, y, s = self._get_xykt(xp) + tt = xp.asarray([0]*(k+1) + [2.5, 4.0] + [5]*(k+1)) + + t, c, k = splrep(x, y, k=k, s=s) + t, c = xp.asarray(t), xp.asarray(c) + assert all(t == tt) + + spl = make_splrep(x, y, k=k, s=s) + xp_assert_close(c[:spl.c.shape[0]], spl.c, atol=1e-15) + + def test_with_knots(self): + k = 3 + x, y, s = self._get_xykt() + + t = list(generate_knots(x, y, k=k, s=s))[-1] + + spl_auto = make_splrep(x, y, k=k, s=s) + spl_t = make_splrep(x, y, t=t, k=k, s=s) + + xp_assert_close(spl_auto.t, spl_t.t, atol=1e-15) + xp_assert_close(spl_auto.c, spl_t.c, atol=1e-15) + assert spl_auto.k == spl_t.k + + def test_no_internal_knots(self, xp): + # should not fail if there are no internal knots + n = 10 + x = xp.arange(n, dtype=xp.float64) + y = x**3 + k = 3 + spl = make_splrep(x, y, k=k, s=1) + assert spl.t.shape[0] == 2*(k+1) + + def test_default_s(self, xp): + n = 10 + x = xp.arange(n, dtype=xp.float64) + y = x**3 + spl = make_splrep(x, y, k=3) + spl_i = make_interp_spline(x, y, k=3) + + xp_assert_close(spl.c, spl_i.c, atol=1e-15) + + def test_s_too_small(self): + # both splrep and make_splrep warn that "s too small": ier=2 + n = 14 + x = np.arange(n) + y = x**3 + + with pytest.warns(RuntimeWarning) as r: + tck = splrep(x, y, k=3, s=1e-50) + spl = make_splrep(x, y, k=3, s=1e-50) + xp_assert_equal(spl.t, tck[0]) + xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)], + tck[1], atol=5e-13) + assert len(r) == 2 + + def test_issue_22704(self): + # Reference - https://github.com/scipy/scipy/issues/22704 + x = np.asarray([20.00, 153.81, 175.57, 202.47, 237.11, + 253.61, 258.56, 273.40, 284.54, 293.61, + 298.56, 301.86, 305.57, 307.22, 308.45, + 310.10, 310.10, 310.50], dtype=np.float64) + y = np.asarray([53.00, 49.50, 48.60, 46.80, 43.20, + 40.32, 39.60, 36.00, 32.40, 28.80, + 25.20, 21.60, 18.00, 14.40, 10.80, + 7.20, 3.60, 0.0], dtype=np.float64) + w = np.asarray([1.38723] * y.shape[0], dtype=np.float64) + with assert_raises(ValueError): + make_splrep(x, y, w=w, k=2, s=12) + + def test_shape(self, xp): + # make sure coefficients have the right shape (not extra dims) + n, k = 10, 3 + x = xp.arange(n, dtype=xp.float64) + y = x**3 + + spl = make_splrep(x, y, k=k) + spl_1 = make_splrep(x, y, k=k, s=1e-5) + + assert spl.c.ndim == 1 + assert spl_1.c.ndim == 1 + + # force the general code path, not shortcuts + spl_2 = make_splrep(x, y + 1/(1+y), k=k, s=1e-5) + assert spl_2.c.ndim == 1 + + def test_s0_vs_not(self, xp): + # check that the shapes are consistent + n, k = 10, 3 + x = xp.arange(n, dtype=xp.float64) + y = x**3 + + spl_0 = make_splrep(x, y, k=3, s=0) + spl_1 = make_splrep(x, y, k=3, s=1) + + assert spl_0.c.ndim == 1 + assert spl_1.c.ndim == 1 + + assert spl_0.t.shape[0] == n + k + 1 + assert spl_1.t.shape[0] == 2 * (k + 1) + + +@make_xp_test_case(make_splrep) +class TestMakeSplrepPeriodic(_TestMakeSplrepBase): + + bc_type = 'periodic' + + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6]) + def test_no_internal_knots(self, k, xp): + # should not fail if there are no internal knots + x = xp.linspace(0, 10, 11) # nodes + y = xp.ones((11,)) + + spl = make_splrep(x, y, k=k, s=1, bc_type=self.bc_type) + assert spl.t.shape[0] == 2*(k+1) + + @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6]) + def test_s0_vs_not(self, k): + # check that the shapes are consistent + n = 10 + x = np.linspace(0, 2*np.pi, n) + y = np.sin(x) + np.cos(x) + + spl_0 = make_splrep(x, y, k=k, s=0, bc_type=self.bc_type) + spl_1 = make_splrep(x, y, k=k, s=1, bc_type=self.bc_type) + + assert spl_0.c.ndim == 1 + assert spl_1.c.ndim == 1 + + assert spl_0.t.shape[0] == n + 2 * k + + def test_periodic_with_periodic_data(self, xp): + N = 10 + a, b = 0, 2*xp.pi + x = xp.linspace(a, b, N + 1, dtype=xp.float64) # nodes + + y = xp.cos(x) + spl = make_splrep(x, y, s=1e-8, bc_type=self.bc_type) + xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-4) + + y = xp.sin(x) + xp.cos(x) + spl = make_splrep(x, y, s=1e-12, bc_type=self.bc_type) + xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-6) + + y = 5*xp.sin(x) + xp.cos(x)*3 + spl = make_splrep(x, y, s=1e-8, bc_type=self.bc_type) + xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-4) + + def test_periodic_with_non_periodic_data(self): + N = 10 + a, b = 0, 2*np.pi + x = np.linspace(a, b, N + 1) # nodes + + y = np.exp(x) + with assert_raises(ValueError): + make_splrep(x, y, s=1e-8, bc_type=self.bc_type) + + @pytest.mark.parametrize("s", [0, 1e-50]) + def test_make_splrep_periodic_m_eq_2_k_eq_1(self, s): + # Two data points (m = 2) + x = np.array([0.0, 1.0]) + y = np.array([5.0, 5.0]) # constant function + w = np.array([1.0, 1.0]) if s > 0 else None + + # Degree 1 periodic spline + spl = make_splrep(x, y, w=w, k=1, bc_type="periodic", s=s) + tck = splrep(x, y, w=w, k=1, per=1, s=s) + + if s > 0: + xp_assert_close(spl.t, tck[0]) + xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)], + tck[1]) + + @pytest.mark.parametrize("k_fp", [(1, -0.0001), (2, -0.0001), (3, -8.62e-05)]) + @pytest.mark.parametrize("s", [1e-4]) + def test_fperiodic_basic_fit(self, k_fp, s): + n = 10 + x = np.linspace(0, 1, n) + y = np.sin(2 * np.pi * x) + k, fp = k_fp + + tck = splrep(x, y, k=k, s=s, per=1) + + fp0 = 4.5 + + spline = Fperiodic(x, y[:, None], tck[0], k=k, s=s) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + _ = root_rati(spline, 2.0, ((0, fp0 - s), (np.inf, fp - s)), s * 0.001) + + # Check the returned spline is periodic at endpoints + bs = spline.spl + x_check = np.array([0.0, 1.0]) + y_check = bs(x_check) + + xp_assert_close(y_check[0], y_check[1]) + + +@make_xp_test_case(make_splprep) +class TestMakeSplprep: + def _get_xyk(self, m=10, k=3, xp=np): + x = xp.arange(m, dtype=xp.float64) * xp.pi / m + y = [xp.sin(x), xp.cos(x)] + return x, y, k + + @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5]) + def test_simple_vs_splprep(self, s): + # Check/document the interface vs splPrep + # The four values of `s` are to probe all code paths and shortcuts + m, k = 10, 3 + x = np.arange(m) * np.pi / m + y = [np.sin(x), np.cos(x)] + + # the number of knots depends on `s` (this is by construction) + num_knots = {0: 14, 0.1: 8, 1e-3: 8 + 1, 1e-5: 8 + 2} + + # construct the splines + (t, c, k), u_ = splprep(y, s=s) + spl, u = make_splprep(y, s=s) + + # parameters + xp_assert_close(u, u_, atol=1e-15) + + # knots + xp_assert_close(spl.t, t, atol=1e-15) + assert len(t) == num_knots[s] + + # coefficients: note the transpose + cc = np.asarray(c).T + xp_assert_close(spl.c, cc, atol=1e-15) + + # values: note axis=1 + xp_assert_close(spl(u), + BSpline(t, c, k, axis=1)(u), atol=1e-15) + + @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5]) + def test_array_not_list(self, s): + # the argument of splPrep is either a list of arrays or a 2D array (sigh) + _, y, _ = self._get_xyk() + assert isinstance(y, list) + assert np.shape(y)[0] == 2 + + # assert the behavior of FITPACK's splrep + tck, u = splprep(y, s=s) + tck_a, u_a = splprep(np.asarray(y), s=s) + xp_assert_close(u, u_a, atol=s) + xp_assert_close(tck[0], tck_a[0], atol=1e-15) + assert len(tck[1]) == len(tck_a[1]) + xp_assert_close(tck[1], tck_a[1], atol=1e-15) + assert tck[2] == tck_a[2] + assert np.shape(splev(u, tck)) == np.shape(y) + + spl, u = make_splprep(y, s=s) + xp_assert_close(u, u_a, atol=1e-15) + xp_assert_close(spl.t, tck_a[0], atol=1e-15) + xp_assert_close(spl.c.T, tck_a[1], atol=1e-15) + assert spl.k == tck_a[2] + assert spl(u).shape == np.shape(y) + + spl, u = make_splprep(np.asarray(y), s=s) + xp_assert_close(u, u_a, atol=1e-15) + xp_assert_close(spl.t, tck_a[0], atol=1e-15) + xp_assert_close(spl.c.T, tck_a[1], atol=1e-15) + assert spl.k == tck_a[2] + assert spl(u).shape == np.shape(y) + + with assert_raises(ValueError): + make_splprep(np.asarray(y).T, s=s) + + def test_default_s_is_zero(self, xp): + x, y, k = self._get_xyk(m=10, xp=xp) + + spl, u = make_splprep(y) + xp_assert_close(spl(u), xp.stack(y), atol=1e-15) + + def test_s_zero_vs_near_zero(self, xp): + # s=0 and s \approx 0 are consistent + x, y, k = self._get_xyk(m=10, xp=xp) + + spl_i, u_i = make_splprep(y, s=0) + spl_n, u_n = make_splprep(y, s=1e-15) + + xp_assert_close(u_i, u_n, atol=1e-15) + xp_assert_close(spl_i(u_i), xp.stack(y), atol=1e-15) + xp_assert_close(spl_n(u_n), xp.stack(y), atol=1e-7) + assert spl_i.axis == spl_n.axis + assert spl_i.c.shape == spl_n.c.shape + + def test_1D(self): + x = np.arange(8, dtype=float) + with assert_raises(ValueError): + splprep(x) + + with assert_raises(ValueError): + make_splprep(x, s=0) + + with assert_raises(ValueError): + make_splprep(x, s=0.1) + + tck, u_ = splprep([x], s=1e-5) + spl, u = make_splprep([x], s=1e-5) + + assert spl(u).shape == (1, 8) + xp_assert_close(spl(u), [x], atol=1e-15) + + +@make_xp_test_case(make_splprep) +class TestMakeSplprepPeriodic: + + def _get_xyk(self, n=10, k=3, xp=np): + x = xp.linspace(0, 2*xp.pi, n, dtype=xp.float64) + y = [xp.sin(x), xp.cos(x)] + return x, y, k + + @pytest.mark.parametrize('s', [0, 1e-4, 1e-5, 1e-6]) + def test_simple_vs_splprep(self, s): + # Check/document the interface vs splPrep + # The four values of `s` are to probe all code paths and shortcuts + n = 10 + x = np.linspace(0, 2*np.pi, n) + y = [np.sin(x), np.cos(x)] + + # the number of knots depends on `s` (this is by construction) + num_knots = {0: 14, 1e-4: 16, 1e-5: 16, 1e-6: 16} + + # construct the splines + (t, c, k), u_ = splprep(y, s=s, per=1) + spl, u = make_splprep(y, s=s, bc_type="periodic") + + # parameters + xp_assert_close(u, u_, atol=1e-15) + + # knots + assert len(spl.t) == num_knots[s] + + # values: note axis=1 + xp_assert_close(spl(u), BSpline(t, c, k, axis=1)(u), + atol=1e-06, rtol=1e-06) + + @pytest.mark.parametrize('s', [0, 1e-4, 1e-5, 1e-6]) + def test_array_not_list(self, s): + # the argument of splPrep is either a list of arrays or a 2D array (sigh) + _, y, _ = self._get_xyk() + assert isinstance(y, list) + assert np.shape(y)[0] == 2 + + # assert the behavior of FITPACK's splrep + tck, u = splprep(y, s=s, per=1) + tck_a, u_a = splprep(np.asarray(y), s=s, per=1) + xp_assert_close(u, u_a, atol=s) + xp_assert_close(tck[0], tck_a[0], atol=1e-15) + assert len(tck[1]) == len(tck_a[1]) + for c1, c2 in zip(tck[1], tck_a[1]): + xp_assert_close(c1, c2, atol=1e-15) + assert tck[2] == tck_a[2] + assert np.shape(splev(u, tck)) == np.shape(y) + + spl, u = make_splprep(y, s=s, bc_type="periodic") + xp_assert_close(u, u_a, atol=1e-15) + assert spl.k == tck_a[2] + assert spl(u).shape == np.shape(y) + + spl, u = make_splprep(np.asarray(y), s=s, bc_type="periodic") + xp_assert_close(u, u_a, atol=1e-15) + assert spl.k == tck_a[2] + assert spl(u).shape == np.shape(y) + + with assert_raises(ValueError): + make_splprep(np.asarray(y).T, s=s, bc_type="periodic") + + def test_default_s_is_zero(self, xp): + x, y, k = self._get_xyk(n=10, xp=xp) + + spl, u = make_splprep(y, bc_type="periodic") + xp_assert_close(spl(u), xp.stack(y), atol=1e-15) + + def test_s_zero_vs_near_zero(self, xp): + # s=0 and s \approx 0 are consistent + x, y, k = self._get_xyk(n=10, xp=xp) + + spl_i, u_i = make_splprep(y, s=0, bc_type="periodic") + spl_n, u_n = make_splprep(y, s=1e-12, bc_type="periodic") + + xp_assert_close(u_i, u_n, atol=1e-15) + + y_arr = xp.stack(y) # xp_assert_close chokes on the list `y` + xp_assert_close(spl_i(u_i), y_arr, atol=1e-15) + xp_assert_close(spl_n(u_n), y_arr, atol=1e-7, rtol=1e-6) + assert spl_i.axis == spl_n.axis + + def test_1D(self): + x = np.linspace(0, 2*np.pi, 8) + x = np.sin(x) + with assert_raises(ValueError): + splprep(x, per=1) + + with assert_raises(ValueError): + make_splprep(x, s=0, bc_type="periodic") + + with assert_raises(ValueError): + make_splprep(x, s=0.1, bc_type="periodic") + + spl, u = make_splprep([x], s=1e-15, bc_type="periodic") + + assert spl(u).shape == (1, 8) + xp_assert_close(spl(u), [x], atol=1e-15) + + +class BatchSpline: + # BSpline-line class with reference batch behavior + def __init__(self, x, y, axis, *, spline, **kwargs): + y = np.moveaxis(y, axis, -1) + self._batch_shape = y.shape[:-1] + self._splines = [spline(x, yi, **kwargs) for yi in y.reshape(-1, y.shape[-1])] + self._axis = axis + + def __call__(self, x): + y = [spline(x) for spline in self._splines] + y = np.reshape(y, self._batch_shape + x.shape) + return np.moveaxis(y, -1, self._axis) if x.shape else y + + def integrate(self, a, b, extrapolate=None): + y = [spline.integrate(a, b, extrapolate) for spline in self._splines] + return np.reshape(y, self._batch_shape) + + def derivative(self, nu): + res = copy.deepcopy(self) + res._splines = [spline.derivative(nu) for spline in res._splines] + return res + + def antiderivative(self, nu): + res = copy.deepcopy(self) + res._splines = [spline.antiderivative(nu) for spline in res._splines] + return res + + +class TestBatch: + @pytest.mark.parametrize('make_spline, kwargs', + [(make_interp_spline, {}), + (make_smoothing_spline, {}), + (make_smoothing_spline, {'lam': 1.0}), + (make_lsq_spline, {'method': "norm-eq"}), + (make_lsq_spline, {'method': "qr"}), + ]) + @pytest.mark.parametrize('eval_shape', [(), (1,), (3,)]) + @pytest.mark.parametrize('axis', [-1, 0, 1]) + def test_batch(self, make_spline, kwargs, axis, eval_shape): + rng = np.random.default_rng(4329872134985134) + n = 10 + shape = (2, 3, 4, n) + domain = (0, 10) + + x = np.linspace(*domain, n) + y = np.moveaxis(rng.random(shape), -1, axis) + + if make_spline == make_lsq_spline: + k = 3 # spline degree, if needed + t = (x[0],) * (k + 1) + (x[-1],) * (k + 1) # valid knots, if needed + kwargs = kwargs | dict(t=t, k=k) + + res = make_spline(x, y, axis=axis, **kwargs) + ref = BatchSpline(x, y, axis=axis, spline=make_spline, **kwargs) + + x = rng.uniform(*domain, size=eval_shape) + np.testing.assert_allclose(res(x), ref(x)) + + res, ref = res.antiderivative(1), ref.antiderivative(1) + np.testing.assert_allclose(res(x), ref(x)) + + res, ref = res.derivative(2), ref.derivative(2) + np.testing.assert_allclose(res(x), ref(x)) + + np.testing.assert_allclose(res.integrate(*domain), ref.integrate(*domain)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_fitpack.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_fitpack.py new file mode 100644 index 0000000000000000000000000000000000000000..c37ff4e313d90e780d7bec2b08981d219a3c255c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_fitpack.py @@ -0,0 +1,534 @@ +import itertools +import os + +import numpy as np +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal +) +from pytest import raises as assert_raises +import pytest +from scipy._lib._testutils import check_free_memory + +from scipy.interpolate import RectBivariateSpline +from scipy.interpolate import make_splrep + +from scipy.interpolate._fitpack_py import (splrep, splev, bisplrep, bisplev, + sproot, splprep, splint, spalde, splder, splantider, insert, dblint) +from scipy.interpolate._dfitpack import regrid_smth +from scipy.interpolate._fitpack2 import dfitpack_int + + +def data_file(basename): + return os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', basename) + + +def norm2(x): + return np.sqrt(np.dot(x.T, x)) + + +def f1(x, d=0): + """Derivatives of sin->cos->-sin->-cos.""" + if d % 4 == 0: + return np.sin(x) + if d % 4 == 1: + return np.cos(x) + if d % 4 == 2: + return -np.sin(x) + if d % 4 == 3: + return -np.cos(x) + + +def makepairs(x, y): + """Helper function to create an array of pairs of x and y.""" + xy = np.array(list(itertools.product(np.asarray(x), np.asarray(y)))) + return xy.T + + +class TestSmokeTests: + """ + Smoke tests (with a few asserts) for fitpack routines -- mostly + check that they are runnable + """ + def check_1(self, per=0, s=0, a=0, b=2*np.pi, at_nodes=False, + xb=None, xe=None): + if xb is None: + xb = a + if xe is None: + xe = b + + N = 20 + # nodes and middle points of the nodes + x = np.linspace(a, b, N + 1) + x1 = a + (b - a) * np.arange(1, N, dtype=float) / float(N - 1) + v = f1(x) + + def err_est(k, d): + # Assume f has all derivatives < 1 + h = 1.0 / N + tol = 5 * h**(.75*(k-d)) + if s > 0: + tol += 1e5*s + return tol + + for k in range(1, 6): + tck = splrep(x, v, s=s, per=per, k=k, xe=xe) + tt = tck[0][k:-k] if at_nodes else x1 + + for d in range(k+1): + tol = err_est(k, d) + err = norm2(f1(tt, d) - splev(tt, tck, d)) / norm2(f1(tt, d)) + assert err < tol + + # smoke test make_splrep + if not per: + spl = make_splrep(x, v, k=k, s=s, xb=xb, xe=xe) + if len(spl.t) == len(tck[0]): + xp_assert_close(spl.t, tck[0], atol=1e-15) + xp_assert_close(spl.c, tck[1][:spl.c.size], atol=1e-13) + else: + assert k == 5 # knot length differ in some k=5 cases + else: + if np.allclose(v[0], v[-1], atol=1e-15): + spl = make_splrep(x, v, k=k, s=s, xb=xb, xe=xe, bc_type='periodic') + if k != 1: # knots for k == 1 in some cases + xp_assert_close(spl.t, tck[0], atol=1e-15) + xp_assert_close(spl.c, tck[1][:spl.c.size], atol=1e-13) + else: + with assert_raises(ValueError): + spl = make_splrep(x, v, k=k, s=s, + xb=xb, xe=xe, bc_type='periodic') + + def check_2(self, per=0, N=20, ia=0, ib=2*np.pi): + a, b, dx = 0, 2*np.pi, 0.2*np.pi + x = np.linspace(a, b, N+1) # nodes + v = np.sin(x) + + def err_est(k, d): + # Assume f has all derivatives < 1 + h = 1.0 / N + tol = 5 * h**(.75*(k-d)) + return tol + + nk = [] + for k in range(1, 6): + tck = splrep(x, v, s=0, per=per, k=k, xe=b) + nk.append([splint(ia, ib, tck), spalde(dx, tck)]) + + k = 1 + for r in nk: + d = 0 + for dr in r[1]: + tol = err_est(k, d) + xp_assert_close(dr, f1(dx, d), atol=0, rtol=tol) + d = d+1 + k = k+1 + + def test_smoke_splrep_splev(self): + self.check_1(s=1e-6) + self.check_1(b=1.5*np.pi) + + def test_smoke_splrep_splev_periodic(self): + self.check_1(b=1.5*np.pi, xe=2*np.pi, per=1, s=1e-1) + self.check_1(b=2*np.pi, per=1, s=1e-1) + + @pytest.mark.parametrize('per', [0, 1]) + @pytest.mark.parametrize('at_nodes', [True, False]) + def test_smoke_splrep_splev_2(self, per, at_nodes): + self.check_1(per=per, at_nodes=at_nodes) + + @pytest.mark.parametrize('N', [20, 50]) + @pytest.mark.parametrize('per', [0, 1]) + def test_smoke_splint_spalde(self, N, per): + self.check_2(per=per, N=N) + + @pytest.mark.parametrize('N', [20, 50]) + @pytest.mark.parametrize('per', [0, 1]) + def test_smoke_splint_spalde_iaib(self, N, per): + self.check_2(ia=0.2*np.pi, ib=np.pi, N=N, per=per) + + def test_smoke_sproot(self): + # sproot is only implemented for k=3 + a, b = 0.1, 15 + x = np.linspace(a, b, 20) + v = np.sin(x) + + for k in [1, 2, 4, 5]: + tck = splrep(x, v, s=0, per=0, k=k, xe=b) + with assert_raises(ValueError): + sproot(tck) + + k = 3 + tck = splrep(x, v, s=0, k=3) + roots = sproot(tck) + xp_assert_close(splev(roots, tck), np.zeros(len(roots)), atol=1e-10, rtol=1e-10) + xp_assert_close(roots, np.pi * np.array([1, 2, 3, 4]), rtol=1e-3) + + @pytest.mark.parametrize('N', [20, 50]) + @pytest.mark.parametrize('k', [1, 2, 3, 4, 5]) + def test_smoke_splprep_splrep_splev(self, N, k): + a, b, dx = 0, 2.*np.pi, 0.2*np.pi + x = np.linspace(a, b, N+1) # nodes + v = np.sin(x) + + tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1) + uv = splev(dx, tckp) + err1 = abs(uv[1] - np.sin(uv[0])) + assert err1 < 1e-2 + + tck = splrep(x, v, s=0, per=0, k=k) + err2 = abs(splev(uv[0], tck) - np.sin(uv[0])) + assert err2 < 1e-2 + + # Derivatives of parametric cubic spline at u (first function) + if k == 3: + tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1) + for d in range(1, k+1): + uv = splev(dx, tckp, d) + + def test_smoke_bisplrep_bisplev(self): + xb, xe = 0, 2.*np.pi + yb, ye = 0, 2.*np.pi + kx, ky = 3, 3 + Nx, Ny = 20, 20 + + def f2(x, y): + return np.sin(x+y) + + x = np.linspace(xb, xe, Nx + 1) + y = np.linspace(yb, ye, Ny + 1) + xy = makepairs(x, y) + tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky) + + tt = [tck[0][kx:-kx], tck[1][ky:-ky]] + t2 = makepairs(tt[0], tt[1]) + v1 = bisplev(tt[0], tt[1], tck) + v2 = f2(t2[0], t2[1]) + v2 = v2.reshape(len(tt[0]), len(tt[1])) + + assert norm2(np.ravel(v1 - v2)) < 1e-2 + + +class TestSplev: + def test_1d_shape(self): + x = [1,2,3,4,5] + y = [4,5,6,7,8] + tck = splrep(x, y) + z = splev([1], tck) + assert z.shape == (1,) + z = splev(1, tck) + assert z.shape == () + + def test_2d_shape(self): + x = [1, 2, 3, 4, 5] + y = [4, 5, 6, 7, 8] + tck = splrep(x, y) + t = np.array([[1.0, 1.5, 2.0, 2.5], + [3.0, 3.5, 4.0, 4.5]]) + z = splev(t, tck) + z0 = splev(t[0], tck) + z1 = splev(t[1], tck) + xp_assert_equal(z, np.vstack((z0, z1))) + + def test_extrapolation_modes(self): + # test extrapolation modes + # * if ext=0, return the extrapolated value. + # * if ext=1, return 0 + # * if ext=2, raise a ValueError + # * if ext=3, return the boundary value. + x = [1,2,3] + y = [0,2,4] + tck = splrep(x, y, k=1) + + rstl = [[-2, 6], [0, 0], None, [0, 4]] + for ext in (0, 1, 3): + assert_array_almost_equal(splev([0, 4], tck, ext=ext), rstl[ext]) + + assert_raises(ValueError, splev, [0, 4], tck, ext=2) + + +class TestSplder: + def setup_method(self): + # non-uniform grid, just to make it sure + x = np.linspace(0, 1, 100)**3 + y = np.sin(20 * x) + self.spl = splrep(x, y) + + # double check that knots are non-uniform + assert np.ptp(np.diff(self.spl[0])) > 0 + + def test_inverse(self): + # Check that antiderivative + derivative is identity. + for n in range(5): + spl2 = splantider(self.spl, n) + spl3 = splder(spl2, n) + xp_assert_close(self.spl[0], spl3[0]) + xp_assert_close(self.spl[1], spl3[1]) + assert self.spl[2] == spl3[2] + + def test_splder_vs_splev(self): + # Check derivative vs. FITPACK + + for n in range(3+1): + # Also extrapolation! + xx = np.linspace(-1, 2, 2000) + if n == 3: + # ... except that FITPACK extrapolates strangely for + # order 0, so let's not check that. + xx = xx[(xx >= 0) & (xx <= 1)] + + dy = splev(xx, self.spl, n) + spl2 = splder(self.spl, n) + dy2 = splev(xx, spl2) + if n == 1: + xp_assert_close(dy, dy2, rtol=2e-6) + else: + xp_assert_close(dy, dy2) + + def test_splantider_vs_splint(self): + # Check antiderivative vs. FITPACK + spl2 = splantider(self.spl) + + # no extrapolation, splint assumes function is zero outside + # range + xx = np.linspace(0, 1, 20) + + for x1 in xx: + for x2 in xx: + y1 = splint(x1, x2, self.spl) + y2 = splev(x2, spl2) - splev(x1, spl2) + xp_assert_close(np.asarray(y1), np.asarray(y2)) + + def test_order0_diff(self): + assert_raises(ValueError, splder, self.spl, 4) + + def test_kink(self): + # Should refuse to differentiate splines with kinks + + spl2 = insert(0.5, self.spl, m=2) + splder(spl2, 2) # Should work + assert_raises(ValueError, splder, spl2, 3) + + spl2 = insert(0.5, self.spl, m=3) + splder(spl2, 1) # Should work + assert_raises(ValueError, splder, spl2, 2) + + spl2 = insert(0.5, self.spl, m=4) + assert_raises(ValueError, splder, spl2, 1) + + def test_multidim(self): + # c can have trailing dims + for n in range(3): + t, c, k = self.spl + c2 = np.c_[c, c, c] + c2 = np.dstack((c2, c2)) + + spl2 = splantider((t, c2, k), n) + spl3 = splder(spl2, n) + + xp_assert_close(t, spl3[0]) + xp_assert_close(c2, spl3[1]) + assert k == spl3[2] + + +class TestSplint: + def test_len_c(self): + n, k = 7, 3 + x = np.arange(n) + y = x**3 + t, c, k = splrep(x, y, s=0) + + # note that len(c) == len(t) == 11 (== len(x) + 2*(k-1)) + assert len(t) == len(c) == n + 2*(k-1) + + # integrate directly: $\int_0^6 x^3 dx = 6^4 / 4$ + res = splint(0, 6, (t, c, k)) + expected = 6**4 / 4 + assert abs(res - expected) < 1e-13 + + # check that the coefficients past len(t) - k - 1 are ignored + c0 = c.copy() + c0[len(t) - k - 1:] = np.nan + res0 = splint(0, 6, (t, c0, k)) + assert abs(res0 - expected) < 1e-13 + + # however, all other coefficients *are* used + c0[6] = np.nan + assert np.isnan(splint(0, 6, (t, c0, k))) + + # check that the coefficient array can have length `len(t) - k - 1` + c1 = c[:len(t) - k - 1] + res1 = splint(0, 6, (t, c1, k)) + assert (res1 - expected) < 1e-13 + + + # however shorter c arrays raise. The error from f2py is a + # `dftipack.error`, which is an Exception but not ValueError etc. + with assert_raises(Exception, match=r">=n-k-1"): + splint(0, 1, (np.ones(10), np.ones(5), 3)) + + +class TestBisplrep: + def test_overflow(self): + from numpy.lib.stride_tricks import as_strided + if dfitpack_int.itemsize == 8: + size = 1500000**2 + else: + size = 400**2 + # Don't allocate a real array, as it's very big, but rely + # on that it's not referenced + x = as_strided(np.zeros(()), shape=(size,)) + assert_raises(OverflowError, bisplrep, x, x, x, w=x, + xb=0, xe=1, yb=0, ye=1, s=0) + + def test_regression_1310(self): + # Regression test for gh-1310 + with np.load(data_file('bug-1310.npz')) as loaded_data: + data = loaded_data['data'] + + # Shouldn't crash -- the input data triggers work array sizes + # that caused previously some data to not be aligned on + # sizeof(double) boundaries in memory, which made the Fortran + # code to crash when compiled with -O3 + bisplrep(data[:,0], data[:,1], data[:,2], kx=3, ky=3, s=0, + full_output=True) + + @pytest.mark.skipif(dfitpack_int != np.int64, reason="needs ilp64 fitpack") + def test_ilp64_bisplrep(self): + check_free_memory(28000) # VM size, doesn't actually use the pages + x = np.linspace(0, 1, 400) + y = np.linspace(0, 1, 400) + x, y = np.meshgrid(x, y) + z = np.zeros_like(x) + tck = bisplrep(x, y, z, kx=3, ky=3, s=0) + xp_assert_close(bisplev(0.5, 0.5, tck), 0.0) + + +def test_dblint(): + # Basic test to see it runs and gives the correct result on a trivial + # problem. Note that `dblint` is not exposed in the interpolate namespace. + x = np.linspace(0, 1) + y = np.linspace(0, 1) + xx, yy = np.meshgrid(x, y) + rect = RectBivariateSpline(x, y, 4 * xx * yy) + tck = list(rect.tck) + tck.extend(rect.degrees) + + assert abs(dblint(0, 1, 0, 1, tck) - 1) < 1e-10 + assert abs(dblint(0, 0.5, 0, 1, tck) - 0.25) < 1e-10 + assert abs(dblint(0.5, 1, 0, 1, tck) - 0.75) < 1e-10 + assert abs(dblint(-100, 100, -100, 100, tck) - 1) < 1e-10 + + +def test_splev_der_k(): + # regression test for gh-2188: splev(x, tck, der=k) gives garbage or crashes + # for x outside of knot range + + # test case from gh-2188 + tck = (np.array([0., 0., 2.5, 2.5]), + np.array([-1.56679978, 2.43995873, 0., 0.]), + 1) + t, c, k = tck + x = np.array([-3, 0, 2.5, 3]) + + # an explicit form of the linear spline + xp_assert_close(splev(x, tck), c[0] + (c[1] - c[0]) * x/t[2]) + xp_assert_close(splev(x, tck, 1), + np.ones_like(x) * (c[1] - c[0]) / t[2] + ) + + # now check a random spline vs splder + np.random.seed(1234) + x = np.sort(np.random.random(30)) + y = np.random.random(30) + t, c, k = splrep(x, y) + + x = [t[0] - 1., t[-1] + 1.] + tck2 = splder((t, c, k), k) + xp_assert_close(splev(x, (t, c, k), k), splev(x, tck2)) + + +def test_splprep_segfault(): + # regression test for gh-3847: splprep segfaults if knots are specified + # for task=-1 + t = np.arange(0, 1.1, 0.1) + x = np.sin(2*np.pi*t) + y = np.cos(2*np.pi*t) + tck, u = splprep([x, y], s=0) + np.arange(0, 1.01, 0.01) + + uknots = tck[0] # using the knots from the previous fitting + tck, u = splprep([x, y], task=-1, t=uknots) # here is the crash + + +@pytest.mark.skipif(dfitpack_int == np.int64, + reason='Will crash (see gh-23396), test only meant for 32-bit overflow') +def test_bisplev_integer_overflow(): + np.random.seed(1) + + x = np.linspace(0, 1, 11) + y = x + z = np.random.randn(11, 11).ravel() + kx = 1 + ky = 1 + + nx, tx, ny, ty, c, fp, ier = regrid_smth( + x, y, z, None, None, None, None, kx=kx, ky=ky, s=0.0) + tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], kx, ky) + + xp = np.zeros([2621440]) + yp = np.zeros([2621440]) + + assert_raises((RuntimeError, MemoryError), bisplev, xp, yp, tck) + + +@pytest.mark.xslow +def test_gh_1766(): + # this should fail gracefully instead of segfaulting (int overflow) + size = 22 + kx, ky = 3, 3 + def f2(x, y): + return np.sin(x+y) + + x = np.linspace(0, 10, size) + y = np.linspace(50, 700, size) + xy = makepairs(x, y) + tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky) + # the size value here can either segfault + # or produce a MemoryError on main + tx_ty_size = 500000 + tck[0] = np.arange(tx_ty_size) + tck[1] = np.arange(tx_ty_size) * 4 + tt_0 = np.arange(50) + tt_1 = np.arange(50) * 3 + with pytest.raises(MemoryError): + bisplev(tt_0, tt_1, tck, 1, 1) + + +def test_spalde_scalar_input(): + # Ticket #629 + x = np.linspace(0, 10) + y = x**3 + tck = splrep(x, y, k=3, t=[5]) + res = spalde(np.float64(1), tck) + des = np.array([1., 3., 6., 6.]) + assert_almost_equal(res, des) + + +def test_spalde_nc(): + # regression test for https://github.com/scipy/scipy/issues/19002 + # here len(t) = 29 and len(c) = 25 (== len(t) - k - 1) + x = np.asarray([-10., -9., -8., -7., -6., -5., -4., -3., -2.5, -2., -1.5, + -1., -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 4., 5., 6.], + dtype="float") + t = [-10.0, -10.0, -10.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, + -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, + 5.0, 6.0, 6.0, 6.0, 6.0] + c = np.asarray([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) + k = 3 + + res = spalde(x, (t, c, k)) + res = np.vstack(res) + res_splev = np.asarray([splev(x, (t, c, k), nu) for nu in range(4)]) + xp_assert_close(res, res_splev.T, atol=1e-15) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_fitpack2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_fitpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..e7adc7be52bfd41e9b4e51bf0465b2db42ffc60b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_fitpack2.py @@ -0,0 +1,1474 @@ +# Created by Pearu Peterson, June 2003 +import itertools +import sys +import warnings + +import numpy as np +import pytest +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal +) + +from numpy import array, diff, linspace, meshgrid, ones, pi, shape +from scipy.interpolate._fitpack_py import bisplrep, bisplev, splrep, spalde +from scipy.interpolate._fitpack2 import (UnivariateSpline, + LSQUnivariateSpline, InterpolatedUnivariateSpline, + LSQBivariateSpline, SmoothBivariateSpline, RectBivariateSpline, + LSQSphereBivariateSpline, SmoothSphereBivariateSpline, + RectSphereBivariateSpline) + +from scipy._lib._testutils import _run_concurrent_barrier + +from scipy.interpolate import make_splrep, NdBSpline + +def convert_to_ndbspline(lut): + tx, ty = lut.get_knots() + kx, ky = lut.degrees + nx, ny = len(tx), len(ty) + c = lut.get_coeffs().reshape((nx - kx - 1, ny - ky - 1)) + return NdBSpline((tx, ty), c, (kx, ky)) + +class TestUnivariateSpline: + def test_linear_constant(self): + x = [1,2,3] + y = [3,3,3] + lut = UnivariateSpline(x,y,k=1) + assert_array_almost_equal(lut.get_knots(), [1, 3]) + assert_array_almost_equal(lut.get_coeffs(), [3, 3]) + assert abs(lut.get_residual()) < 1e-10 + assert_array_almost_equal(lut([1, 1.5, 2]), [3, 3, 3]) + + @pytest.mark.parametrize("bc_type", [None, 'periodic']) + def test_linear_constant_periodic(self, bc_type): + x = [1,2,3] + y = [3,3,3] + lut = UnivariateSpline(x,y,k=1) + + spl = make_splrep(x, y, k=1, s=len(x), bc_type=bc_type) + xp_assert_close(spl.t[1:-1], lut.get_knots(), atol=1e-15) + xp_assert_close(spl.c, lut.get_coeffs(), atol=1e-15) + + def test_preserve_shape(self): + x = [1, 2, 3] + y = [0, 2, 4] + lut = UnivariateSpline(x, y, k=1) + arg = 2 + assert shape(arg) == shape(lut(arg)) + assert shape(arg) == shape(lut(arg, nu=1)) + arg = [1.5, 2, 2.5] + assert shape(arg) == shape(lut(arg)) + assert shape(arg) == shape(lut(arg, nu=1)) + + def test_linear_1d(self): + x = [1,2,3] + y = [0,2,4] + lut = UnivariateSpline(x,y,k=1) + assert_array_almost_equal(lut.get_knots(),[1,3]) + assert_array_almost_equal(lut.get_coeffs(),[0,4]) + assert abs(lut.get_residual()) < 1e-15 + assert_array_almost_equal(lut([1,1.5,2]),[0,1,2]) + + def test_subclassing(self): + # See #731 + + class ZeroSpline(UnivariateSpline): + def __call__(self, x): + return 0*array(x) + + sp = ZeroSpline([1,2,3,4,5], [3,2,3,2,3], k=2) + xp_assert_equal(sp([1.5, 2.5]), [0., 0.]) + + def test_empty_input(self): + # Test whether empty input returns an empty output. Ticket 1014 + x = [1,3,5,7,9] + y = [0,4,9,12,21] + spl = UnivariateSpline(x, y, k=3) + xp_assert_equal(spl([]), array([])) + + def test_roots(self): + x = [1, 3, 5, 7, 9] + y = [0, 4, 9, 12, 21] + spl = UnivariateSpline(x, y, k=3) + assert_almost_equal(spl.roots()[0], 1.050290639101332) + + def test_roots_length(self): # for gh18335 + x = np.linspace(0, 50 * np.pi, 1000) + y = np.cos(x) + spl = UnivariateSpline(x, y, s=0) + assert len(spl.roots()) == 50 + + def test_derivatives(self): + x = [1, 3, 5, 7, 9] + y = [0, 4, 9, 12, 21] + spl = UnivariateSpline(x, y, k=3) + assert_almost_equal(spl.derivatives(3.5), + [5.5152902, 1.7146577, -0.1830357, 0.3125]) + + def test_derivatives_2(self): + x = np.arange(8) + y = x**3 + 2.*x**2 + + tck = splrep(x, y, s=0) + ders = spalde(3, tck) + xp_assert_close(ders, [45., # 3**3 + 2*(3)**2 + 39., # 3*(3)**2 + 4*(3) + 22., # 6*(3) + 4 + 6.], # 6*3**0 + atol=1e-15) + spl = UnivariateSpline(x, y, s=0, k=3) + xp_assert_close(spl.derivatives(3), + ders, + atol=1e-15) + + def test_resize_regression(self): + """Regression test for #1375.""" + x = [-1., -0.65016502, -0.58856235, -0.26903553, -0.17370892, + -0.10011001, 0., 0.10011001, 0.17370892, 0.26903553, 0.58856235, + 0.65016502, 1.] + y = [1.,0.62928599, 0.5797223, 0.39965815, 0.36322694, 0.3508061, + 0.35214793, 0.3508061, 0.36322694, 0.39965815, 0.5797223, + 0.62928599, 1.] + w = [1.00000000e+12, 6.88875973e+02, 4.89314737e+02, 4.26864807e+02, + 6.07746770e+02, 4.51341444e+02, 3.17480210e+02, 4.51341444e+02, + 6.07746770e+02, 4.26864807e+02, 4.89314737e+02, 6.88875973e+02, + 1.00000000e+12] + spl = UnivariateSpline(x=x, y=y, w=w, s=None) + desired = array([0.35100374, 0.51715855, 0.87789547, 0.98719344]) + xp_assert_close(spl([0.1, 0.5, 0.9, 0.99]), desired, atol=5e-4) + + def test_out_of_range_regression(self): + # Test different extrapolation modes. See ticket 3557 + x = np.arange(5, dtype=float) + y = x**3 + + xp = linspace(-8, 13, 100) + xp_zeros = xp.copy() + xp_zeros[np.logical_or(xp_zeros < 0., xp_zeros > 4.)] = 0 + xp_clip = xp.copy() + xp_clip[xp_clip < x[0]] = x[0] + xp_clip[xp_clip > x[-1]] = x[-1] + + for cls in [UnivariateSpline, InterpolatedUnivariateSpline]: + spl = cls(x=x, y=y) + for ext in [0, 'extrapolate']: + xp_assert_close(spl(xp, ext=ext), xp**3, atol=1e-16) + xp_assert_close(cls(x, y, ext=ext)(xp), xp**3, atol=1e-16) + for ext in [1, 'zeros']: + xp_assert_close(spl(xp, ext=ext), xp_zeros**3, atol=1e-16) + xp_assert_close(cls(x, y, ext=ext)(xp), xp_zeros**3, atol=1e-16) + for ext in [2, 'raise']: + assert_raises(ValueError, spl, xp, **dict(ext=ext)) + for ext in [3, 'const']: + xp_assert_close(spl(xp, ext=ext), xp_clip**3, atol=2e-16) + xp_assert_close(cls(x, y, ext=ext)(xp), xp_clip**3, atol=2e-16) + + # also test LSQUnivariateSpline [which needs explicit knots] + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + spl = LSQUnivariateSpline(x, y, t) + xp_assert_close(spl(xp, ext=0), xp**3, atol=1e-16) + xp_assert_close(spl(xp, ext=1), xp_zeros**3, atol=1e-16) + assert_raises(ValueError, spl, xp, **dict(ext=2)) + xp_assert_close(spl(xp, ext=3), xp_clip**3, atol=1e-16) + + # also make sure that unknown values for `ext` are caught early + for ext in [-1, 'unknown']: + spl = UnivariateSpline(x, y) + assert_raises(ValueError, spl, xp, **dict(ext=ext)) + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, ext=ext)) + + def test_lsq_fpchec(self): + xs = np.arange(100) * 1. + ys = np.arange(100) * 1. + knots = np.linspace(0, 99, 10) + bbox = (-1, 101) + assert_raises(ValueError, LSQUnivariateSpline, xs, ys, knots, + bbox=bbox) + + def test_derivative_and_antiderivative(self): + # Thin wrappers to splder/splantider, so light smoke test only. + x = np.linspace(0, 1, 70)**3 + y = np.cos(x) + + spl = UnivariateSpline(x, y, s=0) + spl2 = spl.antiderivative(2).derivative(2) + xp_assert_close(spl(0.3), spl2(0.3)) + + spl2 = spl.antiderivative(1) + xp_assert_close(spl2(0.6) - spl2(0.2), + spl.integral(0.2, 0.6)) + + def test_derivative_extrapolation(self): + # Regression test for gh-10195: for a const-extrapolation spline + # its derivative evaluates to zero for extrapolation + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 5] + f = UnivariateSpline(x_values, y_values, ext='const', k=3) + + x = [-1, 0, -0.5, 9, 9.5, 10] + xp_assert_close(f.derivative()(x), np.zeros_like(x), atol=1e-15) + + def test_integral_out_of_bounds(self): + # Regression test for gh-7906: .integral(a, b) is wrong if both + # a and b are out-of-bounds + x = np.linspace(0., 1., 7) + for ext in range(4): + f = UnivariateSpline(x, x, s=0, ext=ext) + for (a, b) in [(1, 1), (1, 5), (2, 5), + (0, 0), (-2, 0), (-2, -1)]: + assert abs(f.integral(a, b)) < 1e-15 + + def test_nan(self): + # bail out early if the input data contains nans + x = np.arange(10, dtype=float) + y = x**3 + w = np.ones_like(x) + # also test LSQUnivariateSpline [which needs explicit knots] + spl = UnivariateSpline(x, y, check_finite=True) + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + y_end = y[-1] + for z in [np.nan, np.inf, -np.inf]: + y[-1] = z + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, LSQUnivariateSpline, + **dict(x=x, y=y, t=t, check_finite=True)) + y[-1] = y_end # check valid y but invalid w + w[-1] = z + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, w=w, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, w=w, check_finite=True)) + assert_raises(ValueError, LSQUnivariateSpline, + **dict(x=x, y=y, t=t, w=w, check_finite=True)) + + def test_strictly_increasing_x(self): + # Test the x is required to be strictly increasing for + # UnivariateSpline if s=0 and for InterpolatedUnivariateSpline, + # but merely increasing for UnivariateSpline if s>0 + # and for LSQUnivariateSpline; see gh-8535 + xx = np.arange(10, dtype=float) + yy = xx**3 + x = np.arange(10, dtype=float) + x[1] = x[0] + y = x**3 + w = np.ones_like(x) + # also test LSQUnivariateSpline [which needs explicit knots] + spl = UnivariateSpline(xx, yy, check_finite=True) + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + UnivariateSpline(x=x, y=y, w=w, s=1, check_finite=True) + LSQUnivariateSpline(x=x, y=y, t=t, w=w, check_finite=True) + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, s=0, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + + def test_increasing_x(self): + # Test that x is required to be increasing, see gh-8535 + xx = np.arange(10, dtype=float) + yy = xx**3 + x = np.arange(10, dtype=float) + x[1] = x[0] - 1.0 + y = x**3 + w = np.ones_like(x) + # also test LSQUnivariateSpline [which needs explicit knots] + spl = UnivariateSpline(xx, yy, check_finite=True) + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, LSQUnivariateSpline, + **dict(x=x, y=y, t=t, w=w, check_finite=True)) + + def test_invalid_input_for_univariate_spline(self): + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5] + UnivariateSpline(x_values, y_values) + assert "x and y should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + w_values = [-1.0, 1.0, 1.0, 1.0] + UnivariateSpline(x_values, y_values, w=w_values) + assert "x, y, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-1) + UnivariateSpline(x_values, y_values, bbox=bbox) + assert "bbox shape should be (2,)" in str(info.value) + + with assert_raises(ValueError) as info: + UnivariateSpline(x_values, y_values, k=6) + assert "k should be 1 <= k <= 5" in str(info.value) + + with assert_raises(ValueError) as info: + UnivariateSpline(x_values, y_values, s=-1.0) + assert "s should be s >= 0.0" in str(info.value) + + def test_invalid_input_for_interpolated_univariate_spline(self): + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5] + InterpolatedUnivariateSpline(x_values, y_values) + assert "x and y should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + w_values = [-1.0, 1.0, 1.0, 1.0] + InterpolatedUnivariateSpline(x_values, y_values, w=w_values) + assert "x, y, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-1) + InterpolatedUnivariateSpline(x_values, y_values, bbox=bbox) + assert "bbox shape should be (2,)" in str(info.value) + + with assert_raises(ValueError) as info: + InterpolatedUnivariateSpline(x_values, y_values, k=6) + assert "k should be 1 <= k <= 5" in str(info.value) + + def test_invalid_input_for_lsq_univariate_spline(self): + + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + spl = UnivariateSpline(x_values, y_values, check_finite=True) + t_values = spl.get_knots()[3:4] # interior knots w/ default k=3 + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5] + LSQUnivariateSpline(x_values, y_values, t_values) + assert "x and y should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + w_values = [1.0, 1.0, 1.0, 1.0] + LSQUnivariateSpline(x_values, y_values, t_values, w=w_values) + assert "x, y, and w should have a same length" in str(info.value) + + message = "Interior knots t must satisfy Schoenberg-Whitney conditions" + with assert_raises(ValueError, match=message) as info: + bbox = (100, -100) + LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox) + + with assert_raises(ValueError) as info: + bbox = (-1) + LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox) + assert "bbox shape should be (2,)" in str(info.value) + + with assert_raises(ValueError) as info: + LSQUnivariateSpline(x_values, y_values, t_values, k=6) + assert "k should be 1 <= k <= 5" in str(info.value) + + def test_array_like_input(self): + x_values = np.array([1, 2, 4, 6, 8.5]) + y_values = np.array([0.5, 0.8, 1.3, 2.5, 2.8]) + w_values = np.array([1.0, 1.0, 1.0, 1.0, 1.0]) + bbox = np.array([-100, 100]) + # np.array input + spl1 = UnivariateSpline(x=x_values, y=y_values, w=w_values, + bbox=bbox) + # list input + spl2 = UnivariateSpline(x=x_values.tolist(), y=y_values.tolist(), + w=w_values.tolist(), bbox=bbox.tolist()) + + xp_assert_close(spl1([0.1, 0.5, 0.9, 0.99]), + spl2([0.1, 0.5, 0.9, 0.99])) + + def test_fpknot_oob_crash(self): + # https://github.com/scipy/scipy/issues/3691 + x = range(109) + y = [0., 0., 0., 0., 0., 10.9, 0., 11., 0., + 0., 0., 10.9, 0., 0., 0., 0., 0., 0., + 10.9, 0., 0., 0., 11., 0., 0., 0., 10.9, + 0., 0., 0., 10.5, 0., 0., 0., 10.7, 0., + 0., 0., 11., 0., 0., 0., 0., 0., 0., + 10.9, 0., 0., 10.7, 0., 0., 0., 10.6, 0., + 0., 0., 10.5, 0., 0., 10.7, 0., 0., 10.5, + 0., 0., 11.5, 0., 0., 0., 10.7, 0., 0., + 10.7, 0., 0., 10.9, 0., 0., 10.8, 0., 0., + 0., 10.7, 0., 0., 10.6, 0., 0., 0., 10.4, + 0., 0., 10.6, 0., 0., 10.5, 0., 0., 0., + 10.7, 0., 0., 0., 10.4, 0., 0., 0., 10.8, 0.] + msg = r"does not satisfy the condition abs\(fp-s\)/s < tol" + with pytest.warns(UserWarning, match=msg): + UnivariateSpline(x, y, k=1) + + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to + # UnivariateSpline + xx = np.arange(100, dtype=float) + yy = xx**3 + x = np.arange(100, dtype=float) + x[1] = x[0] + spl = UnivariateSpline(xx, yy, check_finite=True) + + def worker_fn(_, interp, x): + interp(x) + + _run_concurrent_barrier(10, worker_fn, spl, x) + + +class TestLSQBivariateSpline: + # NOTE: The systems in this test class are rank-deficient + def test_linear_constant(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [3,3,3,3,3,3,3,3,3] + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r: + lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1) + assert len(r) == 1 + + assert_almost_equal(lut(2, 2), np.asarray(3.)) + + def test_bilinearity(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [0,7,8,3,4,7,1,3,4] + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with pytest.warns(UserWarning, match="\nThe coefficients of the spline"): + # This seems to fail (ier=1, see ticket 1642). + lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1) + + tx, ty = lut.get_knots() + for xa, xb in zip(tx[:-1], tx[1:]): + for ya, yb in zip(ty[:-1], ty[1:]): + for t in [0.1, 0.5, 0.9]: + for s in [0.3, 0.4, 0.7]: + xp = xa*(1-t) + xb*t + yp = ya*(1-s) + yb*s + zp = (+ lut(xa, ya)*(1-t)*(1-s) + + lut(xb, ya)*t*(1-s) + + lut(xa, yb)*(1-t)*s + + lut(xb, yb)*t*s) + assert_almost_equal(lut(xp,yp), zp) + + def test_integral(self): + x = [1,1,1,2,2,2,8,8,8] + y = [1,2,3,1,2,3,1,2,3] + z = array([0,7,8,3,4,7,1,3,4]) + + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r: + lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1) + assert len(r) == 1 + tx, ty = lut.get_knots() + tz = lut(tx, ty) + trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:] + * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum() + + assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-1], ty[0], ty[-1])), + np.asarray(trpz)) + + def test_empty_input(self): + # Test whether empty inputs returns an empty output. Ticket 1014 + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [3,3,3,3,3,3,3,3,3] + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r: + lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1) + assert len(r) == 1 + + xp_assert_equal(lut([], []), np.zeros((0,0))) + xp_assert_equal(lut([], [], grid=False), np.zeros((0,))) + + def test_invalid_input(self): + s = 0.1 + tx = [1 + s, 3 - s] + ty = [1 + s, 3 - s] + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0, num=10) + LSQBivariateSpline(x, y, z, tx, ty) + assert "x, y, and z should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0) + w = np.linspace(1.0, 10.0, num=20) + LSQBivariateSpline(x, y, z, tx, ty, w=w) + assert "x, y, z, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + w = np.linspace(-1.0, 10.0) + LSQBivariateSpline(x, y, z, tx, ty, w=w) + assert "w should be positive" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-100, 100, -100) + LSQBivariateSpline(x, y, z, tx, ty, bbox=bbox) + assert "bbox shape should be (4,)" in str(info.value) + + with assert_raises(ValueError) as info: + LSQBivariateSpline(x, y, z, tx, ty, kx=10, ky=10) + assert "The length of x, y and z should be at least (kx+1) * (ky+1)" in \ + str(info.value) + + with assert_raises(ValueError) as exc_info: + LSQBivariateSpline(x, y, z, tx, ty, eps=0.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + LSQBivariateSpline(x, y, z, tx, ty, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + def test_array_like_input(self): + s = 0.1 + tx = np.array([1 + s, 3 - s]) + ty = np.array([1 + s, 3 - s]) + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0) + w = np.linspace(1.0, 10.0) + bbox = np.array([1.0, 10.0, 1.0, 10.0]) + + with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r: + # np.array input + spl1 = LSQBivariateSpline(x, y, z, tx, ty, w=w, bbox=bbox) + # list input + spl2 = LSQBivariateSpline(x.tolist(), y.tolist(), z.tolist(), + tx.tolist(), ty.tolist(), w=w.tolist(), + bbox=bbox) + xp_assert_close(spl1(2.0, 2.0), spl2(2.0, 2.0)) + assert len(r) == 2 + + def test_unequal_length_of_knots(self): + """Test for the case when the input knot-location arrays in x and y are + of different lengths. + """ + x, y = np.mgrid[0:100, 0:100] + x = x.ravel() + y = y.ravel() + z = 3.0 * np.ones_like(x) + tx = np.linspace(0.1, 98.0, 29) + ty = np.linspace(0.1, 98.0, 33) + with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r: + lut = LSQBivariateSpline(x,y,z,tx,ty) + assert len(r) == 1 + + assert_almost_equal(lut(x, y, grid=False), z) + + +class TestSmoothBivariateSpline: + def test_linear_constant(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [3,3,3,3,3,3,3,3,3] + lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1) + for t in lut.get_knots(): + assert_array_almost_equal(t, [1, 1, 3, 3]) + + assert_array_almost_equal(lut.get_coeffs(), [3, 3, 3, 3]) + assert abs(lut.get_residual()) < 1e-15 + assert_array_almost_equal(lut([1, 1.5, 2], [1, 1.5]), [[3, 3], [3, 3], [3, 3]]) + + def test_linear_1d(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [0,0,0,2,2,2,4,4,4] + lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1) + for t in lut.get_knots(): + xp_assert_close(t, np.asarray([1.0, 1, 3, 3])) + assert_array_almost_equal(lut.get_coeffs(), [0, 0, 4, 4]) + assert abs(lut.get_residual()) < 1e-15 + assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[0,0],[1,1],[2,2]]) + + def test_integral(self): + x = [1,1,1,2,2,2,4,4,4] + y = [1,2,3,1,2,3,1,2,3] + z = array([0,7,8,3,4,7,1,3,4]) + + with warnings.catch_warnings(): + # This seems to fail (ier=1, see ticket 1642). + warnings.filterwarnings( + "ignore", "\nThe required storage space", UserWarning) + lut = SmoothBivariateSpline(x, y, z, kx=1, ky=1, s=0) + + tx = [1,2,4] + ty = [1,2,3] + + tz = lut(tx, ty) + trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:] + * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum() + assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-1], ty[0], ty[-1])), + np.asarray(trpz)) + + lut2 = SmoothBivariateSpline(x, y, z, kx=2, ky=2, s=0) + assert_almost_equal(np.asarray(lut2.integral(tx[0], tx[-1], ty[0], ty[-1])), + np.asarray(trpz), + decimal=0) # the quadratures give 23.75 and 23.85 + + tz = lut(tx[:-1], ty[:-1]) + trpz = .25*(diff(tx[:-1])[:,None]*diff(ty[:-1])[None,:] + * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum() + assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-2], ty[0], ty[-2])), + np.asarray(trpz)) + + def test_rerun_lwrk2_too_small(self): + # in this setting, lwrk2 is too small in the default run. Here we + # check for equality with the bisplrep/bisplev output because there, + # an automatic re-run of the spline representation is done if ier>10. + x = np.linspace(-2, 2, 80) + y = np.linspace(-2, 2, 80) + z = x + y + xi = np.linspace(-1, 1, 100) + yi = np.linspace(-2, 2, 100) + tck = bisplrep(x, y, z) + res1 = bisplev(xi, yi, tck) + interp_ = SmoothBivariateSpline(x, y, z) + res2 = interp_(xi, yi) + assert_almost_equal(res1, res2) + + def test_invalid_input(self): + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0, num=10) + SmoothBivariateSpline(x, y, z) + assert "x, y, and z should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0) + w = np.linspace(1.0, 10.0, num=20) + SmoothBivariateSpline(x, y, z, w=w) + assert "x, y, z, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + w = np.linspace(-1.0, 10.0) + SmoothBivariateSpline(x, y, z, w=w) + assert "w should be positive" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-100, 100, -100) + SmoothBivariateSpline(x, y, z, bbox=bbox) + assert "bbox shape should be (4,)" in str(info.value) + + with assert_raises(ValueError) as info: + SmoothBivariateSpline(x, y, z, kx=10, ky=10) + assert "The length of x, y and z should be at least (kx+1) * (ky+1)" in\ + str(info.value) + + with assert_raises(ValueError) as info: + SmoothBivariateSpline(x, y, z, s=-1.0) + assert "s should be s >= 0.0" in str(info.value) + + with assert_raises(ValueError) as exc_info: + SmoothBivariateSpline(x, y, z, eps=0.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothBivariateSpline(x, y, z, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + def test_array_like_input(self): + x = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3]) + y = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3]) + z = np.array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + w = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1]) + bbox = np.array([1.0, 3.0, 1.0, 3.0]) + # np.array input + spl1 = SmoothBivariateSpline(x, y, z, w=w, bbox=bbox, kx=1, ky=1) + # list input + spl2 = SmoothBivariateSpline(x.tolist(), y.tolist(), z.tolist(), + bbox=bbox.tolist(), w=w.tolist(), + kx=1, ky=1) + xp_assert_close(spl1(0.1, 0.5), spl2(0.1, 0.5)) + + +class TestLSQSphereBivariateSpline: + def setup_method(self): + # define the input data and coordinates + ntheta, nphi = 70, 90 + theta = linspace(0.5/(ntheta - 1), 1 - 0.5/(ntheta - 1), ntheta) * pi + phi = linspace(0.5/(nphi - 1), 1 - 0.5/(nphi - 1), nphi) * 2. * pi + data = ones((theta.shape[0], phi.shape[0])) + # define knots and extract data values at the knots + knotst = theta[::5] + knotsp = phi[::5] + knotdata = data[::5, ::5] + # calculate spline coefficients + lats, lons = meshgrid(theta, phi) + lut_lsq = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp) + self.lut_lsq = lut_lsq + self.data = knotdata + self.new_lons, self.new_lats = knotsp, knotst + + def test_linear_constant(self): + assert abs(self.lut_lsq.get_residual()) < 1e-15 + assert_array_almost_equal(self.lut_lsq(self.new_lats, self.new_lons), + self.data) + + def test_empty_input(self): + assert_array_almost_equal(self.lut_lsq([], []), np.zeros((0,0))) + assert_array_almost_equal(self.lut_lsq([], [], grid=False), np.zeros((0,))) + + def test_invalid_input(self): + ntheta, nphi = 70, 90 + theta = linspace(0.5 / (ntheta - 1), 1 - 0.5 / (ntheta - 1), + ntheta) * pi + phi = linspace(0.5 / (nphi - 1), 1 - 0.5 / (nphi - 1), nphi) * 2. * pi + data = ones((theta.shape[0], phi.shape[0])) + # define knots and extract data values at the knots + knotst = theta[::5] + knotsp = phi[::5] + + with assert_raises(ValueError) as exc_info: + invalid_theta = linspace(-0.1, 1.0, num=ntheta) * pi + invalid_lats, lons = meshgrid(invalid_theta, phi) + LSQSphereBivariateSpline(invalid_lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_theta = linspace(0.1, 1.1, num=ntheta) * pi + invalid_lats, lons = meshgrid(invalid_theta, phi) + LSQSphereBivariateSpline(invalid_lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = linspace(-0.1, 1.0, num=ntheta) * 2.0 * pi + lats, invalid_lons = meshgrid(theta, invalid_phi) + LSQSphereBivariateSpline(lats.ravel(), invalid_lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = linspace(0.0, 1.1, num=ntheta) * 2.0 * pi + lats, invalid_lons = meshgrid(theta, invalid_phi) + LSQSphereBivariateSpline(lats.ravel(), invalid_lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + lats, lons = meshgrid(theta, phi) + + with assert_raises(ValueError) as exc_info: + invalid_knotst = np.copy(knotst) + invalid_knotst[0] = -0.1 + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), invalid_knotst, knotsp) + assert "tt should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_knotst = np.copy(knotst) + invalid_knotst[0] = pi + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), invalid_knotst, knotsp) + assert "tt should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_knotsp = np.copy(knotsp) + invalid_knotsp[0] = -0.1 + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, invalid_knotsp) + assert "tp should be between (0, 2pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_knotsp = np.copy(knotsp) + invalid_knotsp[0] = 2 * pi + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, invalid_knotsp) + assert "tp should be between (0, 2pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_w = array([-1.0, 1.0, 1.5, 0.5, 1.0, 1.5, 0.5, 1.0, 1.0]) + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(), + knotst, knotsp, w=invalid_w) + assert "w should be positive" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(), + knotst, knotsp, eps=0.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(), + knotst, knotsp, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + def test_array_like_input(self): + ntheta, nphi = 70, 90 + theta = linspace(0.5 / (ntheta - 1), 1 - 0.5 / (ntheta - 1), + ntheta) * pi + phi = linspace(0.5 / (nphi - 1), 1 - 0.5 / (nphi - 1), + nphi) * 2. * pi + lats, lons = meshgrid(theta, phi) + data = ones((theta.shape[0], phi.shape[0])) + # define knots and extract data values at the knots + knotst = theta[::5] + knotsp = phi[::5] + w = ones(lats.ravel().shape[0]) + + # np.array input + spl1 = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp, w=w) + # list input + spl2 = LSQSphereBivariateSpline(lats.ravel().tolist(), + lons.ravel().tolist(), + data.T.ravel().tolist(), + knotst.tolist(), + knotsp.tolist(), w=w.tolist()) + assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0)) + + +class TestSmoothSphereBivariateSpline: + def setup_method(self): + theta = array([.25*pi, .25*pi, .25*pi, .5*pi, .5*pi, .5*pi, .75*pi, + .75*pi, .75*pi]) + phi = array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, pi, + 1.5 * pi]) + r = array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + self.lut = SmoothSphereBivariateSpline(theta, phi, r, s=1E10) + + def test_linear_constant(self): + assert abs(self.lut.get_residual()) < 1e-15 + assert_array_almost_equal(self.lut([1, 1.5, 2],[1, 1.5]), + [[3, 3], [3, 3], [3, 3]]) + + def test_empty_input(self): + assert_array_almost_equal(self.lut([], []), np.zeros((0,0))) + assert_array_almost_equal(self.lut([], [], grid=False), np.zeros((0,))) + + def test_invalid_input(self): + theta = array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, .5 * pi, .5 * pi, + .75 * pi, .75 * pi, .75 * pi]) + phi = array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, pi, + 1.5 * pi]) + r = array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + + with assert_raises(ValueError) as exc_info: + invalid_theta = array([-0.1 * pi, .25 * pi, .25 * pi, .5 * pi, + .5 * pi, .5 * pi, .75 * pi, .75 * pi, + .75 * pi]) + SmoothSphereBivariateSpline(invalid_theta, phi, r, s=1E10) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_theta = array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, + .5 * pi, .5 * pi, .75 * pi, .75 * pi, + 1.1 * pi]) + SmoothSphereBivariateSpline(invalid_theta, phi, r, s=1E10) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = array([-.1 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, + .5 * pi, pi, 1.5 * pi]) + SmoothSphereBivariateSpline(theta, invalid_phi, r, s=1E10) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = array([1.0 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, + .5 * pi, pi, 2.1 * pi]) + SmoothSphereBivariateSpline(theta, invalid_phi, r, s=1E10) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_w = array([-1.0, 1.0, 1.5, 0.5, 1.0, 1.5, 0.5, 1.0, 1.0]) + SmoothSphereBivariateSpline(theta, phi, r, w=invalid_w, s=1E10) + assert "w should be positive" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothSphereBivariateSpline(theta, phi, r, s=-1.0) + assert "s should be positive" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothSphereBivariateSpline(theta, phi, r, eps=-1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothSphereBivariateSpline(theta, phi, r, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + def test_array_like_input(self): + theta = np.array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, .5 * pi, + .5 * pi, .75 * pi, .75 * pi, .75 * pi]) + phi = np.array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, + pi, 1.5 * pi]) + r = np.array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + w = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # np.array input + spl1 = SmoothSphereBivariateSpline(theta, phi, r, w=w, s=1E10) + + # list input + spl2 = SmoothSphereBivariateSpline(theta.tolist(), phi.tolist(), + r.tolist(), w=w.tolist(), s=1E10) + assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0)) + + +class TestRectBivariateSpline: + def test_defaults(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + lut = RectBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y),z) + + def test_evaluate(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + lut = RectBivariateSpline(x,y,z) + + xi = [1, 2.3, 5.3, 0.5, 3.3, 1.2, 3] + yi = [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3] + zi = lut.ev(xi, yi) + zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)]) + + assert_almost_equal(zi, zi2) + + def test_derivatives_grid(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + dx = array([[0,0,-20,0,0],[0,0,13,0,0],[0,0,4,0,0], + [0,0,-11,0,0],[0,0,4,0,0]])/6. + dy = array([[4,-1,0,1,-4],[4,-1,0,1,-4],[0,1.5,0,-1.5,0], + [2,.25,0,-.25,-2],[4,-1,0,1,-4]]) + dxdy = array([[40,-25,0,25,-40],[-26,16.25,0,-16.25,26], + [-8,5,0,-5,8],[22,-13.75,0,13.75,-22],[-8,5,0,-5,8]])/6. + lut = RectBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y,dx=1),dx) + assert_array_almost_equal(lut(x,y,dy=1),dy) + assert_array_almost_equal(lut(x,y,dx=1,dy=1),dxdy) + + def test_derivatives(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + dx = array([0,0,2./3,0,0]) + dy = array([4,-1,0,-.25,-4]) + dxdy = array([160,65,0,55,32])/24. + lut = RectBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y,dx=1,grid=False),dx) + assert_array_almost_equal(lut(x,y,dy=1,grid=False),dy) + assert_array_almost_equal(lut(x,y,dx=1,dy=1,grid=False),dxdy) + + def make_pair_grid(self, x, y): + """ + Create an array of (xi, yi) pairs for all xi in x and yi in y, + and reshape it to the desired shape. + + Parameters + ---------- + x : array_like + 1D array of x-values. + y : array_like + 1D array of y-values. + dest_shape : tuple + Desired output shape. + + Returns + ------- + np.ndarray + Reshaped array of (x, y) pairs. + """ + return np.array([[xi, yi] for xi in x for yi in y]) + + def test_partial_derivative_method_grid(self): + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], + [1, 2, 1, 2, 1], + [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], + [1, 2, 1, 2, 1]]) + dx = array([[0, 0, -20, 0, 0], + [0, 0, 13, 0, 0], + [0, 0, 4, 0, 0], + [0, 0, -11, 0, 0], + [0, 0, 4, 0, 0]]) / 6. + dy = array([[4, -1, 0, 1, -4], + [4, -1, 0, 1, -4], + [0, 1.5, 0, -1.5, 0], + [2, .25, 0, -.25, -2], + [4, -1, 0, 1, -4]]) + dxdy = array([[40, -25, 0, 25, -40], + [-26, 16.25, 0, -16.25, 26], + [-8, 5, 0, -5, 8], + [22, -13.75, 0, 13.75, -22], + [-8, 5, 0, -5, 8]]) / 6. + lut = RectBivariateSpline(x, y, z) + lut_ndbspline = convert_to_ndbspline(lut) + for orders, expected in [([1, 0], dx), ([0, 1], dy), ([1, 1], dxdy)]: + actual_rect = lut.partial_derivative(*orders)(x, y) + actual_ndb = lut_ndbspline.derivative(orders)( + self.make_pair_grid(x, y) + ).reshape(expected.shape) + + assert_array_almost_equal(actual_rect, expected) + assert_array_almost_equal(actual_ndb, expected) + + def test_partial_derivative_method(self): + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], + [1, 2, 1, 2, 1], + [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], + [1, 2, 1, 2, 1]]) + expected = { + (1, 0): array([0, 0, 2./3, 0, 0]), # dx + (0, 1): array([4, -1, 0, -.25, -4]), # dy + (1, 1): array([160, 65, 0, 55, 32]) / 24. # dxdy + } + + lut = RectBivariateSpline(x, y, z) + lut_ndbspline = convert_to_ndbspline(lut) + + points = self.make_pair_grid(x, y) # shape: (25, 2) + + # Evaluate only the diagonal points: (x[i], y[i]) + diag_idx = np.arange(len(x)) + diag_points = points[diag_idx * len(y) + diag_idx] + + for orders, expected_vals in expected.items(): + dx, dy = orders + # RectBivariateSpline result + actual_rbs = lut.partial_derivative(dx, dy)(x, y, grid=False) + assert_array_almost_equal(actual_rbs, expected_vals) + + # NdBSpline result + actual_ndb = lut_ndbspline.derivative([dx, dy])(diag_points) + assert_array_almost_equal(actual_ndb, expected_vals) + + def test_partial_derivative_order_too_large(self): + x = array([0, 1, 2, 3, 4], dtype=float) + y = x.copy() + z = ones((x.size, y.size)) + lut = RectBivariateSpline(x, y, z) + lut_ndbspline = convert_to_ndbspline(lut) + with assert_raises(ValueError): + lut.partial_derivative(4, 1) + + assert (lut_ndbspline.derivative([4, 1]).c == 0.0).all() + + def test_broadcast(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + lut = RectBivariateSpline(x,y,z) + xp_assert_close(lut(x, y), lut(x[:,None], y[None,:], grid=False)) + + def test_invalid_input(self): + + with assert_raises(ValueError) as info: + x = array([6, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + RectBivariateSpline(x, y, z) + assert "x must be strictly increasing" in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([2, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + RectBivariateSpline(x, y, z) + assert "y must be strictly increasing" in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1]]) + RectBivariateSpline(x, y, z) + assert "x dimension of z must have same number of elements as x"\ + in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 3, 2], + [1, 2, 2, 2], [1, 2, 1, 2]]) + RectBivariateSpline(x, y, z) + assert "y dimension of z must have same number of elements as y"\ + in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + bbox = (-100, 100, -100) + RectBivariateSpline(x, y, z, bbox=bbox) + assert "bbox shape should be (4,)" in str(info.value) + + with assert_raises(ValueError) as info: + RectBivariateSpline(x, y, z, s=-1.0) + assert "s should be s >= 0.0" in str(info.value) + + def test_array_like_input(self): + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + bbox = array([1, 5, 1, 5]) + + spl1 = RectBivariateSpline(x, y, z, bbox=bbox) + spl2 = RectBivariateSpline(x.tolist(), y.tolist(), z.tolist(), + bbox=bbox.tolist()) + assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0)) + + def test_not_increasing_input(self): + # gh-8565 + NSamp = 20 + Theta = np.random.uniform(0, np.pi, NSamp) + Phi = np.random.uniform(0, 2 * np.pi, NSamp) + Data = np.ones(NSamp) + + Interpolator = SmoothSphereBivariateSpline(Theta, Phi, Data, s=3.5) + + NLon = 6 + NLat = 3 + GridPosLats = np.arange(NLat) / NLat * np.pi + GridPosLons = np.arange(NLon) / NLon * 2 * np.pi + + # No error + Interpolator(GridPosLats, GridPosLons) + + nonGridPosLats = GridPosLats.copy() + nonGridPosLats[2] = 0.001 + with assert_raises(ValueError) as exc_info: + Interpolator(nonGridPosLats, GridPosLons) + assert "x must be strictly increasing" in str(exc_info.value) + + nonGridPosLons = GridPosLons.copy() + nonGridPosLons[2] = 0.001 + with assert_raises(ValueError) as exc_info: + Interpolator(GridPosLats, nonGridPosLons) + assert "y must be strictly increasing" in str(exc_info.value) + + def _sample_large_2d_data(self, nx, ny): + rng = np.random.default_rng(1) + x = np.arange(nx) + y = np.arange(ny) + z = rng.integers(0, 100, (nx, ny)) + + return x, y, z.astype(np.float64) + + @pytest.mark.slow() + @pytest.mark.parametrize('shape', [(350, 850), (2000, 170)]) + @pytest.mark.parametrize('s_tols', [(0, 1e-12, 1e-7), + (1, 7e-3, 1e-4), + (3, 2e-2, 1e-4)]) + def test_spline_large_2d(self, shape, s_tols): + # Reference - https://github.com/scipy/scipy/issues/17787 + nx, ny = shape + s, atol, rtol = s_tols + x, y, z = self._sample_large_2d_data(nx, ny) + + spl = RectBivariateSpline(x, y, z, s=s) + z_spl = spl(x, y) + assert(not np.isnan(z_spl).any()) + xp_assert_close(z_spl, z, atol=atol, rtol=rtol) + + @pytest.mark.slow() + @pytest.mark.skipif(sys.maxsize <= 2**32, reason="Segfaults on 32-bit system " + "due to large input data") + def test_spline_large_2d_maxit(self): + # Reference - for https://github.com/scipy/scipy/issues/17787 + nx, ny = 1000, 1700 + s, atol, rtol = 2, 2e-2, 1e-12 + x, y, z = self._sample_large_2d_data(nx, ny) + + spl = RectBivariateSpline(x, y, z, s=s, maxit=25) + z_spl = spl(x, y) + assert(not np.isnan(z_spl).any()) + xp_assert_close(z_spl, z, atol=atol, rtol=rtol) + + +class TestRectSphereBivariateSpline: + def test_defaults(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + lut = RectSphereBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y),z) + + def test_evaluate(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + lut = RectSphereBivariateSpline(x,y,z) + yi = [0.2, 1, 2.3, 2.35, 3.0, 3.99, 5.25] + xi = [1.5, 0.4, 1.1, 0.45, 0.2345, 1., 0.0001] + zi = lut.ev(xi, yi) + zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)]) + assert_almost_equal(zi, zi2) + + def test_invalid_input(self): + data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T, + np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(-1, 170, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 181, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-181, 10, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[0] should be between [-pi, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-10, 360, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[-1] should be v[0] + 2pi or less" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(10, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data, s=-1) + assert "s should be positive" in str(exc_info.value) + + def test_derivatives_grid(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + + lut = RectSphereBivariateSpline(x,y,z) + + y = linspace(0.02, 2*pi-0.02, 7) + x = linspace(0.02, pi-0.02, 7) + + xp_assert_close(lut(x, y, dtheta=1), _numdiff_2d(lut, x, y, dx=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dphi=1), _numdiff_2d(lut, x, y, dy=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dtheta=1, dphi=1), + _numdiff_2d(lut, x, y, dx=1, dy=1, eps=1e-6), + rtol=1e-3, atol=1e-3) + + xp_assert_equal(lut(x, y, dtheta=1), + lut.partial_derivative(1, 0)(x, y)) + xp_assert_equal(lut(x, y, dphi=1), + lut.partial_derivative(0, 1)(x, y)) + xp_assert_equal(lut(x, y, dtheta=1, dphi=1), + lut.partial_derivative(1, 1)(x, y)) + + xp_assert_equal(lut(x, y, dtheta=1, grid=False), + lut.partial_derivative(1, 0)(x, y, grid=False)) + xp_assert_equal(lut(x, y, dphi=1, grid=False), + lut.partial_derivative(0, 1)(x, y, grid=False)) + xp_assert_equal(lut(x, y, dtheta=1, dphi=1, grid=False), + lut.partial_derivative(1, 1)(x, y, grid=False)) + + def test_derivatives(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + + lut = RectSphereBivariateSpline(x,y,z) + + y = linspace(0.02, 2*pi-0.02, 7) + x = linspace(0.02, pi-0.02, 7) + + assert lut(x, y, dtheta=1, grid=False).shape == x.shape + xp_assert_close(lut(x, y, dtheta=1, grid=False), + _numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dx=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dphi=1, grid=False), + _numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dy=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dtheta=1, dphi=1, grid=False), + _numdiff_2d(lambda x,y: lut(x,y,grid=False), + x, y, dx=1, dy=1, eps=1e-6), + rtol=1e-3, atol=1e-3) + + def test_invalid_input_2(self): + data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T, + np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(0, 170, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 180, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-181, 10, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[0] should be between [-pi, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-10, 360, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[-1] should be v[0] + 2pi or less" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(10, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data, s=-1) + assert "s should be positive" in str(exc_info.value) + + def test_array_like_input(self): + y = linspace(0.01, 2 * pi - 0.01, 7) + x = linspace(0.01, pi - 0.01, 7) + z = array([[1, 2, 1, 2, 1, 2, 1], [1, 2, 1, 2, 1, 2, 1], + [1, 2, 3, 2, 1, 2, 1], + [1, 2, 2, 2, 1, 2, 1], [1, 2, 1, 2, 1, 2, 1], + [1, 2, 2, 2, 1, 2, 1], + [1, 2, 1, 2, 1, 2, 1]]) + # np.array input + spl1 = RectSphereBivariateSpline(x, y, z) + # list input + spl2 = RectSphereBivariateSpline(x.tolist(), y.tolist(), z.tolist()) + assert_array_almost_equal(spl1(x, y), spl2(x, y)) + + def test_negative_evaluation(self): + lats = np.array([25, 30, 35, 40, 45]) + lons = np.array([-90, -85, -80, -75, 70]) + mesh = np.meshgrid(lats, lons) + data = mesh[0] + mesh[1] # lon + lat value + lat_r = np.radians(lats) + lon_r = np.radians(lons) + interpolator = RectSphereBivariateSpline(lat_r, lon_r, data) + query_lat = np.radians(np.array([35, 37.5])) + query_lon = np.radians(np.array([-80, -77.5])) + data_interp = interpolator(query_lat, query_lon) + ans = np.array([[-45.0, -42.480862], + [-49.0625, -46.54315]]) + assert_array_almost_equal(data_interp, ans) + + def test_pole_continuity_gh_14591(self): + # regression test for https://github.com/scipy/scipy/issues/14591 + # with pole_continuty=(True, True), the internal work array size + # was too small, leading to a FITPACK data validation error. + + # The reproducer in gh-14591 was using a NetCDF4 file with + # 361x507 arrays, so here we trivialize array sizes to a minimum + # which still demonstrates the issue. + u = np.arange(1, 10) * np.pi / 10 + v = np.arange(1, 10) * np.pi / 10 + r = np.zeros((9, 9)) + for p in [(True, True), (True, False), (False, False)]: + RectSphereBivariateSpline(u, v, r, s=0, pole_continuity=p) + + +def _numdiff_2d(func, x, y, dx=0, dy=0, eps=1e-8): + if dx == 0 and dy == 0: + return func(x, y) + elif dx == 1 and dy == 0: + return (func(x + eps, y) - func(x - eps, y)) / (2*eps) + elif dx == 0 and dy == 1: + return (func(x, y + eps) - func(x, y - eps)) / (2*eps) + elif dx == 1 and dy == 1: + return (func(x + eps, y + eps) - func(x - eps, y + eps) + - func(x + eps, y - eps) + func(x - eps, y - eps)) / (2*eps)**2 + else: + raise ValueError("invalid derivative order") + + +class Test_DerivedBivariateSpline: + """Test the creation, usage, and attribute access of the (private) + _DerivedBivariateSpline class. + """ + def setup_method(self): + x = np.concatenate(list(zip(range(10), range(10)))) + y = np.concatenate(list(zip(range(10), range(1, 11)))) + z = np.concatenate((np.linspace(3, 1, 10), np.linspace(1, 3, 10))) + with pytest.warns(UserWarning, match="\nThe coefficients of the spline"): + self.lut_lsq = LSQBivariateSpline(x, y, z, + linspace(0.5, 19.5, 4), + linspace(1.5, 20.5, 4), + eps=1e-2) + self.lut_smooth = SmoothBivariateSpline(x, y, z) + xx = linspace(0, 1, 20) + yy = xx + 1.0 + zz = array([np.roll(z, i) for i in range(z.size)]) + self.lut_rect = RectBivariateSpline(xx, yy, zz) + self.orders = list(itertools.product(range(3), range(3))) + + def test_creation_from_LSQ(self): + for nux, nuy in self.orders: + lut_der = self.lut_lsq.partial_derivative(nux, nuy) + a = lut_der(3.5, 3.5, grid=False) + b = self.lut_lsq(3.5, 3.5, dx=nux, dy=nuy, grid=False) + assert a == b + + def test_creation_from_Smooth(self): + for nux, nuy in self.orders: + lut_der = self.lut_smooth.partial_derivative(nux, nuy) + a = lut_der(5.5, 5.5, grid=False) + b = self.lut_smooth(5.5, 5.5, dx=nux, dy=nuy, grid=False) + assert a == b + + def test_creation_from_Rect(self): + for nux, nuy in self.orders: + lut_der = self.lut_rect.partial_derivative(nux, nuy) + lut_ndspline = convert_to_ndbspline(self.lut_rect) + lut_der_ndbspline = lut_ndspline.derivative((nux, nuy)) + a = lut_der(0.5, 1.5, grid=False) + a_ndbspline = lut_der_ndbspline([(0.5, 1.5)]) + b = self.lut_rect(0.5, 1.5, dx=nux, dy=nuy, grid=False) + b_ndbspline = lut_ndspline([(0.5, 1.5)], nu=(nux, nuy)) + assert a == b + assert_almost_equal(a_ndbspline, b_ndbspline) + + def test_invalid_attribute_fp(self): + der = self.lut_rect.partial_derivative(1, 1) + lut_ndspline = convert_to_ndbspline(self.lut_rect) + der_ndbspline = lut_ndspline.derivative((1, 1)) + with assert_raises(AttributeError): + der.fp + with assert_raises(AttributeError): + der_ndbspline.fp + + def test_invalid_attribute_get_residual(self): + der = self.lut_smooth.partial_derivative(1, 1) + with assert_raises(AttributeError): + der.get_residual() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_gil.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_gil.py new file mode 100644 index 0000000000000000000000000000000000000000..a51311ce7e36300bdb394f8b578de0ab84c9fdb2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_gil.py @@ -0,0 +1,64 @@ +import itertools +import threading +import time + +import numpy as np +import pytest +import scipy.interpolate + + +class TestGIL: + """Check if the GIL is properly released by scipy.interpolate functions.""" + + def setup_method(self): + self.messages = [] + + def log(self, message): + self.messages.append(message) + + def make_worker_thread(self, target, args): + log = self.log + + class WorkerThread(threading.Thread): + def run(self): + log('interpolation started') + target(*args) + log('interpolation complete') + + return WorkerThread() + + @pytest.mark.xslow + @pytest.mark.xfail(reason='race conditions, may depend on system load') + def test_rectbivariatespline(self): + def generate_params(n_points): + x = y = np.linspace(0, 1000, n_points) + x_grid, y_grid = np.meshgrid(x, y) + z = x_grid * y_grid + return x, y, z + + def calibrate_delay(requested_time): + for n_points in itertools.count(5000, 1000): + args = generate_params(n_points) + time_started = time.time() + interpolate(*args) + if time.time() - time_started > requested_time: + return args + + def interpolate(x, y, z): + scipy.interpolate.RectBivariateSpline(x, y, z) + + args = calibrate_delay(requested_time=3) + worker_thread = self.make_worker_thread(interpolate, args) + worker_thread.start() + for i in range(3): + time.sleep(0.5) + self.log('working') + worker_thread.join() + assert self.messages == [ + 'interpolation started', + 'working', + 'working', + 'working', + 'interpolation complete', + ] + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_interpnd.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_interpnd.py new file mode 100644 index 0000000000000000000000000000000000000000..c47945e0969d43665d88bdb1328cf21cf22784e1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_interpnd.py @@ -0,0 +1,454 @@ +import os +import sys +import warnings + +import numpy as np +from pytest import raises as assert_raises +import pytest +from scipy._lib._array_api import xp_assert_close, assert_almost_equal + +from scipy._lib._testutils import check_free_memory +import scipy.interpolate._interpnd as interpnd +import scipy.spatial._qhull as qhull + +import pickle +import threading + +_IS_32BIT = (sys.maxsize < 2**32) + + +def data_file(basename): + return os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', basename) + + +class TestLinearNDInterpolation: + def test_smoketest(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + yi = interpnd.LinearNDInterpolator(x, y)(x) + assert_almost_equal(y, yi) + + def test_smoketest_alternate(self): + # Test at single points, alternate calling convention + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + yi = interpnd.LinearNDInterpolator((x[:,0], x[:,1]), y)(x[:,0], x[:,1]) + assert_almost_equal(y, yi) + + def test_complex_smoketest(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + yi = interpnd.LinearNDInterpolator(x, y)(x) + assert_almost_equal(y, yi) + + def test_tri_input(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + interpolator = interpnd.LinearNDInterpolator(tri, y) + yi = interpolator(x) + assert_almost_equal(y, yi) + assert interpolator.tri is tri + + def test_square(self): + # Test barycentric interpolation on a square against a manual + # implementation + + points = np.array([(0,0), (0,1), (1,1), (1,0)], dtype=np.float64) + values = np.array([1., 2., -3., 5.], dtype=np.float64) + + # NB: assume triangles (0, 1, 3) and (1, 2, 3) + # + # 1----2 + # | \ | + # | \ | + # 0----3 + + def ip(x, y): + t1 = (x + y <= 1) + t2 = ~t1 + + x1 = x[t1] + y1 = y[t1] + + x2 = x[t2] + y2 = y[t2] + + z = 0*x + + z[t1] = (values[0]*(1 - x1 - y1) + + values[1]*y1 + + values[3]*x1) + + z[t2] = (values[2]*(x2 + y2 - 1) + + values[1]*(1 - x2) + + values[3]*(1 - y2)) + return z + + xx, yy = np.broadcast_arrays(np.linspace(0, 1, 14)[:,None], + np.linspace(0, 1, 14)[None,:]) + xx = xx.ravel() + yy = yy.ravel() + + xi = np.array([xx, yy]).T.copy() + zi = interpnd.LinearNDInterpolator(points, values)(xi) + + assert_almost_equal(zi, ip(xx, yy)) + + def test_smoketest_rescale(self): + # Test at single points + x = np.array([(0, 0), (-5, -5), (-5, 5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + yi = interpnd.LinearNDInterpolator(x, y, rescale=True)(x) + assert_almost_equal(y, yi) + + def test_square_rescale(self): + # Test barycentric interpolation on a rectangle with rescaling + # agaings the same implementation without rescaling + + points = np.array([(0,0), (0,100), (10,100), (10,0)], dtype=np.float64) + values = np.array([1., 2., -3., 5.], dtype=np.float64) + + xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None], + np.linspace(0, 100, 14)[None,:]) + xx = xx.ravel() + yy = yy.ravel() + xi = np.array([xx, yy]).T.copy() + zi = interpnd.LinearNDInterpolator(points, values)(xi) + zi_rescaled = interpnd.LinearNDInterpolator(points, values, + rescale=True)(xi) + + assert_almost_equal(zi, zi_rescaled) + + def test_tripoints_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + yi = interpnd.LinearNDInterpolator(tri.points, y)(x) + yi_rescale = interpnd.LinearNDInterpolator(tri.points, y, + rescale=True)(x) + assert_almost_equal(yi, yi_rescale) + + def test_tri_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + match = ("Rescaling is not supported when passing a " + "Delaunay triangulation as ``points``.") + with pytest.raises(ValueError, match=match): + interpnd.LinearNDInterpolator(tri, y, rescale=True)(x) + + def test_pickle(self): + # Test at single points + np.random.seed(1234) + x = np.random.rand(30, 2) + y = np.random.rand(30) + 1j*np.random.rand(30) + + ip = interpnd.LinearNDInterpolator(x, y) + ip2 = pickle.loads(pickle.dumps(ip)) + + assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5)) + + @pytest.mark.slow + @pytest.mark.skipif(_IS_32BIT, reason='it fails on 32-bit') + def test_threading(self): + # This test was taken from issue 8856 + # https://github.com/scipy/scipy/issues/8856 + check_free_memory(10000) + + r_ticks = np.arange(0, 4200, 10) + phi_ticks = np.arange(0, 4200, 10) + r_grid, phi_grid = np.meshgrid(r_ticks, phi_ticks) + + def do_interp(interpolator, slice_rows, slice_cols): + grid_x, grid_y = np.mgrid[slice_rows, slice_cols] + res = interpolator((grid_x, grid_y)) + return res + + points = np.vstack((r_grid.ravel(), phi_grid.ravel())).T + values = (r_grid * phi_grid).ravel() + interpolator = interpnd.LinearNDInterpolator(points, values) + + worker_thread_1 = threading.Thread( + target=do_interp, + args=(interpolator, slice(0, 2100), slice(0, 2100))) + worker_thread_2 = threading.Thread( + target=do_interp, + args=(interpolator, slice(2100, 4200), slice(0, 2100))) + worker_thread_3 = threading.Thread( + target=do_interp, + args=(interpolator, slice(0, 2100), slice(2100, 4200))) + worker_thread_4 = threading.Thread( + target=do_interp, + args=(interpolator, slice(2100, 4200), slice(2100, 4200))) + + worker_thread_1.start() + worker_thread_2.start() + worker_thread_3.start() + worker_thread_4.start() + + worker_thread_1.join() + worker_thread_2.join() + worker_thread_3.join() + worker_thread_4.join() + + +class TestEstimateGradients2DGlobal: + def test_smoketest(self): + x = np.array([(0, 0), (0, 2), + (1, 0), (1, 2), (0.25, 0.75), (0.6, 0.8)], dtype=float) + tri = qhull.Delaunay(x) + + # Should be exact for linear functions, independent of triangulation + + funcs = [ + (lambda x, y: 0*x + 1, (0, 0)), + (lambda x, y: 0 + x, (1, 0)), + (lambda x, y: -2 + y, (0, 1)), + (lambda x, y: 3 + 3*x + 14.15*y, (3, 14.15)) + ] + + for j, (func, grad) in enumerate(funcs): + z = func(x[:,0], x[:,1]) + dz = interpnd.estimate_gradients_2d_global(tri, z, tol=1e-6) + + assert dz.shape == (6, 2) + xp_assert_close( + dz, np.array(grad)[None, :] + 0*dz, rtol=1e-5, atol=1e-5, + err_msg=f"item {j}" + ) + + def test_regression_2359(self): + # Check regression --- for certain point sets, gradient + # estimation could end up in an infinite loop + points = np.load(data_file('estimate_gradients_hang.npy')) + values = np.random.rand(points.shape[0]) + tri = qhull.Delaunay(points) + + # This should not hang + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + "Gradient estimation did not converge", + interpnd.GradientEstimationWarning + ) + interpnd.estimate_gradients_2d_global(tri, values, maxiter=1) + + +class TestCloughTocher2DInterpolator: + + def _check_accuracy(self, func, x=None, tol=1e-6, alternate=False, + rescale=False, **kw): + rng = np.random.RandomState(1234) + # np.random.seed(1234) + if x is None: + x = np.array([(0, 0), (0, 1), + (1, 0), (1, 1), (0.25, 0.75), (0.6, 0.8), + (0.5, 0.2)], + dtype=float) + + if not alternate: + ip = interpnd.CloughTocher2DInterpolator(x, func(x[:,0], x[:,1]), + tol=1e-6, rescale=rescale) + else: + ip = interpnd.CloughTocher2DInterpolator((x[:,0], x[:,1]), + func(x[:,0], x[:,1]), + tol=1e-6, rescale=rescale) + + p = rng.rand(50, 2) + + if not alternate: + a = ip(p) + else: + a = ip(p[:,0], p[:,1]) + b = func(p[:,0], p[:,1]) + + try: + xp_assert_close(a, b, **kw) + except AssertionError: + print("_check_accuracy: abs(a-b):", abs(a - b)) + print("ip.grad:", ip.grad) + raise + + def test_linear_smoketest(self): + # Should be exact for linear functions, independent of triangulation + funcs = [ + lambda x, y: 0*x + 1, + lambda x, y: 0 + x, + lambda x, y: -2 + y, + lambda x, y: 3 + 3*x + 14.15*y, + ] + + for j, func in enumerate(funcs): + self._check_accuracy( + func, tol=1e-13, atol=1e-7, rtol=1e-7, err_msg=f"Function {j}" + ) + self._check_accuracy( + func, tol=1e-13, atol=1e-7, rtol=1e-7, alternate=True, + err_msg=f"Function (alternate) {j}" + ) + # check rescaling + self._check_accuracy( + func, tol=1e-13, atol=1e-7, rtol=1e-7, + err_msg=f"Function (rescaled) {j}", rescale=True + ) + self._check_accuracy( + func, tol=1e-13, atol=1e-7, rtol=1e-7, alternate=True, rescale=True, + err_msg=f"Function (alternate, rescaled) {j}" + ) + + def test_quadratic_smoketest(self): + # Should be reasonably accurate for quadratic functions + funcs = [ + lambda x, y: x**2, + lambda x, y: y**2, + lambda x, y: x**2 - y**2, + lambda x, y: x*y, + ] + + for j, func in enumerate(funcs): + self._check_accuracy( + func, tol=1e-9, atol=0.22, rtol=0, err_msg=f"Function {j}" + ) + self._check_accuracy( + func, tol=1e-9, atol=0.22, rtol=0, err_msg=f"Function {j}", rescale=True + ) + + def test_tri_input(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + yi = interpnd.CloughTocher2DInterpolator(tri, y)(x) + assert_almost_equal(y, yi) + + def test_tri_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + match = ("Rescaling is not supported when passing a " + "Delaunay triangulation as ``points``.") + with pytest.raises(ValueError, match=match): + interpnd.CloughTocher2DInterpolator(tri, y, rescale=True)(x) + + def test_tripoints_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + yi = interpnd.CloughTocher2DInterpolator(tri.points, y)(x) + yi_rescale = interpnd.CloughTocher2DInterpolator(tri.points, y, rescale=True)(x) + assert_almost_equal(yi, yi_rescale) + + @pytest.mark.fail_slow(5) + def test_dense(self): + # Should be more accurate for dense meshes + funcs = [ + lambda x, y: x**2, + lambda x, y: y**2, + lambda x, y: x**2 - y**2, + lambda x, y: x*y, + lambda x, y: np.cos(2*np.pi*x)*np.sin(2*np.pi*y) + ] + + rng = np.random.RandomState(4321) # use a different seed than the check! + grid = np.r_[np.array([(0,0), (0,1), (1,0), (1,1)], dtype=float), + rng.rand(30*30, 2)] + + for j, func in enumerate(funcs): + self._check_accuracy( + func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2, err_msg=f"Function {j}" + ) + self._check_accuracy( + func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2, + err_msg=f"Function {j}", rescale=True + ) + + def test_wrong_ndim(self): + x = np.random.randn(30, 3) + y = np.random.randn(30) + assert_raises(ValueError, interpnd.CloughTocher2DInterpolator, x, y) + + def test_pickle(self): + # Test at single points + rng = np.random.RandomState(1234) + x = rng.rand(30, 2) + y = rng.rand(30) + 1j*rng.rand(30) + + ip = interpnd.CloughTocher2DInterpolator(x, y) + ip2 = pickle.loads(pickle.dumps(ip)) + + assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5)) + + def test_boundary_tri_symmetry(self): + # Interpolation at neighbourless triangles should retain + # symmetry with mirroring the triangle. + + # Equilateral triangle + points = np.array([(0, 0), (1, 0), (0.5, np.sqrt(3)/2)]) + values = np.array([1, 0, 0]) + + ip = interpnd.CloughTocher2DInterpolator(points, values) + + # Set gradient to zero at vertices + ip.grad[...] = 0 + + # Interpolation should be symmetric vs. bisector + alpha = 0.3 + p1 = np.array([0.5 * np.cos(alpha), 0.5 * np.sin(alpha)]) + p2 = np.array([0.5 * np.cos(np.pi/3 - alpha), 0.5 * np.sin(np.pi/3 - alpha)]) + + v1 = ip(p1) + v2 = ip(p2) + xp_assert_close(v1, v2) + + # ... and affine invariant + rng = np.random.RandomState(1) + A = rng.randn(2, 2) + b = rng.randn(2) + + points = A.dot(points.T).T + b[None,:] + p1 = A.dot(p1) + b + p2 = A.dot(p2) + b + + ip = interpnd.CloughTocher2DInterpolator(points, values) + ip.grad[...] = 0 + + w1 = ip(p1) + w2 = ip(p2) + xp_assert_close(w1, v1) + xp_assert_close(w2, v2) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_interpolate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4b6a5127e40e0b5f7b93651ceac80fb87bb899 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_interpolate.py @@ -0,0 +1,2692 @@ +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal, + make_xp_test_case +) +from pytest import raises as assert_raises +import pytest + +from numpy import mgrid, pi, sin, poly1d +import numpy as np + +from scipy.interpolate import (interp1d, interp2d, lagrange, PPoly, BPoly, + splrep, splev, splantider, splint, sproot, Akima1DInterpolator, + NdPPoly, BSpline, PchipInterpolator) + +from scipy.special import poch, gamma + +from scipy.interpolate import _ppoly + +from scipy._lib._gcutils import assert_deallocated, IS_PYPY +from scipy._lib._testutils import _run_concurrent_barrier + +from scipy.integrate import nquad + +from scipy.special import binom + +skip_xp_backends = pytest.mark.skip_xp_backends +xfail_xp_backends = pytest.mark.xfail_xp_backends + + +class TestInterp2D: + def test_interp2d(self): + y, x = mgrid[0:2:20j, 0:pi:21j] + z = sin(x+0.5*y) + with assert_raises(NotImplementedError): + interp2d(x, y, z) + + +class TestInterp1D: + + def setup_method(self): + self.x5 = np.arange(5.) + self.x10 = np.arange(10.) + self.y10 = np.arange(10.) + self.x25 = self.x10.reshape((2,5)) + self.x2 = np.arange(2.) + self.y2 = np.arange(2.) + self.x1 = np.array([0.]) + self.y1 = np.array([0.]) + + self.y210 = np.arange(20.).reshape((2, 10)) + self.y102 = np.arange(20.).reshape((10, 2)) + self.y225 = np.arange(20.).reshape((2, 2, 5)) + self.y25 = np.arange(10.).reshape((2, 5)) + self.y235 = np.arange(30.).reshape((2, 3, 5)) + self.y325 = np.arange(30.).reshape((3, 2, 5)) + + # Edge updated test matrix 1 + # array([[ 30, 1, 2, 3, 4, 5, 6, 7, 8, -30], + # [ 30, 11, 12, 13, 14, 15, 16, 17, 18, -30]]) + self.y210_edge_updated = np.arange(20.).reshape((2, 10)) + self.y210_edge_updated[:, 0] = 30 + self.y210_edge_updated[:, -1] = -30 + + # Edge updated test matrix 2 + # array([[ 30, 30], + # [ 2, 3], + # [ 4, 5], + # [ 6, 7], + # [ 8, 9], + # [ 10, 11], + # [ 12, 13], + # [ 14, 15], + # [ 16, 17], + # [-30, -30]]) + self.y102_edge_updated = np.arange(20.).reshape((10, 2)) + self.y102_edge_updated[0, :] = 30 + self.y102_edge_updated[-1, :] = -30 + + self.fill_value = -100.0 + + def test_validation(self): + # Make sure that appropriate exceptions are raised when invalid values + # are given to the constructor. + + # These should all work. + for kind in ('nearest', 'nearest-up', 'zero', 'linear', 'slinear', + 'quadratic', 'cubic', 'previous', 'next'): + interp1d(self.x10, self.y10, kind=kind) + interp1d(self.x10, self.y10, kind=kind, fill_value="extrapolate") + interp1d(self.x10, self.y10, kind='linear', fill_value=(-1, 1)) + interp1d(self.x10, self.y10, kind='linear', + fill_value=np.array([-1])) + interp1d(self.x10, self.y10, kind='linear', + fill_value=(-1,)) + interp1d(self.x10, self.y10, kind='linear', + fill_value=-1) + interp1d(self.x10, self.y10, kind='linear', + fill_value=(-1, -1)) + interp1d(self.x10, self.y10, kind=0) + interp1d(self.x10, self.y10, kind=1) + interp1d(self.x10, self.y10, kind=2) + interp1d(self.x10, self.y10, kind=3) + interp1d(self.x10, self.y210, kind='linear', axis=-1, + fill_value=(-1, -1)) + interp1d(self.x2, self.y210, kind='linear', axis=0, + fill_value=np.ones(10)) + interp1d(self.x2, self.y210, kind='linear', axis=0, + fill_value=(np.ones(10), np.ones(10))) + interp1d(self.x2, self.y210, kind='linear', axis=0, + fill_value=(np.ones(10), -1)) + + # x array must be 1D. + assert_raises(ValueError, interp1d, self.x25, self.y10) + + # y array cannot be a scalar. + assert_raises(ValueError, interp1d, self.x10, np.array(0)) + + # Check for x and y arrays having the same length. + assert_raises(ValueError, interp1d, self.x10, self.y2) + assert_raises(ValueError, interp1d, self.x2, self.y10) + assert_raises(ValueError, interp1d, self.x10, self.y102) + interp1d(self.x10, self.y210) + interp1d(self.x10, self.y102, axis=0) + + # Check for x and y having at least 1 element. + assert_raises(ValueError, interp1d, self.x1, self.y10) + assert_raises(ValueError, interp1d, self.x10, self.y1) + + # Bad fill values + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=(-1, -1, -1)) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=[-1, -1, -1]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=np.array((-1, -1, -1))) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=[[-1]]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=[-1, -1]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=np.array([])) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=()) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear', + axis=0, fill_value=[-1, -1]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear', + axis=0, fill_value=(0., [-1, -1])) # above doesn't bc + + def test_init(self): + # Check that the attributes are initialized appropriately by the + # constructor. + assert interp1d(self.x10, self.y10).copy + assert not interp1d(self.x10, self.y10, copy=False).copy + assert interp1d(self.x10, self.y10).bounds_error + assert not interp1d(self.x10, self.y10, bounds_error=False).bounds_error + assert np.isnan(interp1d(self.x10, self.y10).fill_value) + assert interp1d(self.x10, self.y10, fill_value=3.0).fill_value == 3.0 + assert (interp1d(self.x10, self.y10, fill_value=(1.0, 2.0)).fill_value == + (1.0, 2.0) + ) + assert interp1d(self.x10, self.y10).axis == 0 + assert interp1d(self.x10, self.y210).axis == 1 + assert interp1d(self.x10, self.y102, axis=0).axis == 0 + xp_assert_equal(interp1d(self.x10, self.y10).x, self.x10) + xp_assert_equal(interp1d(self.x10, self.y10).y, self.y10) + xp_assert_equal(interp1d(self.x10, self.y210).y, self.y210) + + def test_assume_sorted(self): + # Check for unsorted arrays + interp10 = interp1d(self.x10, self.y10) + interp10_unsorted = interp1d(self.x10[::-1], self.y10[::-1]) + + assert_array_almost_equal(interp10_unsorted(self.x10), self.y10) + assert_array_almost_equal(interp10_unsorted(1.2), np.array(1.2)) + assert_array_almost_equal(interp10_unsorted([2.4, 5.6, 6.0]), + interp10([2.4, 5.6, 6.0])) + + # Check assume_sorted keyword (defaults to False) + interp10_assume_kw = interp1d(self.x10[::-1], self.y10[::-1], + assume_sorted=False) + assert_array_almost_equal(interp10_assume_kw(self.x10), self.y10) + + interp10_assume_kw2 = interp1d(self.x10[::-1], self.y10[::-1], + assume_sorted=True) + # Should raise an error for unsorted input if assume_sorted=True + assert_raises(ValueError, interp10_assume_kw2, self.x10) + + # Check that if y is a 2-D array, things are still consistent + interp10_y_2d = interp1d(self.x10, self.y210) + interp10_y_2d_unsorted = interp1d(self.x10[::-1], self.y210[:, ::-1]) + assert_array_almost_equal(interp10_y_2d(self.x10), + interp10_y_2d_unsorted(self.x10)) + + def test_linear(self): + for kind in ['linear', 'slinear']: + self._check_linear(kind) + + def _check_linear(self, kind): + # Check the actual implementation of linear interpolation. + interp10 = interp1d(self.x10, self.y10, kind=kind) + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.2)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2.4, 5.6, 6.0])) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind=kind, + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + np.asarray([-1.0, 0, 9, 11]), rtol=1e-14) + + opts = dict(kind=kind, + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + def test_linear_dtypes(self): + # regression test for gh-5898, where 1D linear interpolation has been + # delegated to numpy.interp for all float dtypes, and the latter was + # not handling e.g. np.float128. + for dtyp in [np.float16, + np.float32, + np.float64, + np.longdouble]: + x = np.arange(8, dtype=dtyp) + y = x + yp = interp1d(x, y, kind='linear')(x) + assert yp.dtype == dtyp + xp_assert_close(yp, y, atol=1e-15) + + # regression test for gh-14531, where 1D linear interpolation has been + # has been extended to delegate to numpy.interp for integer dtypes + x = [0, 1, 2] + y = [np.nan, 0, 1] + yp = interp1d(x, y)(x) + xp_assert_close(yp, y, atol=1e-15) + + def test_slinear_dtypes(self): + # regression test for gh-7273: 1D slinear interpolation fails with + # float32 inputs + dt_r = [np.float16, np.float32, np.float64] + dt_rc = dt_r + [np.complex64, np.complex128] + spline_kinds = ['slinear', 'zero', 'quadratic', 'cubic'] + for dtx in dt_r: + x = np.arange(0, 10, dtype=dtx) + for dty in dt_rc: + y = np.exp(-x/3.0).astype(dty) + for dtn in dt_r: + xnew = x.astype(dtn) + for kind in spline_kinds: + f = interp1d(x, y, kind=kind, bounds_error=False) + xp_assert_close(f(xnew), y, atol=1e-7, + check_dtype=False, + err_msg=f"{dtx}, {dty} {dtn}") + + def test_cubic(self): + # Check the actual implementation of spline interpolation. + interp10 = interp1d(self.x10, self.y10, kind='cubic') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.2)) + assert_array_almost_equal(interp10(1.5), np.array(1.5)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2.4, 5.6, 6.0]),) + + def test_nearest(self): + # Check the actual implementation of nearest-neighbour interpolation. + # Nearest asserts that half-integer case (1.5) rounds down to 1 + interp10 = interp1d(self.x10, self.y10, kind='nearest') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(1.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 6., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='nearest', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [0.0, 0, 9, 9], rtol=1e-14) + + opts = dict(kind='nearest', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + def test_nearest_up(self): + # Check the actual implementation of nearest-neighbour interpolation. + # Nearest-up asserts that half-integer case (1.5) rounds up to 2 + interp10 = interp1d(self.x10, self.y10, kind='nearest-up') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(2.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 6., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='nearest-up', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [0.0, 0, 9, 9], rtol=1e-14) + + opts = dict(kind='nearest-up', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + def test_previous(self): + # Check the actual implementation of previous interpolation. + interp10 = interp1d(self.x10, self.y10, kind='previous') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(1.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 5., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='previous', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [np.nan, 0, 9, 9], rtol=1e-14) + + # Tests for gh-9591 + interpolator1D = interp1d(self.x10, self.y10, kind="previous", + fill_value='extrapolate') + xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]), + [np.nan, np.nan, 5, 8, 9, 9]) + + interpolator2D = interp1d(self.x10, self.y210, kind="previous", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[np.nan, np.nan, 5, 8, 9, 9], + [np.nan, np.nan, 15, 18, 19, 19]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="previous", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[np.nan, np.nan], + [10, 11], + [18, 19]]) + + opts = dict(kind='previous', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + # Tests for gh-16813 + interpolator1D = interp1d([0, 1, 2], + [0, 1, -1], kind="previous", + fill_value='extrapolate', + assume_sorted=True) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [np.nan, np.nan, 0, 1, -1, -1, -1]) + + interpolator1D = interp1d([2, 0, 1], # x is not ascending + [-1, 0, 1], kind="previous", + fill_value='extrapolate', + assume_sorted=False) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [np.nan, np.nan, 0, 1, -1, -1, -1]) + + interpolator2D = interp1d(self.x10, self.y210_edge_updated, + kind="previous", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[np.nan, np.nan, 5, 8, -30, -30], + [np.nan, np.nan, 15, 18, -30, -30]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated, + kind="previous", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[np.nan, np.nan], + [10, 11], + [-30, -30]]) + + def test_next(self): + # Check the actual implementation of next interpolation. + interp10 = interp1d(self.x10, self.y10, kind='next') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(2.)) + assert_array_almost_equal(interp10(1.5), np.array(2.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([3., 6., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='next', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [0, 0, 9, np.nan], rtol=1e-14) + + # Tests for gh-9591 + interpolator1D = interp1d(self.x10, self.y10, kind="next", + fill_value='extrapolate') + xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]), + [0, 0, 5, 8, np.nan, np.nan]) + + interpolator2D = interp1d(self.x10, self.y210, kind="next", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[0, 0, 5, 8, np.nan, np.nan], + [10, 10, 15, 18, np.nan, np.nan]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="next", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[0, 1], + [10, 11], + [np.nan, np.nan]]) + + opts = dict(kind='next', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + # Tests for gh-16813 + interpolator1D = interp1d([0, 1, 2], + [0, 1, -1], kind="next", + fill_value='extrapolate', + assume_sorted=True) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [0, 0, 0, 1, -1, np.nan, np.nan]) + + interpolator1D = interp1d([2, 0, 1], # x is not ascending + [-1, 0, 1], kind="next", + fill_value='extrapolate', + assume_sorted=False) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [0, 0, 0, 1, -1, np.nan, np.nan]) + + interpolator2D = interp1d(self.x10, self.y210_edge_updated, + kind="next", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[30, 30, 5, 8, np.nan, np.nan], + [30, 30, 15, 18, np.nan, np.nan]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated, + kind="next", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[30, 30], + [10, 11], + [np.nan, np.nan]]) + + def test_zero(self): + # Check the actual implementation of zero-order spline interpolation. + interp10 = interp1d(self.x10, self.y10, kind='zero') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(1.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 5., 6.])) + + def bounds_check_helper(self, interpolant, test_array, fail_value): + # Asserts that a ValueError is raised and that the error message + # contains the value causing this exception. + assert_raises(ValueError, interpolant, test_array) + try: + interpolant(test_array) + except ValueError as err: + assert (f"{fail_value}" in str(err)) + + def _bounds_check(self, kind='linear'): + # Test that our handling of out-of-bounds input is correct. + extrap10 = interp1d(self.x10, self.y10, fill_value=self.fill_value, + bounds_error=False, kind=kind) + + xp_assert_equal(extrap10(11.2), np.array(self.fill_value)) + xp_assert_equal(extrap10(-3.4), np.array(self.fill_value)) + xp_assert_equal(extrap10([[[11.2], [-3.4], [12.6], [19.3]]]), + np.array(self.fill_value), check_shape=False) + xp_assert_equal(extrap10._check_bounds( + np.array([-1.0, 0.0, 5.0, 9.0, 11.0])), + np.array([[True, False, False, False, False], + [False, False, False, False, True]])) + + raises_bounds_error = interp1d(self.x10, self.y10, bounds_error=True, + kind=kind) + + self.bounds_check_helper(raises_bounds_error, -1.0, -1.0) + self.bounds_check_helper(raises_bounds_error, 11.0, 11.0) + self.bounds_check_helper(raises_bounds_error, [0.0, -1.0, 0.0], -1.0) + self.bounds_check_helper(raises_bounds_error, [0.0, 1.0, 21.0], 21.0) + + raises_bounds_error([0.0, 5.0, 9.0]) + + def _bounds_check_int_nan_fill(self, kind='linear'): + x = np.arange(10).astype(int) + y = np.arange(10).astype(int) + c = interp1d(x, y, kind=kind, fill_value=np.nan, bounds_error=False) + yi = c(x - 1) + assert np.isnan(yi[0]) + assert_array_almost_equal(yi, np.r_[np.nan, y[:-1]]) + + def test_bounds(self): + for kind in ('linear', 'cubic', 'nearest', 'previous', 'next', + 'slinear', 'zero', 'quadratic'): + self._bounds_check(kind) + self._bounds_check_int_nan_fill(kind) + + def _check_fill_value(self, kind): + interp = interp1d(self.x10, self.y10, kind=kind, + fill_value=(-100, 100), bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), np.asarray(-100.)) + assert_array_almost_equal(interp([-10, 10]), [-100, 100]) + + # Proper broadcasting: + # interp along axis of length 5 + # other dim=(2, 3), (3, 2), (2, 2), or (2,) + + # one singleton fill_value (works for all) + for y in (self.y235, self.y325, self.y225, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=100, bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), np.asarray(100.)) + assert_array_almost_equal(interp([-10, 10]), np.asarray(100.)) + + # singleton lower, singleton upper + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=(-100, 100), bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), np.asarray(-100.)) + if y.ndim == 3: + result = [[[-100, 100]] * y.shape[1]] * y.shape[0] + else: + result = [[-100, 100]] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # one broadcastable (3,) fill_value + fill_value = [100, 200, 300] + for y in (self.y325, self.y225): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + interp = interp1d(self.x5, self.y235, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2) + assert_array_almost_equal(interp(-10), [[100, 200, 300]] * 2) + assert_array_almost_equal(interp([-10, 10]), [[[100, 100], + [200, 200], + [300, 300]]] * 2) + + # one broadcastable (2,) fill_value + fill_value = [100, 200] + assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for y in (self.y225, self.y325, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + result = [100, 200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(10), result) + assert_array_almost_equal(interp(-10), result) + result = [[100, 100], [200, 200]] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # broadcastable (3,) lower, singleton upper + fill_value = (np.array([-100, -200, -300]), 100) + for y in (self.y325, self.y225): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + interp = interp1d(self.x5, self.y235, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2) + assert_array_almost_equal(interp([-10, 10]), [[[-100, 100], + [-200, 100], + [-300, 100]]] * 2) + + # broadcastable (2,) lower, singleton upper + fill_value = (np.array([-100, -200]), 100) + assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for y in (self.y225, self.y325, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100)) + result = [-100, -200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(-10), result) + result = [[-100, 100], [-200, 100]] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # broadcastable (3,) lower, broadcastable (3,) upper + fill_value = ([-100, -200, -300], [100, 200, 300]) + for y in (self.y325, self.y225): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for ii in range(2): # check ndarray as well as list here + if ii == 1: + fill_value = tuple(np.array(f) for f in fill_value) + interp = interp1d(self.x5, self.y235, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2) + assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2) + assert_array_almost_equal(interp([-10, 10]), [[[-100, 100], + [-200, 200], + [-300, 300]]] * 2) + # broadcastable (2,) lower, broadcastable (2,) upper + fill_value = ([-100, -200], [100, 200]) + assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for y in (self.y325, self.y225, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + result = [100, 200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(10), result) + result = [-100, -200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(-10), result) + result = [[-100, 100], [-200, 200]] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # one broadcastable (2, 2) array-like + fill_value = [[100, 200], [1000, 2000]] + for y in (self.y235, self.y325, self.y25): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for ii in range(2): + if ii == 1: + fill_value = np.array(fill_value) + interp = interp1d(self.x5, self.y225, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]]) + assert_array_almost_equal(interp(-10), [[100, 200], [1000, 2000]]) + assert_array_almost_equal(interp([-10, 10]), [[[100, 100], + [200, 200]], + [[1000, 1000], + [2000, 2000]]]) + + # broadcastable (2, 2) lower, broadcastable (2, 2) upper + fill_value = ([[-100, -200], [-1000, -2000]], + [[100, 200], [1000, 2000]]) + for y in (self.y235, self.y325, self.y25): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for ii in range(2): + if ii == 1: + fill_value = (np.array(fill_value[0]), np.array(fill_value[1])) + interp = interp1d(self.x5, self.y225, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]]) + assert_array_almost_equal(interp(-10), [[-100, -200], + [-1000, -2000]]) + assert_array_almost_equal(interp([-10, 10]), [[[-100, 100], + [-200, 200]], + [[-1000, 1000], + [-2000, 2000]]]) + + def test_fill_value(self): + # test that two-element fill value works + for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic', + 'zero', 'previous', 'next'): + self._check_fill_value(kind) + + def test_fill_value_writeable(self): + # backwards compat: fill_value is a public writeable attribute + interp = interp1d(self.x10, self.y10, fill_value=123.0) + assert interp.fill_value == 123.0 + interp.fill_value = 321.0 + assert interp.fill_value == 321.0 + + def _nd_check_interp(self, kind='linear'): + # Check the behavior when the inputs and outputs are multidimensional. + + # Multidimensional input. + interp10 = interp1d(self.x10, self.y10, kind=kind) + assert_array_almost_equal(interp10(np.array([[3., 5.], [2., 7.]])), + np.array([[3., 5.], [2., 7.]])) + + # Scalar input -> 0-dim scalar array output + assert isinstance(interp10(1.2), np.ndarray) + assert interp10(1.2).shape == () + + # Multidimensional outputs. + interp210 = interp1d(self.x10, self.y210, kind=kind) + assert_array_almost_equal(interp210(1.), np.array([1., 11.])) + assert_array_almost_equal(interp210(np.array([1., 2.])), + np.array([[1., 2.], [11., 12.]])) + + interp102 = interp1d(self.x10, self.y102, axis=0, kind=kind) + assert_array_almost_equal(interp102(1.), np.array([2.0, 3.0])) + assert_array_almost_equal(interp102(np.array([1., 3.])), + np.array([[2., 3.], [6., 7.]])) + + # Both at the same time! + x_new = np.array([[3., 5.], [2., 7.]]) + assert_array_almost_equal(interp210(x_new), + np.array([[[3., 5.], [2., 7.]], + [[13., 15.], [12., 17.]]])) + assert_array_almost_equal(interp102(x_new), + np.array([[[6., 7.], [10., 11.]], + [[4., 5.], [14., 15.]]])) + + def _nd_check_shape(self, kind='linear'): + # Check large N-D output shape + a = [4, 5, 6, 7] + y = np.arange(np.prod(a)).reshape(*a) + for n, s in enumerate(a): + x = np.arange(s) + z = interp1d(x, y, axis=n, kind=kind) + assert_array_almost_equal(z(x), y, err_msg=kind) + + x2 = np.arange(2*3*1).reshape((2,3,1)) / 12. + b = list(a) + b[n:n+1] = [2, 3, 1] + assert z(x2).shape == tuple(b), kind + + def test_nd(self): + for kind in ('linear', 'cubic', 'slinear', 'quadratic', 'nearest', + 'zero', 'previous', 'next'): + self._nd_check_interp(kind) + self._nd_check_shape(kind) + + def _check_complex(self, dtype=np.complex128, kind='linear'): + x = np.array([1, 2.5, 3, 3.1, 4, 6.4, 7.9, 8.0, 9.5, 10]) + y = x * x ** (1 + 2j) + y = y.astype(dtype) + + # simple test + c = interp1d(x, y, kind=kind) + assert_array_almost_equal(y[:-1], c(x)[:-1]) + + # check against interpolating real+imag separately + xi = np.linspace(1, 10, 31) + cr = interp1d(x, y.real, kind=kind) + ci = interp1d(x, y.imag, kind=kind) + assert_array_almost_equal(c(xi).real, cr(xi)) + assert_array_almost_equal(c(xi).imag, ci(xi)) + + def test_complex(self): + for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic', + 'zero', 'previous', 'next'): + self._check_complex(np.complex64, kind) + self._check_complex(np.complex128, kind) + + @pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy") + def test_circular_refs(self): + # Test interp1d can be automatically garbage collected + x = np.linspace(0, 1) + y = np.linspace(0, 1) + # Confirm interp can be released from memory after use + with assert_deallocated(interp1d, x, y) as interp: + interp([0.1, 0.2]) + del interp + + def test_overflow_nearest(self): + # Test that the x range doesn't overflow when given integers as input + for kind in ('nearest', 'previous', 'next'): + x = np.array([0, 50, 127], dtype=np.int8) + ii = interp1d(x, x, kind=kind) + assert_array_almost_equal(ii(x), x) + + def test_local_nans(self): + # check that for local interpolation kinds (slinear, zero) a single nan + # only affects its local neighborhood + x = np.arange(10).astype(float) + y = x.copy() + y[6] = np.nan + for kind in ('zero', 'slinear'): + ir = interp1d(x, y, kind=kind) + vals = ir([4.9, 7.0]) + assert np.isfinite(vals).all() + + def test_spline_nans(self): + # Backwards compat: a single nan makes the whole spline interpolation + # return nans in an array of the correct shape. And it doesn't raise, + # just quiet nans because of backcompat. + x = np.arange(8).astype(float) + y = x.copy() + yn = y.copy() + yn[3] = np.nan + + for kind in ['quadratic', 'cubic']: + ir = interp1d(x, y, kind=kind) + irn = interp1d(x, yn, kind=kind) + for xnew in (6, [1, 6], [[1, 6], [3, 5]]): + xnew = np.asarray(xnew) + out, outn = ir(x), irn(x) + assert np.isnan(outn).all() + assert out.shape == outn.shape + + def test_all_nans(self): + # regression test for gh-11637: interp1d core dumps with all-nan `x` + x = np.ones(10) * np.nan + y = np.arange(10) + with assert_raises(ValueError): + interp1d(x, y, kind='cubic') + + def test_read_only(self): + x = np.arange(0, 10) + y = np.exp(-x / 3.0) + xnew = np.arange(0, 9, 0.1) + # Check both read-only and not read-only: + for xnew_writeable in (True, False): + xnew.flags.writeable = xnew_writeable + x.flags.writeable = False + for kind in ('linear', 'nearest', 'zero', 'slinear', 'quadratic', + 'cubic'): + f = interp1d(x, y, kind=kind) + vals = f(xnew) + assert np.isfinite(vals).all() + + @pytest.mark.parametrize( + "kind", ("linear", "nearest", "nearest-up", "previous", "next") + ) + def test_single_value(self, kind): + # https://github.com/scipy/scipy/issues/4043 + f = interp1d([1.5], [6], kind=kind, bounds_error=False, + fill_value=(2, 10)) + xp_assert_equal(f([1, 1.5, 2]), np.asarray([2.0, 6, 10])) + # check still error if bounds_error=True + f = interp1d([1.5], [6], kind=kind, bounds_error=True) + with assert_raises(ValueError, match="x_new is above"): + f(2.0) + + +class TestLagrange: + + def test_lagrange(self): + p = poly1d([5,2,1,4,3]) + xs = np.arange(len(p.coeffs)) + ys = p(xs) + pl = lagrange(xs,ys) + assert_array_almost_equal(p.coeffs,pl.coeffs) + + +@make_xp_test_case(Akima1DInterpolator) +class TestAkima1DInterpolator: + def test_eval(self, xp): + x = xp.arange(0., 11., dtype=xp.float64) + y = xp.asarray( + [0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.], dtype=xp.float64 + ) + ak = Akima1DInterpolator(x, y) + xi = xp.asarray([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.], dtype=xp.float64) + yi = xp.asarray([0., 1.375, 2., 1.5, 1.953125, 2.484375, + 4.1363636363636366866103344, 5.9803623910336236590978842, + 5.5067291516462386624652936, 5.2031367459745245795943447, + 4.1796554159017080820603951, 3.4110386597938129327189927, + 3.], dtype=xp.float64) + xp_assert_close(ak(xi), yi) + + def test_eval_mod(self, xp): + # Reference values generated with the following MATLAB code: + # format longG + # x = 0:10; y = [0. 2. 1. 3. 2. 6. 5.5 5.5 2.7 5.1 3.]; + # xi = [0. 0.5 1. 1.5 2.5 3.5 4.5 5.1 6.5 7.2 8.6 9.9 10.]; + # makima(x, y, xi) + x = xp.arange(0., 11., dtype=xp.float64) + y = xp.asarray( + [0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.], dtype=xp.float64 + ) + ak = Akima1DInterpolator(x, y, method="makima") + xi = xp.asarray([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.], dtype=xp.float64) + yi = xp.asarray([ + 0.0, 1.34471153846154, 2.0, 1.44375, 1.94375, 2.51939102564103, + 4.10366931918656, 5.98501550899192, 5.51756330960439, 5.1757231914014, + 4.12326636931311, 3.32931513157895, 3.0], dtype=xp.float64) + xp_assert_close(ak(xi), yi) + + def test_eval_2d(self, xp): + x = xp.arange(0., 11., dtype=xp.float64) + y = xp.asarray( + [0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.], dtype=xp.float64 + ) + y = xp.stack((y, 2. * y), axis=1) + ak = Akima1DInterpolator(x, y) + xi = xp.asarray([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.], dtype=xp.float64) + yi = xp.asarray([0., 1.375, 2., 1.5, 1.953125, 2.484375, + 4.1363636363636366866103344, + 5.9803623910336236590978842, + 5.5067291516462386624652936, + 5.2031367459745245795943447, + 4.1796554159017080820603951, + 3.4110386597938129327189927, 3.], dtype=xp.float64) + yi = xp.stack((yi, 2. * yi), axis=1) + xp_assert_close(ak(xi), yi) + + def test_eval_3d(self): + x = np.arange(0., 11.) + y_ = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + y = np.empty((11, 2, 2)) + y[:, 0, 0] = y_ + y[:, 1, 0] = 2. * y_ + y[:, 0, 1] = 3. * y_ + y[:, 1, 1] = 4. * y_ + ak = Akima1DInterpolator(x, y) + xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.]) + yi = np.empty((13, 2, 2)) + yi_ = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375, + 4.1363636363636366866103344, + 5.9803623910336236590978842, + 5.5067291516462386624652936, + 5.2031367459745245795943447, + 4.1796554159017080820603951, + 3.4110386597938129327189927, 3.]) + yi[:, 0, 0] = yi_ + yi[:, 1, 0] = 2. * yi_ + yi[:, 0, 1] = 3. * yi_ + yi[:, 1, 1] = 4. * yi_ + xp_assert_close(ak(xi), yi) + + def test_linear_interpolant_edge_case_1d(self, xp): + x = xp.asarray([0.0, 1.0], dtype=xp.float64) + y = xp.asarray([0.5, 1.0]) + akima = Akima1DInterpolator(x, y, axis=0, extrapolate=None) + xp_assert_close(akima(0.45), xp.asarray(0.725, dtype=xp.float64)) + + def test_linear_interpolant_edge_case_2d(self, xp): + x = xp.asarray([0., 1.]) + y = xp.stack((x, 2. * x, 3. * x, 4. * x), axis=1) + + ak = Akima1DInterpolator(x, y) + xi = xp.asarray([0.5, 1.]) + yi = xp.asarray([[0.5, 1., 1.5, 2.], + [1., 2., 3., 4.]], dtype=xp.float64 + ) + xp_assert_close(ak(xi), yi) + + ak = Akima1DInterpolator(x, y.T, axis=1) + xp_assert_close(ak(xi), yi.T) + + def test_linear_interpolant_edge_case_3d(self): + x = np.arange(0., 2.) + y_ = np.array([0., 1.]) + y = np.empty((2, 2, 2)) + y[:, 0, 0] = y_ + y[:, 1, 0] = 2. * y_ + y[:, 0, 1] = 3. * y_ + y[:, 1, 1] = 4. * y_ + ak = Akima1DInterpolator(x, y) + yi_ = np.array([0.5, 1.]) + yi = np.empty((2, 2, 2)) + yi[:, 0, 0] = yi_ + yi[:, 1, 0] = 2. * yi_ + yi[:, 0, 1] = 3. * yi_ + yi[:, 1, 1] = 4. * yi_ + xi = yi_ + xp_assert_close(ak(xi), yi) + + ak = Akima1DInterpolator(x, y.transpose(1, 0, 2), axis=1) + xp_assert_close(ak(xi), yi.transpose(1, 0, 2)) + + ak = Akima1DInterpolator(x, y.transpose(2, 1, 0), axis=2) + xp_assert_close(ak(xi), yi.transpose(2, 1, 0)) + + def test_degenerate_case_multidimensional(self, xp): + # This test is for issue #5683. + x = xp.asarray([0, 1, 2], dtype=xp.float64) + y = xp.stack((x, x**2)).T + ak = Akima1DInterpolator(x, y) + x_eval = xp.asarray([0.5, 1.5], dtype=xp.float64) + y_eval = ak(x_eval) + xp_assert_close(y_eval, xp.stack((x_eval, x_eval**2)).T) + + def test_extend(self): + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + ak = Akima1DInterpolator(x, y) + match = "Extending a 1-D Akima interpolator is not yet implemented" + with pytest.raises(NotImplementedError, match=match): + ak.extend(None, None) + + def test_mod_invalid_method(self): + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + match = "`method`=invalid is unsupported." + with pytest.raises(NotImplementedError, match=match): + Akima1DInterpolator(x, y, method="invalid") # type: ignore + + def test_extrapolate_attr(self): + # + x = np.linspace(-5, 5, 11) + y = x**2 + x_ext = np.linspace(-10, 10, 17) + y_ext = x_ext**2 + # Testing all extrapolate cases. + ak_true = Akima1DInterpolator(x, y, extrapolate=True) + ak_false = Akima1DInterpolator(x, y, extrapolate=False) + ak_none = Akima1DInterpolator(x, y, extrapolate=None) + # None should default to False; extrapolated points are NaN. + xp_assert_close(ak_false(x_ext), ak_none(x_ext), atol=1e-15) + xp_assert_equal(ak_false(x_ext)[0:4], np.full(4, np.nan)) + xp_assert_equal(ak_false(x_ext)[-4:-1], np.full(3, np.nan)) + # Extrapolation on call and attribute should be equal. + xp_assert_close(ak_false(x_ext, extrapolate=True), ak_true(x_ext), atol=1e-15) + # Testing extrapoation to actual function. + xp_assert_close(y_ext, ak_true(x_ext), atol=1e-15) + + + def test_no_overflow(self): + # check a large jump does not cause a float overflow + x = np.arange(1, 10) + y = 1.e6*np.sqrt(np.finfo(float).max)*np.heaviside(x-4, 0.5) + + ak1 = Akima1DInterpolator(x, y, method='makima') + ak2 = Akima1DInterpolator(x, y, method='akima') + + y_eval1 = ak1(x) + y_eval2 = ak2(x) + + assert np.isfinite(y_eval1).all() + assert np.isfinite(y_eval2).all() + + +@pytest.mark.parametrize("method", [Akima1DInterpolator, PchipInterpolator]) +def test_complex(method): + # Complex-valued data deprecated + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + y = y - 2j*y + msg = "real values" + with pytest.raises(ValueError, match=msg): + method(x, y) + + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to Akima1D + x = np.linspace(-5, 5, 11) + y = x**2 + x_ext = np.linspace(-10, 10, 17) + ak = Akima1DInterpolator(x, y, extrapolate=True) + + def worker_fn(_, ak, x_ext): + ak(x_ext) + + _run_concurrent_barrier(10, worker_fn, ak, x_ext) + + +@make_xp_test_case(PPoly, BPoly) +class TestPPolyCommon: + # test basic functionality for PPoly and BPoly + def test_sort_check(self, xp): + c = xp.asarray([[1, 4], [2, 5], [3, 6]]) + x = xp.asarray([0, 1, 0.5]) + assert_raises(ValueError, PPoly, c, x) + assert_raises(ValueError, BPoly, c, x) + + def test_ctor_c(self): + # wrong shape: `c` must be at least 2D + with assert_raises(ValueError): + PPoly([1, 2], [0, 1]) + + def test_extend(self, xp): + # Test adding new points to the piecewise polynomial + np.random.seed(1234) + + order = 3 + x = np.unique(np.r_[0, 10 * np.random.rand(30), 10]) + c = 2*np.random.rand(order+1, len(x)-1, 2, 3) - 1 + + c, x = xp.asarray(c), xp.asarray(x) + + for cls in (PPoly, BPoly): + pp = cls(c[:, :9, ...], x[:10]) + pp.extend(c[:, 9:, ...], x[10:]) + + pp2 = cls(c[:, 10:, ...], x[10:]) + pp2.extend(c[:, :10, ...], x[:10]) + + pp3 = cls(c, x) + + xp_assert_equal(pp.c, pp3.c) + xp_assert_equal(pp.x, pp3.x) + xp_assert_equal(pp2.c, pp3.c) + xp_assert_equal(pp2.x, pp3.x) + + def test_extend_diff_orders(self, xp): + # Test extending polynomial with different order one + np.random.seed(1234) + + x = xp.linspace(0, 1, 6) + c = xp.asarray(np.random.rand(2, 5)) + + x2 = xp.linspace(1, 2, 6) + c2 = xp.asarray(np.random.rand(4, 5)) + + for cls in (PPoly, BPoly): + pp1 = cls(c, x) + pp2 = cls(c2, x2) + + pp_comb = cls(c, x) + pp_comb.extend(c2, x2[1:]) + + # NB. doesn't match to pp1 at the endpoint, because pp1 is not + # continuous with pp2 as we took random coefs. + xi1 = xp.linspace(0, 1, 300, endpoint=False) + xi2 = xp.linspace(1, 2, 300) + + xp_assert_close(pp1(xi1), pp_comb(xi1)) + xp_assert_close(pp2(xi2), pp_comb(xi2)) + + def test_extend_descending(self, xp): + np.random.seed(0) + + order = 3 + x = np.sort(np.random.uniform(0, 10, 20)) + c = np.random.rand(order + 1, x.shape[0] - 1, 2, 3) + + c, x = xp.asarray(c), xp.asarray(x) + + for cls in (PPoly, BPoly): + p = cls(c, x) + + p1 = cls(c[:, :9, ...], x[:10]) + p1.extend(c[:, 9:, ...], x[10:]) + + p2 = cls(c[:, 10:, ...], x[10:]) + p2.extend(c[:, :10, ...], x[:10]) + + xp_assert_equal(p1.c, p.c) + xp_assert_equal(p1.x, p.x) + xp_assert_equal(p2.c, p.c) + xp_assert_equal(p2.x, p.x) + + def test_shape(self): + np.random.seed(1234) + c = np.random.rand(8, 12, 5, 6, 7) + x = np.sort(np.random.rand(13)) + xp = np.random.rand(3, 4) + for cls in (PPoly, BPoly): + p = cls(c, x) + assert p(xp).shape == (3, 4, 5, 6, 7) + + # 'scalars' + for cls in (PPoly, BPoly): + p = cls(c[..., 0, 0, 0], x) + + assert np.shape(p(0.5)) == () + assert np.shape(p(np.array(0.5))) == () + + assert_raises(ValueError, p, np.array([[0.1, 0.2], [0.4]], dtype=object)) + + def test_concurrency(self, xp): + # Check that no segfaults appear with concurrent access to BPoly, PPoly + c = np.random.rand(8, 12, 5, 6, 7) + x = np.sort(np.random.rand(13)) + xpp = np.random.rand(3, 4) + + c, x, xpp = map(xp.asarray, (c, x, xpp)) + + for cls in (PPoly, BPoly): + interp = cls(c, x) + + def worker_fn(_, interp, xpp): + interp(xpp) + + _run_concurrent_barrier(10, worker_fn, interp, xpp) + + def test_complex_coef(self): + np.random.seed(12345) + x = np.sort(np.random.random(13)) + c = np.random.random((8, 12)) * (1. + 0.3j) + c_re, c_im = c.real, c.imag + xp = np.random.random(5) + for cls in (PPoly, BPoly): + p, p_re, p_im = cls(c, x), cls(c_re, x), cls(c_im, x) + for nu in [0, 1, 2]: + xp_assert_close(p(xp, nu).real, p_re(xp, nu)) + xp_assert_close(p(xp, nu).imag, p_im(xp, nu)) + + def test_axis(self, xp): + np.random.seed(12345) + c = np.random.rand(3, 4, 5, 6, 7, 8) + c_s = c.shape + xpp = np.random.random((1, 2)) + + c, xpp = xp.asarray(c), xp.asarray(xpp) + + for axis in (0, 1, 2, 3): + m = c.shape[axis+1] + x = xp.asarray(np.sort(np.random.rand(m+1))) + for cls in (PPoly, BPoly): + p = cls(c, x, axis=axis) + assert p.c.shape == c_s[axis:axis+2] + c_s[:axis] + c_s[axis+2:] + res = p(xpp) + targ_shape = c_s[:axis] + xpp.shape + c_s[2+axis:] + assert res.shape == targ_shape + + # deriv/antideriv does not drop the axis + for p1 in [cls(c, x, axis=axis).derivative(), + cls(c, x, axis=axis).derivative(2), + cls(c, x, axis=axis).antiderivative(), + cls(c, x, axis=axis).antiderivative(2)]: + assert p1.axis == p.axis + + # c array needs two axes for the coefficients and intervals, so + # 0 <= axis < c.ndim-1; raise otherwise + for axis in (-1, 4, 5, 6): + for cls in (BPoly, PPoly): + assert_raises(ValueError, cls, **dict(c=c, x=x, axis=axis)) + + +class TestPolySubclassing: + class P(PPoly): + pass + + class B(BPoly): + pass + + def _make_polynomials(self): + np.random.seed(1234) + x = np.sort(np.random.random(3)) + c = np.random.random((4, 2)) + return self.P(c, x), self.B(c, x) + + def test_derivative(self): + pp, bp = self._make_polynomials() + for p in (pp, bp): + pd = p.derivative() + assert p.__class__ == pd.__class__ + + ppa = pp.antiderivative() + assert pp.__class__ == ppa.__class__ + + def test_from_spline(self): + np.random.seed(1234) + x = np.sort(np.r_[0, np.random.rand(11), 1]) + y = np.random.rand(len(x)) + + spl = splrep(x, y, s=0) + pp = self.P.from_spline(spl) + assert pp.__class__ == self.P + + def test_conversions(self): + pp, bp = self._make_polynomials() + + pp1 = self.P.from_bernstein_basis(bp) + assert pp1.__class__ == self.P + + bp1 = self.B.from_power_basis(pp) + assert bp1.__class__ == self.B + + def test_from_derivatives(self): + x = [0, 1, 2] + y = [[1], [2], [3]] + bp = self.B.from_derivatives(x, y) + assert bp.__class__ == self.B + + +@make_xp_test_case(PPoly) +class TestPPoly: + def test_simple(self, xp): + c = xp.asarray([[1, 4], [2, 5], [3, 6]]) + x = xp.asarray([0, 0.5, 1]) + p = PPoly(c, x) + xp_assert_close(p(0.3), xp.asarray(1*0.3**2 + 2*0.3 + 3, dtype=xp.float64)) + xp_assert_close( + p(0.7), xp.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6, dtype=xp.float64) + ) + + def test_periodic(self, xp): + c = xp.asarray([[1, 4], [2, 5], [3, 6]]) + x = xp.asarray([0, 0.5, 1]) + p = PPoly(c, x, extrapolate='periodic') + + xp_assert_close(p(1.3), + xp.asarray(1 * 0.3 ** 2 + 2 * 0.3 + 3, dtype=xp.float64)) + xp_assert_close( + p(-0.3), + xp.asarray(4 * (0.7 - 0.5) ** 2 + 5 * (0.7 - 0.5) + 6, dtype=xp.float64) + ) + + xp_assert_close(p(1.3, 1), xp.asarray(2 * 0.3 + 2, dtype=xp.float64)) + xp_assert_close(p(-0.3, 1), xp.asarray(8 * (0.7 - 0.5) + 5, dtype=xp.float64)) + + def test_read_only(self): + c = np.array([[1, 4], [2, 5], [3, 6]]) + x = np.array([0, 0.5, 1]) + xnew = np.array([0, 0.1, 0.2]) + PPoly(c, x, extrapolate='periodic') + + for writeable in (True, False): + x.flags.writeable = writeable + c.flags.writeable = writeable + f = PPoly(c, x) + vals = f(xnew) + assert np.isfinite(vals).all() + + def test_descending(self): + def binom_matrix(power): + n = np.arange(power + 1).reshape(-1, 1) + k = np.arange(power + 1) + B = binom(n, k) + return B[::-1, ::-1] + + rng = np.random.RandomState(0) + + power = 3 + for m in [10, 20, 30]: + x = np.sort(rng.uniform(0, 10, m + 1)) + ca = rng.uniform(-2, 2, size=(power + 1, m)) + + h = np.diff(x) + h_powers = h[None, :] ** np.arange(power + 1)[::-1, None] + B = binom_matrix(power) + cap = ca * h_powers + cdp = np.dot(B.T, cap) + cd = cdp / h_powers + + pa = PPoly(ca, x, extrapolate=True) + pd = PPoly(cd[:, ::-1], x[::-1], extrapolate=True) + + x_test = rng.uniform(-10, 20, 100) + xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13) + xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13) + + pa_d = pa.derivative() + pd_d = pd.derivative() + + xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13) + + # Antiderivatives won't be equal because fixing continuity is + # done in the reverse order, but surely the differences should be + # equal. + pa_i = pa.antiderivative() + pd_i = pd.antiderivative() + for a, b in rng.uniform(-10, 20, (5, 2)): + int_a = pa.integrate(a, b) + int_d = pd.integrate(a, b) + xp_assert_close(int_a, int_d, rtol=1e-13) + xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a), + rtol=1e-13) + + roots_d = pd.roots() + roots_a = pa.roots() + xp_assert_close(roots_a, np.sort(roots_d), rtol=1e-12) + + def test_multi_shape(self, xp): + c = np.random.rand(6, 2, 1, 2, 3) + x = np.array([0, 0.5, 1]) + + p = PPoly(c, x) + assert p.x.shape == x.shape + assert p.c.shape == c.shape + assert p(0.3).shape == c.shape[2:] + + assert p(np.random.rand(5, 6)).shape == (5, 6) + c.shape[2:] + + dp = p.derivative() + assert dp.c.shape == (5, 2, 1, 2, 3) + ip = p.antiderivative() + assert ip.c.shape == (7, 2, 1, 2, 3) + + def test_construct_fast(self): + np.random.seed(1234) + c = np.array([[1, 4], [2, 5], [3, 6]], dtype=float) + x = np.array([0, 0.5, 1]) + p = PPoly.construct_fast(c, x) + xp_assert_close(p(0.3), np.asarray(1*0.3**2 + 2*0.3 + 3)) + xp_assert_close(p(0.7), np.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6)) + + def test_vs_alternative_implementations(self): + rng = np.random.RandomState(1234) + c = rng.rand(3, 12, 22) + x = np.sort(np.r_[0, rng.rand(11), 1]) + + p = PPoly(c, x) + + xp = np.r_[0.3, 0.5, 0.33, 0.6] + expected = _ppoly_eval_1(c, x, xp) + xp_assert_close(p(xp), expected) + + expected = _ppoly_eval_2(c[:,:,0], x, xp) + xp_assert_close(p(xp)[:, 0], expected) + + def test_from_spline(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0) + pp = PPoly.from_spline(spl) + + xi = np.linspace(0, 1, 200) + xp_assert_close(pp(xi), splev(xi, spl)) + + # make sure .from_spline accepts BSpline objects + b = BSpline(*spl) + ppp = PPoly.from_spline(b) + xp_assert_close(ppp(xi), b(xi)) + + # BSpline's extrapolate attribute propagates unless overridden + t, c, k = spl + for extrap in (None, True, False): + b = BSpline(t, c, k, extrapolate=extrap) + p = PPoly.from_spline(b) + assert p.extrapolate == b.extrapolate + + def test_from_spline_2(self, xp): + # BSpline namespace propagates to PPoly + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + t, c, k = splrep(x, y, s=0) + spl = BSpline(xp.asarray(t), xp.asarray(c), k) + pp = PPoly.from_spline(spl) + + xi = xp.linspace(0, 1, 11) + xp_assert_close(pp(xi), spl(xi)) + + def test_derivative_simple(self, xp): + np.random.seed(1234) + c = xp.asarray([[4, 3, 2, 1]]).T + dc = xp.asarray([[3*4, 2*3, 2]]).T + ddc = xp.asarray([[2*3*4, 1*2*3]]).T + x = xp.asarray([0, 1]) + + pp = PPoly(c, x) + dpp = PPoly(dc, x) + ddpp = PPoly(ddc, x) + + xp_assert_close(pp.derivative().c, dpp.c) + xp_assert_close(pp.derivative(2).c, ddpp.c) + + def test_derivative_eval(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0) + pp = PPoly.from_spline(spl) + + xi = np.linspace(0, 1, 200) + for dx in range(0, 3): + xp_assert_close(pp(xi, dx), splev(xi, spl, dx)) + + def test_derivative(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + xi = np.linspace(0, 1, 200) + for dx in range(0, 10): + xp_assert_close(pp(xi, dx), pp.derivative(dx)(xi), err_msg=f"dx={dx}") + + def test_antiderivative_of_constant(self): + # https://github.com/scipy/scipy/issues/4216 + p = PPoly([[1.]], [0, 1]) + xp_assert_equal(p.antiderivative().c, PPoly([[1], [0]], [0, 1]).c) + xp_assert_equal(p.antiderivative().x, PPoly([[1], [0]], [0, 1]).x) + + def test_antiderivative_regression_4355(self): + # https://github.com/scipy/scipy/issues/4355 + p = PPoly([[1., 0.5]], [0, 1, 2]) + q = p.antiderivative() + xp_assert_equal(q.c, [[1, 0.5], [0, 1]]) + xp_assert_equal(q.x, [0.0, 1, 2]) + xp_assert_close(p.integrate(0, 2), np.asarray(1.5)) + xp_assert_close(np.asarray(q(2) - q(0)), + np.asarray(1.5)) + + def test_antiderivative_simple(self, xp): + # [ p1(x) = 3*x**2 + 2*x + 1, + # p2(x) = 1.6875] + c = xp.asarray([[3, 2, 1], [0, 0, 1.6875]], dtype=xp.float64).T + # [ pp1(x) = x**3 + x**2 + x, + # pp2(x) = 1.6875*(x - 0.25) + pp1(0.25)] + ic = xp.asarray([[1, 1, 1, 0], [0, 0, 1.6875, 0.328125]], dtype=xp.float64).T + # [ ppp1(x) = (1/4)*x**4 + (1/3)*x**3 + (1/2)*x**2, + # ppp2(x) = (1.6875/2)*(x - 0.25)**2 + pp1(0.25)*x + ppp1(0.25)] + iic = xp.asarray([[1/4, 1/3, 1/2, 0, 0], + [0, 0, 1.6875/2, 0.328125, 0.037434895833333336]], + dtype=xp.float64 + ).T + x = xp.asarray([0, 0.25, 1], dtype=xp.float64) + + pp = PPoly(c, x) + ipp = pp.antiderivative() + iipp = pp.antiderivative(2) + iipp2 = ipp.antiderivative() + + xp_assert_close(ipp.x, x) + xp_assert_close(ipp.c.T, ic.T) + xp_assert_close(iipp.c.T, iic.T) + xp_assert_close(iipp2.c.T, iic.T) + + def test_antiderivative_vs_derivative(self): + rng = np.random.RandomState(1234) + x = np.linspace(0, 1, 30)**2 + y = rng.rand(len(x)) + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + for dx in range(0, 10): + ipp = pp.antiderivative(dx) + + # check that derivative is inverse op + pp2 = ipp.derivative(dx) + xp_assert_close(pp.c, pp2.c) + + # check continuity + for k in range(dx): + pp2 = ipp.derivative(k) + + r = 1e-13 + endpoint = r*pp2.x[:-1] + (1 - r)*pp2.x[1:] + + xp_assert_close( + pp2(pp2.x[1:]), pp2(endpoint), rtol=1e-7, err_msg=f"dx={dx} k={k}" + ) + + def test_antiderivative_vs_spline(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + for dx in range(0, 10): + pp2 = pp.antiderivative(dx) + spl2 = splantider(spl, dx) + + xi = np.linspace(0, 1, 200) + xp_assert_close(pp2(xi), splev(xi, spl2), + rtol=1e-7) + + def test_antiderivative_continuity(self): + c = np.array([[2, 1, 2, 2], [2, 1, 3, 3]]).T + x = np.array([0, 0.5, 1]) + + p = PPoly(c, x) + ip = p.antiderivative() + + # check continuity + xp_assert_close(ip(0.5 - 1e-9), ip(0.5 + 1e-9), rtol=1e-8) + + # check that only lowest order coefficients were changed + p2 = ip.derivative() + xp_assert_close(p2.c, p.c) + + def test_integrate(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + a, b = 0.3, 0.9 + ig = pp.integrate(a, b) + + ipp = pp.antiderivative() + xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False) + xp_assert_close(ig, splint(a, b, spl), check_0d=False) + + a, b = -0.3, 0.9 + ig = pp.integrate(a, b, extrapolate=True) + xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False) + + assert np.isnan(pp.integrate(a, b, extrapolate=False)).all() + + def test_integrate_readonly(self): + x = np.array([1, 2, 4]) + c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]]) + + for writeable in (True, False): + x.flags.writeable = writeable + + P = PPoly(c, x) + vals = P.integrate(1, 4) + + assert np.isfinite(vals).all() + + def test_integrate_periodic(self): + x = np.array([1, 2, 4]) + c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]]) + + P = PPoly(c, x, extrapolate='periodic') + I = P.antiderivative() + + period_int = np.asarray(I(4) - I(1)) + + xp_assert_close(P.integrate(1, 4), period_int) + xp_assert_close(P.integrate(-10, -7), period_int) + xp_assert_close(P.integrate(-10, -4), np.asarray(2 * period_int)) + + xp_assert_close(P.integrate(1.5, 2.5), + np.asarray(I(2.5) - I(1.5))) + xp_assert_close(P.integrate(3.5, 5), + np.asarray(I(2) - I(1) + I(4) - I(3.5))) + xp_assert_close(P.integrate(3.5 + 12, 5 + 12), + np.asarray(I(2) - I(1) + I(4) - I(3.5))) + xp_assert_close(P.integrate(3.5, 5 + 12), + np.asarray(I(2) - I(1) + I(4) - I(3.5) + 4 * period_int)) + xp_assert_close(P.integrate(0, -1), + np.asarray(I(2) - I(3))) + xp_assert_close(P.integrate(-9, -10), + np.asarray(I(2) - I(3))) + xp_assert_close(P.integrate(0, -10), + np.asarray(I(2) - I(3) - 3 * period_int)) + + def test_roots(self): + x = np.linspace(0, 1, 31)**2 + y = np.sin(30*x) + + spl = splrep(x, y, s=0, k=3) + pp = PPoly.from_spline(spl) + + r = pp.roots() + r = r[(r >= 0 - 1e-15) & (r <= 1 + 1e-15)] + xp_assert_close(r, sproot(spl), atol=1e-15) + + def test_roots_idzero(self): + # Roots for piecewise polynomials with identically zero + # sections. + c = np.array([[-1, 0.25], [0, 0], [-1, 0.25]]).T + x = np.array([0, 0.4, 0.6, 1.0]) + + pp = PPoly(c, x) + xp_assert_equal(pp.roots(), + [0.25, 0.4, np.nan, 0.6 + 0.25]) + + # ditto for p.solve(const) with sections identically equal const + const = 2. + c1 = c.copy() + c1[1, :] += const + pp1 = PPoly(c1, x) + + xp_assert_equal(pp1.solve(const), + [0.25, 0.4, np.nan, 0.6 + 0.25]) + + def test_roots_all_zero(self): + # test the code path for the polynomial being identically zero everywhere + c = [[0], [0]] + x = [0, 1] + p = PPoly(c, x) + xp_assert_equal(p.roots(), [0, np.nan]) + xp_assert_equal(p.solve(0), [0, np.nan]) + xp_assert_equal(p.solve(1), []) + + c = [[0, 0], [0, 0]] + x = [0, 1, 2] + p = PPoly(c, x) + xp_assert_equal(p.roots(), [0, np.nan, 1, np.nan]) + xp_assert_equal(p.solve(0), [0, np.nan, 1, np.nan]) + xp_assert_equal(p.solve(1), []) + + def test_roots_repeated(self): + # Check roots repeated in multiple sections are reported only + # once. + + # [(x + 1)**2 - 1, -x**2] ; x == 0 is a repeated root + c = np.array([[1, 0, -1], [-1, 0, 0]]).T + x = np.array([-1, 0, 1]) + + pp = PPoly(c, x) + xp_assert_equal(pp.roots(), np.asarray([-2.0, 0.0])) + xp_assert_equal(pp.roots(extrapolate=False), np.asarray([0.0])) + + def test_roots_discont(self): + # Check that a discontinuity across zero is reported as root + c = np.array([[1], [-1]]).T + x = np.array([0, 0.5, 1]) + pp = PPoly(c, x) + xp_assert_equal(pp.roots(), np.asarray([0.5])) + xp_assert_equal(pp.roots(discontinuity=False), np.asarray([])) + + # ditto for a discontinuity across y: + xp_assert_equal(pp.solve(0.5), np.asarray([0.5])) + xp_assert_equal(pp.solve(0.5, discontinuity=False), np.asarray([])) + + xp_assert_equal(pp.solve(1.5), np.asarray([])) + xp_assert_equal(pp.solve(1.5, discontinuity=False), np.asarray([])) + + def test_roots_random(self): + # Check high-order polynomials with random coefficients + rng = np.random.RandomState(1234) + + num = 0 + + for extrapolate in (True, False): + for order in range(0, 20): + x = np.unique(np.r_[0, 10 * rng.rand(30), 10]) + c = 2*rng.rand(order+1, len(x)-1, 2, 3) - 1 + + pp = PPoly(c, x) + for y in [0, rng.random()]: + r = pp.solve(y, discontinuity=False, extrapolate=extrapolate) + + for i in range(2): + for j in range(3): + rr = r[i,j] + if rr.size > 0: + # Check that the reported roots indeed are roots + num += rr.size + val = pp(rr, extrapolate=extrapolate)[:,i,j] + cmpval = pp(rr, nu=1, + extrapolate=extrapolate)[:,i,j] + msg = f"({extrapolate!r}) r = {repr(rr)}" + xp_assert_close((val-y) / cmpval, np.asarray(0.0), + atol=1e-7, + err_msg=msg, check_shape=False) + + # Check that we checked a number of roots + assert num > 100, repr(num) + + def test_roots_croots(self): + # Test the complex root finding algorithm + rng = np.random.RandomState(1234) + + for k in range(1, 15): + c = rng.rand(k, 1, 130) + + if k == 3: + # add a case with zero discriminant + c[:,0,0] = 1, 2, 1 + + for y in [0, rng.random()]: + w = np.empty(c.shape, dtype=complex) + _ppoly._croots_poly1(c, w, y) + + if k == 1: + assert np.isnan(w).all() + continue + + res = -y + cres = 0 + for i in range(k): + res += c[i,None] * w**(k-1-i) + cres += abs(c[i,None] * w**(k-1-i)) + with np.errstate(invalid='ignore'): + res /= cres + res = res.ravel() + res = res[~np.isnan(res)] + xp_assert_close(res, np.zeros_like(res), atol=1e-10) + + def test_extrapolate_attr(self): + # [ 1 - x**2 ] + c = np.array([[-1, 0, 1]]).T + x = np.array([0, 1]) + + for extrapolate in [True, False, None]: + pp = PPoly(c, x, extrapolate=extrapolate) + pp_d = pp.derivative() + pp_i = pp.antiderivative() + + if extrapolate is False: + assert np.isnan(pp([-0.1, 1.1])).all() + assert np.isnan(pp_i([-0.1, 1.1])).all() + assert np.isnan(pp_d([-0.1, 1.1])).all() + assert pp.roots() == [1] + else: + xp_assert_close(pp([-0.1, 1.1]), [1-0.1**2, 1-1.1**2]) + assert not np.isnan(pp_i([-0.1, 1.1])).any() + assert not np.isnan(pp_d([-0.1, 1.1])).any() + xp_assert_close(pp.roots(), np.asarray([1.0, -1.0])) + + +@make_xp_test_case(BPoly) +class TestBPoly: + def test_simple(self, xp): + x = xp.asarray([0, 1]) + c = xp.asarray([[3]]) + bp = BPoly(c, x) + xp_assert_close(bp(0.1), xp.asarray(3., dtype=xp.float64)) + + def test_simple2(self, xp): + x = xp.asarray([0, 1]) + c = xp.asarray([[3], [1]]) + bp = BPoly(c, x) # 3*(1-x) + 1*x + xp_assert_close(bp(0.1), xp.asarray(3*0.9 + 1.*0.1, dtype=xp.float64)) + + def test_simple3(self, xp): + x = xp.asarray([0, 1]) + c = xp.asarray([[3], [1], [4]]) + bp = BPoly(c, x) # 3 * (1-x)**2 + 2 * x (1-x) + 4 * x**2 + xp_assert_close( + bp(0.2), + xp.asarray(3 * 0.8*0.8 + 1 * 2*0.2*0.8 + 4 * 0.2*0.2, dtype=xp.float64) + ) + + def test_simple4(self, xp): + x = xp.asarray([0, 1]) + c = xp.asarray([[1], [1], [1], [2]]) + bp = BPoly(c, x) + xp_assert_close(bp(0.3), + xp.asarray( 0.7**3 + + 3 * 0.7**2 * 0.3 + + 3 * 0.7 * 0.3**2 + + 2 * 0.3**3, dtype=xp.float64) + ) + + def test_simple5(self, xp): + x = xp.asarray([0, 1]) + c = xp.asarray([[1], [1], [8], [2], [1]]) + bp = BPoly(c, x) + xp_assert_close(bp(0.3), + xp.asarray( 0.7**4 + + 4 * 0.7**3 * 0.3 + + 8 * 6 * 0.7**2 * 0.3**2 + + 2 * 4 * 0.7 * 0.3**3 + + 0.3**4, dtype=xp.float64) + ) + + def test_periodic(self, xp): + x = xp.asarray([0, 1, 3]) + c = xp.asarray([[3, 0], [0, 0], [0, 2]]) + # [3*(1-x)**2, 2*((x-1)/2)**2] + bp = BPoly(c, x, extrapolate='periodic') + + xp_assert_close(bp(3.4), xp.asarray(3 * 0.6**2, dtype=xp.float64)) + xp_assert_close(bp(-1.3), xp.asarray(2 * (0.7/2)**2, dtype=xp.float64)) + + xp_assert_close(bp(3.4, 1), xp.asarray(-6 * 0.6, dtype=xp.float64)) + xp_assert_close(bp(-1.3, 1), xp.asarray(2 * (0.7/2), dtype=xp.float64)) + + def test_descending(self): + rng = np.random.RandomState(0) + + power = 3 + for m in [10, 20, 30]: + x = np.sort(rng.uniform(0, 10, m + 1)) + ca = rng.uniform(-0.1, 0.1, size=(power + 1, m)) + # We need only to flip coefficients to get it right! + cd = ca[::-1].copy() + + pa = BPoly(ca, x, extrapolate=True) + pd = BPoly(cd[:, ::-1], x[::-1], extrapolate=True) + + x_test = rng.uniform(-10, 20, 100) + xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13) + xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13) + + pa_d = pa.derivative() + pd_d = pd.derivative() + + xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13) + + # Antiderivatives won't be equal because fixing continuity is + # done in the reverse order, but surely the differences should be + # equal. + pa_i = pa.antiderivative() + pd_i = pd.antiderivative() + for a, b in rng.uniform(-10, 20, (5, 2)): + int_a = pa.integrate(a, b) + int_d = pd.integrate(a, b) + xp_assert_close(int_a, int_d, rtol=1e-12) + xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a), + rtol=1e-12) + + def test_multi_shape(self): + rng = np.random.RandomState(1234) + c = rng.rand(6, 2, 1, 2, 3) + x = np.array([0, 0.5, 1]) + p = BPoly(c, x) + assert p.x.shape == x.shape + assert p.c.shape == c.shape + assert p(0.3).shape == c.shape[2:] + assert p(rng.rand(5, 6)).shape == (5, 6) + c.shape[2:] + + dp = p.derivative() + assert dp.c.shape == (5, 2, 1, 2, 3) + + def test_interval_length(self, xp): + x = xp.asarray([0, 2]) + c = xp.asarray([[3], [1], [4]]) + bp = BPoly(c, x) + xval = 0.1 + s = xval / 2 # s = (x - xa) / (xb - xa) + xp_assert_close( + bp(xval), + xp.asarray(3 * (1-s)*(1-s) + 1 * 2*s*(1-s) + 4 * s*s, dtype=xp.float64) + ) + + def test_two_intervals(self, xp): + x = xp.asarray([0, 1, 3]) + c = xp.asarray([[3, 0], [0, 0], [0, 2]]) + bp = BPoly(c, x) # [3*(1-x)**2, 2*((x-1)/2)**2] + + xp_assert_close(bp(0.4), xp.asarray(3 * 0.6*0.6, dtype=xp.float64)) + xp_assert_close(bp(1.7), xp.asarray(2 * (0.7/2)**2, dtype=xp.float64)) + + def test_extrapolate_attr(self): + x = [0, 2] + c = [[3], [1], [4]] + bp = BPoly(c, x) + + for extrapolate in (True, False, None): + bp = BPoly(c, x, extrapolate=extrapolate) + bp_d = bp.derivative() + if extrapolate is False: + assert np.isnan(bp([-0.1, 2.1])).all() + assert np.isnan(bp_d([-0.1, 2.1])).all() + else: + assert not np.isnan(bp([-0.1, 2.1])).any() + assert not np.isnan(bp_d([-0.1, 2.1])).any() + + +@make_xp_test_case(BPoly) +class TestBPolyCalculus: + def test_derivative(self, xp): + x = xp.asarray([0, 1, 3]) + c = xp.asarray([[3, 0], [0, 0], [0, 2]]) + bp = BPoly(c, x) # [3*(1-x)**2, 2*((x-1)/2)**2] + bp_der = bp.derivative() + xp_assert_close(bp_der(0.4), xp.asarray(-6*(0.6), dtype=xp.float64)) + xp_assert_close(bp_der(1.7), xp.asarray(0.7, dtype=xp.float64)) + + # derivatives in-place + xp_assert_close(xp.stack([bp(0.4, nu) for nu in [1, 2, 3]]), + xp.asarray([-6*(1-0.4), 6., 0.], dtype=xp.float64) + ) + xp_assert_close(xp.stack([bp(1.7, nu) for nu in [1, 2, 3]]), + xp.asarray([0.7, 1., 0], dtype=xp.float64) + ) + + def test_derivative_ppoly(self, xp): + # make sure it's consistent w/ power basis + rng = np.random.RandomState(1234) + m, k = 5, 8 # number of intervals, order + x = np.sort(rng.random(m)) + c = rng.random((k, m-1)) + + c, x = xp.asarray(c), xp.asarray(x) + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + + for d in range(k): + bp = bp.derivative() + pp = pp.derivative() + xpp = xp.linspace(x[0], x[-1], 21) + xp_assert_close(bp(xpp), pp(xpp)) + + def test_deriv_inplace(self): + rng = np.random.RandomState(1234) + m, k = 5, 8 # number of intervals, order + x = np.sort(rng.random(m)) + c = rng.random((k, m-1)) + + # test both real and complex coefficients + for cc in [c.copy(), c*(1. + 2.j)]: + bp = BPoly(cc, x) + xpp = np.linspace(x[0], x[-1], 21) + for i in range(k): + xp_assert_close(bp(xpp, i), bp.derivative(i)(xpp)) + + def test_antiderivative_simple(self, xp): + # f(x) = x for x \in [0, 1), + # (x-1)/2 for x \in [1, 3] + # + # antiderivative is then + # F(x) = x**2 / 2 for x \in [0, 1), + # 0.5*x*(x/2 - 1) + A for x \in [1, 3] + # where A = 3/4 for continuity at x = 1. + x = xp.asarray([0, 1, 3]) + c = xp.asarray([[0, 0], [1, 1]]) + + bp = BPoly(c, x) + bi = bp.antiderivative() + + xx = xp.linspace(0, 3, 11, dtype=xp.float64) + xp_assert_close(bi(xx), + xp.where(xx < 1, xx**2 / 2., + 0.5 * xx * (xx/2. - 1) + 3./4), + atol=1e-12, rtol=1e-12) + + def test_der_antider(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10, 2, 3)) + bp = BPoly(c, x) + + xx = np.linspace(x[0], x[-1], 100) + xp_assert_close(bp.antiderivative().derivative()(xx), + bp(xx), atol=1e-12, rtol=1e-12) + + def test_antider_ppoly(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10, 2, 3)) + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + + xx = np.linspace(x[0], x[-1], 10) + + xp_assert_close(bp.antiderivative(2)(xx), + pp.antiderivative(2)(xx), atol=1e-12, rtol=1e-12) + + def test_antider_continuous(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10)) + bp = BPoly(c, x).antiderivative() + + xx = bp.x[1:-1] + xp_assert_close(bp(xx - 1e-14), + bp(xx + 1e-14), atol=1e-12, rtol=1e-12) + + def test_integrate(self, xp): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10)) + x, c = xp.asarray(x), xp.asarray(c) + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + xp_assert_close(bp.integrate(0, 1), + pp.integrate(0, 1), atol=1e-12, rtol=1e-12, check_0d=False) + + def test_integrate_extrap(self): + c = [[1]] + x = [0, 1] + b = BPoly(c, x) + + # default is extrapolate=True + xp_assert_close(b.integrate(0, 2), np.asarray(2.), + atol=1e-14, check_0d=False) + + # .integrate argument overrides self.extrapolate + b1 = BPoly(c, x, extrapolate=False) + assert np.isnan(b1.integrate(0, 2)) + xp_assert_close(b1.integrate(0, 2, extrapolate=True), + np.asarray(2.), atol=1e-14, check_0d=False) + + def test_integrate_periodic(self, xp): + x = xp.asarray([1, 2, 4]) + c = xp.asarray([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]]) + + P = BPoly.from_power_basis(PPoly(c, x), extrapolate='periodic') + I = P.antiderivative() + + period_int = xp.asarray(I(4) - I(1)) + + xp_assert_close(P.integrate(1, 4), period_int) #, check_0d=False) + xp_assert_close(P.integrate(-10, -7), period_int) + xp_assert_close(P.integrate(-10, -4), xp.asarray(2 * period_int)) + + xp_assert_close(P.integrate(1.5, 2.5), xp.asarray(I(2.5) - I(1.5))) + xp_assert_close(P.integrate(3.5, 5), xp.asarray(I(2) - I(1) + I(4) - I(3.5))) + xp_assert_close(P.integrate(3.5 + 12, 5 + 12), + xp.asarray(I(2) - I(1) + I(4) - I(3.5))) + xp_assert_close(P.integrate(3.5, 5 + 12), + xp.asarray(I(2) - I(1) + I(4) - I(3.5) + 4 * period_int)) + + xp_assert_close(P.integrate(0, -1), xp.asarray(I(2) - I(3))) + xp_assert_close(P.integrate(-9, -10), xp.asarray(I(2) - I(3))) + xp_assert_close(P.integrate(0, -10), xp.asarray(I(2) - I(3) - 3 * period_int)) + + def test_antider_neg(self, xp): + # .derivative(-nu) ==> .andiderivative(nu) and vice versa + c = xp.asarray([[1]]) + x = xp.asarray([0, 1]) + b = BPoly(c, x) + + xx = xp.linspace(0, 1, 21) + + xp_assert_close(b.derivative(-1)(xx), b.antiderivative()(xx), + atol=1e-12, rtol=1e-12) + xp_assert_close(b.derivative(1)(xx), b.antiderivative(-1)(xx), + atol=1e-12, rtol=1e-12) + + +@make_xp_test_case(BPoly, PPoly) +class TestPolyConversions: + def test_bp_from_pp(self, xp): + x = xp.asarray([0, 1, 3]) + c = xp.asarray([[3, 2], [1, 8], [4, 3]]) + pp = PPoly(c, x) + bp = BPoly.from_power_basis(pp) + pp1 = PPoly.from_bernstein_basis(bp) + + xv = xp.asarray([0.1, 1.4]) + xp_assert_close(pp(xv), bp(xv)) + xp_assert_close(pp(xv), pp1(xv)) + + def test_bp_from_pp_random(self): + rng = np.random.RandomState(1234) + m, k = 5, 8 # number of intervals, order + x = np.sort(rng.random(m)) + c = rng.random((k, m-1)) + pp = PPoly(c, x) + bp = BPoly.from_power_basis(pp) + pp1 = PPoly.from_bernstein_basis(bp) + + xv = np.linspace(x[0], x[-1], 21) + xp_assert_close(pp(xv), bp(xv)) + xp_assert_close(pp(xv), pp1(xv)) + + def test_pp_from_bp(self, xp): + x = xp.asarray([0, 1, 3]) + c = xp.asarray([[3, 3], [1, 1], [4, 2]]) + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + bp1 = BPoly.from_power_basis(pp) + + xv = xp.asarray([0.1, 1.4]) + xp_assert_close(bp(xv), pp(xv)) + xp_assert_close(bp(xv), bp1(xv)) + + def test_broken_conversions(self): + # regression test for gh-10597: from_power_basis only accepts PPoly etc. + x = [0, 1, 3] + c = [[3, 3], [1, 1], [4, 2]] + pp = PPoly(c, x) + with assert_raises(TypeError): + PPoly.from_bernstein_basis(pp) + + bp = BPoly(c, x) + with assert_raises(TypeError): + BPoly.from_power_basis(bp) + + +class TestBPolyFromDerivatives: + def test_make_poly_1(self): + c1 = BPoly._construct_from_derivatives(0, 1, [2], [3]) + xp_assert_close(c1, [2., 3.]) + + def test_make_poly_2(self): + c1 = BPoly._construct_from_derivatives(0, 1, [1, 0], [1]) + xp_assert_close(c1, [1., 1., 1.]) + + # f'(0) = 3 + c2 = BPoly._construct_from_derivatives(0, 1, [2, 3], [1]) + xp_assert_close(c2, [2., 7./2, 1.]) + + # f'(1) = 3 + c3 = BPoly._construct_from_derivatives(0, 1, [2], [1, 3]) + xp_assert_close(c3, [2., -0.5, 1.]) + + def test_make_poly_3(self): + # f'(0)=2, f''(0)=3 + c1 = BPoly._construct_from_derivatives(0, 1, [1, 2, 3], [4]) + xp_assert_close(c1, [1., 5./3, 17./6, 4.]) + + # f'(1)=2, f''(1)=3 + c2 = BPoly._construct_from_derivatives(0, 1, [1], [4, 2, 3]) + xp_assert_close(c2, [1., 19./6, 10./3, 4.]) + + # f'(0)=2, f'(1)=3 + c3 = BPoly._construct_from_derivatives(0, 1, [1, 2], [4, 3]) + xp_assert_close(c3, [1., 5./3, 3., 4.]) + + def test_make_poly_12(self): + rng = np.random.RandomState(12345) + ya = np.r_[0, rng.random(5)] + yb = np.r_[0, rng.random(5)] + + c = BPoly._construct_from_derivatives(0, 1, ya, yb) + pp = BPoly(c[:, None], [0, 1]) + for j in range(6): + xp_assert_close(pp(0.), ya[j], check_0d=False) + xp_assert_close(pp(1.), yb[j], check_0d=False) + pp = pp.derivative() + + def test_raise_degree(self): + rng = np.random.RandomState(12345) + x = [0, 1] + k, d = 8, 5 + c = rng.random((k, 1, 2, 3, 4)) + bp = BPoly(c, x) + + c1 = BPoly._raise_degree(c, d) + bp1 = BPoly(c1, x) + + xp = np.linspace(0, 1, 11) + xp_assert_close(bp(xp), bp1(xp)) + + def test_xi_yi(self): + assert_raises(ValueError, BPoly.from_derivatives, [0, 1], [0]) + + def test_coords_order(self): + xi = [0, 0, 1] + yi = [[0], [0], [0]] + assert_raises(ValueError, BPoly.from_derivatives, xi, yi) + + def test_zeros(self): + xi = [0, 1, 2, 3] + yi = [[0, 0], [0], [0, 0], [0, 0]] # NB: will have to raise the degree + pp = BPoly.from_derivatives(xi, yi) + assert pp.c.shape == (4, 3) + + ppd = pp.derivative() + for xp in [0., 0.1, 1., 1.1, 1.9, 2., 2.5]: + xp_assert_close(pp(xp), np.asarray(0.0)) + xp_assert_close(ppd(xp), np.asarray(0.0)) + + + def _make_random_mk(self, m, k): + # k derivatives at each breakpoint + rng = np.random.RandomState(1234) + xi = np.asarray([1. * j**2 for j in range(m+1)]) + yi = [rng.random(k) for j in range(m+1)] + return xi, yi + + def test_random_12(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + pp = BPoly.from_derivatives(xi, yi) + + for order in range(k//2): + xp_assert_close(pp(xi), [yy[order] for yy in yi]) + pp = pp.derivative() + + def test_order_zero(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + assert_raises(ValueError, BPoly.from_derivatives, + **dict(xi=xi, yi=yi, orders=0)) + + def test_orders_too_high(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + + BPoly.from_derivatives(xi, yi, orders=2*k-1) # this is still ok + assert_raises(ValueError, BPoly.from_derivatives, # but this is not + **dict(xi=xi, yi=yi, orders=2*k)) + + def test_orders_global(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + + # ok, this is confusing. Local polynomials will be of the order 5 + # which means that up to the 2nd derivatives will be used at each point + order = 5 + pp = BPoly.from_derivatives(xi, yi, orders=order) + + for j in range(order//2+1): + xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + pp = pp.derivative() + assert not np.allclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + + # now repeat with `order` being even: on each interval, it uses + # order//2 'derivatives' @ the right-hand endpoint and + # order//2+1 @ 'derivatives' the left-hand endpoint + order = 6 + pp = BPoly.from_derivatives(xi, yi, orders=order) + for j in range(order//2): + xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + pp = pp.derivative() + assert not np.allclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + + def test_orders_local(self): + m, k = 7, 12 + xi, yi = self._make_random_mk(m, k) + + orders = [o + 1 for o in range(m)] + for i, x in enumerate(xi[1:-1]): + pp = BPoly.from_derivatives(xi, yi, orders=orders) + for j in range(orders[i] // 2 + 1): + xp_assert_close(pp(x - 1e-12), pp(x + 1e-12)) + pp = pp.derivative() + assert not np.allclose(pp(x - 1e-12), pp(x + 1e-12)) + + def test_yi_trailing_dims(self): + rng = np.random.RandomState(1234) + m, k = 7, 5 + xi = np.sort(rng.random(m+1)) + yi = rng.random((m+1, k, 6, 7, 8)) + pp = BPoly.from_derivatives(xi, yi) + assert pp.c.shape == (2*k, m, 6, 7, 8) + + def test_gh_5430(self): + # At least one of these raises an error unless gh-5430 is + # fixed. In py2k an int is implemented using a C long, so + # which one fails depends on your system. In py3k there is only + # one arbitrary precision integer type, so both should fail. + orders = np.int32(1) + p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders) + assert_almost_equal(p(0), np.asarray(0)) + orders = np.int64(1) + p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders) + assert_almost_equal(p(0), np.asarray(0)) + orders = 1 + # This worked before; make sure it still works + p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders) + assert_almost_equal(p(0), np.asarray(0)) + orders = 1 + + +class TestNdPPoly: + def test_simple_1d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5) + x = np.linspace(0, 1, 5+1) + + xi = rng.rand(200) + + p = NdPPoly(c, (x,)) + v1 = p((xi,)) + + v2 = _ppoly_eval_1(c[:,:,None], x, xi).ravel() + xp_assert_close(v1, v2) + + def test_simple_2d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7) + x = np.linspace(0, 1, 6+1) + y = np.linspace(0, 1, 7+1)**2 + + xi = rng.rand(200) + yi = rng.rand(200) + + v1 = np.empty([len(xi), 1], dtype=c.dtype) + v1.fill(np.nan) + _ppoly.evaluate_nd(c.reshape(4*5, 6*7, 1), + (x, y), + np.array([4, 5], dtype=np.intc), + np.c_[xi, yi], + np.array([0, 0], dtype=np.intc), + 1, + v1) + v1 = v1.ravel() + v2 = _ppoly2d_eval(c, (x, y), xi, yi) + xp_assert_close(v1, v2) + + p = NdPPoly(c, (x, y)) + for nu in (None, (0, 0), (0, 1), (1, 0), (2, 3), (9, 2)): + v1 = p(np.c_[xi, yi], nu=nu) + v2 = _ppoly2d_eval(c, (x, y), xi, yi, nu=nu) + xp_assert_close(v1, v2, err_msg=repr(nu)) + + def test_simple_3d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7, 8, 9) + x = np.linspace(0, 1, 7+1) + y = np.linspace(0, 1, 8+1)**2 + z = np.linspace(0, 1, 9+1)**3 + + xi = rng.rand(40) + yi = rng.rand(40) + zi = rng.rand(40) + + p = NdPPoly(c, (x, y, z)) + + for nu in (None, (0, 0, 0), (0, 1, 0), (1, 0, 0), (2, 3, 0), + (6, 0, 2)): + v1 = p((xi, yi, zi), nu=nu) + v2 = _ppoly3d_eval(c, (x, y, z), xi, yi, zi, nu=nu) + xp_assert_close(v1, v2, err_msg=repr(nu)) + + def test_simple_4d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7, 8, 9, 10, 11) + x = np.linspace(0, 1, 8+1) + y = np.linspace(0, 1, 9+1)**2 + z = np.linspace(0, 1, 10+1)**3 + u = np.linspace(0, 1, 11+1)**4 + + xi = rng.rand(20) + yi = rng.rand(20) + zi = rng.rand(20) + ui = rng.rand(20) + + p = NdPPoly(c, (x, y, z, u)) + v1 = p((xi, yi, zi, ui)) + + v2 = _ppoly4d_eval(c, (x, y, z, u), xi, yi, zi, ui) + xp_assert_close(v1, v2) + + def test_deriv_1d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5) + x = np.linspace(0, 1, 5+1) + + p = NdPPoly(c, (x,)) + + # derivative + dp = p.derivative(nu=[1]) + p1 = PPoly(c, x) + dp1 = p1.derivative() + xp_assert_close(dp.c, dp1.c) + + # antiderivative + dp = p.antiderivative(nu=[2]) + p1 = PPoly(c, x) + dp1 = p1.antiderivative(2) + xp_assert_close(dp.c, dp1.c) + + def test_deriv_3d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7, 8, 9) + x = np.linspace(0, 1, 7+1) + y = np.linspace(0, 1, 8+1)**2 + z = np.linspace(0, 1, 9+1)**3 + + p = NdPPoly(c, (x, y, z)) + + # differentiate vs x + p1 = PPoly(c.transpose(0, 3, 1, 2, 4, 5), x) + dp = p.derivative(nu=[2]) + dp1 = p1.derivative(2) + xp_assert_close(dp.c, + dp1.c.transpose(0, 2, 3, 1, 4, 5)) + + # antidifferentiate vs y + p1 = PPoly(c.transpose(1, 4, 0, 2, 3, 5), y) + dp = p.antiderivative(nu=[0, 1, 0]) + dp1 = p1.antiderivative(1) + xp_assert_close(dp.c, + dp1.c.transpose(2, 0, 3, 4, 1, 5)) + + # differentiate vs z + p1 = PPoly(c.transpose(2, 5, 0, 1, 3, 4), z) + dp = p.derivative(nu=[0, 0, 3]) + dp1 = p1.derivative(3) + xp_assert_close(dp.c, + dp1.c.transpose(2, 3, 0, 4, 5, 1)) + + def test_deriv_3d_simple(self): + # Integrate to obtain function x y**2 z**4 / (2! 4!) + rng = np.random.RandomState(1234) + + c = np.ones((1, 1, 1, 3, 4, 5)) + x = np.linspace(0, 1, 3+1)**1 + y = np.linspace(0, 1, 4+1)**2 + z = np.linspace(0, 1, 5+1)**3 + + p = NdPPoly(c, (x, y, z)) + ip = p.antiderivative((1, 0, 4)) + ip = ip.antiderivative((0, 2, 0)) + + xi = rng.rand(20) + yi = rng.rand(20) + zi = rng.rand(20) + + xp_assert_close(ip((xi, yi, zi)), + xi * yi**2 * zi**4 / (gamma(3)*gamma(5))) + + def test_integrate_2d(self): + rng = np.random.RandomState(1234) + c = rng.rand(4, 5, 16, 17) + x = np.linspace(0, 1, 16+1)**1 + y = np.linspace(0, 1, 17+1)**2 + + # make continuously differentiable so that nquad() has an + # easier time + c = c.transpose(0, 2, 1, 3) + cx = c.reshape(c.shape[0], c.shape[1], -1).copy() + _ppoly.fix_continuity(cx, x, 2) + c = cx.reshape(c.shape) + c = c.transpose(0, 2, 1, 3) + c = c.transpose(1, 3, 0, 2) + cx = c.reshape(c.shape[0], c.shape[1], -1).copy() + _ppoly.fix_continuity(cx, y, 2) + c = cx.reshape(c.shape) + c = c.transpose(2, 0, 3, 1).copy() + + # Check integration + p = NdPPoly(c, (x, y)) + + for ranges in [[(0, 1), (0, 1)], + [(0, 0.5), (0, 1)], + [(0, 1), (0, 0.5)], + [(0.3, 0.7), (0.6, 0.2)]]: + + ig = p.integrate(ranges) + ig2, err2 = nquad(lambda x, y: p((x, y)), ranges, + opts=[dict(epsrel=1e-5, epsabs=1e-5)]*2) + xp_assert_close(ig, ig2, rtol=1e-5, atol=1e-5, check_0d=False, + err_msg=repr(ranges)) + + def test_integrate_1d(self): + rng = np.random.RandomState(1234) + c = rng.rand(4, 5, 6, 16, 17, 18) + x = np.linspace(0, 1, 16+1)**1 + y = np.linspace(0, 1, 17+1)**2 + z = np.linspace(0, 1, 18+1)**3 + + # Check 1-D integration + p = NdPPoly(c, (x, y, z)) + + u = rng.rand(200) + v = rng.rand(200) + a, b = 0.2, 0.7 + + px = p.integrate_1d(a, b, axis=0) + pax = p.antiderivative((1, 0, 0)) + xp_assert_close(px((u, v)), pax((b, u, v)) - pax((a, u, v))) + + py = p.integrate_1d(a, b, axis=1) + pay = p.antiderivative((0, 1, 0)) + xp_assert_close(py((u, v)), pay((u, b, v)) - pay((u, a, v))) + + pz = p.integrate_1d(a, b, axis=2) + paz = p.antiderivative((0, 0, 1)) + xp_assert_close(pz((u, v)), paz((u, v, b)) - paz((u, v, a))) + + def test_concurrency(self): + rng = np.random.default_rng(12345) + + c = rng.uniform(size=(4, 5, 6, 7, 8, 9)) + x = np.linspace(0, 1, 7+1) + y = np.linspace(0, 1, 8+1)**2 + z = np.linspace(0, 1, 9+1)**3 + + p = NdPPoly(c, (x, y, z)) + + def worker_fn(_, spl): + xi = rng.uniform(size=40) + yi = rng.uniform(size=40) + zi = rng.uniform(size=40) + spl((xi, yi, zi)) + + _run_concurrent_barrier(10, worker_fn, p) + + +def _ppoly_eval_1(c, x, xps): + """Evaluate piecewise polynomial manually""" + out = np.zeros((len(xps), c.shape[2])) + for i, xp in enumerate(xps): + if xp < 0 or xp > 1: + out[i,:] = np.nan + continue + j = np.searchsorted(x, xp) - 1 + d = xp - x[j] + assert x[j] <= xp < x[j+1] + r = sum(c[k,j] * d**(c.shape[0]-k-1) + for k in range(c.shape[0])) + out[i,:] = r + return out + + +def _ppoly_eval_2(coeffs, breaks, xnew, fill=np.nan): + """Evaluate piecewise polynomial manually (another way)""" + a = breaks[0] + b = breaks[-1] + K = coeffs.shape[0] + + saveshape = np.shape(xnew) + xnew = np.ravel(xnew) + res = np.empty_like(xnew) + mask = (xnew >= a) & (xnew <= b) + res[~mask] = fill + xx = xnew.compress(mask) + indxs = np.searchsorted(breaks, xx)-1 + indxs = indxs.clip(0, len(breaks)) + pp = coeffs + diff = xx - breaks.take(indxs) + V = np.vander(diff, N=K) + values = np.array([np.dot(V[k, :], pp[:, indxs[k]]) for k in range(len(xx))]) + res[mask] = values + res = res.reshape(saveshape) + return res + + +def _dpow(x, y, n): + """ + d^n (x**y) / dx^n + """ + if n < 0: + raise ValueError("invalid derivative order") + elif n > y: + return 0 + else: + return poch(y - n + 1, n) * x**(y - n) + + +def _ppoly2d_eval(c, xs, xnew, ynew, nu=None): + """ + Straightforward evaluation of 2-D piecewise polynomial + """ + if nu is None: + nu = (0, 0) + + out = np.empty((len(xnew),), dtype=c.dtype) + + nx, ny = c.shape[:2] + + for jout, (x, y) in enumerate(zip(xnew, ynew)): + if not ((xs[0][0] <= x <= xs[0][-1]) and + (xs[1][0] <= y <= xs[1][-1])): + out[jout] = np.nan + continue + + j1 = np.searchsorted(xs[0], x) - 1 + j2 = np.searchsorted(xs[1], y) - 1 + + s1 = x - xs[0][j1] + s2 = y - xs[1][j2] + + val = 0 + + for k1 in range(c.shape[0]): + for k2 in range(c.shape[1]): + val += (c[nx-k1-1,ny-k2-1,j1,j2] + * _dpow(s1, k1, nu[0]) + * _dpow(s2, k2, nu[1])) + + out[jout] = val + + return out + + +def _ppoly3d_eval(c, xs, xnew, ynew, znew, nu=None): + """ + Straightforward evaluation of 3-D piecewise polynomial + """ + if nu is None: + nu = (0, 0, 0) + + out = np.empty((len(xnew),), dtype=c.dtype) + + nx, ny, nz = c.shape[:3] + + for jout, (x, y, z) in enumerate(zip(xnew, ynew, znew)): + if not ((xs[0][0] <= x <= xs[0][-1]) and + (xs[1][0] <= y <= xs[1][-1]) and + (xs[2][0] <= z <= xs[2][-1])): + out[jout] = np.nan + continue + + j1 = np.searchsorted(xs[0], x) - 1 + j2 = np.searchsorted(xs[1], y) - 1 + j3 = np.searchsorted(xs[2], z) - 1 + + s1 = x - xs[0][j1] + s2 = y - xs[1][j2] + s3 = z - xs[2][j3] + + val = 0 + for k1 in range(c.shape[0]): + for k2 in range(c.shape[1]): + for k3 in range(c.shape[2]): + val += (c[nx-k1-1,ny-k2-1,nz-k3-1,j1,j2,j3] + * _dpow(s1, k1, nu[0]) + * _dpow(s2, k2, nu[1]) + * _dpow(s3, k3, nu[2])) + + out[jout] = val + + return out + + +def _ppoly4d_eval(c, xs, xnew, ynew, znew, unew, nu=None): + """ + Straightforward evaluation of 4-D piecewise polynomial + """ + if nu is None: + nu = (0, 0, 0, 0) + + out = np.empty((len(xnew),), dtype=c.dtype) + + mx, my, mz, mu = c.shape[:4] + + for jout, (x, y, z, u) in enumerate(zip(xnew, ynew, znew, unew)): + if not ((xs[0][0] <= x <= xs[0][-1]) and + (xs[1][0] <= y <= xs[1][-1]) and + (xs[2][0] <= z <= xs[2][-1]) and + (xs[3][0] <= u <= xs[3][-1])): + out[jout] = np.nan + continue + + j1 = np.searchsorted(xs[0], x) - 1 + j2 = np.searchsorted(xs[1], y) - 1 + j3 = np.searchsorted(xs[2], z) - 1 + j4 = np.searchsorted(xs[3], u) - 1 + + s1 = x - xs[0][j1] + s2 = y - xs[1][j2] + s3 = z - xs[2][j3] + s4 = u - xs[3][j4] + + val = 0 + for k1 in range(c.shape[0]): + for k2 in range(c.shape[1]): + for k3 in range(c.shape[2]): + for k4 in range(c.shape[3]): + val += (c[mx-k1-1,my-k2-1,mz-k3-1,mu-k4-1,j1,j2,j3,j4] + * _dpow(s1, k1, nu[0]) + * _dpow(s2, k2, nu[1]) + * _dpow(s3, k3, nu[2]) + * _dpow(s4, k4, nu[3])) + + out[jout] = val + + return out diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_ndgriddata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_ndgriddata.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a99838ea9489f6c341203b0b920b3098f26a0a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_ndgriddata.py @@ -0,0 +1,307 @@ +import numpy as np +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close +) +import pytest +from pytest import raises as assert_raises + +from scipy.interpolate import (griddata, NearestNDInterpolator, + LinearNDInterpolator, + CloughTocher2DInterpolator) +from scipy._lib._testutils import _run_concurrent_barrier + + +parametrize_interpolators = pytest.mark.parametrize( + "interpolator", [NearestNDInterpolator, LinearNDInterpolator, + CloughTocher2DInterpolator] +) +parametrize_methods = pytest.mark.parametrize( + 'method', + ('nearest', 'linear', 'cubic'), +) +parametrize_rescale = pytest.mark.parametrize( + 'rescale', + (True, False), +) + + +class TestGriddata: + def test_fill_value(self): + x = [(0,0), (0,1), (1,0)] + y = [1, 2, 3] + + yi = griddata(x, y, [(1,1), (1,2), (0,0)], fill_value=-1) + xp_assert_equal(yi, [-1., -1, 1]) + + yi = griddata(x, y, [(1,1), (1,2), (0,0)]) + xp_assert_equal(yi, [np.nan, np.nan, 1]) + + @parametrize_methods + @parametrize_rescale + def test_alternative_call(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = (np.arange(x.shape[0], dtype=np.float64)[:,None] + + np.array([0,1])[None,:]) + + msg = repr((method, rescale)) + yi = griddata((x[:,0], x[:,1]), y, (x[:,0], x[:,1]), method=method, + rescale=rescale) + xp_assert_close(y, yi, atol=1e-14, err_msg=msg) + + @parametrize_methods + @parametrize_rescale + def test_multivalue_2d(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = (np.arange(x.shape[0], dtype=np.float64)[:,None] + + np.array([0,1])[None,:]) + + msg = repr((method, rescale)) + yi = griddata(x, y, x, method=method, rescale=rescale) + xp_assert_close(y, yi, atol=1e-14, err_msg=msg) + + @parametrize_methods + @parametrize_rescale + def test_multipoint_2d(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + xi = x[:,None,:] + np.array([0,0,0])[None,:,None] + + msg = repr((method, rescale)) + yi = griddata(x, y, xi, method=method, rescale=rescale) + + assert yi.shape == (5, 3), msg + xp_assert_close(yi, np.tile(y[:,None], (1, 3)), + atol=1e-14, err_msg=msg) + + @parametrize_methods + @parametrize_rescale + def test_complex_2d(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 2j*y[::-1] + + xi = x[:,None,:] + np.array([0,0,0])[None,:,None] + + msg = repr((method, rescale)) + yi = griddata(x, y, xi, method=method, rescale=rescale) + + assert yi.shape == (5, 3) + xp_assert_close(yi, np.tile(y[:,None], (1, 3)), + atol=1e-14, err_msg=msg) + + @parametrize_methods + def test_1d(self, method): + x = np.array([1, 2.5, 3, 4.5, 5, 6]) + y = np.array([1, 2, 0, 3.9, 2, 1]) + + xp_assert_close(griddata(x, y, x, method=method), y, + err_msg=method, atol=1e-14) + xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y, + err_msg=method, atol=1e-14) + xp_assert_close(griddata((x,), y, (x,), method=method), y, + err_msg=method, atol=1e-14) + + def test_1d_borders(self): + # Test for nearest neighbor case with xi outside + # the range of the values. + x = np.array([1, 2.5, 3, 4.5, 5, 6]) + y = np.array([1, 2, 0, 3.9, 2, 1]) + xi = np.array([0.9, 6.5]) + yi_should = np.array([1.0, 1.0]) + + method = 'nearest' + xp_assert_close(griddata(x, y, xi, + method=method), yi_should, + err_msg=method, + atol=1e-14) + xp_assert_close(griddata(x.reshape(6, 1), y, xi, + method=method), yi_should, + err_msg=method, + atol=1e-14) + xp_assert_close(griddata((x, ), y, (xi, ), + method=method), yi_should, + err_msg=method, + atol=1e-14) + + @parametrize_methods + def test_1d_unsorted(self, method): + x = np.array([2.5, 1, 4.5, 5, 6, 3]) + y = np.array([1, 2, 0, 3.9, 2, 1]) + + xp_assert_close(griddata(x, y, x, method=method), y, + err_msg=method, atol=1e-10) + xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y, + err_msg=method, atol=1e-10) + xp_assert_close(griddata((x,), y, (x,), method=method), y, + err_msg=method, atol=1e-10) + + @parametrize_methods + def test_square_rescale_manual(self, method): + points = np.array([(0,0), (0,100), (10,100), (10,0), (1, 5)], dtype=np.float64) + points_rescaled = np.array([(0,0), (0,1), (1,1), (1,0), (0.1, 0.05)], + dtype=np.float64) + values = np.array([1., 2., -3., 5., 9.], dtype=np.float64) + + xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None], + np.linspace(0, 100, 14)[None,:]) + xx = xx.ravel() + yy = yy.ravel() + xi = np.array([xx, yy]).T.copy() + + msg = method + zi = griddata(points_rescaled, values, xi/np.array([10, 100.]), + method=method) + zi_rescaled = griddata(points, values, xi, method=method, + rescale=True) + xp_assert_close(zi, zi_rescaled, err_msg=msg, + atol=1e-12) + + @parametrize_methods + def test_xi_1d(self, method): + # Check that 1-D xi is interpreted as a coordinate + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 2j*y[::-1] + + xi = np.array([0.5, 0.5]) + + p1 = griddata(x, y, xi, method=method) + p2 = griddata(x, y, xi[None,:], method=method) + xp_assert_close(p1, p2, err_msg=method) + + xi1 = np.array([0.5]) + xi3 = np.array([0.5, 0.5, 0.5]) + assert_raises(ValueError, griddata, x, y, xi1, + method=method) + assert_raises(ValueError, griddata, x, y, xi3, + method=method) + + +class TestNearestNDInterpolator: + def test_nearest_options(self): + # smoke test that NearestNDInterpolator accept cKDTree options + npts, nd = 4, 3 + x = np.arange(npts*nd).reshape((npts, nd)) + y = np.arange(npts) + nndi = NearestNDInterpolator(x, y) + + opts = {'balanced_tree': False, 'compact_nodes': False} + nndi_o = NearestNDInterpolator(x, y, tree_options=opts) + xp_assert_close(nndi(x), nndi_o(x), atol=1e-14) + + def test_nearest_list_argument(self): + nd = np.array([[0, 0, 0, 0, 1, 0, 1], + [0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 1, 2]]) + d = nd[:, 3:] + + # z is np.array + NI = NearestNDInterpolator((d[0], d[1]), d[2]) + xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0]) + + # z is list + NI = NearestNDInterpolator((d[0], d[1]), list(d[2])) + xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0]) + + def test_nearest_query_options(self): + nd = np.array([[0, 0.5, 0, 1], + [0, 0, 0.5, 1], + [0, 1, 1, 2]]) + delta = 0.1 + query_points = [0 + delta, 1 + delta], [0 + delta, 1 + delta] + + # case 1 - query max_dist is smaller than + # the query points' nearest distance to nd. + NI = NearestNDInterpolator((nd[0], nd[1]), nd[2]) + distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7 + xp_assert_equal(NI(query_points, distance_upper_bound=distance_upper_bound), + [np.nan, np.nan]) + + # case 2 - query p is inf, will return [0, 2] + distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7 + p = np.inf + xp_assert_equal( + NI(query_points, distance_upper_bound=distance_upper_bound, p=p), + [0.0, 2.0] + ) + + # case 3 - query max_dist is larger, so should return non np.nan + distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) + 1e-7 + xp_assert_equal( + NI(query_points, distance_upper_bound=distance_upper_bound), + [0.0, 2.0] + ) + + def test_nearest_query_valid_inputs(self): + nd = np.array([[0, 1, 0, 1], + [0, 0, 1, 1], + [0, 1, 1, 2]]) + NI = NearestNDInterpolator((nd[0], nd[1]), nd[2]) + with assert_raises(TypeError): + NI([0.5, 0.5], query_options="not a dictionary") + + def test_concurrency(self): + npts, nd = 50, 3 + x = np.arange(npts * nd).reshape((npts, nd)) + y = np.arange(npts) + nndi = NearestNDInterpolator(x, y) + + def worker_fn(_, spl): + spl(x) + + _run_concurrent_barrier(10, worker_fn, nndi) + + +class TestNDInterpolators: + @parametrize_interpolators + def test_broadcastable_input(self, interpolator): + # input data + rng = np.random.RandomState(0) + x = rng.random(10) + y = rng.random(10) + z = np.hypot(x, y) + + # x-y grid for interpolation + X = np.linspace(min(x), max(x)) + Y = np.linspace(min(y), max(y)) + X, Y = np.meshgrid(X, Y) + XY = np.vstack((X.ravel(), Y.ravel())).T + interp = interpolator(list(zip(x, y)), z) + # single array input + interp_points0 = interp(XY) + # tuple input + interp_points1 = interp((X, Y)) + interp_points2 = interp((X, 0.0)) + # broadcastable input + interp_points3 = interp(X, Y) + interp_points4 = interp(X, 0.0) + + assert (interp_points0.size == + interp_points1.size == + interp_points2.size == + interp_points3.size == + interp_points4.size) + + @parametrize_interpolators + def test_read_only(self, interpolator): + # input data + rng = np.random.RandomState(0) + xy = rng.random((10, 2)) + x, y = xy[:, 0], xy[:, 1] + z = np.hypot(x, y) + + # interpolation points + XY = rng.random((50, 2)) + + xy.setflags(write=False) + z.setflags(write=False) + XY.setflags(write=False) + + interp = interpolator(xy, z) + interp(XY) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_pade.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_pade.py new file mode 100644 index 0000000000000000000000000000000000000000..3ffd37f1552c87a1ffd1a0a835a304cb6d87197a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_pade.py @@ -0,0 +1,107 @@ +import numpy as np +from scipy.interpolate import pade +from scipy._lib._array_api import ( + xp_assert_equal, assert_array_almost_equal +) + +def test_pade_trivial(): + nump, denomp = pade([1.0], 0) + xp_assert_equal(nump.c, np.asarray([1.0])) + xp_assert_equal(denomp.c, np.asarray([1.0])) + + nump, denomp = pade([1.0], 0, 0) + xp_assert_equal(nump.c, np.asarray([1.0])) + xp_assert_equal(denomp.c, np.asarray([1.0])) + + +def test_pade_4term_exp(): + # First four Taylor coefficients of exp(x). + # Unlike poly1d, the first array element is the zero-order term. + an = [1.0, 1.0, 0.5, 1.0/6] + + nump, denomp = pade(an, 0) + assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0]) + assert_array_almost_equal(denomp.c, [1.0]) + + nump, denomp = pade(an, 1) + assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [-1.0/3, 1.0]) + + nump, denomp = pade(an, 2) + assert_array_almost_equal(nump.c, [1.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0]) + + nump, denomp = pade(an, 3) + assert_array_almost_equal(nump.c, [1.0]) + assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0]) + + # Testing inclusion of optional parameter + nump, denomp = pade(an, 0, 3) + assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0]) + assert_array_almost_equal(denomp.c, [1.0]) + + nump, denomp = pade(an, 1, 2) + assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [-1.0/3, 1.0]) + + nump, denomp = pade(an, 2, 1) + assert_array_almost_equal(nump.c, [1.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0]) + + nump, denomp = pade(an, 3, 0) + assert_array_almost_equal(nump.c, [1.0]) + assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0]) + + # Testing reducing array. + nump, denomp = pade(an, 0, 2) + assert_array_almost_equal(nump.c, [0.5, 1.0, 1.0]) + assert_array_almost_equal(denomp.c, [1.0]) + + nump, denomp = pade(an, 1, 1) + assert_array_almost_equal(nump.c, [1.0/2, 1.0]) + assert_array_almost_equal(denomp.c, [-1.0/2, 1.0]) + + nump, denomp = pade(an, 2, 0) + assert_array_almost_equal(nump.c, [1.0]) + assert_array_almost_equal(denomp.c, [1.0/2, -1.0, 1.0]) + + +def test_pade_ints(): + # Simple test sequences (one of ints, one of floats). + an_int = [1, 2, 3, 4] + an_flt = [1.0, 2.0, 3.0, 4.0] + + # Make sure integer arrays give the same result as float arrays with same values. + for i in range(0, len(an_int)): + for j in range(0, len(an_int) - i): + + # Create float and int pade approximation for given order. + nump_int, denomp_int = pade(an_int, i, j) + nump_flt, denomp_flt = pade(an_flt, i, j) + + # Check that they are the same. + xp_assert_equal(nump_int.c, nump_flt.c) + xp_assert_equal(denomp_int.c, denomp_flt.c) + + +def test_pade_complex(): + # Test sequence with known solutions - see page 6 of 10.1109/PESGM.2012.6344759. + # Variable x is parameter - these tests will work with any complex number. + x = 0.2 + 0.6j + an = [1.0, x, -x*x.conjugate(), x.conjugate()*(x**2) + x*(x.conjugate()**2), + -(x**3)*x.conjugate() - 3*(x*x.conjugate())**2 - x*(x.conjugate()**3)] + + nump, denomp = pade(an, 1, 1) + assert_array_almost_equal(nump.c, [x + x.conjugate(), 1.0]) + assert_array_almost_equal(denomp.c, [x.conjugate(), 1.0]) + + nump, denomp = pade(an, 1, 2) + assert_array_almost_equal(nump.c, [x**2, 2*x + x.conjugate(), 1.0]) + assert_array_almost_equal(denomp.c, [x + x.conjugate(), 1.0]) + + nump, denomp = pade(an, 2, 2) + assert_array_almost_equal( + nump.c, + [x**2 + x*x.conjugate() + x.conjugate()**2, 2*(x + x.conjugate()), 1.0] + ) + assert_array_almost_equal(denomp.c, [x.conjugate()**2, x + 2*x.conjugate(), 1.0]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_polyint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_polyint.py new file mode 100644 index 0000000000000000000000000000000000000000..628f4c51f73d2dcb8bb707aa3b0b40499a5a05a8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_polyint.py @@ -0,0 +1,976 @@ +import warnings +import io +import numpy as np + +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_array_almost_equal, assert_almost_equal, + make_xp_test_case +) +from pytest import raises as assert_raises +import pytest + +from scipy.interpolate import ( + KroghInterpolator, krogh_interpolate, + BarycentricInterpolator, barycentric_interpolate, + approximate_taylor_polynomial, CubicHermiteSpline, pchip, + PchipInterpolator, pchip_interpolate, Akima1DInterpolator, CubicSpline, + make_interp_spline) +from scipy._lib._testutils import _run_concurrent_barrier + +skip_xp_backends = pytest.mark.skip_xp_backends +xfail_xp_backends = pytest.mark.xfail_xp_backends + + +def check_shape(interpolator_cls, x_shape, y_shape, deriv_shape=None, axis=0, + extra_args=None): + if extra_args is None: + extra_args = {} + rng = np.random.RandomState(1234) + + x = [-1, 0, 1, 2, 3, 4] + s = list(range(1, len(y_shape)+1)) + s.insert(axis % (len(y_shape)+1), 0) + y = rng.rand(*((6,) + y_shape)).transpose(s) + + xi = np.zeros(x_shape) + if interpolator_cls is CubicHermiteSpline: + dydx = rng.rand(*((6,) + y_shape)).transpose(s) + yi = interpolator_cls(x, y, dydx, axis=axis, **extra_args)(xi) + else: + yi = interpolator_cls(x, y, axis=axis, **extra_args)(xi) + + target_shape = ((deriv_shape or ()) + y.shape[:axis] + + x_shape + y.shape[axis:][1:]) + assert yi.shape == target_shape + + # check it works also with lists + if x_shape and y.size > 0: + if interpolator_cls is CubicHermiteSpline: + interpolator_cls(list(x), list(y), list(dydx), axis=axis, + **extra_args)(list(xi)) + else: + interpolator_cls(list(x), list(y), axis=axis, + **extra_args)(list(xi)) + + # check also values + if xi.size > 0 and deriv_shape is None: + bs_shape = y.shape[:axis] + (1,)*len(x_shape) + y.shape[axis:][1:] + yv = y[((slice(None,),)*(axis % y.ndim)) + (1,)] + yv = yv.reshape(bs_shape) + + yi, y = np.broadcast_arrays(yi, yv) + xp_assert_close(yi, y) + + +SHAPES = [(), (0,), (1,), (6, 2, 5)] + + +def test_shapes(): + + def spl_interp(x, y, axis): + return make_interp_spline(x, y, axis=axis) + + for ip in [KroghInterpolator, BarycentricInterpolator, CubicHermiteSpline, + pchip, Akima1DInterpolator, CubicSpline, spl_interp]: + for s1 in SHAPES: + for s2 in SHAPES: + for axis in range(-len(s2), len(s2)): + if ip != CubicSpline: + check_shape(ip, s1, s2, None, axis) + else: + for bc in ['natural', 'clamped']: + extra = {'bc_type': bc} + check_shape(ip, s1, s2, None, axis, extra) + +def test_derivs_shapes(): + for ip in [KroghInterpolator, BarycentricInterpolator]: + def interpolator_derivs(x, y, axis=0): + return ip(x, y, axis).derivatives + + for s1 in SHAPES: + for s2 in SHAPES: + for axis in range(-len(s2), len(s2)): + check_shape(interpolator_derivs, s1, s2, (6,), axis) + + +def test_deriv_shapes(): + def krogh_deriv(x, y, axis=0): + return KroghInterpolator(x, y, axis).derivative + + def bary_deriv(x, y, axis=0): + return BarycentricInterpolator(x, y, axis).derivative + + def pchip_deriv(x, y, axis=0): + return pchip(x, y, axis).derivative() + + def pchip_deriv2(x, y, axis=0): + return pchip(x, y, axis).derivative(2) + + def pchip_antideriv(x, y, axis=0): + return pchip(x, y, axis).antiderivative() + + def pchip_antideriv2(x, y, axis=0): + return pchip(x, y, axis).antiderivative(2) + + def pchip_deriv_inplace(x, y, axis=0): + class P(PchipInterpolator): + def __call__(self, x): + return PchipInterpolator.__call__(self, x, 1) + pass + return P(x, y, axis) + + def akima_deriv(x, y, axis=0): + return Akima1DInterpolator(x, y, axis).derivative() + + def akima_antideriv(x, y, axis=0): + return Akima1DInterpolator(x, y, axis).antiderivative() + + def cspline_deriv(x, y, axis=0): + return CubicSpline(x, y, axis).derivative() + + def cspline_antideriv(x, y, axis=0): + return CubicSpline(x, y, axis).antiderivative() + + def bspl_deriv(x, y, axis=0): + return make_interp_spline(x, y, axis=axis).derivative() + + def bspl_antideriv(x, y, axis=0): + return make_interp_spline(x, y, axis=axis).antiderivative() + + for ip in [krogh_deriv, bary_deriv, pchip_deriv, pchip_deriv2, pchip_deriv_inplace, + pchip_antideriv, pchip_antideriv2, akima_deriv, akima_antideriv, + cspline_deriv, cspline_antideriv, bspl_deriv, bspl_antideriv]: + for s1 in SHAPES: + for s2 in SHAPES: + for axis in range(-len(s2), len(s2)): + check_shape(ip, s1, s2, (), axis) + + +def test_complex(): + x = [1, 2, 3, 4] + y = [1, 2, 1j, 3] + + for ip in [KroghInterpolator, BarycentricInterpolator, CubicSpline]: + p = ip(x, y) + xp_assert_close(p(x), np.asarray(y)) + + dydx = [0, -1j, 2, 3j] + p = CubicHermiteSpline(x, y, dydx) + xp_assert_close(p(x), np.asarray(y)) + xp_assert_close(p(x, 1), np.asarray(dydx)) + + +class TestKrogh: + def setup_method(self): + self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2]) + self.test_xs = np.linspace(-1,1,100) + self.xs = np.linspace(-1,1,5) + self.ys = self.true_poly(self.xs) + + def test_lagrange(self): + P = KroghInterpolator(self.xs,self.ys) + assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs)) + + def test_scalar(self): + P = KroghInterpolator(self.xs,self.ys) + assert_almost_equal(self.true_poly(7), P(7), check_0d=False) + assert_almost_equal(self.true_poly(np.array(7)), P(np.array(7)), check_0d=False) + + def test_derivatives(self): + P = KroghInterpolator(self.xs,self.ys) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + assert_almost_equal(self.true_poly.deriv(i)(self.test_xs), + D[i]) + + def test_low_derivatives(self): + P = KroghInterpolator(self.xs,self.ys) + D = P.derivatives(self.test_xs,len(self.xs)+2) + for i in range(D.shape[0]): + assert_almost_equal(self.true_poly.deriv(i)(self.test_xs), + D[i]) + + def test_derivative(self): + P = KroghInterpolator(self.xs,self.ys) + m = 10 + r = P.derivatives(self.test_xs,m) + for i in range(m): + assert_almost_equal(P.derivative(self.test_xs,i),r[i]) + + def test_high_derivative(self): + P = KroghInterpolator(self.xs,self.ys) + for i in range(len(self.xs), 2*len(self.xs)): + assert_almost_equal(P.derivative(self.test_xs,i), + np.zeros(len(self.test_xs))) + + def test_ndim_derivatives(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = KroghInterpolator(self.xs, ys, axis=0) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + xp_assert_close(D[i], + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1)) + + def test_ndim_derivative(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = KroghInterpolator(self.xs, ys, axis=0) + for i in range(P.n): + xp_assert_close(P.derivative(self.test_xs, i), + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1)) + + def test_hermite(self): + P = KroghInterpolator(self.xs,self.ys) + assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs)) + + def test_vector(self): + xs = [0, 1, 2] + ys = np.array([[0,1],[1,0],[2,1]]) + P = KroghInterpolator(xs,ys) + Pi = [KroghInterpolator(xs,ys[:,i]) for i in range(ys.shape[1])] + test_xs = np.linspace(-1,3,100) + assert_almost_equal(P(test_xs), + np.asarray([p(test_xs) for p in Pi]).T) + assert_almost_equal(P.derivatives(test_xs), + np.transpose(np.asarray([p.derivatives(test_xs) for p in Pi]), + (1,2,0))) + + def test_empty(self): + P = KroghInterpolator(self.xs,self.ys) + xp_assert_equal(P([]), np.asarray([])) + + def test_shapes_scalarvalue(self): + P = KroghInterpolator(self.xs,self.ys) + assert np.shape(P(0)) == () + assert np.shape(P(np.array(0))) == () + assert np.shape(P([0])) == (1,) + assert np.shape(P([0,1])) == (2,) + + def test_shapes_scalarvalue_derivative(self): + P = KroghInterpolator(self.xs,self.ys) + n = P.n + assert np.shape(P.derivatives(0)) == (n,) + assert np.shape(P.derivatives(np.array(0))) == (n,) + assert np.shape(P.derivatives([0])) == (n, 1) + assert np.shape(P.derivatives([0, 1])) == (n, 2) + + def test_shapes_vectorvalue(self): + P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3))) + assert np.shape(P(0)) == (3,) + assert np.shape(P([0])) == (1, 3) + assert np.shape(P([0, 1])) == (2, 3) + + def test_shapes_1d_vectorvalue(self): + P = KroghInterpolator(self.xs,np.outer(self.ys,[1])) + assert np.shape(P(0)) == (1,) + assert np.shape(P([0])) == (1, 1) + assert np.shape(P([0,1])) == (2, 1) + + def test_shapes_vectorvalue_derivative(self): + P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3))) + n = P.n + assert np.shape(P.derivatives(0)) == (n, 3) + assert np.shape(P.derivatives([0])) == (n, 1, 3) + assert np.shape(P.derivatives([0,1])) == (n, 2, 3) + + def test_wrapper(self): + P = KroghInterpolator(self.xs, self.ys) + ki = krogh_interpolate + assert_almost_equal(P(self.test_xs), ki(self.xs, self.ys, self.test_xs)) + assert_almost_equal(P.derivative(self.test_xs, 2), + ki(self.xs, self.ys, self.test_xs, der=2)) + assert_almost_equal(P.derivatives(self.test_xs, 2), + ki(self.xs, self.ys, self.test_xs, der=[0, 1])) + + def test_int_inputs(self): + # Check input args are cast correctly to floats, gh-3669 + x = [0, 234, 468, 702, 936, 1170, 1404, 2340, 3744, 6084, 8424, + 13104, 60000] + offset_cdf = np.array([-0.95, -0.86114777, -0.8147762, -0.64072425, + -0.48002351, -0.34925329, -0.26503107, + -0.13148093, -0.12988833, -0.12979296, + -0.12973574, -0.08582937, 0.05]) + f = KroghInterpolator(x, offset_cdf) + + xp_assert_close(abs((f(x) - offset_cdf) / f.derivative(x, 1)), + np.zeros_like(offset_cdf), atol=1e-10) + + def test_derivatives_complex(self): + # regression test for gh-7381: krogh.derivatives(0) fails complex y + x, y = np.array([-1, -1, 0, 1, 1]), np.array([1, 1.0j, 0, -1, 1.0j]) + func = KroghInterpolator(x, y) + cmplx = func.derivatives(0) + + cmplx2 = (KroghInterpolator(x, y.real).derivatives(0) + + 1j*KroghInterpolator(x, y.imag).derivatives(0)) + xp_assert_close(cmplx, cmplx2, atol=1e-15) + + def test_high_degree_warning(self): + with pytest.warns(UserWarning, match="40 degrees provided,"): + KroghInterpolator(np.arange(40), np.ones(40)) + + def test_concurrency(self): + P = KroghInterpolator(self.xs, self.ys) + + def worker_fn(_, interp): + interp(self.xs) + + _run_concurrent_barrier(10, worker_fn, P) + + +class TestTaylor: + def test_exponential(self): + degree = 5 + p = approximate_taylor_polynomial(np.exp, 0, degree, 1, 15) + for i in range(degree+1): + assert_almost_equal(p(0),1) + p = p.deriv() + assert_almost_equal(p(0),0) + + +class TestBarycentric: + def setup_method(self): + self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2]) + self.test_xs = np.linspace(-1, 1, 100) + self.xs = np.linspace(-1, 1, 5) + self.ys = self.true_poly(self.xs) + + def test_lagrange(self): + # Ensure backwards compatible post SPEC7 + P = BarycentricInterpolator(self.xs, self.ys, random_state=1) + xp_assert_close(P(self.test_xs), self.true_poly(self.test_xs)) + + def test_scalar(self): + P = BarycentricInterpolator(self.xs, self.ys, rng=1) + xp_assert_close(P(7), self.true_poly(7), check_0d=False) + xp_assert_close(P(np.array(7)), self.true_poly(np.array(7)), check_0d=False) + + def test_derivatives(self): + P = BarycentricInterpolator(self.xs, self.ys) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + xp_assert_close(self.true_poly.deriv(i)(self.test_xs), D[i]) + + def test_low_derivatives(self): + P = BarycentricInterpolator(self.xs, self.ys) + D = P.derivatives(self.test_xs, len(self.xs)+2) + for i in range(D.shape[0]): + xp_assert_close(self.true_poly.deriv(i)(self.test_xs), + D[i], + atol=1e-12) + + def test_derivative(self): + P = BarycentricInterpolator(self.xs, self.ys) + m = 10 + r = P.derivatives(self.test_xs, m) + for i in range(m): + xp_assert_close(P.derivative(self.test_xs, i), r[i]) + + def test_high_derivative(self): + P = BarycentricInterpolator(self.xs, self.ys) + for i in range(len(self.xs), 5*len(self.xs)): + xp_assert_close(P.derivative(self.test_xs, i), + np.zeros(len(self.test_xs))) + + def test_ndim_derivatives(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = BarycentricInterpolator(self.xs, ys, axis=0) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + xp_assert_close(D[i], + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1), + atol=1e-12) + + def test_ndim_derivative(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = BarycentricInterpolator(self.xs, ys, axis=0) + for i in range(P.n): + xp_assert_close(P.derivative(self.test_xs, i), + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1), + atol=1e-12) + + def test_delayed(self): + P = BarycentricInterpolator(self.xs) + P.set_yi(self.ys) + assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs)) + + def test_append(self): + P = BarycentricInterpolator(self.xs[:3], self.ys[:3]) + P.add_xi(self.xs[3:], self.ys[3:]) + assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs)) + + def test_vector(self): + xs = [0, 1, 2] + ys = np.array([[0, 1], [1, 0], [2, 1]]) + BI = BarycentricInterpolator + P = BI(xs, ys) + Pi = [BI(xs, ys[:, i]) for i in range(ys.shape[1])] + test_xs = np.linspace(-1, 3, 100) + assert_almost_equal(P(test_xs), + np.asarray([p(test_xs) for p in Pi]).T) + + def test_shapes_scalarvalue(self): + P = BarycentricInterpolator(self.xs, self.ys) + assert np.shape(P(0)) == () + assert np.shape(P(np.array(0))) == () + assert np.shape(P([0])) == (1,) + assert np.shape(P([0, 1])) == (2,) + + def test_shapes_scalarvalue_derivative(self): + P = BarycentricInterpolator(self.xs,self.ys) + n = P.n + assert np.shape(P.derivatives(0)) == (n,) + assert np.shape(P.derivatives(np.array(0))) == (n,) + assert np.shape(P.derivatives([0])) == (n,1) + assert np.shape(P.derivatives([0,1])) == (n,2) + + def test_shapes_vectorvalue(self): + P = BarycentricInterpolator(self.xs, np.outer(self.ys, np.arange(3))) + assert np.shape(P(0)) == (3,) + assert np.shape(P([0])) == (1, 3) + assert np.shape(P([0, 1])) == (2, 3) + + def test_shapes_1d_vectorvalue(self): + P = BarycentricInterpolator(self.xs, np.outer(self.ys, [1])) + assert np.shape(P(0)) == (1,) + assert np.shape(P([0])) == (1, 1) + assert np.shape(P([0, 1])) == (2, 1) + + def test_shapes_vectorvalue_derivative(self): + P = BarycentricInterpolator(self.xs,np.outer(self.ys,np.arange(3))) + n = P.n + assert np.shape(P.derivatives(0)) == (n, 3) + assert np.shape(P.derivatives([0])) == (n, 1, 3) + assert np.shape(P.derivatives([0, 1])) == (n, 2, 3) + + def test_wrapper(self): + P = BarycentricInterpolator(self.xs, self.ys, rng=1) + bi = barycentric_interpolate + xp_assert_close(P(self.test_xs), bi(self.xs, self.ys, self.test_xs, rng=1)) + xp_assert_close(P.derivative(self.test_xs, 2), + bi(self.xs, self.ys, self.test_xs, der=2, rng=1)) + xp_assert_close(P.derivatives(self.test_xs, 2), + bi(self.xs, self.ys, self.test_xs, der=[0, 1], rng=1)) + + def test_int_input(self): + x = 1000 * np.arange(1, 11) # np.prod(x[-1] - x[:-1]) overflows + y = np.arange(1, 11) + value = barycentric_interpolate(x, y, 1000 * 9.5) + assert_almost_equal(value, np.asarray(9.5)) + + def test_large_chebyshev(self): + # The weights for Chebyshev points of the second kind have analytically + # solvable weights. Naive calculation of barycentric weights will fail + # for large N because of numerical underflow and overflow. We test + # correctness for large N against analytical Chebyshev weights. + + # Without capacity scaling or permutation, n=800 fails, + # With just capacity scaling, n=1097 fails + # With both capacity scaling and random permutation, n=30000 succeeds + n = 1100 + j = np.arange(n + 1).astype(np.float64) + x = np.cos(j * np.pi / n) + + # See page 506 of Berrut and Trefethen 2004 for this formula + w = (-1) ** j + w[0] *= 0.5 + w[-1] *= 0.5 + + P = BarycentricInterpolator(x) + + # It's okay to have a constant scaling factor in the weights because it + # cancels out in the evaluation of the polynomial. + factor = P.wi[0] + assert_almost_equal(P.wi / (2 * factor), w) + + def test_warning(self): + # Test if the divide-by-zero warning is properly ignored when computing + # interpolated values equals to interpolation points + P = BarycentricInterpolator([0, 1], [1, 2]) + with np.errstate(divide='raise'): + yi = P(P.xi) + + # Check if the interpolated values match the input values + # at the nodes + assert_almost_equal(yi, P.yi.ravel()) + + def test_repeated_node(self): + # check that a repeated node raises a ValueError + # (computing the weights requires division by xi[i] - xi[j]) + xis = np.array([0.1, 0.5, 0.9, 0.5]) + ys = np.array([1, 2, 3, 4]) + with pytest.raises(ValueError, + match="Interpolation points xi must be distinct."): + BarycentricInterpolator(xis, ys) + + def test_concurrency(self): + P = BarycentricInterpolator(self.xs, self.ys) + + def worker_fn(_, interp): + interp(self.xs) + + _run_concurrent_barrier(10, worker_fn, P) + + +class TestPCHIP: + def _make_random(self, npts=20): + rng = np.random.RandomState(1234) + xi = np.sort(rng.random(npts)) + yi = rng.random(npts) + return pchip(xi, yi), xi, yi + + def test_overshoot(self): + # PCHIP should not overshoot + p, xi, yi = self._make_random() + for i in range(len(xi)-1): + x1, x2 = xi[i], xi[i+1] + y1, y2 = yi[i], yi[i+1] + if y1 > y2: + y1, y2 = y2, y1 + xp = np.linspace(x1, x2, 10) + yp = p(xp) + assert ((y1 <= yp + 1e-15) & (yp <= y2 + 1e-15)).all() + + def test_monotone(self): + # PCHIP should preserve monotonicty + p, xi, yi = self._make_random() + for i in range(len(xi)-1): + x1, x2 = xi[i], xi[i+1] + y1, y2 = yi[i], yi[i+1] + xp = np.linspace(x1, x2, 10) + yp = p(xp) + assert ((y2-y1) * (yp[1:] - yp[:1]) > 0).all() + + def test_cast(self): + # regression test for integer input data, see gh-3453 + data = np.array([[0, 4, 12, 27, 47, 60, 79, 87, 99, 100], + [-33, -33, -19, -2, 12, 26, 38, 45, 53, 55]]) + xx = np.arange(100) + curve = pchip(data[0], data[1])(xx) + + data1 = data * 1.0 + curve1 = pchip(data1[0], data1[1])(xx) + + xp_assert_close(curve, curve1, atol=1e-14, rtol=1e-14) + + def test_nag(self): + # Example from NAG C implementation, + # http://nag.com/numeric/cl/nagdoc_cl25/html/e01/e01bec.html + # suggested in gh-5326 as a smoke test for the way the derivatives + # are computed (see also gh-3453) + dataStr = ''' + 7.99 0.00000E+0 + 8.09 0.27643E-4 + 8.19 0.43750E-1 + 8.70 0.16918E+0 + 9.20 0.46943E+0 + 10.00 0.94374E+0 + 12.00 0.99864E+0 + 15.00 0.99992E+0 + 20.00 0.99999E+0 + ''' + data = np.loadtxt(io.StringIO(dataStr)) + pch = pchip(data[:,0], data[:,1]) + + resultStr = ''' + 7.9900 0.0000 + 9.1910 0.4640 + 10.3920 0.9645 + 11.5930 0.9965 + 12.7940 0.9992 + 13.9950 0.9998 + 15.1960 0.9999 + 16.3970 1.0000 + 17.5980 1.0000 + 18.7990 1.0000 + 20.0000 1.0000 + ''' + result = np.loadtxt(io.StringIO(resultStr)) + xp_assert_close(result[:,1], pch(result[:,0]), rtol=0., atol=5e-5) + + def test_endslopes(self): + # this is a smoke test for gh-3453: PCHIP interpolator should not + # set edge slopes to zero if the data do not suggest zero edge derivatives + x = np.array([0.0, 0.1, 0.25, 0.35]) + y1 = np.array([279.35, 0.5e3, 1.0e3, 2.5e3]) + y2 = np.array([279.35, 2.5e3, 1.50e3, 1.0e3]) + for pp in (pchip(x, y1), pchip(x, y2)): + for t in (x[0], x[-1]): + assert pp(t, 1) != 0 + + def test_all_zeros(self): + x = np.arange(10) + y = np.zeros_like(x) + + # this should work and not generate any warnings + with warnings.catch_warnings(): + warnings.filterwarnings('error') + pch = pchip(x, y) + + xx = np.linspace(0, 9, 101) + assert all(pch(xx) == 0.) + + def test_two_points(self): + # regression test for gh-6222: pchip([0, 1], [0, 1]) fails because + # it tries to use a three-point scheme to estimate edge derivatives, + # while there are only two points available. + # Instead, it should construct a linear interpolator. + x = np.linspace(0, 1, 11) + p = pchip([0, 1], [0, 2]) + xp_assert_close(p(x), 2*x, atol=1e-15) + + def test_pchip_interpolate(self): + assert_array_almost_equal( + pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=1), + np.asarray([1.])) + + assert_array_almost_equal( + pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=0), + np.asarray([3.5])) + + assert_array_almost_equal( + np.asarray(pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=[0, 1])), + np.asarray([[3.5], [1]])) + + def test_roots(self): + # regression test for gh-6357: .roots method should work + p = pchip([0, 1], [-1, 1]) + r = p.roots() + xp_assert_close(r, np.asarray([0.5])) + + +@make_xp_test_case(CubicSpline) +class TestCubicSpline: + @staticmethod + def check_correctness(S, bc_start='not-a-knot', bc_end='not-a-knot', + tol=1e-14): + """Check that spline coefficients satisfy the continuity and boundary + conditions.""" + x = S.x + c = S.c + dx = np.diff(x) + dx = dx.reshape([dx.shape[0]] + [1] * (c.ndim - 2)) + dxi = dx[:-1] + + # Check C2 continuity. + xp_assert_close(c[3, 1:], c[0, :-1] * dxi**3 + c[1, :-1] * dxi**2 + + c[2, :-1] * dxi + c[3, :-1], rtol=tol, atol=tol) + xp_assert_close(c[2, 1:], 3 * c[0, :-1] * dxi**2 + + 2 * c[1, :-1] * dxi + c[2, :-1], rtol=tol, atol=tol) + xp_assert_close(c[1, 1:], 3 * c[0, :-1] * dxi + c[1, :-1], + rtol=tol, atol=tol) + + # Check that we found a parabola, the third derivative is 0. + if x.size == 3 and bc_start == 'not-a-knot' and bc_end == 'not-a-knot': + xp_assert_close(c[0], np.zeros_like(c[0]), rtol=tol, atol=tol) + return + + # Check periodic boundary conditions. + if bc_start == 'periodic': + xp_assert_close(S(x[0], 0), S(x[-1], 0), rtol=tol, atol=tol) + xp_assert_close(S(x[0], 1), S(x[-1], 1), rtol=tol, atol=tol) + xp_assert_close(S(x[0], 2), S(x[-1], 2), rtol=tol, atol=tol) + return + + # Check other boundary conditions. + if bc_start == 'not-a-knot': + if x.size == 2: + slope = (S(x[1]) - S(x[0])) / dx[0] + slope = np.asarray(slope) + xp_assert_close(S(x[0], 1), slope, rtol=tol, atol=tol) + else: + xp_assert_close(c[0, 0], c[0, 1], rtol=tol, atol=tol) + elif bc_start == 'clamped': + xp_assert_close( + S(x[0], 1), np.zeros_like(S(x[0], 1)), rtol=tol, atol=tol) + elif bc_start == 'natural': + xp_assert_close( + S(x[0], 2), np.zeros_like(S(x[0], 2)), rtol=tol, atol=tol) + else: + order, value = bc_start + xp_assert_close(S(x[0], order), np.asarray(value), rtol=tol, atol=tol) + + if bc_end == 'not-a-knot': + if x.size == 2: + slope = (S(x[1]) - S(x[0])) / dx[0] + slope = np.asarray(slope) + xp_assert_close(S(x[1], 1), slope, rtol=tol, atol=tol) + else: + xp_assert_close(c[0, -1], c[0, -2], rtol=tol, atol=tol) + elif bc_end == 'clamped': + xp_assert_close(S(x[-1], 1), np.zeros_like(S(x[-1], 1)), + rtol=tol, atol=tol) + elif bc_end == 'natural': + xp_assert_close(S(x[-1], 2), np.zeros_like(S(x[-1], 2)), + rtol=2*tol, atol=2*tol) + else: + order, value = bc_end + xp_assert_close(S(x[-1], order), np.asarray(value), rtol=tol, atol=tol) + + def check_all_bc(self, x, y, axis): + deriv_shape = list(y.shape) + del deriv_shape[axis] + first_deriv = np.empty(deriv_shape) + first_deriv.fill(2) + second_deriv = np.empty(deriv_shape) + second_deriv.fill(-1) + bc_all = [ + 'not-a-knot', + 'natural', + 'clamped', + (1, first_deriv), + (2, second_deriv) + ] + for bc in bc_all[:3]: + S = CubicSpline(x, y, axis=axis, bc_type=bc) + self.check_correctness(S, bc, bc) + + for bc_start in bc_all: + for bc_end in bc_all: + S = CubicSpline(x, y, axis=axis, bc_type=(bc_start, bc_end)) + self.check_correctness(S, bc_start, bc_end, tol=2e-14) + + def test_general(self): + x = np.array([-1, 0, 0.5, 2, 4, 4.5, 5.5, 9]) + y = np.array([0, -0.5, 2, 3, 2.5, 1, 1, 0.5]) + for n in [2, 3, x.size]: + self.check_all_bc(x[:n], y[:n], 0) + + Y = np.empty((2, n, 2)) + Y[0, :, 0] = y[:n] + Y[0, :, 1] = y[:n] - 1 + Y[1, :, 0] = y[:n] + 2 + Y[1, :, 1] = y[:n] + 3 + self.check_all_bc(x[:n], Y, 1) + + def test_periodic(self): + for n in [2, 3, 5]: + x = np.linspace(0, 2 * np.pi, n) + y = np.cos(x) + S = CubicSpline(x, y, bc_type='periodic') + self.check_correctness(S, 'periodic', 'periodic') + + Y = np.empty((2, n, 2)) + Y[0, :, 0] = y + Y[0, :, 1] = y + 2 + Y[1, :, 0] = y - 1 + Y[1, :, 1] = y + 5 + S = CubicSpline(x, Y, axis=1, bc_type='periodic') + self.check_correctness(S, 'periodic', 'periodic') + + def test_periodic_eval(self, xp): + x = xp.linspace(0, 2 * xp.pi, 10, dtype=xp.float64) + y = xp.cos(x) + S = CubicSpline(x, y, bc_type='periodic') + assert_almost_equal(S(1), S(1 + 2 * xp.pi), decimal=15) + + S = CubicSpline(x, y) + assert_almost_equal(S(x), xp.cos(x), decimal=15) + + def test_second_derivative_continuity_gh_11758(self): + # gh-11758: C2 continuity fail + x = np.array([0.9, 1.3, 1.9, 2.1, 2.6, 3.0, 3.9, 4.4, 4.7, 5.0, 6.0, + 7.0, 8.0, 9.2, 10.5, 11.3, 11.6, 12.0, 12.6, 13.0, 13.3]) + y = np.array([1.3, 1.5, 1.85, 2.1, 2.6, 2.7, 2.4, 2.15, 2.05, 2.1, + 2.25, 2.3, 2.25, 1.95, 1.4, 0.9, 0.7, 0.6, 0.5, 0.4, 1.3]) + S = CubicSpline(x, y, bc_type='periodic', extrapolate='periodic') + self.check_correctness(S, 'periodic', 'periodic') + + def test_three_points(self): + # gh-11758: Fails computing a_m2_m1 + # In this case, s (first derivatives) could be found manually by solving + # system of 2 linear equations. Due to solution of this system, + # s[i] = (h1m2 + h2m1) / (h1 + h2), where h1 = x[1] - x[0], h2 = x[2] - x[1], + # m1 = (y[1] - y[0]) / h1, m2 = (y[2] - y[1]) / h2 + x = np.array([1.0, 2.75, 3.0]) + y = np.array([1.0, 15.0, 1.0]) + S = CubicSpline(x, y, bc_type='periodic') + self.check_correctness(S, 'periodic', 'periodic') + xp_assert_close(S.derivative(1)(x), np.array([-48.0, -48.0, -48.0])) + + def test_periodic_three_points_multidim(self): + # make sure one multidimensional interpolator does the same as multiple + # one-dimensional interpolators + x = np.array([0.0, 1.0, 3.0]) + y = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]) + S = CubicSpline(x, y, bc_type="periodic") + self.check_correctness(S, 'periodic', 'periodic') + S0 = CubicSpline(x, y[:, 0], bc_type="periodic") + S1 = CubicSpline(x, y[:, 1], bc_type="periodic") + q = np.linspace(0, 2, 5) + xp_assert_close(S(q)[:, 0], S0(q)) + xp_assert_close(S(q)[:, 1], S1(q)) + + def test_dtypes(self): + x = np.array([0, 1, 2, 3], dtype=int) + y = np.array([-5, 2, 3, 1], dtype=int) + S = CubicSpline(x, y) + self.check_correctness(S) + + y = np.array([-1+1j, 0.0, 1-1j, 0.5-1.5j]) + S = CubicSpline(x, y) + self.check_correctness(S) + + S = CubicSpline(x, x ** 3, bc_type=("natural", (1, 2j))) + self.check_correctness(S, "natural", (1, 2j)) + + y = np.array([-5, 2, 3, 1]) + S = CubicSpline(x, y, bc_type=[(1, 2 + 0.5j), (2, 0.5 - 1j)]) + self.check_correctness(S, (1, 2 + 0.5j), (2, 0.5 - 1j)) + + def test_small_dx(self): + rng = np.random.RandomState(0) + x = np.sort(rng.uniform(size=100)) + y = 1e4 + rng.uniform(size=100) + S = CubicSpline(x, y) + self.check_correctness(S, tol=1e-13) + + def test_incorrect_inputs(self): + x = np.array([1, 2, 3, 4]) + y = np.array([1, 2, 3, 4]) + xc = np.array([1 + 1j, 2, 3, 4]) + xn = np.array([np.nan, 2, 3, 4]) + xo = np.array([2, 1, 3, 4]) + yn = np.array([np.nan, 2, 3, 4]) + y3 = [1, 2, 3] + x1 = [1] + y1 = [1] + + assert_raises(ValueError, CubicSpline, xc, y) + assert_raises(ValueError, CubicSpline, xn, y) + assert_raises(ValueError, CubicSpline, x, yn) + assert_raises(ValueError, CubicSpline, xo, y) + assert_raises(ValueError, CubicSpline, x, y3) + assert_raises(ValueError, CubicSpline, x[:, np.newaxis], y) + assert_raises(ValueError, CubicSpline, x1, y1) + + wrong_bc = [('periodic', 'clamped'), + ((2, 0), (3, 10)), + ((1, 0), ), + (0., 0.), + 'not-a-typo'] + + for bc_type in wrong_bc: + assert_raises(ValueError, CubicSpline, x, y, 0, bc_type, True) + + # Shapes mismatch when giving arbitrary derivative values: + Y = np.c_[y, y] + bc1 = ('clamped', (1, 0)) + bc2 = ('clamped', (1, [0, 0, 0])) + bc3 = ('clamped', (1, [[0, 0]])) + assert_raises(ValueError, CubicSpline, x, Y, 0, bc1, True) + assert_raises(ValueError, CubicSpline, x, Y, 0, bc2, True) + assert_raises(ValueError, CubicSpline, x, Y, 0, bc3, True) + + # periodic condition, y[-1] must be equal to y[0]: + assert_raises(ValueError, CubicSpline, x, y, 0, 'periodic', True) + + +@make_xp_test_case(CubicHermiteSpline) +def test_CubicHermiteSpline_correctness(xp): + x = xp.asarray([0, 2, 7]) + y = xp.asarray([-1, 2, 3]) + dydx = xp.asarray([0, 3, 7]) + s = CubicHermiteSpline(x, y, dydx) + xp_assert_close(s(x), y, check_shape=False, check_dtype=False, rtol=1e-15) + xp_assert_close(s(x, 1), dydx, check_shape=False, check_dtype=False, rtol=1e-15) + + +def test_CubicHermiteSpline_error_handling(): + x = [1, 2, 3] + y = [0, 3, 5] + dydx = [1, -1, 2, 3] + assert_raises(ValueError, CubicHermiteSpline, x, y, dydx) + + dydx_with_nan = [1, 0, np.nan] + assert_raises(ValueError, CubicHermiteSpline, x, y, dydx_with_nan) + + +def test_roots_extrapolate_gh_11185(): + x = np.array([0.001, 0.002]) + y = np.array([1.66066935e-06, 1.10410807e-06]) + dy = np.array([-1.60061854, -1.600619]) + p = CubicHermiteSpline(x, y, dy) + + # roots(extrapolate=True) for a polynomial with a single interval + # should return all three real roots + r = p.roots(extrapolate=True) + assert p.c.shape[1] == 1 + assert r.size == 3 + + +class TestZeroSizeArrays: + # regression tests for gh-17241 : CubicSpline et al must not segfault + # when y.size == 0 + # The two methods below are _almost_ the same, but not quite: + # one is for objects which have the `bc_type` argument (CubicSpline) + # and the other one is for those which do not (Pchip, Akima1D) + + @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)), + np.zeros((10, 5, 0))]) + @pytest.mark.parametrize('bc_type', + ['not-a-knot', 'periodic', 'natural', 'clamped']) + @pytest.mark.parametrize('axis', [0, 1, 2]) + @pytest.mark.parametrize('cls', [make_interp_spline, CubicSpline]) + def test_zero_size(self, cls, y, bc_type, axis): + x = np.arange(10) + xval = np.arange(3) + + obj = cls(x, y, bc_type=bc_type) + assert obj(xval).size == 0 + assert obj(xval).shape == xval.shape + y.shape[1:] + + # Also check with an explicit non-default axis + yt = np.moveaxis(y, 0, axis) # (10, 0, 5) --> (0, 10, 5) if axis=1 etc + + obj = cls(x, yt, bc_type=bc_type, axis=axis) + sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:] + assert obj(xval).size == 0 + assert obj(xval).shape == sh + + @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)), + np.zeros((10, 5, 0))]) + @pytest.mark.parametrize('axis', [0, 1, 2]) + @pytest.mark.parametrize('cls', [PchipInterpolator, Akima1DInterpolator]) + def test_zero_size_2(self, cls, y, axis): + x = np.arange(10) + xval = np.arange(3) + + obj = cls(x, y) + assert obj(xval).size == 0 + assert obj(xval).shape == xval.shape + y.shape[1:] + + # Also check with an explicit non-default axis + yt = np.moveaxis(y, 0, axis) # (10, 0, 5) --> (0, 10, 5) if axis=1 etc + + obj = cls(x, yt, axis=axis) + sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:] + assert obj(xval).size == 0 + assert obj(xval).shape == sh diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rbf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rbf.py new file mode 100644 index 0000000000000000000000000000000000000000..bffe43c7e16f7bd31d397c20ed5a747789dac159 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rbf.py @@ -0,0 +1,244 @@ +# Created by John Travers, Robert Hetland, 2007 +""" Test functions for rbf module """ + +import numpy as np + + +from scipy._lib._array_api import assert_array_almost_equal, assert_almost_equal + +from numpy import linspace, sin, cos, exp, allclose +from scipy.interpolate._rbf import Rbf +from scipy._lib._testutils import _run_concurrent_barrier + + +FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian', + 'cubic', 'quintic', 'thin-plate', 'linear') + + +def check_rbf1d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (1D) + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y, function=function) + yi = rbf(x) + assert_array_almost_equal(y, yi) + assert_almost_equal(rbf(float(x[0])), y[0], check_0d=False) + + +def check_rbf2d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (2D). + rng = np.random.RandomState(1234) + x = rng.rand(50,1)*4-2 + y = rng.rand(50,1)*4-2 + z = x*exp(-x**2-1j*y**2) + rbf = Rbf(x, y, z, epsilon=2, function=function) + zi = rbf(x, y) + zi = zi.reshape(x.shape) + assert_array_almost_equal(z, zi) + + +def check_rbf3d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (3D). + rng = np.random.RandomState(1234) + x = rng.rand(50, 1)*4 - 2 + y = rng.rand(50, 1)*4 - 2 + z = rng.rand(50, 1)*4 - 2 + d = x*exp(-x**2 - y**2) + rbf = Rbf(x, y, z, d, epsilon=2, function=function) + di = rbf(x, y, z) + di = di.reshape(x.shape) + assert_array_almost_equal(di, d) + + +def test_rbf_interpolation(): + for function in FUNCTIONS: + check_rbf1d_interpolation(function) + check_rbf2d_interpolation(function) + check_rbf3d_interpolation(function) + + +def check_2drbf1d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (1D) + x = linspace(0, 10, 9) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, function=function, mode='N-D') + yi = rbf(x) + assert_array_almost_equal(y, yi) + assert_almost_equal(rbf(float(x[0])), y[0]) + + +def check_2drbf2d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (2D). + rng = np.random.RandomState(1234) + x = rng.rand(50, ) * 4 - 2 + y = rng.rand(50, ) * 4 - 2 + z0 = x * exp(-x ** 2 - 1j * y ** 2) + z1 = y * exp(-y ** 2 - 1j * x ** 2) + z = np.vstack([z0, z1]).T + rbf = Rbf(x, y, z, epsilon=2, function=function, mode='N-D') + zi = rbf(x, y) + zi = zi.reshape(z.shape) + assert_array_almost_equal(z, zi) + + +def check_2drbf3d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (3D). + rng = np.random.RandomState(1234) + x = rng.rand(50, ) * 4 - 2 + y = rng.rand(50, ) * 4 - 2 + z = rng.rand(50, ) * 4 - 2 + d0 = x * exp(-x ** 2 - y ** 2) + d1 = y * exp(-y ** 2 - x ** 2) + d = np.vstack([d0, d1]).T + rbf = Rbf(x, y, z, d, epsilon=2, function=function, mode='N-D') + di = rbf(x, y, z) + di = di.reshape(d.shape) + assert_array_almost_equal(di, d) + + +def test_2drbf_interpolation(): + for function in FUNCTIONS: + check_2drbf1d_interpolation(function) + check_2drbf2d_interpolation(function) + check_2drbf3d_interpolation(function) + + +def check_rbf1d_regularity(function, atol): + # Check that the Rbf function approximates a smooth function well away + # from the nodes. + x = linspace(0, 10, 9) + y = sin(x) + rbf = Rbf(x, y, function=function) + xi = linspace(0, 10, 100) + yi = rbf(xi) + msg = f"abs-diff: {abs(yi - sin(xi)).max():f}" + assert allclose(yi, sin(xi), atol=atol), msg + + +def test_rbf_regularity(): + tolerances = { + 'multiquadric': 0.1, + 'inverse multiquadric': 0.15, + 'gaussian': 0.15, + 'cubic': 0.15, + 'quintic': 0.1, + 'thin-plate': 0.1, + 'linear': 0.2 + } + for function in FUNCTIONS: + check_rbf1d_regularity(function, tolerances.get(function, 1e-2)) + + +def check_2drbf1d_regularity(function, atol): + # Check that the 2-D Rbf function approximates a smooth function well away + # from the nodes. + x = linspace(0, 10, 9) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, function=function, mode='N-D') + xi = linspace(0, 10, 100) + yi = rbf(xi) + msg = f"abs-diff: {abs(yi - np.vstack([sin(xi), cos(xi)]).T).max():f}" + assert allclose(yi, np.vstack([sin(xi), cos(xi)]).T, atol=atol), msg + + +def test_2drbf_regularity(): + tolerances = { + 'multiquadric': 0.1, + 'inverse multiquadric': 0.15, + 'gaussian': 0.15, + 'cubic': 0.15, + 'quintic': 0.1, + 'thin-plate': 0.15, + 'linear': 0.2 + } + for function in FUNCTIONS: + check_2drbf1d_regularity(function, tolerances.get(function, 1e-2)) + + +def check_rbf1d_stability(function): + # Check that the Rbf function with default epsilon is not subject + # to overshoot. Regression for issue #4523. + # + # Generate some data (fixed random seed hence deterministic) + rng = np.random.RandomState(1234) + x = np.linspace(0, 10, 50) + z = x + 4.0 * rng.randn(len(x)) + + rbf = Rbf(x, z, function=function) + xi = np.linspace(0, 10, 1000) + yi = rbf(xi) + + # subtract the linear trend and make sure there no spikes + assert np.abs(yi-xi).max() / np.abs(z-x).max() < 1.1 + +def test_rbf_stability(): + for function in FUNCTIONS: + check_rbf1d_stability(function) + + +def test_default_construction(): + # Check that the Rbf class can be constructed with the default + # multiquadric basis function. Regression test for ticket #1228. + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_function_is_callable(): + # Check that the Rbf class can be constructed with function=callable. + x = linspace(0,10,9) + y = sin(x) + def linfunc(x): + return x + rbf = Rbf(x, y, function=linfunc) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_two_arg_function_is_callable(): + # Check that the Rbf class can be constructed with a two argument + # function=callable. + def _func(self, r): + return self.epsilon + r + + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y, function=_func) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_rbf_epsilon_none(): + x = linspace(0, 10, 9) + y = sin(x) + Rbf(x, y, epsilon=None) + + +def test_rbf_epsilon_none_collinear(): + # Check that collinear points in one dimension doesn't cause an error + # due to epsilon = 0 + x = [1, 2, 3] + y = [4, 4, 4] + z = [5, 6, 7] + rbf = Rbf(x, y, z, epsilon=None) + assert rbf.epsilon > 0 + + +def test_rbf_concurrency(): + x = linspace(0, 10, 100) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, mode='N-D') + + def worker_fn(_, interp, xp): + interp(xp) + + _run_concurrent_barrier(10, worker_fn, rbf, x) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rbfinterp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rbfinterp.py new file mode 100644 index 0000000000000000000000000000000000000000..53ac66177124326f7c9653279602758b23734753 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rbfinterp.py @@ -0,0 +1,577 @@ +import pickle +import pytest +import numpy as np +from numpy.linalg import LinAlgError +from scipy._lib._array_api import xp_assert_close, make_xp_test_case +from scipy.stats.qmc import Halton +from scipy.spatial import cKDTree # type: ignore[attr-defined] +from scipy.interpolate._rbfinterp import ( + _AVAILABLE, _SCALE_INVARIANT, _NAME_TO_MIN_DEGREE, RBFInterpolator, + _get_backend + ) +from scipy.interpolate import _rbfinterp_pythran +from scipy._lib._testutils import _run_concurrent_barrier + +skip_xp_backends = pytest.mark.skip_xp_backends + + +def _vandermonde(x, degree, xp=np): + # Returns a matrix of monomials that span polynomials with the specified + # degree evaluated at x. + backend = _get_backend(xp) + powers = backend._monomial_powers(x.shape[1], degree, xp) + return backend.polynomial_matrix(x, powers, xp) + + +def _1d_test_function(x, xp): + # Test function used in Wahba's "Spline Models for Observational Data". + # domain ~= (0, 3), range ~= (-1.0, 0.2) + x = x[:, 0] + y = 4.26*(xp.exp(-x) - 4*xp.exp(-2*x) + 3*xp.exp(-3*x)) + return y + + +def _2d_test_function(x, xp): + # Franke's test function. + # domain ~= (0, 1) X (0, 1), range ~= (0.0, 1.2) + x1, x2 = x[:, 0], x[:, 1] + term1 = 0.75 * xp.exp(-(9*x1-2)**2/4 - (9*x2-2)**2/4) + term2 = 0.75 * xp.exp(-(9*x1+1)**2/49 - (9*x2+1)/10) + term3 = 0.5 * xp.exp(-(9*x1-7)**2/4 - (9*x2-3)**2/4) + term4 = -0.2 * xp.exp(-(9*x1-4)**2 - (9*x2-7)**2) + y = term1 + term2 + term3 + term4 + return y + + +def _is_conditionally_positive_definite(kernel, m): + # Tests whether the kernel is conditionally positive definite of order m. + # See chapter 7 of Fasshauer's "Meshfree Approximation Methods with + # MATLAB". + nx = 10 + ntests = 100 + for ndim in [1, 2, 3, 4, 5]: + # Generate sample points with a Halton sequence to avoid samples that + # are too close to each other, which can make the matrix singular. + seq = Halton(ndim, scramble=False, seed=np.random.RandomState()) + for _ in range(ntests): + x = 2*seq.random(nx) - 1 + A = _rbfinterp_pythran._kernel_matrix(x, kernel) + P = _vandermonde(x, m - 1) + Q, R = np.linalg.qr(P, mode='complete') + # Q2 forms a basis spanning the space where P.T.dot(x) = 0. Project + # A onto this space, and then see if it is positive definite using + # the Cholesky decomposition. If not, then the kernel is not c.p.d. + # of order m. + Q2 = Q[:, P.shape[1]:] + B = Q2.T.dot(A).dot(Q2) + try: + np.linalg.cholesky(B) + except np.linalg.LinAlgError: + return False + + return True + + +# Sorting the parametrize arguments is necessary to avoid a parallelization +# issue described here: https://github.com/pytest-dev/pytest-xdist/issues/432. +@pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) +def test_conditionally_positive_definite(kernel): + # Test if each kernel in _AVAILABLE is conditionally positive definite of + # order m, where m comes from _NAME_TO_MIN_DEGREE. This is a necessary + # condition for the smoothed RBF interpolant to be well-posed in general. + m = _NAME_TO_MIN_DEGREE.get(kernel, -1) + 1 + assert _is_conditionally_positive_definite(kernel, m) + + +class _TestRBFInterpolator: + @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT)) + def test_scale_invariance_1d(self, kernel, xp): + # Verify that the functions in _SCALE_INVARIANT are insensitive to the + # shape parameter (when smoothing == 0) in 1d. + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + x = 3*seq.random(50) + x = xp.asarray(x) + + y = _1d_test_function(x, xp) + xitp = 3*seq.random(50) + xitp = xp.asarray(xitp) + + yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp) + yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp) + xp_assert_close(yitp1, yitp2, atol=1e-8) + + @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT)) + def test_scale_invariance_2d(self, kernel, xp): + # Verify that the functions in _SCALE_INVARIANT are insensitive to the + # shape parameter (when smoothing == 0) in 2d. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + x = seq.random(100) + x = xp.asarray(x) + + y = _2d_test_function(x, xp) + xitp = seq.random(100) + xitp = xp.asarray(xitp) + + yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp) + yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp) + xp_assert_close(yitp1, yitp2, atol=1e-8) + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_extreme_domains(self, kernel, xp): + # Make sure the interpolant remains numerically stable for very + # large/small domains. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + scale = 1e50 + shift = 1e55 + + x = seq.random(100) + x = xp.asarray(x) + + y = _2d_test_function(x, xp) + xitp = seq.random(100) + xitp = xp.asarray(xitp) + + if kernel in _SCALE_INVARIANT: + yitp1 = self.build(x, y, kernel=kernel)(xitp) + yitp2 = self.build( + x*scale + shift, y, + kernel=kernel + )(xitp*scale + shift) + else: + yitp1 = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp) + yitp2 = self.build( + x*scale + shift, y, + epsilon=5.0/scale, + kernel=kernel + )(xitp*scale + shift) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_polynomial_reproduction(self, xp): + # If the observed data comes from a polynomial, then the interpolant + # should be able to reproduce the polynomial exactly, provided that + # `degree` is sufficiently high. + rng = np.random.RandomState(0) + seq = Halton(2, scramble=False, seed=rng) + degree = 3 + + x = seq.random(50) + xitp = seq.random(50) + x = xp.asarray(x) + xitp = xp.asarray(xitp) + + P = _vandermonde(x, degree, xp) + Pitp = _vandermonde(xitp, degree, xp) + + poly_coeffs = rng.normal(0.0, 1.0, P.shape[1]) + poly_coeffs = xp.asarray(poly_coeffs) + + y = P @ poly_coeffs #y = P.dot(poly_coeffs) + yitp1 = Pitp @ poly_coeffs #yitp1 = Pitp.dot(poly_coeffs) + yitp2 = self.build(x, y, degree=degree)(xitp) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + @pytest.mark.slow + def test_chunking(self, monkeypatch, xp): + # If the observed data comes from a polynomial, then the interpolant + # should be able to reproduce the polynomial exactly, provided that + # `degree` is sufficiently high. + rng = np.random.RandomState(0) + seq = Halton(2, scramble=False, seed=rng) + degree = 3 + + largeN = 1000 + 33 + # this is large to check that chunking of the RBFInterpolator is tested + x = seq.random(50) + xitp = seq.random(largeN) + + x = xp.asarray(x) + xitp = xp.asarray(xitp) + + P = _vandermonde(x, degree, xp) + Pitp = _vandermonde(xitp, degree, xp) + + poly_coeffs = rng.normal(0.0, 1.0, P.shape[1]) + poly_coeffs = xp.asarray(poly_coeffs) + + y = P @ poly_coeffs # y = P.dot(poly_coeffs) + yitp1 = Pitp @ poly_coeffs # yitp1 = Pitp.dot(poly_coeffs) + interp = self.build(x, y, degree=degree) + ce_real = interp._chunk_evaluator + + def _chunk_evaluator(*args, **kwargs): + kwargs.update(memory_budget=100) + return ce_real(*args, **kwargs) + + monkeypatch.setattr(interp, '_chunk_evaluator', _chunk_evaluator) + yitp2 = interp(xitp) + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_vector_data(self, xp): + # Make sure interpolating a vector field is the same as interpolating + # each component separately. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + + x = xp.asarray(x) + xitp = xp.asarray(xitp) + + y = xp.stack([_2d_test_function(x, xp), + _2d_test_function(xp.flip(x, axis=1), xp)]).T + + yitp1 = self.build(x, y)(xitp) + yitp2 = self.build(x, y[:, 0])(xitp) + yitp3 = self.build(x, y[:, 1])(xitp) + + xp_assert_close(yitp1[:, 0], yitp2) + xp_assert_close(yitp1[:, 1], yitp3) + + def test_complex_data(self, xp): + # Interpolating complex input should be the same as interpolating the + # real and complex components. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x, np) + 1j*_2d_test_function(x[:, ::-1], np) + + x, xitp, y = map(xp.asarray, (x, xitp, y)) + + yitp1 = self.build(x, y)(xitp) + yitp2 = self.build(x, y.real)(xitp) + yitp3 = self.build(x, y.imag)(xitp) + + xp_assert_close(yitp1.real, yitp2) + xp_assert_close(yitp1.imag, yitp3) + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_interpolation_misfit_1d(self, kernel, xp): + # Make sure that each kernel, with its default `degree` and an + # appropriate `epsilon`, does a good job at interpolation in 1d. + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + + x = xp.asarray(x) + xitp = xp.asarray(xitp) + + y = _1d_test_function(x, xp) + ytrue = _1d_test_function(xitp, xp) + yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp) + + mse = xp.mean((yitp - ytrue)**2) + assert mse < 1.0e-4 + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_interpolation_misfit_2d(self, kernel, xp): + # Make sure that each kernel, with its default `degree` and an + # appropriate `epsilon`, does a good job at interpolation in 2d. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + x = xp.asarray(x) + xitp = xp.asarray(xitp) + + y = _2d_test_function(x, xp) + ytrue = _2d_test_function(xitp, xp) + yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp) + + mse = xp.mean((yitp - ytrue)**2) + assert mse < 2.0e-4 + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_smoothing_misfit(self, kernel, xp): + # Make sure we can find a smoothing parameter for each kernel that + # removes a sufficient amount of noise. + rng = np.random.RandomState(0) + seq = Halton(1, scramble=False, seed=rng) + + noise = 0.2 + rmse_tol = 0.1 + smoothing_range = 10**xp.linspace(-4, 1, 20) + + x = 3*seq.random(100) + y = _1d_test_function(x, np) + rng.normal(0.0, noise, (100,)) + + x = xp.asarray(x) + y = xp.asarray(y) + ytrue = _1d_test_function(x, xp) + rmse_within_tol = False + for smoothing in smoothing_range: + ysmooth = self.build( + x, y, + epsilon=1.0, + smoothing=smoothing, + kernel=kernel)(x) + rmse = xp.sqrt(xp.mean((ysmooth - ytrue)**2)) + if rmse < rmse_tol: + rmse_within_tol = True + break + + assert rmse_within_tol + + def test_array_smoothing(self, xp): + # Test using an array for `smoothing` to give less weight to a known + # outlier. + rng = np.random.RandomState(0) + seq = Halton(1, scramble=False, seed=rng) + degree = 2 + + x = seq.random(50) + P = _vandermonde(x, degree) + poly_coeffs = rng.normal(0.0, 1.0, P.shape[1]) + y = P @ poly_coeffs # y = P.dot(poly_coeffs) + + y_with_outlier = y.copy() + y_with_outlier[10] += 1.0 + smoothing = np.zeros((50,)) + smoothing[10] = 1000.0 + + x, P, poly_coeffs, y = map(xp.asarray, (x, P, poly_coeffs, y)) + y_with_outlier, smoothing = map(xp.asarray, (y_with_outlier, smoothing)) + + yitp = self.build(x, y_with_outlier, smoothing=smoothing)(x) + # Should be able to reproduce the uncorrupted data almost exactly. + xp_assert_close(yitp, y, atol=1e-4) + + def test_inconsistent_x_dimensions_error(self): + # ValueError should be raised if the observation points and evaluation + # points have a different number of dimensions. + y = Halton(2, scramble=False, seed=np.random.RandomState()).random(10) + d = _2d_test_function(y, np) + x = Halton(1, scramble=False, seed=np.random.RandomState()).random(10) + match = 'Expected the second axis of `x`' + with pytest.raises(ValueError, match=match): + self.build(y, d)(x) + + def test_inconsistent_d_length_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(1) + match = 'Expected the first axis of `d`' + with pytest.raises(ValueError, match=match): + self.build(y, d) + + def test_y_not_2d_error(self): + y = np.linspace(0, 1, 5) + d = np.zeros(5) + match = '`y` must be a 2-dimensional array.' + with pytest.raises(ValueError, match=match): + self.build(y, d) + + def test_inconsistent_smoothing_length_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + smoothing = np.ones(1) + match = 'Expected `smoothing` to be' + with pytest.raises(ValueError, match=match): + self.build(y, d, smoothing=smoothing) + + def test_invalid_kernel_name_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + match = '`kernel` must be one of' + with pytest.raises(ValueError, match=match): + self.build(y, d, kernel='test') + + def test_epsilon_not_specified_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + for kernel in _AVAILABLE: + if kernel in _SCALE_INVARIANT: + continue + + match = '`epsilon` must be specified' + with pytest.raises(ValueError, match=match): + self.build(y, d, kernel=kernel) + + def test_x_not_2d_error(self): + y = np.linspace(0, 1, 5)[:, None] + x = np.linspace(0, 1, 5) + d = np.zeros(5) + match = '`x` must be a 2-dimensional array.' + with pytest.raises(ValueError, match=match): + self.build(y, d)(x) + + def test_not_enough_observations_error(self): + y = np.linspace(0, 1, 1)[:, None] + d = np.zeros(1) + match = 'At least 2 data points are required' + with pytest.raises(ValueError, match=match): + self.build(y, d, kernel='thin_plate_spline') + + def test_degree_warning(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + for kernel, deg in _NAME_TO_MIN_DEGREE.items(): + # Only test for kernels that its minimum degree is not 0. + if deg >= 1: + match = f'`degree` should not be below {deg}' + with pytest.warns(Warning, match=match): + self.build(y, d, epsilon=1.0, kernel=kernel, degree=deg-1) + + def test_minus_one_degree(self): + # Make sure a degree of -1 is accepted without any warning. + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + for kernel, _ in _NAME_TO_MIN_DEGREE.items(): + self.build(y, d, epsilon=1.0, kernel=kernel, degree=-1) + + @skip_xp_backends("jax.numpy", reason="solve raises no error for a singular matrix") + @skip_xp_backends("cupy", reason="solve raises no error for a singular matrix") + def test_rank_error(self, xp): + # An error should be raised when `kernel` is "thin_plate_spline" and + # observations are 2-D and collinear. + y = xp.asarray([[2.0, 0.0], [1.0, 0.0], [0.0, 0.0]]) + d = xp.asarray([0.0, 0.0, 0.0]) + match = 'does not have full column rank' + with pytest.raises(LinAlgError, match=match): + self.build(y, d, kernel='thin_plate_spline')(y) + + def test_single_point(self, xp): + # Make sure interpolation still works with only one point (in 1, 2, and + # 3 dimensions). + for dim in [1, 2, 3]: + y = xp.zeros((1, dim)) + d = xp.ones((1,), dtype=xp.float64) + f = self.build(y, d, kernel='linear')(y) + xp_assert_close(f, d) + + def test_pickleable(self, xp): + # Make sure we can pickle and unpickle the interpolant without any + # changes in the behavior. + seq = Halton(1, scramble=False, seed=np.random.RandomState(2305982309)) + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + x, xitp = xp.asarray(x), xp.asarray(xitp) + + y = _1d_test_function(x, xp) + + interp = self.build(x, y) + + yitp1 = interp(xitp) + yitp2 = pickle.loads(pickle.dumps(interp))(xitp) + + xp_assert_close(yitp1, yitp2, atol=1e-16) + + +@make_xp_test_case(RBFInterpolator) +class TestRBFInterpolatorNeighborsNone(_TestRBFInterpolator): + def build(self, *args, **kwargs): + return RBFInterpolator(*args, **kwargs) + + def test_smoothing_limit_1d(self): + # For large smoothing parameters, the interpolant should approach a + # least squares fit of a polynomial with the specified degree. + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + + degree = 3 + smoothing = 1e8 + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + y = _1d_test_function(x, np) + + yitp1 = self.build( + x, y, + degree=degree, + smoothing=smoothing + )(xitp) + + P = _vandermonde(x, degree) + Pitp = _vandermonde(xitp, degree) + yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0]) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_smoothing_limit_2d(self): + # For large smoothing parameters, the interpolant should approach a + # least squares fit of a polynomial with the specified degree. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + degree = 3 + smoothing = 1e8 + + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x, np) + + yitp1 = self.build( + x, y, + degree=degree, + smoothing=smoothing + )(xitp) + + P = _vandermonde(x, degree) + Pitp = _vandermonde(xitp, degree) + yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0]) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + +@skip_xp_backends(np_only=True, reason="neighbors not None uses KDTree") +class TestRBFInterpolatorNeighbors20(_TestRBFInterpolator): + # RBFInterpolator using 20 nearest neighbors. + def build(self, *args, **kwargs): + return RBFInterpolator(*args, **kwargs, neighbors=20) + + def test_equivalent_to_rbf_interpolator(self): + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x, np) + + yitp1 = self.build(x, y)(xitp) + + yitp2 = [] + tree = cKDTree(x) + for xi in xitp: + _, nbr = tree.query(xi, 20) + yitp2.append(RBFInterpolator(x[nbr], y[nbr])(xi[None])[0]) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to + # RbfInterpolator + seq = Halton(2, scramble=False, seed=np.random.RandomState(0)) + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x, np) + + interp = self.build(x, y) + + def worker_fn(_, interp, xp): + interp(xp) + + _run_concurrent_barrier(10, worker_fn, interp, xitp) + + +@skip_xp_backends(np_only=True, reason="neighbors not None uses KDTree") +class TestRBFInterpolatorNeighborsInf(TestRBFInterpolatorNeighborsNone): + # RBFInterpolator using neighbors=np.inf. This should give exactly the same + # results as neighbors=None, but it will be slower. + def build(self, *args, **kwargs): + return RBFInterpolator(*args, **kwargs, neighbors=np.inf) + + def test_equivalent_to_rbf_interpolator(self): + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + + y = _1d_test_function(x, np) + yitp1 = self.build(x, y)(xitp) + yitp2 = RBFInterpolator(x, y)(xitp) + + xp_assert_close(yitp1, yitp2, atol=1e-8) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rgi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rgi.py new file mode 100644 index 0000000000000000000000000000000000000000..919393d02e371ac51f555e74708f8b617a2b98c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/interpolate/tests/test_rgi.py @@ -0,0 +1,1233 @@ +import itertools + +import pytest +import numpy as np + +from numpy.exceptions import ComplexWarning + +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_array_almost_equal, + make_xp_test_case +) +from scipy.conftest import skip_xp_invalid_arg + +from pytest import raises as assert_raises + +from scipy.interpolate import (RegularGridInterpolator, interpn, + RectBivariateSpline, + NearestNDInterpolator, LinearNDInterpolator) + +from scipy.sparse._sputils import matrix +from scipy._lib._testutils import _run_concurrent_barrier + + +parametrize_rgi_interp_methods = pytest.mark.parametrize( + "method", RegularGridInterpolator._ALL_METHODS +) + +@make_xp_test_case(RegularGridInterpolator) +class TestRegularGridInterpolator: + def _get_sample_4d(self, xp): + # create a 4-D grid of 3 points in each dimension + points = [(0., .5, 1.)] * 4 + values = xp.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def _get_sample_4d_2(self, xp): + # create another 4-D grid of 3 points in each dimension + points = [(0., .5, 1.)] * 2 + [(0., 5., 10.)] * 2 + values = xp.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def _get_sample_4d_3(self, xp): + # create another 4-D grid of 7 points in each dimension + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0)] * 4 + values = xp.asarray([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def _get_sample_4d_4(self, xp): + # create another 4-D grid of 2 points in each dimension + points = [(0.0, 1.0)] * 4 + values = xp.asarray([0.0, 1.0]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + @parametrize_rgi_interp_methods + def test_list_input(self, method): + points, values = self._get_sample_4d_3(xp=np) + + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + + interp = RegularGridInterpolator(points, + values.tolist(), + method=method) + v1 = interp(sample.tolist()) + interp = RegularGridInterpolator(points, + values, + method=method) + v2 = interp(sample) + xp_assert_close(v1, v2) + + @pytest.mark.parametrize('method', ['cubic', 'quintic', 'pchip']) + def test_spline_dim_error(self, method, xp): + points, values = self._get_sample_4d_4(xp) + points = list(xp.asarray(p) for p in points) + match = "points in dimension" + + # Check error raise when creating interpolator + with pytest.raises(ValueError, match=match): + RegularGridInterpolator(points, values, method=method) + + # Check error raise when creating interpolator + interp = RegularGridInterpolator(points, values) + sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + with pytest.raises(ValueError, match=match): + interp(sample, method=method) + + @pytest.mark.parametrize( + "points_values, sample", + [ + ( + _get_sample_4d, + np.asarray( + [[0.1, 0.1, 1.0, 0.9], + [0.2, 0.1, 0.45, 0.8], + [0.5, 0.5, 0.5, 0.5]] + ), + ), + (_get_sample_4d_2, np.asarray([0.1, 0.1, 10.0, 9.0])), + ], + ) + def test_linear_and_slinear_close(self, points_values, sample, xp): + points, values = points_values(self, xp) + points, sample = list(xp.asarray(p) for p in points), xp.asarray(sample) + interp = RegularGridInterpolator(points, values, method="linear") + v1 = interp(sample) + interp = RegularGridInterpolator(points, values, method="slinear") + v2 = interp(sample) + xp_assert_close(v1, v2) + + def test_derivatives(self, xp): + points, values = self._get_sample_4d(xp) + points = list(xp.asarray(p) for p in points) + sample = xp.asarray([[0.1 , 0.1 , 1. , 0.9 ], + [0.2 , 0.1 , 0.45, 0.8 ], + [0.5 , 0.5 , 0.5 , 0.5 ]]) + interp = RegularGridInterpolator(points, values, method="slinear") + + with assert_raises(ValueError): + # wrong number of derivatives (need 4) + interp(sample, nu=1) + + xp_assert_close(interp(sample, nu=(1, 0, 0, 0)), + xp.asarray([1.0, 1, 1], dtype=xp.float64), atol=1e-15) + xp_assert_close(interp(sample, nu=(0, 1, 0, 0)), + xp.asarray([10.0, 10, 10], dtype=xp.float64), atol=1e-15) + + # 2nd derivatives of a linear function are zero + xp_assert_close(interp(sample, nu=(0, 1, 1, 0)), + xp.asarray([0.0, 0, 0], dtype=xp.float64), atol=2e-12) + + @parametrize_rgi_interp_methods + def test_complex(self, method, xp): + if method == "pchip": + pytest.skip("pchip does not make sense for complex data") + points, values = self._get_sample_4d_3(xp) + points = list(xp.asarray(p) for p in points) + values = values - 2j*values + sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + + interp = RegularGridInterpolator(points, values, method=method) + rinterp = RegularGridInterpolator(points, xp.real(values), method=method) + iinterp = RegularGridInterpolator(points, xp.imag(values), method=method) + + v1 = interp(sample) + v2 = rinterp(sample) + 1j*iinterp(sample) + xp_assert_close(v1, v2) + + def test_cubic_vs_pchip(self, xp): + x, y = xp.asarray([1, 2, 3, 4]), xp.asarray([1, 2, 3, 4]) + xg, yg = xp.meshgrid(x, y, indexing='ij') + + values = (lambda x, y: x**4 * y**4)(xg, yg) + cubic = RegularGridInterpolator((x, y), values, method='cubic') + pchip = RegularGridInterpolator((x, y), values, method='pchip') + + vals_cubic = cubic([1.5, 2]) + vals_pchip = pchip([1.5, 2]) + #assert not np.allclose(vals_cubic, vals_pchip, atol=1e-14, rtol=0) + assert not xp.all(xp.abs(vals_cubic - vals_pchip) < 1e-14) + + def test_linear_xi1d(self, xp): + points, values = self._get_sample_4d_2(xp) + points = list(xp.asarray(p) for p in points) + interp = RegularGridInterpolator(points, values) + sample = xp.asarray([0.1, 0.1, 10., 9.]) + wanted = xp.asarray([1001.1], dtype=xp.float64) + assert_array_almost_equal(interp(sample), wanted) + + def test_linear_xi3d(self, xp): + points, values = self._get_sample_4d(xp) + points = list(xp.asarray(p) for p in points) + interp = RegularGridInterpolator(points, values) + sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + wanted = xp.asarray([1001.1, 846.2, 555.5]) + assert_array_almost_equal(interp(sample), wanted) + + @pytest.mark.parametrize( + "sample, wanted", + [ + ([0.1, 0.1, 0.9, 0.9], 1100.0), + ([0.1, 0.1, 0.1, 0.1], 0.0), + ([0.0, 0.0, 0.0, 0.0], 0.0), + ([1.0, 1.0, 1.0, 1.0], 1111.0), + ([0.1, 0.4, 0.6, 0.9], 1055.0), + ], + ) + def test_nearest(self, sample, wanted, xp): + points, values = self._get_sample_4d(xp) + points, sample = tuple(xp.asarray(p) for p in points), xp.asarray(sample) + interp = RegularGridInterpolator(points, values, method="nearest") + wanted = xp.asarray([wanted], dtype=xp.float64) + assert_array_almost_equal(interp(sample), wanted) + + def test_linear_edges(self, xp): + points, values = self._get_sample_4d(xp) + points = list(xp.asarray(p) for p in points) + interp = RegularGridInterpolator(points, values) + sample = xp.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]]) + wanted = xp.asarray([0., 1111.]) + assert_array_almost_equal(interp(sample), wanted) + + def test_valid_create(self): + # create a 2-D grid of 3 points in each dimension + points = [(0., .5, 1.), (0., 1., .5)] + values = np.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis] + values1 = values[np.newaxis, :] + values = (values0 + values1 * 10) + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [((0., .5, 1.), ), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [(0., .5, .75, 1.), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [(0., .5, 1.), (0., .5, 1.), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [(0., .5, 1.), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values, + method="undefmethod") + + def test_valid_call(self, xp): + points, values = self._get_sample_4d(xp) + points = list(xp.asarray(p) for p in points) + interp = RegularGridInterpolator(points, values) + sample = xp.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]]) + with assert_raises(ValueError): + interp(sample, "undefmethod") + + sample = xp.asarray([[0., 0., 0.], [1., 1., 1.]]) + with assert_raises(ValueError): + interp(sample) + + sample = xp.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.1]]) + with assert_raises(ValueError): + interp(sample) + + def test_out_of_bounds_extrap(self, xp): + points, values = self._get_sample_4d(xp) + points = list(xp.asarray(p) for p in points) + interp = RegularGridInterpolator(points, values, bounds_error=False, + fill_value=None) + sample = xp.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1], + [21, 2.1, -1.1, -11], [2.1, 2.1, -1.1, -1.1]], + dtype=xp.float64) + wanted = xp.asarray([0., 1111., 11., 11.], dtype=xp.float64) + assert_array_almost_equal(interp(sample, method="nearest"), wanted) + wanted = xp.asarray([-111.1, 1222.1, -11068., -1186.9], dtype=xp.float64) + assert_array_almost_equal(interp(sample, method="linear"), wanted) + + def test_out_of_bounds_extrap2(self, xp): + points, values = self._get_sample_4d_2(xp) + points = list(xp.asarray(p) for p in points) + interp = RegularGridInterpolator(points, values, bounds_error=False, + fill_value=None) + sample = xp.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1], + [21, 2.1, -1.1, -11], [2.1, 2.1, -1.1, -1.1]], + dtype=xp.float64) + wanted = xp.asarray([0., 11., 11., 11.], dtype=xp.float64) + assert_array_almost_equal(interp(sample, method="nearest"), wanted) + wanted = xp.asarray([-12.1, 133.1, -1069., -97.9], dtype=xp.float64) + assert_array_almost_equal(interp(sample, method="linear"), wanted) + + def test_out_of_bounds_fill(self, xp): + points, values = self._get_sample_4d(xp) + points = list(xp.asarray(p) for p in points) + interp = RegularGridInterpolator(points, values, bounds_error=False, + fill_value=xp.nan) + sample = xp.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1], + [2.1, 2.1, -1.1, -1.1]]) + wanted = xp.asarray([xp.nan, xp.nan, xp.nan]) + assert_array_almost_equal(interp(sample, method="nearest"), wanted) + assert_array_almost_equal(interp(sample, method="linear"), wanted) + sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + wanted = xp.asarray([1001.1, 846.2, 555.5]) + assert_array_almost_equal(interp(sample), wanted) + + def test_nearest_compare_qhull(self): + points, values = self._get_sample_4d(np) + interp = RegularGridInterpolator(points, values, method="nearest") + points_qhull = itertools.product(*points) + points_qhull = [p for p in points_qhull] + points_qhull = np.asarray(points_qhull) + values_qhull = values.reshape(-1) + interp_qhull = NearestNDInterpolator(points_qhull, values_qhull) + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + assert_array_almost_equal(interp(sample), interp_qhull(sample)) + + def test_linear_compare_qhull(self): + points, values = self._get_sample_4d(np) + interp = RegularGridInterpolator(points, values) + points_qhull = itertools.product(*points) + points_qhull = [p for p in points_qhull] + points_qhull = np.asarray(points_qhull) + values_qhull = values.reshape(-1) + interp_qhull = LinearNDInterpolator(points_qhull, values_qhull) + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + assert_array_almost_equal(interp(sample), interp_qhull(sample)) + + @pytest.mark.parametrize("method", ["nearest", "linear"]) + def test_duck_typed_values(self, method): + x = np.linspace(0, 2, 5) + y = np.linspace(0, 1, 7) + + values = MyValue((5, 7)) + + interp = RegularGridInterpolator((x, y), values, method=method) + v1 = interp([0.4, 0.7]) + + interp = RegularGridInterpolator((x, y), values._v, method=method) + v2 = interp([0.4, 0.7]) + xp_assert_close(v1, v2, check_dtype=False) + + def test_invalid_fill_value(self): + np.random.seed(1234) + x = np.linspace(0, 2, 5) + y = np.linspace(0, 1, 7) + values = np.random.rand(5, 7) + + # integers can be cast to floats + RegularGridInterpolator((x, y), values, fill_value=1) + + # complex values cannot + assert_raises(ValueError, RegularGridInterpolator, + (x, y), values, fill_value=1+2j) + + def test_fillvalue_type(self): + # from #3703; test that interpolator object construction succeeds + values = np.ones((10, 20, 30), dtype='>f4') + points = [np.arange(n) for n in values.shape] + # xi = [(1, 1, 1)] + RegularGridInterpolator(points, values) + RegularGridInterpolator(points, values, fill_value=0.) + + @pytest.mark.parametrize("dtype", [np.float32, np.float64]) + @pytest.mark.parametrize("ndim", [1, 2, 3]) + @pytest.mark.parametrize("method", ["linear", "nearest"]) + def test_length_one_axis_all(self, dtype, ndim, method): + # gh-23171: length-1 axes in all dimensions are legal + # for all methods parametrized above. + + # Construct test point 'x0' with coordinates[0, 1, ..., ndim-1]. + # NOTE: choice of coordinates is arbitrary, could be random numbers, + # but using np.arange for convenience. + x0 = np.arange(ndim, dtype=dtype) + + # Unpack 'x0'; loosly speaking this is the inverse of np.mgrid. + # By construction 'points' defines a grid of length one along all axes. + points = tuple(np.asarray([xi]) for xi in x0) + + # Construct 'values' array of dimensions (1, 1, ...) from 0D 'val'. + val = np.asarray(1/7, dtype=dtype) + values = np.full(shape=(1, )*ndim, fill_value=val) + + # Fill value, as a 0D array of correct dtype. + fill = np.asarray(1/42, dtype=dtype) + + # method "linear" promotes results to np.float64 + promoted_dtype = np.float64 if method == "linear" else dtype + + # Create interpolator instances, with and without 'bounds_error' check. + interp_fill = RegularGridInterpolator( + points, values, method=method, bounds_error=False, fill_value=fill + ) + interp_err = RegularGridInterpolator( + points, values, method=method, bounds_error=True, + ) + + # Check interpolator returns correct value for valid sample. + sample = np.asarray([x0]) + wanted = np.asarray([val], dtype=promoted_dtype) + for result in [interp_fill(sample), interp_err(sample)]: + xp_assert_equal(result, wanted) + + # Check out of bound point along first direction. + x0[0] += 1 + sample = np.asarray([x0]) + wanted = np.asarray([fill], dtype=promoted_dtype) + result = interp_fill(sample) + xp_assert_equal(result, wanted) + with pytest.raises( + ValueError, + match="^One of the requested xi is out of bounds in dimension 0$", + ): + interp_err(sample) + + # check point with NaN in first direction + x0[0] = np.nan + sample = np.asarray([x0]) + wanted = np.asarray([np.nan], dtype=promoted_dtype) + result = interp_fill(sample) + xp_assert_equal(result, wanted) + with pytest.raises( + ValueError, + match="^One of the requested xi is out of bounds in dimension 0$", + ): + interp_err(sample) + + def test_length_one_axis(self): + # gh-5890, gh-9524 : length-1 axis is legal for method='linear'. + # Along the axis it's linear interpolation; away from the length-1 + # axis, it's an extrapolation, so fill_value should be used. + def f(x, y): + return x + y + x = np.linspace(1, 1, 1) + y = np.linspace(1, 10, 10) + data = f(*np.meshgrid(x, y, indexing="ij", sparse=True)) + + interp = RegularGridInterpolator((x, y), data, method="linear", + bounds_error=False, fill_value=101) + + # check values at the grid + xp_assert_close(interp(np.array([[1, 1], [1, 5], [1, 10]])), + np.asarray([2.0, 6, 11]), + atol=1e-14) + + # check off-grid interpolation is indeed linear + xp_assert_close(interp(np.array([[1, 1.4], [1, 5.3], [1, 10]])), + [2.4, 6.3, 11], + atol=1e-14) + + # check exrapolation w/ fill_value + xp_assert_close(interp(np.array([1.1, 2.4])), + interp.fill_value, + check_dtype=False, check_shape=False, check_0d=False, + atol=1e-14) + + # check extrapolation: linear along the `y` axis, const along `x` + interp.fill_value = None + xp_assert_close(interp([[1, 0.3], [1, 11.5]]), + [1.3, 12.5], atol=1e-15) + + xp_assert_close(interp([[1.5, 0.3], [1.9, 11.5]]), + [1.3, 12.5], atol=1e-15) + + # extrapolation with method='nearest' + interp = RegularGridInterpolator((x, y), data, method="nearest", + bounds_error=False, fill_value=None) + xp_assert_close(interp([[1.5, 1.8], [-4, 5.1]]), + np.asarray([3.0, 6]), + atol=1e-15) + + @pytest.mark.parametrize("fill_value", [None, np.nan, np.pi]) + @pytest.mark.parametrize("method", ['linear', 'nearest']) + def test_length_one_axis2(self, fill_value, method): + options = {"fill_value": fill_value, "bounds_error": False, + "method": method} + + x = np.linspace(0, 2*np.pi, 20) + z = np.sin(x) + + fa = RegularGridInterpolator((x,), z[:], **options) + fb = RegularGridInterpolator((x, [0]), z[:, None], **options) + + x1a = np.linspace(-1, 2*np.pi+1, 100) + za = fa(x1a) + + # evaluated at provided y-value, fb should behave exactly as fa + y1b = np.zeros(100) + zb = fb(np.vstack([x1a, y1b]).T) + xp_assert_close(zb, za) + + # evaluated at a different y-value, fb should return fill value + y1b = np.ones(100) + zb = fb(np.vstack([x1a, y1b]).T) + if fill_value is None: + xp_assert_close(zb, za) + else: + xp_assert_close(zb, np.full_like(zb, fill_value)) + + @pytest.mark.parametrize("method", ['nearest', 'linear']) + def test_nan_x_1d(self, method): + # gh-6624 : if x is nan, result should be nan + f = RegularGridInterpolator(([1, 2, 3],), [10, 20, 30], fill_value=1, + bounds_error=False, method=method) + assert np.isnan(f([np.nan])) + + # test arbitrary nan pattern + rng = np.random.default_rng(8143215468) + x = rng.random(size=100)*4 + i = rng.random(size=100) > 0.5 + x[i] = np.nan + with np.errstate(invalid='ignore'): + # out-of-bounds comparisons, `out_of_bounds += x < grid[0]`, + # generate numpy warnings if `x` contains nans. + # These warnings should propagate to user (since `x` is user + # input) and we simply filter them out. + res = f(x) + + assert np.isnan(res[i]).all() + xp_assert_equal(res[~i], f(x[~i])) + + # also test the length-one axis f(nan) + x = [1, 2, 3] + y = [1, ] + data = np.ones((3, 1)) + f = RegularGridInterpolator((x, y), data, fill_value=1, + bounds_error=False, method=method) + assert np.all(np.isnan(f([np.nan, 1]))) + assert np.all(np.isnan(f([1, np.nan]))) + + @pytest.mark.parametrize("method", ['nearest', 'linear']) + def test_nan_x_2d(self, method): + x, y = np.array([0, 1, 2]), np.array([1, 3, 7]) + + def f(x, y): + return x**2 + y**2 + + xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True) + data = f(xg, yg) + interp = RegularGridInterpolator((x, y), data, + method=method, bounds_error=False) + + with np.errstate(invalid='ignore'): + res = interp([[1.5, np.nan], [1, 1]]) + xp_assert_close(res[1], 2.0, atol=1e-14) + assert np.isnan(res[0]) + + # test arbitrary nan pattern + rng = np.random.default_rng(8143215468) + x = rng.random(size=100)*4-1 + y = rng.random(size=100)*8 + i1 = rng.random(size=100) > 0.5 + i2 = rng.random(size=100) > 0.5 + i = i1 | i2 + x[i1] = np.nan + y[i2] = np.nan + z = np.array([x, y]).T + with np.errstate(invalid='ignore'): + # out-of-bounds comparisons, `out_of_bounds += x < grid[0]`, + # generate numpy warnings if `x` contains nans. + # These warnings should propagate to user (since `x` is user + # input) and we simply filter them out. + res = interp(z) + + assert np.isnan(res[i]).all() + xp_assert_equal(res[~i], interp(z[~i]), check_dtype=False) + + @pytest.mark.fail_slow(10) + @parametrize_rgi_interp_methods + @pytest.mark.parametrize(("ndims", "func"), [ + (2, lambda x, y: 2 * x ** 3 + 3 * y ** 2), + (3, lambda x, y, z: 2 * x ** 3 + 3 * y ** 2 - z), + (4, lambda x, y, z, a: 2 * x ** 3 + 3 * y ** 2 - z + a), + (5, lambda x, y, z, a, b: 2 * x ** 3 + 3 * y ** 2 - z + a * b), + ]) + def test_descending_points_nd(self, method, ndims, func): + + if ndims >= 4 and method in {"cubic", "quintic"}: + pytest.skip("too slow; OOM (quintic); or nearly so (cubic)") + + rng = np.random.default_rng(42) + sample_low = 1 + sample_high = 5 + test_points = rng.uniform(sample_low, sample_high, size=(2, ndims)) + + ascending_points = [np.linspace(sample_low, sample_high, 12) + for _ in range(ndims)] + + ascending_values = func(*np.meshgrid(*ascending_points, + indexing="ij", + sparse=True)) + + ascending_interp = RegularGridInterpolator(ascending_points, + ascending_values, + method=method) + ascending_result = ascending_interp(test_points) + + descending_points = [xi[::-1] for xi in ascending_points] + descending_values = func(*np.meshgrid(*descending_points, + indexing="ij", + sparse=True)) + descending_interp = RegularGridInterpolator(descending_points, + descending_values, + method=method) + descending_result = descending_interp(test_points) + + xp_assert_equal(ascending_result, descending_result) + + def test_invalid_points_order(self): + def val_func_2d(x, y): + return 2 * x ** 3 + 3 * y ** 2 + + x = np.array([.5, 2., 0., 4., 5.5]) # not ascending or descending + y = np.array([.5, 2., 3., 4., 5.5]) + points = (x, y) + values = val_func_2d(*np.meshgrid(*points, indexing='ij', + sparse=True)) + match = "must be strictly ascending or descending" + with pytest.raises(ValueError, match=match): + RegularGridInterpolator(points, values) + + @parametrize_rgi_interp_methods + def test_fill_value(self, method): + interp = RegularGridInterpolator([np.arange(6)], np.ones(6), + method=method, bounds_error=False) + assert np.isnan(interp([10])) + + @pytest.mark.fail_slow(5) + @parametrize_rgi_interp_methods + def test_nonscalar_values(self, method): + + if method == "quintic": + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also works + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5)] * 2 + [ + (0.0, 5.0, 10.0, 15.0, 20, 25.0) + ] * 2 + + rng = np.random.default_rng(1234) + values = rng.random((6, 6, 6, 6, 8)) + sample = rng.random((7, 3, 4)) + + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=False) + v = interp(sample) + assert v.shape == (7, 3, 8), method + + vs = [] + for j in range(8): + interp = RegularGridInterpolator(points, values[..., j], + method=method, + bounds_error=False) + vs.append(interp(sample)) + v2 = np.array(vs).transpose(1, 2, 0) + + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + @parametrize_rgi_interp_methods + @pytest.mark.parametrize("flip_points", [False, True]) + def test_nonscalar_values_2(self, method, flip_points): + + if method in {"cubic", "quintic"}: + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also work : use different + # lengths of axes to simplify tracing the internals + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5), + (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0, 47)] + + # verify, that strictly decreasing dimensions work + if flip_points: + points = [tuple(reversed(p)) for p in points] + + rng = np.random.default_rng(1234) + + trailing_points = (3, 2) + # NB: values has a `num_trailing_dims` trailing dimension + values = rng.random((6, 7, 8, 9, *trailing_points)) + sample = rng.random(4) # a single sample point ! + + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=False) + v = interp(sample) + + # v has a single sample point *per entry in the trailing dimensions* + assert v.shape == (1, *trailing_points) + + # check the values, too : manually loop over the trailing dimensions + vs = np.empty(values.shape[-2:]) + for i in range(values.shape[-2]): + for j in range(values.shape[-1]): + interp = RegularGridInterpolator(points, values[..., i, j], + method=method, + bounds_error=False) + vs[i, j] = interp(sample).item() + v2 = np.expand_dims(vs, axis=0) + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + def test_nonscalar_values_linear_2D(self): + # Verify that non-scalar values work in the 2D fast path + method = 'linear' + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5), + (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), ] + + rng = np.random.default_rng(1234) + + trailing_points = (3, 4) + # NB: values has a `num_trailing_dims` trailing dimension + values = rng.random((6, 7, *trailing_points)) + sample = rng.random(2) # a single sample point ! + + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=False) + v = interp(sample) + + # v has a single sample point *per entry in the trailing dimensions* + assert v.shape == (1, *trailing_points) + + # check the values, too : manually loop over the trailing dimensions + vs = np.empty(values.shape[-2:]) + for i in range(values.shape[-2]): + for j in range(values.shape[-1]): + interp = RegularGridInterpolator(points, values[..., i, j], + method=method, + bounds_error=False) + vs[i, j] = interp(sample).item() + v2 = np.expand_dims(vs, axis=0) + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + @pytest.mark.parametrize( + "dtype", + [np.float32, np.float64, np.complex64, np.complex128] + ) + @pytest.mark.parametrize("xi_dtype", [np.float32, np.float64]) + def test_float32_values(self, dtype, xi_dtype): + # regression test for gh-17718: values.dtype=float32 fails + def f(x, y): + return 2 * x**3 + 3 * y**2 + + x = np.linspace(1, 4, 11) + y = np.linspace(4, 7, 22) + + xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True) + data = f(xg, yg) + + data = data.astype(dtype) + + interp = RegularGridInterpolator((x, y), data) + + pts = np.array([[2.1, 6.2], + [3.3, 5.2]], dtype=xi_dtype) + + # the values here are just what the call returns; the test checks that + # that the call succeeds at all, instead of failing with cython not + # having a float32 kernel + xp_assert_close(interp(pts), [134.10469388, 153.40069388], + atol=1e-7, rtol=1e-7, check_dtype=False) + + def test_bad_solver(self): + x = np.linspace(0, 3, 7) + y = np.linspace(0, 3, 7) + xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True) + data = xg + yg + + # default method 'linear' does not accept 'solver' + with assert_raises(ValueError): + RegularGridInterpolator((x, y), data, solver=lambda x: x) + + with assert_raises(TypeError): + # wrong solver interface + RegularGridInterpolator( + (x, y), data, method='slinear', solver=lambda x: x + ) + + with assert_raises(TypeError): + # unknown argument + RegularGridInterpolator( + (x, y), data, method='slinear', solver=lambda x: x, woof='woof' + ) + + with assert_raises(TypeError): + # unknown argument + RegularGridInterpolator( + (x, y), data, method='slinear', solver_args={'woof': 42} + ) + + def test_concurrency(self): + points, values = self._get_sample_4d(np) + sample = np.array([[0.1 , 0.1 , 1. , 0.9 ], + [0.2 , 0.1 , 0.45, 0.8 ], + [0.5 , 0.5 , 0.5 , 0.5 ], + [0.3 , 0.1 , 0.2 , 0.4 ]]) + interp = RegularGridInterpolator(points, values, method="slinear") + + # A call to RGI with a method different from the one specified on the + # constructor, should not mutate it. + methods = ['slinear', 'nearest'] + def worker_fn(tid, interp): + spline = interp._spline + method = methods[tid % 2] + interp(sample, method=method) + assert interp._spline is spline + + _run_concurrent_barrier(10, worker_fn, interp) + + +class MyValue: + """ + Minimal indexable object + """ + + def __init__(self, shape): + self.ndim = 2 + self.shape = shape + self._v = np.arange(np.prod(shape)).reshape(shape) + + def __getitem__(self, idx): + return self._v[idx] + + def __array_interface__(self): + return None + + def __array__(self, dtype=None, copy=None): + raise RuntimeError("No array representation") + + +class TestInterpN: + def _sample_2d_data(self): + x = np.array([.5, 2., 3., 4., 5.5, 6.]) + y = np.array([.5, 2., 3., 4., 5.5, 6.]) + z = np.array( + [ + [1, 2, 1, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 3, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + ] + ) + return x, y, z + + def test_spline_2d(self): + x, y, z = self._sample_2d_data() + lut = RectBivariateSpline(x, y, z) + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + assert_array_almost_equal(interpn((x, y), z, xi, method="splinef2d"), + lut.ev(xi[:, 0], xi[:, 1])) + + @parametrize_rgi_interp_methods + def test_list_input(self, method): + x, y, z = self._sample_2d_data() + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + v1 = interpn((x, y), z, xi, method=method) + v2 = interpn( + (x.tolist(), y.tolist()), z.tolist(), xi.tolist(), method=method + ) + xp_assert_close(v1, v2, err_msg=method) + + def test_spline_2d_outofbounds(self): + x = np.array([.5, 2., 3., 4., 5.5]) + y = np.array([.5, 2., 3., 4., 5.5]) + z = np.array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + lut = RectBivariateSpline(x, y, z) + + xi = np.array([[1, 2.3, 6.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, -4.0, 5.0, 1.0, 3]]).T + actual = interpn((x, y), z, xi, method="splinef2d", + bounds_error=False, fill_value=999.99) + expected = lut.ev(xi[:, 0], xi[:, 1]) + expected[2:4] = 999.99 + assert_array_almost_equal(actual, expected) + + # no extrapolation for splinef2d + assert_raises(ValueError, interpn, (x, y), z, xi, method="splinef2d", + bounds_error=False, fill_value=None) + + def _sample_4d_data(self): + points = [(0., .5, 1.)] * 2 + [(0., 5., 10.)] * 2 + values = np.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def test_linear_4d(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + interp_rg = RegularGridInterpolator(points, values) + sample = np.asarray([[0.1, 0.1, 10., 9.]]) + wanted = interpn(points, values, sample, method="linear") + assert_array_almost_equal(interp_rg(sample), wanted) + + def test_4d_linear_outofbounds(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + sample = np.asarray([[0.1, -0.1, 10.1, 9.]]) + wanted = np.asarray([999.99]) + actual = interpn(points, values, sample, method="linear", + bounds_error=False, fill_value=999.99) + assert_array_almost_equal(actual, wanted) + + def test_nearest_4d(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + interp_rg = RegularGridInterpolator(points, values, method="nearest") + sample = np.asarray([[0.1, 0.1, 10., 9.]]) + wanted = interpn(points, values, sample, method="nearest") + assert_array_almost_equal(interp_rg(sample), wanted) + + def test_4d_nearest_outofbounds(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + sample = np.asarray([[0.1, -0.1, 10.1, 9.]]) + wanted = np.asarray([999.99]) + actual = interpn(points, values, sample, method="nearest", + bounds_error=False, fill_value=999.99) + assert_array_almost_equal(actual, wanted) + + def test_xi_1d(self): + # verify that 1-D xi works as expected + points, values = self._sample_4d_data() + sample = np.asarray([0.1, 0.1, 10., 9.]) + v1 = interpn(points, values, sample, bounds_error=False) + v2 = interpn(points, values, sample[None,:], bounds_error=False) + xp_assert_close(v1, v2) + + def test_xi_nd(self): + # verify that higher-d xi works as expected + points, values = self._sample_4d_data() + + np.random.seed(1234) + sample = np.random.rand(2, 3, 4) + + v1 = interpn(points, values, sample, method='nearest', + bounds_error=False) + assert v1.shape == (2, 3) + + v2 = interpn(points, values, sample.reshape(-1, 4), + method='nearest', bounds_error=False) + xp_assert_close(v1, v2.reshape(v1.shape)) + + @parametrize_rgi_interp_methods + def test_xi_broadcast(self, method): + # verify that the interpolators broadcast xi + x, y, values = self._sample_2d_data() + points = (x, y) + + xi = np.linspace(0, 1, 2) + yi = np.linspace(0, 3, 3) + + sample = (xi[:, None], yi[None, :]) + v1 = interpn(points, values, sample, method=method, bounds_error=False) + assert v1.shape == (2, 3) + + xx, yy = np.meshgrid(xi, yi) + sample = np.c_[xx.T.ravel(), yy.T.ravel()] + + v2 = interpn(points, values, sample, + method=method, bounds_error=False) + xp_assert_close(v1, v2.reshape(v1.shape)) + + @pytest.mark.fail_slow(5) + @parametrize_rgi_interp_methods + def test_nonscalar_values(self, method): + + if method == "quintic": + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also works + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5)] * 2 + [ + (0.0, 5.0, 10.0, 15.0, 20, 25.0) + ] * 2 + + rng = np.random.default_rng(1234) + values = rng.random((6, 6, 6, 6, 8)) + sample = rng.random((7, 3, 4)) + + v = interpn(points, values, sample, method=method, + bounds_error=False) + assert v.shape == (7, 3, 8), method + + vs = [interpn(points, values[..., j], sample, method=method, + bounds_error=False) for j in range(8)] + v2 = np.array(vs).transpose(1, 2, 0) + + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + @parametrize_rgi_interp_methods + def test_nonscalar_values_2(self, method): + + if method in {"cubic", "quintic"}: + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also work : use different + # lengths of axes to simplify tracing the internals + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5), + (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0, 47)] + + rng = np.random.default_rng(1234) + + trailing_points = (3, 2) + # NB: values has a `num_trailing_dims` trailing dimension + values = rng.random((6, 7, 8, 9, *trailing_points)) + sample = rng.random(4) # a single sample point ! + + v = interpn(points, values, sample, method=method, bounds_error=False) + + # v has a single sample point *per entry in the trailing dimensions* + assert v.shape == (1, *trailing_points) + + # check the values, too : manually loop over the trailing dimensions + vs = [[ + interpn(points, values[..., i, j], sample, method=method, + bounds_error=False) for i in range(values.shape[-2]) + ] for j in range(values.shape[-1])] + + xp_assert_close(v, np.asarray(vs).T, atol=1e-14, err_msg=method) + + def test_non_scalar_values_splinef2d(self): + # Vector-valued splines supported with fitpack + points, values = self._sample_4d_data() + + np.random.seed(1234) + values = np.random.rand(3, 3, 3, 3, 6) + sample = np.random.rand(7, 11, 4) + assert_raises(ValueError, interpn, points, values, sample, + method='splinef2d') + + @parametrize_rgi_interp_methods + def test_complex(self, method): + if method == "pchip": + pytest.skip("pchip does not make sense for complex data") + + x, y, values = self._sample_2d_data() + points = (x, y) + values = values - 2j*values + + sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + v1 = interpn(points, values, sample, method=method) + v2r = interpn(points, values.real, sample, method=method) + v2i = interpn(points, values.imag, sample, method=method) + v2 = v2r + 1j*v2i + + xp_assert_close(v1, v2) + + def test_complex_pchip(self): + # Complex-valued data deprecated for pchip + x, y, values = self._sample_2d_data() + points = (x, y) + values = values - 2j*values + + sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + with pytest.raises(ValueError, match='real'): + interpn(points, values, sample, method='pchip') + + def test_complex_spline2fd(self): + # Complex-valued data not supported by spline2fd + x, y, values = self._sample_2d_data() + points = (x, y) + values = values - 2j*values + + sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + with pytest.warns(ComplexWarning): + interpn(points, values, sample, method='splinef2d') + + @pytest.mark.parametrize( + "method", + ["linear", "nearest"] + ) + def test_duck_typed_values(self, method): + x = np.linspace(0, 2, 5) + y = np.linspace(0, 1, 7) + + values = MyValue((5, 7)) + + v1 = interpn((x, y), values, [0.4, 0.7], method=method) + v2 = interpn((x, y), values._v, [0.4, 0.7], method=method) + xp_assert_close(v1, v2, check_dtype=False) + + @skip_xp_invalid_arg + @parametrize_rgi_interp_methods + def test_matrix_input(self, method): + """np.matrix inputs are allowed for backwards compatibility""" + x = np.linspace(0, 2, 6) + y = np.linspace(0, 1, 7) + + values = matrix(np.random.rand(6, 7)) + + sample = np.random.rand(3, 7, 2) + + v1 = interpn((x, y), values, sample, method=method) + v2 = interpn((x, y), np.asarray(values), sample, method=method) + if method == "quintic": + # https://github.com/scipy/scipy/issues/20472 + xp_assert_close(v1, v2, atol=5e-5, rtol=2e-6) + else: + xp_assert_close(v1, v2) + + def test_length_one_axis(self): + # gh-5890, gh-9524 : length-1 axis is legal for method='linear'. + # Along the axis it's linear interpolation; away from the length-1 + # axis, it's an extrapolation, so fill_value should be used. + + values = np.array([[0.1, 1, 10]]) + xi = np.array([[1, 2.2], [1, 3.2], [1, 3.8]]) + + res = interpn(([1], [2, 3, 4]), values, xi) + wanted = [0.9*0.2 + 0.1, # on [2, 3) it's 0.9*(x-2) + 0.1 + 9*0.2 + 1, # on [3, 4] it's 9*(x-3) + 1 + 9*0.8 + 1] + + xp_assert_close(res, wanted, atol=1e-15) + + # check extrapolation + xi = np.array([[1.1, 2.2], [1.5, 3.2], [-2.3, 3.8]]) + res = interpn(([1], [2, 3, 4]), values, xi, + bounds_error=False, fill_value=None) + + xp_assert_close(res, wanted, atol=1e-15) + + def test_descending_points(self): + def value_func_4d(x, y, z, a): + return 2 * x ** 3 + 3 * y ** 2 - z - a + + x1 = np.array([0, 1, 2, 3]) + x2 = np.array([0, 10, 20, 30]) + x3 = np.array([0, 10, 20, 30]) + x4 = np.array([0, .1, .2, .30]) + points = (x1, x2, x3, x4) + values = value_func_4d( + *np.meshgrid(*points, indexing='ij', sparse=True)) + pts = (0.1, 0.3, np.transpose(np.linspace(0, 30, 4)), + np.linspace(0, 0.3, 4)) + correct_result = interpn(points, values, pts) + + x1_descend = x1[::-1] + x2_descend = x2[::-1] + x3_descend = x3[::-1] + x4_descend = x4[::-1] + points_shuffled = (x1_descend, x2_descend, x3_descend, x4_descend) + values_shuffled = value_func_4d( + *np.meshgrid(*points_shuffled, indexing='ij', sparse=True)) + test_result = interpn(points_shuffled, values_shuffled, pts) + + xp_assert_equal(correct_result, test_result) + + def test_invalid_points_order(self): + x = np.array([.5, 2., 0., 4., 5.5]) # not ascending or descending + y = np.array([.5, 2., 3., 4., 5.5]) + z = np.array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + xi = np.array([[1, 2.3, 6.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, -4.0, 5.0, 1.0, 3]]).T + + match = "must be strictly ascending or descending" + with pytest.raises(ValueError, match=match): + interpn((x, y), z, xi) + + def test_invalid_xi_dimensions(self): + # https://github.com/scipy/scipy/issues/16519 + points = [(0, 1)] + values = [0, 1] + xi = np.ones((1, 1, 3)) + msg = ("The requested sample points xi have dimension 3, but this " + "RegularGridInterpolator has dimension 1") + with assert_raises(ValueError, match=msg): + interpn(points, values, xi) + + def test_readonly_grid(self): + # https://github.com/scipy/scipy/issues/17716 + x = np.linspace(0, 4, 5) + y = np.linspace(0, 5, 6) + z = np.linspace(0, 6, 7) + points = (x, y, z) + values = np.ones((5, 6, 7)) + point = np.array([2.21, 3.12, 1.15]) + for d in points: + d.flags.writeable = False + values.flags.writeable = False + point.flags.writeable = False + interpn(points, values, point) + RegularGridInterpolator(points, values)(point) + + def test_2d_readonly_grid(self): + # https://github.com/scipy/scipy/issues/17716 + # test special 2d case + x = np.linspace(0, 4, 5) + y = np.linspace(0, 5, 6) + points = (x, y) + values = np.ones((5, 6)) + point = np.array([2.21, 3.12]) + for d in points: + d.flags.writeable = False + values.flags.writeable = False + point.flags.writeable = False + interpn(points, values, point) + RegularGridInterpolator(points, values)(point) + + def test_non_c_contiguous_grid(self): + # https://github.com/scipy/scipy/issues/17716 + x = np.linspace(0, 4, 5) + x = np.vstack((x, np.empty_like(x))).T.copy()[:, 0] + assert not x.flags.c_contiguous + y = np.linspace(0, 5, 6) + z = np.linspace(0, 6, 7) + points = (x, y, z) + values = np.ones((5, 6, 7)) + point = np.array([2.21, 3.12, 1.15]) + interpn(points, values, point) + RegularGridInterpolator(points, values)(point) + + @pytest.mark.parametrize("dtype", ['>f8', '= 2**31 or cursor.header.ncols >= 2**31: + # Dimensions are too large to fit in int32 + index_dtype = "int64" + + i = np.zeros(cursor.header.nnz, dtype=index_dtype) + j = np.zeros(cursor.header.nnz, dtype=index_dtype) + data = np.zeros(cursor.header.nnz, dtype=_field_to_dtype.get(cursor.header.field)) + + _fmm_core.read_body_coo(cursor, i, j, data) + + if generalize_symmetry and cursor.header.symmetry != "general": + off_diagonal_mask = (i != j) + off_diagonal_rows = i[off_diagonal_mask] + off_diagonal_cols = j[off_diagonal_mask] + off_diagonal_data = data[off_diagonal_mask] + + if cursor.header.symmetry == "skew-symmetric": + off_diagonal_data *= -1 + elif cursor.header.symmetry == "hermitian": + off_diagonal_data = off_diagonal_data.conjugate() + + i = np.concatenate((i, off_diagonal_cols)) + j = np.concatenate((j, off_diagonal_rows)) + data = np.concatenate((data, off_diagonal_data)) + + return (data, (i, j)), cursor.header.shape + + +def _get_read_cursor(source, parallelism=None): + """ + Open file for reading. + """ + from . import _fmm_core + + ret_stream_to_close = None + if parallelism is None: + parallelism = PARALLELISM + + try: + source = os.fspath(source) + # It's a file path + is_path = True + except TypeError: + is_path = False + + if is_path: + path = str(source) + if path.endswith('.gz'): + import gzip + source = gzip.GzipFile(path, 'r') + ret_stream_to_close = source + elif path.endswith('.bz2'): + import bz2 + source = bz2.BZ2File(path, 'rb') + ret_stream_to_close = source + else: + if not os.path.exists(path): + raise FileNotFoundError(f"The source file does not exist: {path}") + return _fmm_core.open_read_file(path, parallelism), ret_stream_to_close + + # Stream object. + if hasattr(source, "read"): + if isinstance(source, io.TextIOBase): + source = _TextToBytesWrapper(source) + return _fmm_core.open_read_stream(source, parallelism), ret_stream_to_close + else: + raise TypeError("Unknown source type") + + +def _get_write_cursor(target, h=None, comment=None, parallelism=None, + symmetry="general", precision=None): + """ + Open file for writing. + """ + from . import _fmm_core + + if parallelism is None: + parallelism = PARALLELISM + if comment is None: + comment = '' + if symmetry is None: + symmetry = "general" + if precision is None: + precision = -1 + + if not h: + h = _fmm_core.header(comment=comment, symmetry=symmetry) + + try: + target = os.fspath(target) + # It's a file path + if target[-4:] != '.mtx': + target += '.mtx' + return _fmm_core.open_write_file(str(target), h, parallelism, precision) + except TypeError: + pass + + if hasattr(target, "write"): + # Stream object. + if isinstance(target, io.TextIOBase): + raise TypeError("target stream must be open in binary mode.") + return _fmm_core.open_write_stream(target, h, parallelism, precision) + else: + raise TypeError("Unknown source object") + + +def _apply_field(data, field, no_pattern=False): + """ + Ensure that ``data.dtype`` is compatible with the specified MatrixMarket field type. + + Parameters + ---------- + data : ndarray + Input array. + + field : str + Matrix Market field, such as 'real', 'complex', 'integer', 'pattern'. + + no_pattern : bool, optional + Whether an empty array may be returned for a 'pattern' field. + + Returns + ------- + data : ndarray + Input data if no conversion necessary, or a converted version + """ + + if field is None: + return data + if field == "pattern": + if no_pattern: + return data + else: + return np.zeros(0) + + dtype = _field_to_dtype.get(field, None) + if dtype is None: + raise ValueError("Invalid field.") + + return np.asarray(data, dtype=dtype) + + +def _validate_symmetry(symmetry): + """ + Check that the symmetry parameter is one that MatrixMarket allows.. + """ + if symmetry is None: + return "general" + + symmetry = str(symmetry).lower() + symmetries = ["general", "symmetric", "skew-symmetric", "hermitian"] + if symmetry not in symmetries: + raise ValueError("Invalid symmetry. Must be one of: " + ", ".join(symmetries)) + + return symmetry + + +def mmread(source, *, spmatrix=True): + """ + Reads the contents of a Matrix Market file-like 'source' into a matrix. + + Parameters + ---------- + source : str or file-like + Matrix Market filename (extensions .mtx, .mtz.gz) + or open file-like object. + spmatrix : bool, optional (default: True) + If ``True``, return sparse matrix. Otherwise return sparse array. + + Returns + ------- + a : ndarray or coo_array + Dense or sparse array depending on the matrix format in the + Matrix Market file. + + Notes + ----- + .. versionchanged:: 1.12.0 + C++ implementation. + + Examples + -------- + >>> from io import StringIO + >>> from scipy.io import mmread + + >>> text = '''%%MatrixMarket matrix coordinate real general + ... 5 5 7 + ... 2 3 1.0 + ... 3 4 2.0 + ... 3 5 3.0 + ... 4 1 4.0 + ... 4 2 5.0 + ... 4 3 6.0 + ... 4 4 7.0 + ... ''' + + ``mmread(source)`` returns the data as sparse array in COO format. + + >>> m = mmread(StringIO(text), spmatrix=False) + >>> m + + >>> m.toarray() + array([[0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0.], + [0., 0., 0., 2., 3.], + [4., 5., 6., 7., 0.], + [0., 0., 0., 0., 0.]]) + + This method is threaded. + The default number of threads is equal to the number of CPUs in the system. + Use `threadpoolctl `_ to override: + + >>> import threadpoolctl + >>> + >>> with threadpoolctl.threadpool_limits(limits=2): + ... m = mmread(StringIO(text), spmatrix=False) + + """ + cursor, stream_to_close = _get_read_cursor(source) + + if cursor.header.format == "array": + mat = _read_body_array(cursor) + if stream_to_close: + stream_to_close.close() + return mat + else: + triplet, shape = _read_body_coo(cursor, generalize_symmetry=True) + if stream_to_close: + stream_to_close.close() + if spmatrix: + return coo_matrix(triplet, shape=shape) + return coo_array(triplet, shape=shape) + + +def mmwrite(target, a, comment=None, field=None, precision=None, symmetry="AUTO"): + r""" + Writes the sparse or dense array `a` to Matrix Market file-like `target`. + + Parameters + ---------- + target : str or file-like + Matrix Market filename (extension .mtx) or open file-like object. + a : array like + Sparse or dense 2-D array. + comment : str, optional + Comments to be prepended to the Matrix Market file. + field : None or str, optional + Either 'real', 'complex', 'pattern', or 'integer'. + precision : None or int, optional + Number of digits to display for real or complex values. + symmetry : None or str, optional + Either 'AUTO', 'general', 'symmetric', 'skew-symmetric', or 'hermitian'. + If symmetry is None the symmetry type of 'a' is determined by its + values. If symmetry is 'AUTO' the symmetry type of 'a' is either + determined or set to 'general', at mmwrite's discretion. + + Returns + ------- + None + + Notes + ----- + .. versionchanged:: 1.12.0 + C++ implementation. + + Examples + -------- + >>> from io import BytesIO + >>> import numpy as np + >>> from scipy.sparse import coo_array + >>> from scipy.io import mmwrite + + Write a small NumPy array to a matrix market file. The file will be + written in the ``'array'`` format. + + >>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]]) + >>> target = BytesIO() + >>> mmwrite(target, a) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix array real general + % + 2 4 + 1 + 0 + 0 + 2.5 + 0 + 0 + 0 + 6.25 + + Add a comment to the output file, and set the precision to 3. + + >>> target = BytesIO() + >>> mmwrite(target, a, comment='\n Some test data.\n', precision=3) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix array real general + % + % Some test data. + % + 2 4 + 1.00e+00 + 0.00e+00 + 0.00e+00 + 2.50e+00 + 0.00e+00 + 0.00e+00 + 0.00e+00 + 6.25e+00 + + Convert to a sparse matrix before calling ``mmwrite``. This will + result in the output format being ``'coordinate'`` rather than + ``'array'``. + + >>> target = BytesIO() + >>> mmwrite(target, coo_array(a), precision=3) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix coordinate real general + % + 2 4 3 + 1 1 1.00e+00 + 2 2 2.50e+00 + 2 4 6.25e+00 + + Write a complex Hermitian array to a matrix market file. Note that + only six values are actually written to the file; the other values + are implied by the symmetry. + + >>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]]) + >>> z + array([[ 3. +0.j, 1. +2.j, 4. -3.j], + [ 1. -2.j, 1. +0.j, -0. -5.j], + [ 4. +3.j, 0. +5.j, 2.5+0.j]]) + + >>> target = BytesIO() + >>> mmwrite(target, z, precision=2) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix array complex hermitian + % + 3 3 + 3.0e+00 0.0e+00 + 1.0e+00 -2.0e+00 + 4.0e+00 3.0e+00 + 1.0e+00 0.0e+00 + 0.0e+00 5.0e+00 + 2.5e+00 0.0e+00 + + This method is threaded. + The default number of threads is equal to the number of CPUs in the system. + Use `threadpoolctl `_ to override: + + >>> import threadpoolctl + >>> + >>> target = BytesIO() + >>> with threadpoolctl.threadpool_limits(limits=2): + ... mmwrite(target, a) + + """ + from . import _fmm_core + + if isinstance(a, list) or isinstance(a, tuple) or hasattr(a, "__array__"): + a = np.asarray(a) + + if symmetry == "AUTO": + if ALWAYS_FIND_SYMMETRY or (hasattr(a, "shape") and max(a.shape) < 100): + symmetry = None + else: + symmetry = "general" + + if symmetry is None: + symmetry = _mmio.MMFile()._get_symmetry(a) + + symmetry = _validate_symmetry(symmetry) + cursor = _get_write_cursor(target, comment=comment, + precision=precision, symmetry=symmetry) + + if isinstance(a, np.ndarray): + # Write dense numpy arrays + a = _apply_field(a, field, no_pattern=True) + _fmm_core.write_body_array(cursor, a) + + elif issparse(a): + # Write sparse scipy matrices + a = a.tocoo() + + if symmetry is not None and symmetry != "general": + # A symmetric matrix only specifies the elements below the diagonal. + # Ensure that the matrix satisfies this requirement. + lower_triangle_mask = a.row >= a.col + a = coo_array((a.data[lower_triangle_mask], + (a.row[lower_triangle_mask], + a.col[lower_triangle_mask])), shape=a.shape) + + data = _apply_field(a.data, field) + _fmm_core.write_body_coo(cursor, a.shape, a.row, a.col, data) + + else: + raise ValueError(f"unknown matrix type: {type(a)}") + + +def mminfo(source): + """ + Return size and storage parameters from Matrix Market file-like 'source'. + + Parameters + ---------- + source : str or file-like + Matrix Market filename (extension .mtx) or open file-like object + + Returns + ------- + rows : int + Number of matrix rows. + cols : int + Number of matrix columns. + entries : int + Number of non-zero entries of a sparse matrix + or rows*cols for a dense matrix. + format : str + Either 'coordinate' or 'array'. + field : str + Either 'real', 'complex', 'pattern', or 'integer'. + symmetry : str + Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'. + + Notes + ----- + .. versionchanged:: 1.12.0 + C++ implementation. + + Examples + -------- + >>> from io import StringIO + >>> from scipy.io import mminfo + + >>> text = '''%%MatrixMarket matrix coordinate real general + ... 5 5 7 + ... 2 3 1.0 + ... 3 4 2.0 + ... 3 5 3.0 + ... 4 1 4.0 + ... 4 2 5.0 + ... 4 3 6.0 + ... 4 4 7.0 + ... ''' + + + ``mminfo(source)`` returns the number of rows, number of columns, + format, field type and symmetry attribute of the source file. + + >>> mminfo(StringIO(text)) + (5, 5, 7, 'coordinate', 'real', 'general') + """ + cursor, stream_to_close = _get_read_cursor(source, 1) + h = cursor.header + cursor.close() + if stream_to_close: + stream_to_close.close() + return h.nrows, h.ncols, h.nnz, h.format, h.field, h.symmetry diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_fast_matrix_market/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_fast_matrix_market/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82737ff3c0e7a232e0e361276dd52dc9dd82155c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_fast_matrix_market/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cp311-win_amd64.dll.a b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cp311-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..3f5b319be34b5742e163c6a6b90df689fb59b62d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cp311-win_amd64.dll.a differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db22d56cf320dbfe5efeb6d057ed956dc017f92d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__init__.py @@ -0,0 +1,7 @@ +from .hb import hb_read, hb_write + +__all__ = ["hb_read", "hb_write"] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c09c24e52a411c9a0c0f7ac0983034d76e90093 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/_fortran_format_parser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/_fortran_format_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c66fa858abe0a9b2ce5deacbc92a2bde20b327c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/_fortran_format_parser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/hb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/hb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..258981a3ef1bb31a97b3873fbc364a7aaf999988 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/__pycache__/hb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..3b035ff7f626ab8cccb22e7a58d4fc34541dda3f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py @@ -0,0 +1,316 @@ +""" +Preliminary module to handle Fortran formats for IO. Does not use this outside +scipy.sparse io for now, until the API is deemed reasonable. + +The *Format classes handle conversion between Fortran and Python format, and +FortranFormatParser can create *Format instances from raw Fortran format +strings (e.g. '(3I4)', '(10I3)', etc...) +""" +import re +import threading + +import numpy as np + + +__all__ = ["BadFortranFormat", "FortranFormatParser", "IntFormat", "ExpFormat"] + + +TOKENS = { + "LPAR": r"\(", + "RPAR": r"\)", + "INT_ID": r"I", + "EXP_ID": r"E", + "INT": r"\d+", + "DOT": r"\.", +} + + +class BadFortranFormat(SyntaxError): + pass + + +def number_digits(n): + return int(np.floor(np.log10(np.abs(n))) + 1) + + +class IntFormat: + @classmethod + def from_number(cls, n, min=None): + """Given an integer, returns a "reasonable" IntFormat instance to represent + any number between 0 and n if n > 0, -n and n if n < 0 + + Parameters + ---------- + n : int + max number one wants to be able to represent + min : int + minimum number of characters to use for the format + + Returns + ------- + res : IntFormat + IntFormat instance with reasonable (see Notes) computed width + + Notes + ----- + Reasonable should be understood as the minimal string length necessary + without losing precision. For example, IntFormat.from_number(1) will + return an IntFormat instance of width 2, so that any 0 and 1 may be + represented as 1-character strings without loss of information. + """ + width = number_digits(n) + 1 + if n < 0: + width += 1 + repeat = 80 // width + return cls(width, min, repeat=repeat) + + def __init__(self, width, min=None, repeat=None): + self.width = width + self.repeat = repeat + self.min = min + + def __repr__(self): + r = "IntFormat(" + if self.repeat: + r += f"{self.repeat}" + r += f"I{self.width}" + if self.min: + r += f".{self.min}" + return r + ")" + + @property + def fortran_format(self): + r = "(" + if self.repeat: + r += f"{self.repeat}" + r += f"I{self.width}" + if self.min: + r += f".{self.min}" + return r + ")" + + @property + def python_format(self): + return "%" + str(self.width) + "d" + + +class ExpFormat: + @classmethod + def from_number(cls, n, min=None): + """Given a float number, returns a "reasonable" ExpFormat instance to + represent any number between -n and n. + + Parameters + ---------- + n : float + max number one wants to be able to represent + min : int + minimum number of characters to use for the format + + Returns + ------- + res : ExpFormat + ExpFormat instance with reasonable (see Notes) computed width + + Notes + ----- + Reasonable should be understood as the minimal string length necessary + to avoid losing precision. + """ + # len of one number in exp format: sign + 1|0 + "." + + # number of digit for fractional part + 'E' + sign of exponent + + # len of exponent + finfo = np.finfo(n.dtype) + # Number of digits for fractional part + n_prec = finfo.precision + 1 + # Number of digits for exponential part + n_exp = number_digits(np.max(np.abs([finfo.maxexp, finfo.minexp]))) + width = 1 + 1 + n_prec + 1 + n_exp + 1 + if n < 0: + width += 1 + repeat = int(np.floor(80 / width)) + return cls(width, n_prec, min, repeat=repeat) + + def __init__(self, width, significand, min=None, repeat=None): + """\ + Parameters + ---------- + width : int + number of characters taken by the string (includes space). + """ + self.width = width + self.significand = significand + self.repeat = repeat + self.min = min + + def __repr__(self): + r = "ExpFormat(" + if self.repeat: + r += f"{self.repeat}" + r += f"E{self.width}.{self.significand}" + if self.min: + r += f"E{self.min}" + return r + ")" + + @property + def fortran_format(self): + r = "(" + if self.repeat: + r += f"{self.repeat}" + r += f"E{self.width}.{self.significand}" + if self.min: + r += f"E{self.min}" + return r + ")" + + @property + def python_format(self): + return "%" + str(self.width-1) + "." + str(self.significand) + "E" + + +class Token: + def __init__(self, type, value, pos): + self.type = type + self.value = value + self.pos = pos + + def __str__(self): + return f"""Token('{self.type}', "{self.value}")""" + + def __repr__(self): + return self.__str__() + + +class Tokenizer: + def __init__(self): + self.tokens = list(TOKENS.keys()) + self.res = [re.compile(TOKENS[i]) for i in self.tokens] + + def input(self, s): + self.data = s + self.curpos = 0 + self.len = len(s) + + def next_token(self): + curpos = self.curpos + + while curpos < self.len: + for i, r in enumerate(self.res): + m = r.match(self.data, curpos) + if m is None: + continue + else: + self.curpos = m.end() + return Token(self.tokens[i], m.group(), self.curpos) + raise SyntaxError( + f"Unknown character at position {self.curpos} " + f"({self.data[self.curpos]})" + ) + + +# Grammar for fortran format: +# format : LPAR format_string RPAR +# format_string : repeated | simple +# repeated : repeat simple +# simple : int_fmt | exp_fmt +# int_fmt : INT_ID width +# exp_fmt : simple_exp_fmt +# simple_exp_fmt : EXP_ID width DOT significand +# extended_exp_fmt : EXP_ID width DOT significand EXP_ID ndigits +# repeat : INT +# width : INT +# significand : INT +# ndigits : INT + +# Naive fortran formatter - parser is hand-made +class FortranFormatParser: + """Parser for Fortran format strings. The parse method returns a *Format + instance. + + Notes + ----- + Only ExpFormat (exponential format for floating values) and IntFormat + (integer format) for now. + """ + def __init__(self): + self.tokenizer = threading.local() + + def parse(self, s): + if not hasattr(self.tokenizer, 't'): + self.tokenizer.t = Tokenizer() + + self.tokenizer.t.input(s) + + tokens = [] + + try: + while True: + t = self.tokenizer.t.next_token() + if t is None: + break + else: + tokens.append(t) + return self._parse_format(tokens) + except SyntaxError as e: + raise BadFortranFormat(str(e)) from e + + def _get_min(self, tokens): + next = tokens.pop(0) + if not next.type == "DOT": + raise SyntaxError() + next = tokens.pop(0) + return next.value + + def _expect(self, token, tp): + if not token.type == tp: + raise SyntaxError() + + def _parse_format(self, tokens): + if not tokens[0].type == "LPAR": + raise SyntaxError( + f"Expected left parenthesis at position {0} (got '{tokens[0].value}')" + ) + elif not tokens[-1].type == "RPAR": + raise SyntaxError("Expected right parenthesis at position " + f"{len(tokens)} (got '{tokens[-1].value}')") + + tokens = tokens[1:-1] + types = [t.type for t in tokens] + if types[0] == "INT": + repeat = int(tokens.pop(0).value) + else: + repeat = None + + next = tokens.pop(0) + if next.type == "INT_ID": + next = self._next(tokens, "INT") + width = int(next.value) + if tokens: + min = int(self._get_min(tokens)) + else: + min = None + return IntFormat(width, min, repeat) + elif next.type == "EXP_ID": + next = self._next(tokens, "INT") + width = int(next.value) + + next = self._next(tokens, "DOT") + + next = self._next(tokens, "INT") + significand = int(next.value) + + if tokens: + next = self._next(tokens, "EXP_ID") + + next = self._next(tokens, "INT") + min = int(next.value) + else: + min = None + return ExpFormat(width, significand, min, repeat) + else: + raise SyntaxError(f"Invalid formatter type {next.value}") + + def _next(self, tokens, tp): + if not len(tokens) > 0: + raise SyntaxError() + next = tokens.pop(0) + self._expect(next, tp) + return next diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/hb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/hb.py new file mode 100644 index 0000000000000000000000000000000000000000..3f627e6db001235165fcad32c59407660268bcc8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/hb.py @@ -0,0 +1,571 @@ +""" +Implementation of Harwell-Boeing read/write. + +At the moment not the full Harwell-Boeing format is supported. Supported +features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + +""" +# TODO: +# - Add more support (symmetric/complex matrices, non-assembled matrices ?) + +# XXX: reading is reasonably efficient (>= 85 % is in numpy.fromstring), but +# takes a lot of memory. Being faster would require compiled code. +# write is not efficient. Although not a terribly exciting task, +# having reusable facilities to efficiently read/write fortran-formatted files +# would be useful outside this module. + +import warnings + +import numpy as np +from scipy.sparse import csc_array, csc_matrix +from ._fortran_format_parser import FortranFormatParser, IntFormat, ExpFormat + +__all__ = ["hb_read", "hb_write"] + + +class MalformedHeader(Exception): + pass + + +class LineOverflow(Warning): + pass + + +def _nbytes_full(fmt, nlines): + """Return the number of bytes to read to get every full lines for the + given parsed fortran format.""" + return (fmt.repeat * fmt.width + 1) * (nlines - 1) + + +class HBInfo: + @classmethod + def from_data(cls, m, title="Default title", key="0", mxtype=None, fmt=None): + """Create a HBInfo instance from an existing sparse matrix. + + Parameters + ---------- + m : sparse array or matrix + the HBInfo instance will derive its parameters from m + title : str + Title to put in the HB header + key : str + Key + mxtype : HBMatrixType + type of the input matrix + fmt : dict + not implemented + + Returns + ------- + hb_info : HBInfo instance + """ + m = m.tocsc(copy=False) + + pointer = m.indptr + indices = m.indices + values = m.data + + nrows, ncols = m.shape + nnon_zeros = m.nnz + + if fmt is None: + # +1 because HB use one-based indexing (Fortran), and we will write + # the indices /pointer as such + pointer_fmt = IntFormat.from_number(np.max(pointer+1)) + indices_fmt = IntFormat.from_number(np.max(indices+1)) + + if values.dtype.kind in np.typecodes["AllFloat"]: + values_fmt = ExpFormat.from_number(-np.max(np.abs(values))) + elif values.dtype.kind in np.typecodes["AllInteger"]: + values_fmt = IntFormat.from_number(-np.max(np.abs(values))) + else: + message = f"type {values.dtype.kind} not implemented yet" + raise NotImplementedError(message) + else: + raise NotImplementedError("fmt argument not supported yet.") + + if mxtype is None: + if not np.isrealobj(values): + raise ValueError("Complex values not supported yet") + if values.dtype.kind in np.typecodes["AllInteger"]: + tp = "integer" + elif values.dtype.kind in np.typecodes["AllFloat"]: + tp = "real" + else: + raise NotImplementedError( + f"type {values.dtype} for values not implemented") + mxtype = HBMatrixType(tp, "unsymmetric", "assembled") + else: + raise ValueError("mxtype argument not handled yet.") + + def _nlines(fmt, size): + nlines = size // fmt.repeat + if nlines * fmt.repeat != size: + nlines += 1 + return nlines + + pointer_nlines = _nlines(pointer_fmt, pointer.size) + indices_nlines = _nlines(indices_fmt, indices.size) + values_nlines = _nlines(values_fmt, values.size) + + total_nlines = pointer_nlines + indices_nlines + values_nlines + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_fmt.fortran_format, indices_fmt.fortran_format, + values_fmt.fortran_format) + + @classmethod + def from_file(cls, fid): + """Create a HBInfo instance from a file object containing a matrix in the + HB format. + + Parameters + ---------- + fid : file-like matrix + File or file-like object containing a matrix in the HB format. + + Returns + ------- + hb_info : HBInfo instance + """ + # First line + line = fid.readline().strip("\n") + if not len(line) > 72: + raise ValueError("Expected at least 72 characters for first line, " + f"got: \n{line}") + title = line[:72] + key = line[72:] + + # Second line + line = fid.readline().strip("\n") + if not len(line.rstrip()) >= 56: + raise ValueError("Expected at least 56 characters for second line, " + f"got: \n{line}") + total_nlines = _expect_int(line[:14]) + pointer_nlines = _expect_int(line[14:28]) + indices_nlines = _expect_int(line[28:42]) + values_nlines = _expect_int(line[42:56]) + + rhs_nlines = line[56:72].strip() + if rhs_nlines == '': + rhs_nlines = 0 + else: + rhs_nlines = _expect_int(rhs_nlines) + if not rhs_nlines == 0: + raise ValueError("Only files without right hand side supported for " + "now.") + + # Third line + line = fid.readline().strip("\n") + if not len(line) >= 70: + raise ValueError(f"Expected at least 72 character for third line, " + f"got:\n{line}") + + mxtype_s = line[:3].upper() + if not len(mxtype_s) == 3: + raise ValueError("mxtype expected to be 3 characters long") + + mxtype = HBMatrixType.from_fortran(mxtype_s) + if mxtype.value_type not in ["real", "integer"]: + raise ValueError("Only real or integer matrices supported for " + f"now (detected {mxtype})") + if not mxtype.structure == "unsymmetric": + raise ValueError("Only unsymmetric matrices supported for " + f"now (detected {mxtype})") + if not mxtype.storage == "assembled": + raise ValueError("Only assembled matrices supported for now") + + if not line[3:14] == " " * 11: + raise ValueError(f"Malformed data for third line: {line}") + + nrows = _expect_int(line[14:28]) + ncols = _expect_int(line[28:42]) + nnon_zeros = _expect_int(line[42:56]) + nelementals = _expect_int(line[56:70]) + if not nelementals == 0: + raise ValueError( + f"Unexpected value {nelementals} for nltvl (last entry of line 3)" + ) + + # Fourth line + line = fid.readline().strip("\n") + + ct = line.split() + if not len(ct) == 3: + raise ValueError(f"Expected 3 formats, got {ct}") + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + ct[0], ct[1], ct[2], + rhs_nlines, nelementals) + + def __init__(self, title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_format_str, indices_format_str, values_format_str, + right_hand_sides_nlines=0, nelementals=0): + """Do not use this directly, but the class ctrs (from_* functions).""" + if title is None: + title = "No Title" + if len(title) > 72: + raise ValueError("title cannot be > 72 characters") + + if key is None: + key = "|No Key" + if len(key) > 8: + warnings.warn(f"key is > 8 characters (key is {key})", + LineOverflow, stacklevel=3) + self.title = title + self.key = key + + self.total_nlines = total_nlines + self.pointer_nlines = pointer_nlines + self.indices_nlines = indices_nlines + self.values_nlines = values_nlines + + parser = FortranFormatParser() + pointer_format = parser.parse(pointer_format_str) + if not isinstance(pointer_format, IntFormat): + raise ValueError("Expected int format for pointer format, got " + f"{pointer_format}") + + indices_format = parser.parse(indices_format_str) + if not isinstance(indices_format, IntFormat): + raise ValueError("Expected int format for indices format, got " + f"{indices_format}") + + values_format = parser.parse(values_format_str) + if isinstance(values_format, ExpFormat): + if mxtype.value_type not in ["real", "complex"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + values_dtype = np.float64 + elif isinstance(values_format, IntFormat): + if mxtype.value_type not in ["integer"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + # XXX: fortran int -> dtype association ? + values_dtype = int + else: + raise ValueError(f"Unsupported format for values {values_format!r}") + + self.pointer_format = pointer_format + self.indices_format = indices_format + self.values_format = values_format + + self.pointer_dtype = np.int32 + self.indices_dtype = np.int32 + self.values_dtype = values_dtype + + self.pointer_nlines = pointer_nlines + self.pointer_nbytes_full = _nbytes_full(pointer_format, pointer_nlines) + + self.indices_nlines = indices_nlines + self.indices_nbytes_full = _nbytes_full(indices_format, indices_nlines) + + self.values_nlines = values_nlines + self.values_nbytes_full = _nbytes_full(values_format, values_nlines) + + self.nrows = nrows + self.ncols = ncols + self.nnon_zeros = nnon_zeros + self.nelementals = nelementals + self.mxtype = mxtype + + def dump(self): + """Gives the header corresponding to this instance as a string.""" + header = [self.title.ljust(72) + self.key.ljust(8)] + + header.append(f"{self.total_nlines:14d}{self.pointer_nlines:14d}{self.indices_nlines:14d}{self.values_nlines:14d}") + header.append(f"{self.mxtype.fortran_format.ljust(14):14s}{self.nrows:14d}{self.ncols:14d}{self.nnon_zeros:14d}{0:14d}") + + pffmt = self.pointer_format.fortran_format + iffmt = self.indices_format.fortran_format + vffmt = self.values_format.fortran_format + header.append(f"{pffmt.ljust(16):16s}{iffmt.ljust(16):16s}{vffmt.ljust(20):20s}") + return "\n".join(header) + + +def _expect_int(value, msg=None): + try: + return int(value) + except ValueError as e: + if msg is None: + msg = "Expected an int, got %s" + raise ValueError(msg % value) from e + + +def _read_hb_data(content, header): + # XXX: look at a way to reduce memory here (big string creation) + ptr_string = "".join([content.read(header.pointer_nbytes_full), + content.readline()]) + ptr = np.fromstring(ptr_string, + dtype=int, sep=' ') + + ind_string = "".join([content.read(header.indices_nbytes_full), + content.readline()]) + ind = np.fromstring(ind_string, + dtype=int, sep=' ') + + val_string = "".join([content.read(header.values_nbytes_full), + content.readline()]) + val = np.fromstring(val_string, + dtype=header.values_dtype, sep=' ') + + return csc_array((val, ind-1, ptr-1), shape=(header.nrows, header.ncols)) + + +def _write_data(m, fid, header): + m = m.tocsc(copy=False) + + def write_array(f, ar, nlines, fmt): + # ar_nlines is the number of full lines, n is the number of items per + # line, ffmt the fortran format + pyfmt = fmt.python_format + pyfmt_full = pyfmt * fmt.repeat + + # for each array to write, we first write the full lines, and special + # case for partial line + full = ar[:(nlines - 1) * fmt.repeat] + for row in full.reshape((nlines-1, fmt.repeat)): + f.write(pyfmt_full % tuple(row) + "\n") + nremain = ar.size - full.size + if nremain > 0: + f.write((pyfmt * nremain) % tuple(ar[ar.size - nremain:]) + "\n") + + fid.write(header.dump()) + fid.write("\n") + # +1 is for Fortran one-based indexing + write_array(fid, m.indptr+1, header.pointer_nlines, + header.pointer_format) + write_array(fid, m.indices+1, header.indices_nlines, + header.indices_format) + write_array(fid, m.data, header.values_nlines, + header.values_format) + + +class HBMatrixType: + """Class to hold the matrix type.""" + # q2f* translates qualified names to Fortran character + _q2f_type = { + "real": "R", + "complex": "C", + "pattern": "P", + "integer": "I", + } + _q2f_structure = { + "symmetric": "S", + "unsymmetric": "U", + "hermitian": "H", + "skewsymmetric": "Z", + "rectangular": "R" + } + _q2f_storage = { + "assembled": "A", + "elemental": "E", + } + + _f2q_type = {j: i for i, j in _q2f_type.items()} + _f2q_structure = {j: i for i, j in _q2f_structure.items()} + _f2q_storage = {j: i for i, j in _q2f_storage.items()} + + @classmethod + def from_fortran(cls, fmt): + if not len(fmt) == 3: + raise ValueError("Fortran format for matrix type should be 3 " + "characters long") + try: + value_type = cls._f2q_type[fmt[0]] + structure = cls._f2q_structure[fmt[1]] + storage = cls._f2q_storage[fmt[2]] + return cls(value_type, structure, storage) + except KeyError as e: + raise ValueError(f"Unrecognized format {fmt}") from e + + def __init__(self, value_type, structure, storage="assembled"): + self.value_type = value_type + self.structure = structure + self.storage = storage + + if value_type not in self._q2f_type: + raise ValueError(f"Unrecognized type {value_type}") + if structure not in self._q2f_structure: + raise ValueError(f"Unrecognized structure {structure}") + if storage not in self._q2f_storage: + raise ValueError(f"Unrecognized storage {storage}") + + @property + def fortran_format(self): + return self._q2f_type[self.value_type] + \ + self._q2f_structure[self.structure] + \ + self._q2f_storage[self.storage] + + def __repr__(self): + return f"HBMatrixType({self.value_type}, {self.structure}, {self.storage})" + + +class HBFile: + def __init__(self, file, hb_info=None): + """Create a HBFile instance. + + Parameters + ---------- + file : file-object + StringIO work as well + hb_info : HBInfo, optional + Should be given as an argument for writing, in which case the file + should be writable. + """ + self._fid = file + if hb_info is None: + self._hb_info = HBInfo.from_file(file) + else: + #raise OSError("file %s is not writable, and hb_info " + # "was given." % file) + self._hb_info = hb_info + + @property + def title(self): + return self._hb_info.title + + @property + def key(self): + return self._hb_info.key + + @property + def type(self): + return self._hb_info.mxtype.value_type + + @property + def structure(self): + return self._hb_info.mxtype.structure + + @property + def storage(self): + return self._hb_info.mxtype.storage + + def read_matrix(self): + return _read_hb_data(self._fid, self._hb_info) + + def write_matrix(self, m): + return _write_data(m, self._fid, self._hb_info) + + +def hb_read(path_or_open_file, *, spmatrix=True): + """Read HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before reading. + spmatrix : bool, optional (default: True) + If ``True``, return sparse matrix. Otherwise return sparse array. + + Returns + ------- + data : csc_array or csc_matrix + The data read from the HB file as a sparse array. + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_array, eye + >>> data = csr_array(eye(3)) # create a sparse array + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb", spmatrix=False)) # read a hb file + + Coords Values + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + """ + def _get_matrix(fid): + hb = HBFile(fid) + return hb.read_matrix() + + if hasattr(path_or_open_file, 'read'): + data = _get_matrix(path_or_open_file) + else: + with open(path_or_open_file) as f: + data = _get_matrix(f) + if spmatrix: + return csc_matrix(data) + return data + + +def hb_write(path_or_open_file, m, hb_info=None): + """Write HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before writing. + m : sparse array or matrix + the sparse array to write + hb_info : HBInfo + contains the meta-data for write + + Returns + ------- + None + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_array, eye + >>> data = csr_array(eye(3)) # create a sparse array + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb", spmatrix=False)) # read a hb file + + Coords Values + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + """ + m = m.tocsc(copy=False) + + if hb_info is None: + hb_info = HBInfo.from_data(m) + + def _set_matrix(fid): + hb = HBFile(fid, hb_info) + return hb.write_matrix(m) + + if hasattr(path_or_open_file, 'write'): + return _set_matrix(path_or_open_file) + else: + with open(path_or_open_file, 'w') as f: + return _set_matrix(f) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47bdf03673656a956d4dd9ca3713a10d1b223e1f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4ec7f74cea8d3e29ca31bd5ba1b2aed5f8c0655 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74d1301ca79db78d24668db48ecf91cd228a8a7c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4552216566a4283b92154e1e1c595f241335b9f3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py @@ -0,0 +1,74 @@ +import numpy as np + +from numpy.testing import assert_equal +from pytest import raises as assert_raises + +from scipy.io._harwell_boeing._fortran_format_parser import ( + FortranFormatParser, IntFormat, ExpFormat, BadFortranFormat) + + +class TestFortranFormatParser: + def setup_method(self): + self.parser = FortranFormatParser() + + def _test_equal(self, format, ref): + ret = self.parser.parse(format) + assert_equal(ret.__dict__, ref.__dict__) + + def test_simple_int(self): + self._test_equal("(I4)", IntFormat(4)) + + def test_simple_repeated_int(self): + self._test_equal("(3I4)", IntFormat(4, repeat=3)) + + def test_simple_exp(self): + self._test_equal("(E4.3)", ExpFormat(4, 3)) + + def test_exp_exp(self): + self._test_equal("(E8.3E3)", ExpFormat(8, 3, 3)) + + def test_repeat_exp(self): + self._test_equal("(2E4.3)", ExpFormat(4, 3, repeat=2)) + + def test_repeat_exp_exp(self): + self._test_equal("(2E8.3E3)", ExpFormat(8, 3, 3, repeat=2)) + + def test_wrong_formats(self): + def _test_invalid(bad_format): + assert_raises(BadFortranFormat, lambda: self.parser.parse(bad_format)) + _test_invalid("I4") + _test_invalid("(E4)") + _test_invalid("(E4.)") + _test_invalid("(E4.E3)") + + +class TestIntFormat: + def test_to_fortran(self): + f = [IntFormat(10), IntFormat(12, 10), IntFormat(12, 10, 3)] + res = ["(I10)", "(I12.10)", "(3I12.10)"] + + for i, j in zip(f, res): + assert_equal(i.fortran_format, j) + + def test_from_number(self): + f = [10, -12, 123456789] + r_f = [IntFormat(3, repeat=26), IntFormat(4, repeat=20), + IntFormat(10, repeat=8)] + for i, j in zip(f, r_f): + assert_equal(IntFormat.from_number(i).__dict__, j.__dict__) + + +class TestExpFormat: + def test_to_fortran(self): + f = [ExpFormat(10, 5), ExpFormat(12, 10), ExpFormat(12, 10, min=3), + ExpFormat(10, 5, repeat=3)] + res = ["(E10.5)", "(E12.10)", "(E12.10E3)", "(3E10.5)"] + + for i, j in zip(f, res): + assert_equal(i.fortran_format, j) + + def test_from_number(self): + f = np.array([1.0, -1.2]) + r_f = [ExpFormat(24, 16, repeat=3), ExpFormat(25, 16, repeat=3)] + for i, j in zip(f, r_f): + assert_equal(ExpFormat.from_number(i).__dict__, j.__dict__) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py new file mode 100644 index 0000000000000000000000000000000000000000..123d29d55f28f376d04463e4d44129312bbb012b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py @@ -0,0 +1,70 @@ +from io import StringIO +import tempfile + +import numpy as np + +from numpy.testing import assert_equal, \ + assert_array_almost_equal_nulp + +from scipy.sparse import coo_array, csc_array, random_array, isspmatrix + +from scipy.io import hb_read, hb_write + + +SIMPLE = """\ +No Title |No Key + 9 4 1 4 +RUA 100 100 10 0 +(26I3) (26I3) (3E23.15) +1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9 +9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11 +37 71 89 18 30 45 70 19 25 52 +2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01 +6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01 +4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01 +6.912334991524289e-01 +""" + +SIMPLE_MATRIX = coo_array( + ((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799, + 0.0661749042483, 0.887037034319, 0.419647859016, + 0.564960307211, 0.993442388709, 0.691233499152,), + (np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51], + [0, 4, 58, 61, 61, 72, 72, 73, 99, 99]])))) + + +def assert_csc_almost_equal(r, l): + r = csc_array(r) + l = csc_array(l) + assert_equal(r.indptr, l.indptr) + assert_equal(r.indices, l.indices) + assert_array_almost_equal_nulp(r.data, l.data, 10000) + + +class TestHBReader: + def test_simple(self): + m = hb_read(StringIO(SIMPLE), spmatrix=False) + assert_csc_almost_equal(m, SIMPLE_MATRIX) + assert not isspmatrix(m) + m = hb_read(StringIO(SIMPLE), spmatrix=True) + assert isspmatrix(m) + m = hb_read(StringIO(SIMPLE)) # default + assert isspmatrix(m) + + +class TestHBReadWrite: + + def check_save_load(self, value): + with tempfile.NamedTemporaryFile(mode='w+t') as file: + hb_write(file, value) + file.file.seek(0) + value_loaded = hb_read(file, spmatrix=False) + assert_csc_almost_equal(value, value_loaded) + + def test_simple(self): + random_arr = random_array((10, 100), density=0.1) + for format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'): + arr = random_arr.asformat(format, copy=False) + self.check_save_load(arr) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5d074bda55ad25d489670acf1c04304842de98 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__init__.py @@ -0,0 +1,28 @@ +""" +Module to read ARFF files +========================= +ARFF is the standard data format for WEKA. +It is a text file format which support numerical, string and data values. +The format can also represent missing data and sparse data. + +Notes +----- +The ARFF support in ``scipy.io`` provides file reading functionality only. +For more extensive ARFF functionality, see `liac-arff +`_. + +See the `WEKA website `_ +for more details about the ARFF format and available datasets. + +""" +from ._arffread import * +from . import _arffread + +# Deprecated namespaces, to be removed in v2.0.0 +from .import arffread + +__all__ = _arffread.__all__ + ['arffread'] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2606776a1b053a0e6d8895928873b3b9b55d624 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/_arffread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/_arffread.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..684d00ed1b8d1c2726678dc58554ea6416b65712 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/_arffread.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/arffread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/arffread.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d46d32a850ddc040f8634f7da096314bb749b33a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/__pycache__/arffread.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/_arffread.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/_arffread.py new file mode 100644 index 0000000000000000000000000000000000000000..c94730f1af51f8ea01f211c10dda97eb6c84e6cd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/_arffread.py @@ -0,0 +1,885 @@ +# Last Change: Mon Aug 20 08:00 PM 2007 J +import re +import datetime + +import numpy as np + +import csv +import ctypes + +"""A module to read arff files.""" + +__all__ = ['MetaData', 'loadarff', 'ArffError', 'ParseArffError'] + +# An Arff file is basically two parts: +# - header +# - data +# +# A header has each of its components starting by @META where META is one of +# the keyword (attribute of relation, for now). + +# TODO: +# - both integer and reals are treated as numeric -> the integer info +# is lost! +# - Replace ValueError by ParseError or something + +# We know can handle the following: +# - numeric and nominal attributes +# - missing values for numeric attributes + +r_meta = re.compile(r'^\s*@') +# Match a comment +r_comment = re.compile(r'^%') +# Match an empty line +r_empty = re.compile(r'^\s+$') +# Match a header line, that is a line which starts by @ + a word +r_headerline = re.compile(r'^\s*@\S*') +r_datameta = re.compile(r'^@[Dd][Aa][Tt][Aa]') +r_relation = re.compile(r'^@[Rr][Ee][Ll][Aa][Tt][Ii][Oo][Nn]\s*(\S*)') +r_attribute = re.compile(r'^\s*@[Aa][Tt][Tt][Rr][Ii][Bb][Uu][Tt][Ee]\s*(..*$)') + +r_nominal = re.compile(r'{(.+)}') +r_date = re.compile(r"[Dd][Aa][Tt][Ee]\s+[\"']?(.+?)[\"']?$") + +# To get attributes name enclosed with '' +r_comattrval = re.compile(r"'(..+)'\s+(..+$)") +# To get normal attributes +r_wcomattrval = re.compile(r"(\S+)\s+(..+$)") + +# ------------------------ +# Module defined exception +# ------------------------ + + +class ArffError(OSError): + """ + Base exception for errors when reading ARFF files. + + Raised when an ARFF file cannot be read due to file access issues, + corruption, or unsupported features. + """ + pass + + +class ParseArffError(ArffError): + """ + Exception for syntax and parsing errors in ARFF files. + + Raised when an ARFF file has invalid syntax, malformed attributes, + or data that doesn't match the expected format. + """ + pass + + +# ---------- +# Attributes +# ---------- +class Attribute: + + type_name = None + + def __init__(self, name): + self.name = name + self.range = None + self.dtype = np.object_ + + @classmethod + def parse_attribute(cls, name, attr_string): + """ + Parse the attribute line if it knows how. Returns the parsed + attribute, or None. + """ + return None + + def parse_data(self, data_str): + """ + Parse a value of this type. + """ + return None + + def __str__(self): + """ + Parse a value of this type. + """ + return self.name + ',' + self.type_name + + +class NominalAttribute(Attribute): + + type_name = 'nominal' + + def __init__(self, name, values): + super().__init__(name) + self.values = values + self.range = values + self.dtype = (np.bytes_, max(len(i) for i in values)) + + @staticmethod + def _get_nom_val(atrv): + """Given a string containing a nominal type, returns a tuple of the + possible values. + + A nominal type is defined as something framed between braces ({}). + + Parameters + ---------- + atrv : str + Nominal type definition + + Returns + ------- + poss_vals : tuple + possible values + + Examples + -------- + >>> from scipy.io.arff._arffread import NominalAttribute + >>> NominalAttribute._get_nom_val("{floup, bouga, fl, ratata}") + ('floup', 'bouga', 'fl', 'ratata') + """ + m = r_nominal.match(atrv) + if m: + attrs, _ = split_data_line(m.group(1)) + return tuple(attrs) + else: + raise ValueError("This does not look like a nominal string") + + @classmethod + def parse_attribute(cls, name, attr_string): + """ + Parse the attribute line if it knows how. Returns the parsed + attribute, or None. + + For nominal attributes, the attribute string would be like '{, + , }'. + """ + if attr_string[0] == '{': + values = cls._get_nom_val(attr_string) + return cls(name, values) + else: + return None + + def parse_data(self, data_str): + """ + Parse a value of this type. + """ + if data_str in self.values: + return data_str + elif data_str == '?': + return data_str + else: + raise ValueError(f"{str(data_str)} value not in {str(self.values)}") + + def __str__(self): + msg = self.name + ",{" + for i in range(len(self.values)-1): + msg += self.values[i] + "," + msg += self.values[-1] + msg += "}" + return msg + + +class NumericAttribute(Attribute): + + def __init__(self, name): + super().__init__(name) + self.type_name = 'numeric' + self.dtype = np.float64 + + @classmethod + def parse_attribute(cls, name, attr_string): + """ + Parse the attribute line if it knows how. Returns the parsed + attribute, or None. + + For numeric attributes, the attribute string would be like + 'numeric' or 'int' or 'real'. + """ + + attr_string = attr_string.lower().strip() + + if (attr_string[:len('numeric')] == 'numeric' or + attr_string[:len('int')] == 'int' or + attr_string[:len('real')] == 'real'): + return cls(name) + else: + return None + + def parse_data(self, data_str): + """ + Parse a value of this type. + + Parameters + ---------- + data_str : str + string to convert + + Returns + ------- + f : float + where float can be nan + + Examples + -------- + >>> from scipy.io.arff._arffread import NumericAttribute + >>> atr = NumericAttribute('atr') + >>> atr.parse_data('1') + 1.0 + >>> atr.parse_data('1\\n') + 1.0 + >>> atr.parse_data('?\\n') + nan + """ + if '?' in data_str: + return np.nan + else: + return float(data_str) + + def _basic_stats(self, data): + nbfac = data.size * 1. / (data.size - 1) + return (np.nanmin(data), np.nanmax(data), + np.mean(data), np.std(data) * nbfac) + + +class StringAttribute(Attribute): + + def __init__(self, name): + super().__init__(name) + self.type_name = 'string' + + @classmethod + def parse_attribute(cls, name, attr_string): + """ + Parse the attribute line if it knows how. Returns the parsed + attribute, or None. + + For string attributes, the attribute string would be like + 'string'. + """ + + attr_string = attr_string.lower().strip() + + if attr_string[:len('string')] == 'string': + return cls(name) + else: + return None + + +class DateAttribute(Attribute): + + def __init__(self, name, date_format, datetime_unit): + super().__init__(name) + self.date_format = date_format + self.datetime_unit = datetime_unit + self.type_name = 'date' + self.range = date_format + self.dtype = np.datetime64(0, self.datetime_unit) + + @staticmethod + def _get_date_format(atrv): + m = r_date.match(atrv) + if m: + pattern = m.group(1).strip() + # convert time pattern from Java's SimpleDateFormat to C's format + datetime_unit = None + if "yyyy" in pattern: + pattern = pattern.replace("yyyy", "%Y") + datetime_unit = "Y" + elif "yy": + pattern = pattern.replace("yy", "%y") + datetime_unit = "Y" + if "MM" in pattern: + pattern = pattern.replace("MM", "%m") + datetime_unit = "M" + if "dd" in pattern: + pattern = pattern.replace("dd", "%d") + datetime_unit = "D" + if "HH" in pattern: + pattern = pattern.replace("HH", "%H") + datetime_unit = "h" + if "mm" in pattern: + pattern = pattern.replace("mm", "%M") + datetime_unit = "m" + if "ss" in pattern: + pattern = pattern.replace("ss", "%S") + datetime_unit = "s" + if "z" in pattern or "Z" in pattern: + raise ValueError("Date type attributes with time zone not " + "supported, yet") + + if datetime_unit is None: + raise ValueError("Invalid or unsupported date format") + + return pattern, datetime_unit + else: + raise ValueError("Invalid or no date format") + + @classmethod + def parse_attribute(cls, name, attr_string): + """ + Parse the attribute line if it knows how. Returns the parsed + attribute, or None. + + For date attributes, the attribute string would be like + 'date '. + """ + + attr_string_lower = attr_string.lower().strip() + + if attr_string_lower[:len('date')] == 'date': + date_format, datetime_unit = cls._get_date_format(attr_string) + return cls(name, date_format, datetime_unit) + else: + return None + + def parse_data(self, data_str): + """ + Parse a value of this type. + """ + date_str = data_str.strip().strip("'").strip('"') + if date_str == '?': + return np.datetime64('NaT', self.datetime_unit) + else: + dt = datetime.datetime.strptime(date_str, self.date_format) + return np.datetime64(dt).astype( + f"datetime64[{self.datetime_unit}]") + + def __str__(self): + return super().__str__() + ',' + self.date_format + + +class RelationalAttribute(Attribute): + + def __init__(self, name): + super().__init__(name) + self.type_name = 'relational' + self.dtype = np.object_ + self.attributes = [] + self.dialect = None + + @classmethod + def parse_attribute(cls, name, attr_string): + """ + Parse the attribute line if it knows how. Returns the parsed + attribute, or None. + + For date attributes, the attribute string would be like + 'date '. + """ + + attr_string_lower = attr_string.lower().strip() + + if attr_string_lower[:len('relational')] == 'relational': + return cls(name) + else: + return None + + def parse_data(self, data_str): + # Copy-pasted + elems = list(range(len(self.attributes))) + + escaped_string = data_str.encode().decode("unicode-escape") + + row_tuples = [] + + for raw in escaped_string.split("\n"): + row, self.dialect = split_data_line(raw, self.dialect) + + row_tuples.append(tuple( + [self.attributes[i].parse_data(row[i]) for i in elems])) + + return np.array(row_tuples, + [(a.name, a.dtype) for a in self.attributes]) + + def __str__(self): + return (super().__str__() + '\n\t' + + '\n\t'.join(str(a) for a in self.attributes)) + + +# ----------------- +# Various utilities +# ----------------- +def to_attribute(name, attr_string): + attr_classes = (NominalAttribute, NumericAttribute, DateAttribute, + StringAttribute, RelationalAttribute) + + for cls in attr_classes: + attr = cls.parse_attribute(name, attr_string) + if attr is not None: + return attr + + raise ParseArffError(f"unknown attribute {attr_string}") + + +def csv_sniffer_has_bug_last_field(): + """ + Checks if the bug https://bugs.python.org/issue30157 is unpatched. + """ + + # We only compute this once. + has_bug = getattr(csv_sniffer_has_bug_last_field, "has_bug", None) + + if has_bug is None: + dialect = csv.Sniffer().sniff("3, 'a'") + csv_sniffer_has_bug_last_field.has_bug = dialect.quotechar != "'" + has_bug = csv_sniffer_has_bug_last_field.has_bug + + return has_bug + + +def workaround_csv_sniffer_bug_last_field(sniff_line, dialect, delimiters): + """ + Workaround for the bug https://bugs.python.org/issue30157 if is unpatched. + """ + if csv_sniffer_has_bug_last_field(): + # Reuses code from the csv module + right_regex = r'(?P[^\w\n"\'])(?P ?)(?P["\']).*?(?P=quote)(?:$|\n)' # noqa: E501 + + for restr in (r'(?P[^\w\n"\'])(?P ?)(?P["\']).*?(?P=quote)(?P=delim)', # ,".*?", # noqa: E501 + r'(?:^|\n)(?P["\']).*?(?P=quote)(?P[^\w\n"\'])(?P ?)', # .*?", # noqa: E501 + right_regex, # ,".*?" + r'(?:^|\n)(?P["\']).*?(?P=quote)(?:$|\n)'): # ".*?" (no delim, no space) # noqa: E501 + regexp = re.compile(restr, re.DOTALL | re.MULTILINE) + matches = regexp.findall(sniff_line) + if matches: + break + + # If it does not match the expression that was bugged, + # then this bug does not apply + if restr != right_regex: + return + + groupindex = regexp.groupindex + + # There is only one end of the string + assert len(matches) == 1 + m = matches[0] + + n = groupindex['quote'] - 1 + quote = m[n] + + n = groupindex['delim'] - 1 + delim = m[n] + + n = groupindex['space'] - 1 + space = bool(m[n]) + + dq_regexp = re.compile( + rf"(({re.escape(delim)})|^)\W*{quote}[^{re.escape(delim)}\n]*{quote}[^{re.escape(delim)}\n]*{quote}\W*(({re.escape(delim)})|$)", re.MULTILINE # noqa: E501 + ) + + doublequote = bool(dq_regexp.search(sniff_line)) + + dialect.quotechar = quote + if delim in delimiters: + dialect.delimiter = delim + dialect.doublequote = doublequote + dialect.skipinitialspace = space + + +def split_data_line(line, dialect=None): + delimiters = ",\t" + + # This can not be done in a per reader basis, and relational fields + # can be HUGE + csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2)) + + # Remove the line end if any + if line[-1] == '\n': + line = line[:-1] + + # Remove potential trailing whitespace + line = line.strip() + + sniff_line = line + + # Add a delimiter if none is present, so that the csv.Sniffer + # does not complain for a single-field CSV. + if not any(d in line for d in delimiters): + sniff_line += "," + + if dialect is None: + dialect = csv.Sniffer().sniff(sniff_line, delimiters=delimiters) + workaround_csv_sniffer_bug_last_field(sniff_line=sniff_line, + dialect=dialect, + delimiters=delimiters) + + row = next(csv.reader([line], dialect)) + + return row, dialect + + +# -------------- +# Parsing header +# -------------- +def tokenize_attribute(iterable, attribute): + """Parse a raw string in header (e.g., starts by @attribute). + + Given a raw string attribute, try to get the name and type of the + attribute. Constraints: + + * The first line must start with @attribute (case insensitive, and + space like characters before @attribute are allowed) + * Works also if the attribute is spread on multilines. + * Works if empty lines or comments are in between + + Parameters + ---------- + attribute : str + the attribute string. + + Returns + ------- + name : str + name of the attribute + value : str + value of the attribute + next : str + next line to be parsed + + Examples + -------- + If attribute is a string defined in python as r"floupi real", will + return floupi as name, and real as value. + + >>> from scipy.io.arff._arffread import tokenize_attribute + >>> iterable = iter([0] * 10) # dummy iterator + >>> tokenize_attribute(iterable, r"@attribute floupi real") + ('floupi', 'real', 0) + + If attribute is r"'floupi 2' real", will return 'floupi 2' as name, + and real as value. + + >>> tokenize_attribute(iterable, r" @attribute 'floupi 2' real ") + ('floupi 2', 'real', 0) + + """ + sattr = attribute.strip() + mattr = r_attribute.match(sattr) + if mattr: + # atrv is everything after @attribute + atrv = mattr.group(1) + if r_comattrval.match(atrv): + name, type = tokenize_single_comma(atrv) + next_item = next(iterable) + elif r_wcomattrval.match(atrv): + name, type = tokenize_single_wcomma(atrv) + next_item = next(iterable) + else: + # Not sure we should support this, as it does not seem supported by + # weka. + raise ValueError("multi line not supported yet") + else: + raise ValueError(f"First line unparsable: {sattr}") + + attribute = to_attribute(name, type) + + if type.lower() == 'relational': + next_item = read_relational_attribute(iterable, attribute, next_item) + # raise ValueError("relational attributes not supported yet") + + return attribute, next_item + + +def tokenize_single_comma(val): + # XXX we match twice the same string (here and at the caller level). It is + # stupid, but it is easier for now... + m = r_comattrval.match(val) + if m: + try: + name = m.group(1).strip() + type = m.group(2).strip() + except IndexError as e: + raise ValueError("Error while tokenizing attribute") from e + else: + raise ValueError(f"Error while tokenizing single {val}") + return name, type + + +def tokenize_single_wcomma(val): + # XXX we match twice the same string (here and at the caller level). It is + # stupid, but it is easier for now... + m = r_wcomattrval.match(val) + if m: + try: + name = m.group(1).strip() + type = m.group(2).strip() + except IndexError as e: + raise ValueError("Error while tokenizing attribute") from e + else: + raise ValueError(f"Error while tokenizing single {val}") + return name, type + + +def read_relational_attribute(ofile, relational_attribute, i): + """Read the nested attributes of a relational attribute""" + + r_end_relational = re.compile(r'^@[Ee][Nn][Dd]\s*' + + relational_attribute.name + r'\s*$') + + while not r_end_relational.match(i): + m = r_headerline.match(i) + if m: + isattr = r_attribute.match(i) + if isattr: + attr, i = tokenize_attribute(ofile, i) + relational_attribute.attributes.append(attr) + else: + raise ValueError(f"Error parsing line {i}") + else: + i = next(ofile) + + i = next(ofile) + return i + + +def read_header(ofile): + """Read the header of the iterable ofile.""" + i = next(ofile) + + # Pass first comments + while r_comment.match(i): + i = next(ofile) + + # Header is everything up to DATA attribute ? + relation = None + attributes = [] + while not r_datameta.match(i): + m = r_headerline.match(i) + if m: + isattr = r_attribute.match(i) + if isattr: + attr, i = tokenize_attribute(ofile, i) + attributes.append(attr) + else: + isrel = r_relation.match(i) + if isrel: + relation = isrel.group(1) + else: + raise ValueError(f"Error parsing line {i}") + i = next(ofile) + else: + i = next(ofile) + + return relation, attributes + + +class MetaData: + """Small container to keep useful information on a ARFF dataset. + + Knows about attributes names and types. + + Examples + -------- + :: + + data, meta = loadarff('iris.arff') + # This will print the attributes names of the iris.arff dataset + for i in meta: + print(i) + # This works too + meta.names() + # Getting attribute type + types = meta.types() + + Methods + ------- + names + types + + Notes + ----- + Also maintains the list of attributes in order, i.e., doing for i in + meta, where meta is an instance of MetaData, will return the + different attribute names in the order they were defined. + """ + def __init__(self, rel, attr): + self.name = rel + self._attributes = {a.name: a for a in attr} + + def __repr__(self): + msg = "" + msg += f"Dataset: {self.name}\n" + for i in self._attributes: + msg += f"\t{i}'s type is {self._attributes[i].type_name}" + if self._attributes[i].range: + msg += f", range is {str(self._attributes[i].range)}" + msg += '\n' + return msg + + def __iter__(self): + return iter(self._attributes) + + def __getitem__(self, key): + attr = self._attributes[key] + + return (attr.type_name, attr.range) + + def names(self): + """Return the list of attribute names. + + Returns + ------- + attrnames : list of str + The attribute names. + """ + return list(self._attributes) + + def types(self): + """Return the list of attribute types. + + Returns + ------- + attr_types : list of str + The attribute types. + """ + attr_types = [self._attributes[name].type_name + for name in self._attributes] + return attr_types + + +def loadarff(f): + """ + Read an arff file. + + The data is returned as a record array, which can be accessed much like + a dictionary of NumPy arrays. For example, if one of the attributes is + called 'pressure', then its first 10 data points can be accessed from the + ``data`` record array like so: ``data['pressure'][0:10]`` + + + Parameters + ---------- + f : file-like or str + File-like object to read from, or filename to open. + + Returns + ------- + data : record array + The data of the arff file, accessible by attribute names. + meta : `MetaData` + Contains information about the arff file such as name and + type of attributes, the relation (name of the dataset), etc. + + Raises + ------ + ParseArffError + This is raised if the given file is not ARFF-formatted. + NotImplementedError + The ARFF file has an attribute which is not supported yet. + + Notes + ----- + + This function should be able to read most arff files. Not + implemented functionality include: + + * date type attributes + * string type attributes + + It can read files with numeric and nominal attributes. It cannot read + files with sparse data ({} in the file). However, this function can + read files with missing data (? in the file), representing the data + points as NaNs. + + Examples + -------- + >>> from scipy.io import arff + >>> from io import StringIO + >>> content = \"\"\" + ... @relation foo + ... @attribute width numeric + ... @attribute height numeric + ... @attribute color {red,green,blue,yellow,black} + ... @data + ... 5.0,3.25,blue + ... 4.5,3.75,green + ... 3.0,4.00,red + ... \"\"\" + >>> f = StringIO(content) + >>> data, meta = arff.loadarff(f) + >>> data + array([(5.0, 3.25, 'blue'), (4.5, 3.75, 'green'), (3.0, 4.0, 'red')], + dtype=[('width', '>> meta + Dataset: foo + \twidth's type is numeric + \theight's type is numeric + \tcolor's type is nominal, range is ('red', 'green', 'blue', 'yellow', 'black') + + """ + if hasattr(f, 'read'): + ofile = f + else: + ofile = open(f) + try: + return _loadarff(ofile) + finally: + if ofile is not f: # only close what we opened + ofile.close() + + +def _loadarff(ofile): + # Parse the header file + try: + rel, attr = read_header(ofile) + except ValueError as e: + msg = "Error while parsing header, error was: " + str(e) + raise ParseArffError(msg) from e + + # Check whether we have a string attribute (not supported yet) + hasstr = False + for a in attr: + if isinstance(a, StringAttribute): + hasstr = True + + meta = MetaData(rel, attr) + + # XXX The following code is not great + # Build the type descriptor descr and the list of converters to convert + # each attribute to the suitable type (which should match the one in + # descr). + + # This can be used once we want to support integer as integer values and + # not as numeric anymore (using masked arrays ?). + + if hasstr: + # How to support string efficiently ? Ideally, we should know the max + # size of the string before allocating the numpy array. + raise NotImplementedError("String attributes not supported yet, sorry") + + ni = len(attr) + + def generator(row_iter, delim=','): + # TODO: this is where we are spending time (~80%). I think things + # could be made more efficiently: + # - We could for example "compile" the function, because some values + # do not change here. + # - The function to convert a line to dtyped values could also be + # generated on the fly from a string and be executed instead of + # looping. + # - The regex are overkill: for comments, checking that a line starts + # by % should be enough and faster, and for empty lines, same thing + # --> this does not seem to change anything. + + # 'compiling' the range since it does not change + # Note, I have already tried zipping the converters and + # row elements and got slightly worse performance. + elems = list(range(ni)) + + dialect = None + for raw in row_iter: + # We do not abstract skipping comments and empty lines for + # performance reasons. + if r_comment.match(raw) or r_empty.match(raw): + continue + + row, dialect = split_data_line(raw, dialect) + + yield tuple([attr[i].parse_data(row[i]) for i in elems]) + + a = list(generator(ofile)) + # No error should happen here: it is a bug otherwise + data = np.array(a, [(a.name, a.dtype) for a in attr]) + return data, meta + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/arffread.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/arffread.py new file mode 100644 index 0000000000000000000000000000000000000000..80ceffbc8936a27ba84c6749a7402cf41acfe090 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/arffread.py @@ -0,0 +1,19 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.arff` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'MetaData', 'loadarff', 'ArffError', 'ParseArffError', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.arff", module="arffread", + private_modules=["_arffread"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c96dbd034e61da6bda323ce68136339237ccbc1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__pycache__/test_arffread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__pycache__/test_arffread.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5341cc0736c857595916a8617beb68a4d507e24 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/__pycache__/test_arffread.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/iris.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/iris.arff new file mode 100644 index 0000000000000000000000000000000000000000..2634fca53ae203fc636679a08207e5c2bf51a27d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/iris.arff @@ -0,0 +1,225 @@ +% 1. Title: Iris Plants Database +% +% 2. Sources: +% (a) Creator: R.A. Fisher +% (b) Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov) +% (c) Date: July, 1988 +% +% 3. Past Usage: +% - Publications: too many to mention!!! Here are a few. +% 1. Fisher,R.A. "The use of multiple measurements in taxonomic problems" +% Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions +% to Mathematical Statistics" (John Wiley, NY, 1950). +% 2. Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis. +% (Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218. +% 3. Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System +% Structure and Classification Rule for Recognition in Partially Exposed +% Environments". IEEE Transactions on Pattern Analysis and Machine +% Intelligence, Vol. PAMI-2, No. 1, 67-71. +% -- Results: +% -- very low misclassification rates (0% for the setosa class) +% 4. Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE +% Transactions on Information Theory, May 1972, 431-433. +% -- Results: +% -- very low misclassification rates again +% 5. See also: 1988 MLC Proceedings, 54-64. Cheeseman et al's AUTOCLASS II +% conceptual clustering system finds 3 classes in the data. +% +% 4. Relevant Information: +% --- This is perhaps the best known database to be found in the pattern +% recognition literature. Fisher's paper is a classic in the field +% and is referenced frequently to this day. (See Duda & Hart, for +% example.) The data set contains 3 classes of 50 instances each, +% where each class refers to a type of iris plant. One class is +% linearly separable from the other 2; the latter are NOT linearly +% separable from each other. +% --- Predicted attribute: class of iris plant. +% --- This is an exceedingly simple domain. +% +% 5. Number of Instances: 150 (50 in each of three classes) +% +% 6. Number of Attributes: 4 numeric, predictive attributes and the class +% +% 7. Attribute Information: +% 1. sepal length in cm +% 2. sepal width in cm +% 3. petal length in cm +% 4. petal width in cm +% 5. class: +% -- Iris Setosa +% -- Iris Versicolour +% -- Iris Virginica +% +% 8. Missing Attribute Values: None +% +% Summary Statistics: +% Min Max Mean SD Class Correlation +% sepal length: 4.3 7.9 5.84 0.83 0.7826 +% sepal width: 2.0 4.4 3.05 0.43 -0.4194 +% petal length: 1.0 6.9 3.76 1.76 0.9490 (high!) +% petal width: 0.1 2.5 1.20 0.76 0.9565 (high!) +% +% 9. Class Distribution: 33.3% for each of 3 classes. + +@RELATION iris + +@ATTRIBUTE sepallength REAL +@ATTRIBUTE sepalwidth REAL +@ATTRIBUTE petallength REAL +@ATTRIBUTE petalwidth REAL +@ATTRIBUTE class {Iris-setosa,Iris-versicolor,Iris-virginica} + +@DATA +5.1,3.5,1.4,0.2,Iris-setosa +4.9,3.0,1.4,0.2,Iris-setosa +4.7,3.2,1.3,0.2,Iris-setosa +4.6,3.1,1.5,0.2,Iris-setosa +5.0,3.6,1.4,0.2,Iris-setosa +5.4,3.9,1.7,0.4,Iris-setosa +4.6,3.4,1.4,0.3,Iris-setosa +5.0,3.4,1.5,0.2,Iris-setosa +4.4,2.9,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5.4,3.7,1.5,0.2,Iris-setosa +4.8,3.4,1.6,0.2,Iris-setosa +4.8,3.0,1.4,0.1,Iris-setosa +4.3,3.0,1.1,0.1,Iris-setosa +5.8,4.0,1.2,0.2,Iris-setosa +5.7,4.4,1.5,0.4,Iris-setosa +5.4,3.9,1.3,0.4,Iris-setosa +5.1,3.5,1.4,0.3,Iris-setosa +5.7,3.8,1.7,0.3,Iris-setosa +5.1,3.8,1.5,0.3,Iris-setosa +5.4,3.4,1.7,0.2,Iris-setosa +5.1,3.7,1.5,0.4,Iris-setosa +4.6,3.6,1.0,0.2,Iris-setosa +5.1,3.3,1.7,0.5,Iris-setosa +4.8,3.4,1.9,0.2,Iris-setosa +5.0,3.0,1.6,0.2,Iris-setosa +5.0,3.4,1.6,0.4,Iris-setosa +5.2,3.5,1.5,0.2,Iris-setosa +5.2,3.4,1.4,0.2,Iris-setosa +4.7,3.2,1.6,0.2,Iris-setosa +4.8,3.1,1.6,0.2,Iris-setosa +5.4,3.4,1.5,0.4,Iris-setosa +5.2,4.1,1.5,0.1,Iris-setosa +5.5,4.2,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5.0,3.2,1.2,0.2,Iris-setosa +5.5,3.5,1.3,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +4.4,3.0,1.3,0.2,Iris-setosa +5.1,3.4,1.5,0.2,Iris-setosa +5.0,3.5,1.3,0.3,Iris-setosa +4.5,2.3,1.3,0.3,Iris-setosa +4.4,3.2,1.3,0.2,Iris-setosa +5.0,3.5,1.6,0.6,Iris-setosa +5.1,3.8,1.9,0.4,Iris-setosa +4.8,3.0,1.4,0.3,Iris-setosa +5.1,3.8,1.6,0.2,Iris-setosa +4.6,3.2,1.4,0.2,Iris-setosa +5.3,3.7,1.5,0.2,Iris-setosa +5.0,3.3,1.4,0.2,Iris-setosa +7.0,3.2,4.7,1.4,Iris-versicolor +6.4,3.2,4.5,1.5,Iris-versicolor +6.9,3.1,4.9,1.5,Iris-versicolor +5.5,2.3,4.0,1.3,Iris-versicolor +6.5,2.8,4.6,1.5,Iris-versicolor +5.7,2.8,4.5,1.3,Iris-versicolor +6.3,3.3,4.7,1.6,Iris-versicolor +4.9,2.4,3.3,1.0,Iris-versicolor +6.6,2.9,4.6,1.3,Iris-versicolor +5.2,2.7,3.9,1.4,Iris-versicolor +5.0,2.0,3.5,1.0,Iris-versicolor +5.9,3.0,4.2,1.5,Iris-versicolor +6.0,2.2,4.0,1.0,Iris-versicolor +6.1,2.9,4.7,1.4,Iris-versicolor +5.6,2.9,3.6,1.3,Iris-versicolor +6.7,3.1,4.4,1.4,Iris-versicolor +5.6,3.0,4.5,1.5,Iris-versicolor +5.8,2.7,4.1,1.0,Iris-versicolor +6.2,2.2,4.5,1.5,Iris-versicolor +5.6,2.5,3.9,1.1,Iris-versicolor +5.9,3.2,4.8,1.8,Iris-versicolor +6.1,2.8,4.0,1.3,Iris-versicolor +6.3,2.5,4.9,1.5,Iris-versicolor +6.1,2.8,4.7,1.2,Iris-versicolor +6.4,2.9,4.3,1.3,Iris-versicolor +6.6,3.0,4.4,1.4,Iris-versicolor +6.8,2.8,4.8,1.4,Iris-versicolor +6.7,3.0,5.0,1.7,Iris-versicolor +6.0,2.9,4.5,1.5,Iris-versicolor +5.7,2.6,3.5,1.0,Iris-versicolor +5.5,2.4,3.8,1.1,Iris-versicolor +5.5,2.4,3.7,1.0,Iris-versicolor +5.8,2.7,3.9,1.2,Iris-versicolor +6.0,2.7,5.1,1.6,Iris-versicolor +5.4,3.0,4.5,1.5,Iris-versicolor +6.0,3.4,4.5,1.6,Iris-versicolor +6.7,3.1,4.7,1.5,Iris-versicolor +6.3,2.3,4.4,1.3,Iris-versicolor +5.6,3.0,4.1,1.3,Iris-versicolor +5.5,2.5,4.0,1.3,Iris-versicolor +5.5,2.6,4.4,1.2,Iris-versicolor +6.1,3.0,4.6,1.4,Iris-versicolor +5.8,2.6,4.0,1.2,Iris-versicolor +5.0,2.3,3.3,1.0,Iris-versicolor +5.6,2.7,4.2,1.3,Iris-versicolor +5.7,3.0,4.2,1.2,Iris-versicolor +5.7,2.9,4.2,1.3,Iris-versicolor +6.2,2.9,4.3,1.3,Iris-versicolor +5.1,2.5,3.0,1.1,Iris-versicolor +5.7,2.8,4.1,1.3,Iris-versicolor +6.3,3.3,6.0,2.5,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +7.1,3.0,5.9,2.1,Iris-virginica +6.3,2.9,5.6,1.8,Iris-virginica +6.5,3.0,5.8,2.2,Iris-virginica +7.6,3.0,6.6,2.1,Iris-virginica +4.9,2.5,4.5,1.7,Iris-virginica +7.3,2.9,6.3,1.8,Iris-virginica +6.7,2.5,5.8,1.8,Iris-virginica +7.2,3.6,6.1,2.5,Iris-virginica +6.5,3.2,5.1,2.0,Iris-virginica +6.4,2.7,5.3,1.9,Iris-virginica +6.8,3.0,5.5,2.1,Iris-virginica +5.7,2.5,5.0,2.0,Iris-virginica +5.8,2.8,5.1,2.4,Iris-virginica +6.4,3.2,5.3,2.3,Iris-virginica +6.5,3.0,5.5,1.8,Iris-virginica +7.7,3.8,6.7,2.2,Iris-virginica +7.7,2.6,6.9,2.3,Iris-virginica +6.0,2.2,5.0,1.5,Iris-virginica +6.9,3.2,5.7,2.3,Iris-virginica +5.6,2.8,4.9,2.0,Iris-virginica +7.7,2.8,6.7,2.0,Iris-virginica +6.3,2.7,4.9,1.8,Iris-virginica +6.7,3.3,5.7,2.1,Iris-virginica +7.2,3.2,6.0,1.8,Iris-virginica +6.2,2.8,4.8,1.8,Iris-virginica +6.1,3.0,4.9,1.8,Iris-virginica +6.4,2.8,5.6,2.1,Iris-virginica +7.2,3.0,5.8,1.6,Iris-virginica +7.4,2.8,6.1,1.9,Iris-virginica +7.9,3.8,6.4,2.0,Iris-virginica +6.4,2.8,5.6,2.2,Iris-virginica +6.3,2.8,5.1,1.5,Iris-virginica +6.1,2.6,5.6,1.4,Iris-virginica +7.7,3.0,6.1,2.3,Iris-virginica +6.3,3.4,5.6,2.4,Iris-virginica +6.4,3.1,5.5,1.8,Iris-virginica +6.0,3.0,4.8,1.8,Iris-virginica +6.9,3.1,5.4,2.1,Iris-virginica +6.7,3.1,5.6,2.4,Iris-virginica +6.9,3.1,5.1,2.3,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +6.8,3.2,5.9,2.3,Iris-virginica +6.7,3.3,5.7,2.5,Iris-virginica +6.7,3.0,5.2,2.3,Iris-virginica +6.3,2.5,5.0,1.9,Iris-virginica +6.5,3.0,5.2,2.0,Iris-virginica +6.2,3.4,5.4,2.3,Iris-virginica +5.9,3.0,5.1,1.8,Iris-virginica +% +% +% diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/missing.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/missing.arff new file mode 100644 index 0000000000000000000000000000000000000000..253311895dd4c2aaa1726246ac05e88332cae751 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/missing.arff @@ -0,0 +1,8 @@ +% This arff file contains some missing data +@relation missing +@attribute yop real +@attribute yap real +@data +1,5 +2,4 +?,? diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/nodata.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/nodata.arff new file mode 100644 index 0000000000000000000000000000000000000000..c9e3b1f8c147908ac776d3578d14473608af0739 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/nodata.arff @@ -0,0 +1,11 @@ +@RELATION iris + +@ATTRIBUTE sepallength REAL +@ATTRIBUTE sepalwidth REAL +@ATTRIBUTE petallength REAL +@ATTRIBUTE petalwidth REAL +@ATTRIBUTE class {Iris-setosa,Iris-versicolor,Iris-virginica} + +@DATA + +% This file has no data diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/quoted_nominal.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/quoted_nominal.arff new file mode 100644 index 0000000000000000000000000000000000000000..20b73cde998c21cf023b49b7425a87632146a139 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/quoted_nominal.arff @@ -0,0 +1,13 @@ +% Regression test for issue #10232 : Exception in loadarff with quoted nominal attributes +% Spaces between elements are stripped by the parser + +@relation SOME_DATA +@attribute age numeric +@attribute smoker {'yes', 'no'} +@data +18, 'no' +24, 'yes' +44, 'no' +56, 'no' +89,'yes' +11, 'no' diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/quoted_nominal_spaces.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/quoted_nominal_spaces.arff new file mode 100644 index 0000000000000000000000000000000000000000..613ca783139d7712de422eff9cf9aa710f9e94f0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/quoted_nominal_spaces.arff @@ -0,0 +1,13 @@ +% Regression test for issue #10232 : Exception in loadarff with quoted nominal attributes +% Spaces inside quotes are NOT stripped by the parser + +@relation SOME_DATA +@attribute age numeric +@attribute smoker {' yes', 'no '} +@data +18,'no ' +24,' yes' +44,'no ' +56,'no ' +89,' yes' +11,'no ' diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test1.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test1.arff new file mode 100644 index 0000000000000000000000000000000000000000..f4094225d16c5a7dd1c1a83ea5810cfa5e0c3cb9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test1.arff @@ -0,0 +1,10 @@ +@RELATION test1 + +@ATTRIBUTE attr0 REAL +@ATTRIBUTE attr1 REAL +@ATTRIBUTE attr2 REAL +@ATTRIBUTE attr3 REAL +@ATTRIBUTE class {class0, class1, class2, class3} + +@DATA +0.1, 0.2, 0.3, 0.4,class1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test10.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test10.arff new file mode 100644 index 0000000000000000000000000000000000000000..766c121383781011c505e6cb69ff2475db9759c4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test10.arff @@ -0,0 +1,8 @@ +@relation test9 + +@attribute attr_relational relational + @attribute attr_number integer +@end attr_relational + +@data +'0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n501\n502\n503\n504\n505\n506\n507\n508\n509\n510\n511\n512\n513\n514\n515\n516\n517\n518\n519\n520\n521\n522\n523\n524\n525\n526\n527\n528\n529\n530\n531\n532\n533\n534\n535\n536\n537\n538\n539\n540\n541\n542\n543\n544\n545\n546\n547\n548\n549\n550\n551\n552\n553\n554\n555\n556\n557\n558\n559\n560\n561\n562\n563\n564\n565\n566\n567\n568\n569\n570\n571\n572\n573\n574\n575\n576\n577\n578\n579\n580\n581\n582\n583\n584\n585\n586\n587\n588\n589\n590\n591\n592\n593\n594\n595\n596\n597\n598\n599\n600\n601\n602\n603\n604\n605\n606\n607\n608\n609\n610\n611\n612\n613\n614\n615\n616\n617\n618\n619\n620\n621\n622\n623\n624\n625\n626\n627\n628\n629\n630\n631\n632\n633\n634\n635\n636\n637\n638\n639\n640\n641\n642\n643\n644\n645\n646\n647\n648\n649\n650\n651\n652\n653\n654\n655\n656\n657\n658\n659\n660\n661\n662\n663\n664\n665\n666\n667\n668\n669\n670\n671\n672\n673\n674\n675\n676\n677\n678\n679\n680\n681\n682\n683\n684\n685\n686\n687\n688\n689\n690\n691\n692\n693\n694\n695\n696\n697\n698\n699\n700\n701\n702\n703\n704\n705\n706\n707\n708\n709\n710\n711\n712\n713\n714\n715\n716\n717\n718\n719\n720\n721\n722\n723\n724\n725\n726\n727\n728\n729\n730\n731\n732\n733\n734\n735\n736\n737\n738\n739\n740\n741\n742\n743\n744\n745\n746\n747\n748\n749\n750\n751\n752\n753\n754\n755\n756\n757\n758\n759\n760\n761\n762\n763\n764\n765\n766\n767\n768\n769\n770\n771\n772\n773\n774\n775\n776\n777\n778\n779\n780\n781\n782\n783\n784\n785\n786\n787\n788\n789\n790\n791\n792\n793\n794\n795\n796\n797\n798\n799\n800\n801\n802\n803\n804\n805\n806\n807\n808\n809\n810\n811\n812\n813\n814\n815\n816\n817\n818\n819\n820\n821\n822\n823\n824\n825\n826\n827\n828\n829\n830\n831\n832\n833\n834\n835\n836\n837\n838\n839\n840\n841\n842\n843\n844\n845\n846\n847\n848\n849\n850\n851\n852\n853\n854\n855\n856\n857\n858\n859\n860\n861\n862\n863\n864\n865\n866\n867\n868\n869\n870\n871\n872\n873\n874\n875\n876\n877\n878\n879\n880\n881\n882\n883\n884\n885\n886\n887\n888\n889\n890\n891\n892\n893\n894\n895\n896\n897\n898\n899\n900\n901\n902\n903\n904\n905\n906\n907\n908\n909\n910\n911\n912\n913\n914\n915\n916\n917\n918\n919\n920\n921\n922\n923\n924\n925\n926\n927\n928\n929\n930\n931\n932\n933\n934\n935\n936\n937\n938\n939\n940\n941\n942\n943\n944\n945\n946\n947\n948\n949\n950\n951\n952\n953\n954\n955\n956\n957\n958\n959\n960\n961\n962\n963\n964\n965\n966\n967\n968\n969\n970\n971\n972\n973\n974\n975\n976\n977\n978\n979\n980\n981\n982\n983\n984\n985\n986\n987\n988\n989\n990\n991\n992\n993\n994\n995\n996\n997\n998\n999\n1000\n1001\n1002\n1003\n1004\n1005\n1006\n1007\n1008\n1009\n1010\n1011\n1012\n1013\n1014\n1015\n1016\n1017\n1018\n1019\n1020\n1021\n1022\n1023\n1024\n1025\n1026\n1027\n1028\n1029\n1030\n1031\n1032\n1033\n1034\n1035\n1036\n1037\n1038\n1039\n1040\n1041\n1042\n1043\n1044\n1045\n1046\n1047\n1048\n1049\n1050\n1051\n1052\n1053\n1054\n1055\n1056\n1057\n1058\n1059\n1060\n1061\n1062\n1063\n1064\n1065\n1066\n1067\n1068\n1069\n1070\n1071\n1072\n1073\n1074\n1075\n1076\n1077\n1078\n1079\n1080\n1081\n1082\n1083\n1084\n1085\n1086\n1087\n1088\n1089\n1090\n1091\n1092\n1093\n1094\n1095\n1096\n1097\n1098\n1099\n1100\n1101\n1102\n1103\n1104\n1105\n1106\n1107\n1108\n1109\n1110\n1111\n1112\n1113\n1114\n1115\n1116\n1117\n1118\n1119\n1120\n1121\n1122\n1123\n1124\n1125\n1126\n1127\n1128\n1129\n1130\n1131\n1132\n1133\n1134\n1135\n1136\n1137\n1138\n1139\n1140\n1141\n1142\n1143\n1144\n1145\n1146\n1147\n1148\n1149\n1150\n1151\n1152\n1153\n1154\n1155\n1156\n1157\n1158\n1159\n1160\n1161\n1162\n1163\n1164\n1165\n1166\n1167\n1168\n1169\n1170\n1171\n1172\n1173\n1174\n1175\n1176\n1177\n1178\n1179\n1180\n1181\n1182\n1183\n1184\n1185\n1186\n1187\n1188\n1189\n1190\n1191\n1192\n1193\n1194\n1195\n1196\n1197\n1198\n1199\n1200\n1201\n1202\n1203\n1204\n1205\n1206\n1207\n1208\n1209\n1210\n1211\n1212\n1213\n1214\n1215\n1216\n1217\n1218\n1219\n1220\n1221\n1222\n1223\n1224\n1225\n1226\n1227\n1228\n1229\n1230\n1231\n1232\n1233\n1234\n1235\n1236\n1237\n1238\n1239\n1240\n1241\n1242\n1243\n1244\n1245\n1246\n1247\n1248\n1249\n1250\n1251\n1252\n1253\n1254\n1255\n1256\n1257\n1258\n1259\n1260\n1261\n1262\n1263\n1264\n1265\n1266\n1267\n1268\n1269\n1270\n1271\n1272\n1273\n1274\n1275\n1276\n1277\n1278\n1279\n1280\n1281\n1282\n1283\n1284\n1285\n1286\n1287\n1288\n1289\n1290\n1291\n1292\n1293\n1294\n1295\n1296\n1297\n1298\n1299\n1300\n1301\n1302\n1303\n1304\n1305\n1306\n1307\n1308\n1309\n1310\n1311\n1312\n1313\n1314\n1315\n1316\n1317\n1318\n1319\n1320\n1321\n1322\n1323\n1324\n1325\n1326\n1327\n1328\n1329\n1330\n1331\n1332\n1333\n1334\n1335\n1336\n1337\n1338\n1339\n1340\n1341\n1342\n1343\n1344\n1345\n1346\n1347\n1348\n1349\n1350\n1351\n1352\n1353\n1354\n1355\n1356\n1357\n1358\n1359\n1360\n1361\n1362\n1363\n1364\n1365\n1366\n1367\n1368\n1369\n1370\n1371\n1372\n1373\n1374\n1375\n1376\n1377\n1378\n1379\n1380\n1381\n1382\n1383\n1384\n1385\n1386\n1387\n1388\n1389\n1390\n1391\n1392\n1393\n1394\n1395\n1396\n1397\n1398\n1399\n1400\n1401\n1402\n1403\n1404\n1405\n1406\n1407\n1408\n1409\n1410\n1411\n1412\n1413\n1414\n1415\n1416\n1417\n1418\n1419\n1420\n1421\n1422\n1423\n1424\n1425\n1426\n1427\n1428\n1429\n1430\n1431\n1432\n1433\n1434\n1435\n1436\n1437\n1438\n1439\n1440\n1441\n1442\n1443\n1444\n1445\n1446\n1447\n1448\n1449\n1450\n1451\n1452\n1453\n1454\n1455\n1456\n1457\n1458\n1459\n1460\n1461\n1462\n1463\n1464\n1465\n1466\n1467\n1468\n1469\n1470\n1471\n1472\n1473\n1474\n1475\n1476\n1477\n1478\n1479\n1480\n1481\n1482\n1483\n1484\n1485\n1486\n1487\n1488\n1489\n1490\n1491\n1492\n1493\n1494\n1495\n1496\n1497\n1498\n1499\n1500\n1501\n1502\n1503\n1504\n1505\n1506\n1507\n1508\n1509\n1510\n1511\n1512\n1513\n1514\n1515\n1516\n1517\n1518\n1519\n1520\n1521\n1522\n1523\n1524\n1525\n1526\n1527\n1528\n1529\n1530\n1531\n1532\n1533\n1534\n1535\n1536\n1537\n1538\n1539\n1540\n1541\n1542\n1543\n1544\n1545\n1546\n1547\n1548\n1549\n1550\n1551\n1552\n1553\n1554\n1555\n1556\n1557\n1558\n1559\n1560\n1561\n1562\n1563\n1564\n1565\n1566\n1567\n1568\n1569\n1570\n1571\n1572\n1573\n1574\n1575\n1576\n1577\n1578\n1579\n1580\n1581\n1582\n1583\n1584\n1585\n1586\n1587\n1588\n1589\n1590\n1591\n1592\n1593\n1594\n1595\n1596\n1597\n1598\n1599\n1600\n1601\n1602\n1603\n1604\n1605\n1606\n1607\n1608\n1609\n1610\n1611\n1612\n1613\n1614\n1615\n1616\n1617\n1618\n1619\n1620\n1621\n1622\n1623\n1624\n1625\n1626\n1627\n1628\n1629\n1630\n1631\n1632\n1633\n1634\n1635\n1636\n1637\n1638\n1639\n1640\n1641\n1642\n1643\n1644\n1645\n1646\n1647\n1648\n1649\n1650\n1651\n1652\n1653\n1654\n1655\n1656\n1657\n1658\n1659\n1660\n1661\n1662\n1663\n1664\n1665\n1666\n1667\n1668\n1669\n1670\n1671\n1672\n1673\n1674\n1675\n1676\n1677\n1678\n1679\n1680\n1681\n1682\n1683\n1684\n1685\n1686\n1687\n1688\n1689\n1690\n1691\n1692\n1693\n1694\n1695\n1696\n1697\n1698\n1699\n1700\n1701\n1702\n1703\n1704\n1705\n1706\n1707\n1708\n1709\n1710\n1711\n1712\n1713\n1714\n1715\n1716\n1717\n1718\n1719\n1720\n1721\n1722\n1723\n1724\n1725\n1726\n1727\n1728\n1729\n1730\n1731\n1732\n1733\n1734\n1735\n1736\n1737\n1738\n1739\n1740\n1741\n1742\n1743\n1744\n1745\n1746\n1747\n1748\n1749\n1750\n1751\n1752\n1753\n1754\n1755\n1756\n1757\n1758\n1759\n1760\n1761\n1762\n1763\n1764\n1765\n1766\n1767\n1768\n1769\n1770\n1771\n1772\n1773\n1774\n1775\n1776\n1777\n1778\n1779\n1780\n1781\n1782\n1783\n1784\n1785\n1786\n1787\n1788\n1789\n1790\n1791\n1792\n1793\n1794\n1795\n1796\n1797\n1798\n1799\n1800\n1801\n1802\n1803\n1804\n1805\n1806\n1807\n1808\n1809\n1810\n1811\n1812\n1813\n1814\n1815\n1816\n1817\n1818\n1819\n1820\n1821\n1822\n1823\n1824\n1825\n1826\n1827\n1828\n1829\n1830\n1831\n1832\n1833\n1834\n1835\n1836\n1837\n1838\n1839\n1840\n1841\n1842\n1843\n1844\n1845\n1846\n1847\n1848\n1849\n1850\n1851\n1852\n1853\n1854\n1855\n1856\n1857\n1858\n1859\n1860\n1861\n1862\n1863\n1864\n1865\n1866\n1867\n1868\n1869\n1870\n1871\n1872\n1873\n1874\n1875\n1876\n1877\n1878\n1879\n1880\n1881\n1882\n1883\n1884\n1885\n1886\n1887\n1888\n1889\n1890\n1891\n1892\n1893\n1894\n1895\n1896\n1897\n1898\n1899\n1900\n1901\n1902\n1903\n1904\n1905\n1906\n1907\n1908\n1909\n1910\n1911\n1912\n1913\n1914\n1915\n1916\n1917\n1918\n1919\n1920\n1921\n1922\n1923\n1924\n1925\n1926\n1927\n1928\n1929\n1930\n1931\n1932\n1933\n1934\n1935\n1936\n1937\n1938\n1939\n1940\n1941\n1942\n1943\n1944\n1945\n1946\n1947\n1948\n1949\n1950\n1951\n1952\n1953\n1954\n1955\n1956\n1957\n1958\n1959\n1960\n1961\n1962\n1963\n1964\n1965\n1966\n1967\n1968\n1969\n1970\n1971\n1972\n1973\n1974\n1975\n1976\n1977\n1978\n1979\n1980\n1981\n1982\n1983\n1984\n1985\n1986\n1987\n1988\n1989\n1990\n1991\n1992\n1993\n1994\n1995\n1996\n1997\n1998\n1999\n2000\n2001\n2002\n2003\n2004\n2005\n2006\n2007\n2008\n2009\n2010\n2011\n2012\n2013\n2014\n2015\n2016\n2017\n2018\n2019\n2020\n2021\n2022\n2023\n2024\n2025\n2026\n2027\n2028\n2029\n2030\n2031\n2032\n2033\n2034\n2035\n2036\n2037\n2038\n2039\n2040\n2041\n2042\n2043\n2044\n2045\n2046\n2047\n2048\n2049\n2050\n2051\n2052\n2053\n2054\n2055\n2056\n2057\n2058\n2059\n2060\n2061\n2062\n2063\n2064\n2065\n2066\n2067\n2068\n2069\n2070\n2071\n2072\n2073\n2074\n2075\n2076\n2077\n2078\n2079\n2080\n2081\n2082\n2083\n2084\n2085\n2086\n2087\n2088\n2089\n2090\n2091\n2092\n2093\n2094\n2095\n2096\n2097\n2098\n2099\n2100\n2101\n2102\n2103\n2104\n2105\n2106\n2107\n2108\n2109\n2110\n2111\n2112\n2113\n2114\n2115\n2116\n2117\n2118\n2119\n2120\n2121\n2122\n2123\n2124\n2125\n2126\n2127\n2128\n2129\n2130\n2131\n2132\n2133\n2134\n2135\n2136\n2137\n2138\n2139\n2140\n2141\n2142\n2143\n2144\n2145\n2146\n2147\n2148\n2149\n2150\n2151\n2152\n2153\n2154\n2155\n2156\n2157\n2158\n2159\n2160\n2161\n2162\n2163\n2164\n2165\n2166\n2167\n2168\n2169\n2170\n2171\n2172\n2173\n2174\n2175\n2176\n2177\n2178\n2179\n2180\n2181\n2182\n2183\n2184\n2185\n2186\n2187\n2188\n2189\n2190\n2191\n2192\n2193\n2194\n2195\n2196\n2197\n2198\n2199\n2200\n2201\n2202\n2203\n2204\n2205\n2206\n2207\n2208\n2209\n2210\n2211\n2212\n2213\n2214\n2215\n2216\n2217\n2218\n2219\n2220\n2221\n2222\n2223\n2224\n2225\n2226\n2227\n2228\n2229\n2230\n2231\n2232\n2233\n2234\n2235\n2236\n2237\n2238\n2239\n2240\n2241\n2242\n2243\n2244\n2245\n2246\n2247\n2248\n2249\n2250\n2251\n2252\n2253\n2254\n2255\n2256\n2257\n2258\n2259\n2260\n2261\n2262\n2263\n2264\n2265\n2266\n2267\n2268\n2269\n2270\n2271\n2272\n2273\n2274\n2275\n2276\n2277\n2278\n2279\n2280\n2281\n2282\n2283\n2284\n2285\n2286\n2287\n2288\n2289\n2290\n2291\n2292\n2293\n2294\n2295\n2296\n2297\n2298\n2299\n2300\n2301\n2302\n2303\n2304\n2305\n2306\n2307\n2308\n2309\n2310\n2311\n2312\n2313\n2314\n2315\n2316\n2317\n2318\n2319\n2320\n2321\n2322\n2323\n2324\n2325\n2326\n2327\n2328\n2329\n2330\n2331\n2332\n2333\n2334\n2335\n2336\n2337\n2338\n2339\n2340\n2341\n2342\n2343\n2344\n2345\n2346\n2347\n2348\n2349\n2350\n2351\n2352\n2353\n2354\n2355\n2356\n2357\n2358\n2359\n2360\n2361\n2362\n2363\n2364\n2365\n2366\n2367\n2368\n2369\n2370\n2371\n2372\n2373\n2374\n2375\n2376\n2377\n2378\n2379\n2380\n2381\n2382\n2383\n2384\n2385\n2386\n2387\n2388\n2389\n2390\n2391\n2392\n2393\n2394\n2395\n2396\n2397\n2398\n2399\n2400\n2401\n2402\n2403\n2404\n2405\n2406\n2407\n2408\n2409\n2410\n2411\n2412\n2413\n2414\n2415\n2416\n2417\n2418\n2419\n2420\n2421\n2422\n2423\n2424\n2425\n2426\n2427\n2428\n2429\n2430\n2431\n2432\n2433\n2434\n2435\n2436\n2437\n2438\n2439\n2440\n2441\n2442\n2443\n2444\n2445\n2446\n2447\n2448\n2449\n2450\n2451\n2452\n2453\n2454\n2455\n2456\n2457\n2458\n2459\n2460\n2461\n2462\n2463\n2464\n2465\n2466\n2467\n2468\n2469\n2470\n2471\n2472\n2473\n2474\n2475\n2476\n2477\n2478\n2479\n2480\n2481\n2482\n2483\n2484\n2485\n2486\n2487\n2488\n2489\n2490\n2491\n2492\n2493\n2494\n2495\n2496\n2497\n2498\n2499\n2500\n2501\n2502\n2503\n2504\n2505\n2506\n2507\n2508\n2509\n2510\n2511\n2512\n2513\n2514\n2515\n2516\n2517\n2518\n2519\n2520\n2521\n2522\n2523\n2524\n2525\n2526\n2527\n2528\n2529\n2530\n2531\n2532\n2533\n2534\n2535\n2536\n2537\n2538\n2539\n2540\n2541\n2542\n2543\n2544\n2545\n2546\n2547\n2548\n2549\n2550\n2551\n2552\n2553\n2554\n2555\n2556\n2557\n2558\n2559\n2560\n2561\n2562\n2563\n2564\n2565\n2566\n2567\n2568\n2569\n2570\n2571\n2572\n2573\n2574\n2575\n2576\n2577\n2578\n2579\n2580\n2581\n2582\n2583\n2584\n2585\n2586\n2587\n2588\n2589\n2590\n2591\n2592\n2593\n2594\n2595\n2596\n2597\n2598\n2599\n2600\n2601\n2602\n2603\n2604\n2605\n2606\n2607\n2608\n2609\n2610\n2611\n2612\n2613\n2614\n2615\n2616\n2617\n2618\n2619\n2620\n2621\n2622\n2623\n2624\n2625\n2626\n2627\n2628\n2629\n2630\n2631\n2632\n2633\n2634\n2635\n2636\n2637\n2638\n2639\n2640\n2641\n2642\n2643\n2644\n2645\n2646\n2647\n2648\n2649\n2650\n2651\n2652\n2653\n2654\n2655\n2656\n2657\n2658\n2659\n2660\n2661\n2662\n2663\n2664\n2665\n2666\n2667\n2668\n2669\n2670\n2671\n2672\n2673\n2674\n2675\n2676\n2677\n2678\n2679\n2680\n2681\n2682\n2683\n2684\n2685\n2686\n2687\n2688\n2689\n2690\n2691\n2692\n2693\n2694\n2695\n2696\n2697\n2698\n2699\n2700\n2701\n2702\n2703\n2704\n2705\n2706\n2707\n2708\n2709\n2710\n2711\n2712\n2713\n2714\n2715\n2716\n2717\n2718\n2719\n2720\n2721\n2722\n2723\n2724\n2725\n2726\n2727\n2728\n2729\n2730\n2731\n2732\n2733\n2734\n2735\n2736\n2737\n2738\n2739\n2740\n2741\n2742\n2743\n2744\n2745\n2746\n2747\n2748\n2749\n2750\n2751\n2752\n2753\n2754\n2755\n2756\n2757\n2758\n2759\n2760\n2761\n2762\n2763\n2764\n2765\n2766\n2767\n2768\n2769\n2770\n2771\n2772\n2773\n2774\n2775\n2776\n2777\n2778\n2779\n2780\n2781\n2782\n2783\n2784\n2785\n2786\n2787\n2788\n2789\n2790\n2791\n2792\n2793\n2794\n2795\n2796\n2797\n2798\n2799\n2800\n2801\n2802\n2803\n2804\n2805\n2806\n2807\n2808\n2809\n2810\n2811\n2812\n2813\n2814\n2815\n2816\n2817\n2818\n2819\n2820\n2821\n2822\n2823\n2824\n2825\n2826\n2827\n2828\n2829\n2830\n2831\n2832\n2833\n2834\n2835\n2836\n2837\n2838\n2839\n2840\n2841\n2842\n2843\n2844\n2845\n2846\n2847\n2848\n2849\n2850\n2851\n2852\n2853\n2854\n2855\n2856\n2857\n2858\n2859\n2860\n2861\n2862\n2863\n2864\n2865\n2866\n2867\n2868\n2869\n2870\n2871\n2872\n2873\n2874\n2875\n2876\n2877\n2878\n2879\n2880\n2881\n2882\n2883\n2884\n2885\n2886\n2887\n2888\n2889\n2890\n2891\n2892\n2893\n2894\n2895\n2896\n2897\n2898\n2899\n2900\n2901\n2902\n2903\n2904\n2905\n2906\n2907\n2908\n2909\n2910\n2911\n2912\n2913\n2914\n2915\n2916\n2917\n2918\n2919\n2920\n2921\n2922\n2923\n2924\n2925\n2926\n2927\n2928\n2929\n2930\n2931\n2932\n2933\n2934\n2935\n2936\n2937\n2938\n2939\n2940\n2941\n2942\n2943\n2944\n2945\n2946\n2947\n2948\n2949\n2950\n2951\n2952\n2953\n2954\n2955\n2956\n2957\n2958\n2959\n2960\n2961\n2962\n2963\n2964\n2965\n2966\n2967\n2968\n2969\n2970\n2971\n2972\n2973\n2974\n2975\n2976\n2977\n2978\n2979\n2980\n2981\n2982\n2983\n2984\n2985\n2986\n2987\n2988\n2989\n2990\n2991\n2992\n2993\n2994\n2995\n2996\n2997\n2998\n2999\n3000\n3001\n3002\n3003\n3004\n3005\n3006\n3007\n3008\n3009\n3010\n3011\n3012\n3013\n3014\n3015\n3016\n3017\n3018\n3019\n3020\n3021\n3022\n3023\n3024\n3025\n3026\n3027\n3028\n3029\n3030\n3031\n3032\n3033\n3034\n3035\n3036\n3037\n3038\n3039\n3040\n3041\n3042\n3043\n3044\n3045\n3046\n3047\n3048\n3049\n3050\n3051\n3052\n3053\n3054\n3055\n3056\n3057\n3058\n3059\n3060\n3061\n3062\n3063\n3064\n3065\n3066\n3067\n3068\n3069\n3070\n3071\n3072\n3073\n3074\n3075\n3076\n3077\n3078\n3079\n3080\n3081\n3082\n3083\n3084\n3085\n3086\n3087\n3088\n3089\n3090\n3091\n3092\n3093\n3094\n3095\n3096\n3097\n3098\n3099\n3100\n3101\n3102\n3103\n3104\n3105\n3106\n3107\n3108\n3109\n3110\n3111\n3112\n3113\n3114\n3115\n3116\n3117\n3118\n3119\n3120\n3121\n3122\n3123\n3124\n3125\n3126\n3127\n3128\n3129\n3130\n3131\n3132\n3133\n3134\n3135\n3136\n3137\n3138\n3139\n3140\n3141\n3142\n3143\n3144\n3145\n3146\n3147\n3148\n3149\n3150\n3151\n3152\n3153\n3154\n3155\n3156\n3157\n3158\n3159\n3160\n3161\n3162\n3163\n3164\n3165\n3166\n3167\n3168\n3169\n3170\n3171\n3172\n3173\n3174\n3175\n3176\n3177\n3178\n3179\n3180\n3181\n3182\n3183\n3184\n3185\n3186\n3187\n3188\n3189\n3190\n3191\n3192\n3193\n3194\n3195\n3196\n3197\n3198\n3199\n3200\n3201\n3202\n3203\n3204\n3205\n3206\n3207\n3208\n3209\n3210\n3211\n3212\n3213\n3214\n3215\n3216\n3217\n3218\n3219\n3220\n3221\n3222\n3223\n3224\n3225\n3226\n3227\n3228\n3229\n3230\n3231\n3232\n3233\n3234\n3235\n3236\n3237\n3238\n3239\n3240\n3241\n3242\n3243\n3244\n3245\n3246\n3247\n3248\n3249\n3250\n3251\n3252\n3253\n3254\n3255\n3256\n3257\n3258\n3259\n3260\n3261\n3262\n3263\n3264\n3265\n3266\n3267\n3268\n3269\n3270\n3271\n3272\n3273\n3274\n3275\n3276\n3277\n3278\n3279\n3280\n3281\n3282\n3283\n3284\n3285\n3286\n3287\n3288\n3289\n3290\n3291\n3292\n3293\n3294\n3295\n3296\n3297\n3298\n3299\n3300\n3301\n3302\n3303\n3304\n3305\n3306\n3307\n3308\n3309\n3310\n3311\n3312\n3313\n3314\n3315\n3316\n3317\n3318\n3319\n3320\n3321\n3322\n3323\n3324\n3325\n3326\n3327\n3328\n3329\n3330\n3331\n3332\n3333\n3334\n3335\n3336\n3337\n3338\n3339\n3340\n3341\n3342\n3343\n3344\n3345\n3346\n3347\n3348\n3349\n3350\n3351\n3352\n3353\n3354\n3355\n3356\n3357\n3358\n3359\n3360\n3361\n3362\n3363\n3364\n3365\n3366\n3367\n3368\n3369\n3370\n3371\n3372\n3373\n3374\n3375\n3376\n3377\n3378\n3379\n3380\n3381\n3382\n3383\n3384\n3385\n3386\n3387\n3388\n3389\n3390\n3391\n3392\n3393\n3394\n3395\n3396\n3397\n3398\n3399\n3400\n3401\n3402\n3403\n3404\n3405\n3406\n3407\n3408\n3409\n3410\n3411\n3412\n3413\n3414\n3415\n3416\n3417\n3418\n3419\n3420\n3421\n3422\n3423\n3424\n3425\n3426\n3427\n3428\n3429\n3430\n3431\n3432\n3433\n3434\n3435\n3436\n3437\n3438\n3439\n3440\n3441\n3442\n3443\n3444\n3445\n3446\n3447\n3448\n3449\n3450\n3451\n3452\n3453\n3454\n3455\n3456\n3457\n3458\n3459\n3460\n3461\n3462\n3463\n3464\n3465\n3466\n3467\n3468\n3469\n3470\n3471\n3472\n3473\n3474\n3475\n3476\n3477\n3478\n3479\n3480\n3481\n3482\n3483\n3484\n3485\n3486\n3487\n3488\n3489\n3490\n3491\n3492\n3493\n3494\n3495\n3496\n3497\n3498\n3499\n3500\n3501\n3502\n3503\n3504\n3505\n3506\n3507\n3508\n3509\n3510\n3511\n3512\n3513\n3514\n3515\n3516\n3517\n3518\n3519\n3520\n3521\n3522\n3523\n3524\n3525\n3526\n3527\n3528\n3529\n3530\n3531\n3532\n3533\n3534\n3535\n3536\n3537\n3538\n3539\n3540\n3541\n3542\n3543\n3544\n3545\n3546\n3547\n3548\n3549\n3550\n3551\n3552\n3553\n3554\n3555\n3556\n3557\n3558\n3559\n3560\n3561\n3562\n3563\n3564\n3565\n3566\n3567\n3568\n3569\n3570\n3571\n3572\n3573\n3574\n3575\n3576\n3577\n3578\n3579\n3580\n3581\n3582\n3583\n3584\n3585\n3586\n3587\n3588\n3589\n3590\n3591\n3592\n3593\n3594\n3595\n3596\n3597\n3598\n3599\n3600\n3601\n3602\n3603\n3604\n3605\n3606\n3607\n3608\n3609\n3610\n3611\n3612\n3613\n3614\n3615\n3616\n3617\n3618\n3619\n3620\n3621\n3622\n3623\n3624\n3625\n3626\n3627\n3628\n3629\n3630\n3631\n3632\n3633\n3634\n3635\n3636\n3637\n3638\n3639\n3640\n3641\n3642\n3643\n3644\n3645\n3646\n3647\n3648\n3649\n3650\n3651\n3652\n3653\n3654\n3655\n3656\n3657\n3658\n3659\n3660\n3661\n3662\n3663\n3664\n3665\n3666\n3667\n3668\n3669\n3670\n3671\n3672\n3673\n3674\n3675\n3676\n3677\n3678\n3679\n3680\n3681\n3682\n3683\n3684\n3685\n3686\n3687\n3688\n3689\n3690\n3691\n3692\n3693\n3694\n3695\n3696\n3697\n3698\n3699\n3700\n3701\n3702\n3703\n3704\n3705\n3706\n3707\n3708\n3709\n3710\n3711\n3712\n3713\n3714\n3715\n3716\n3717\n3718\n3719\n3720\n3721\n3722\n3723\n3724\n3725\n3726\n3727\n3728\n3729\n3730\n3731\n3732\n3733\n3734\n3735\n3736\n3737\n3738\n3739\n3740\n3741\n3742\n3743\n3744\n3745\n3746\n3747\n3748\n3749\n3750\n3751\n3752\n3753\n3754\n3755\n3756\n3757\n3758\n3759\n3760\n3761\n3762\n3763\n3764\n3765\n3766\n3767\n3768\n3769\n3770\n3771\n3772\n3773\n3774\n3775\n3776\n3777\n3778\n3779\n3780\n3781\n3782\n3783\n3784\n3785\n3786\n3787\n3788\n3789\n3790\n3791\n3792\n3793\n3794\n3795\n3796\n3797\n3798\n3799\n3800\n3801\n3802\n3803\n3804\n3805\n3806\n3807\n3808\n3809\n3810\n3811\n3812\n3813\n3814\n3815\n3816\n3817\n3818\n3819\n3820\n3821\n3822\n3823\n3824\n3825\n3826\n3827\n3828\n3829\n3830\n3831\n3832\n3833\n3834\n3835\n3836\n3837\n3838\n3839\n3840\n3841\n3842\n3843\n3844\n3845\n3846\n3847\n3848\n3849\n3850\n3851\n3852\n3853\n3854\n3855\n3856\n3857\n3858\n3859\n3860\n3861\n3862\n3863\n3864\n3865\n3866\n3867\n3868\n3869\n3870\n3871\n3872\n3873\n3874\n3875\n3876\n3877\n3878\n3879\n3880\n3881\n3882\n3883\n3884\n3885\n3886\n3887\n3888\n3889\n3890\n3891\n3892\n3893\n3894\n3895\n3896\n3897\n3898\n3899\n3900\n3901\n3902\n3903\n3904\n3905\n3906\n3907\n3908\n3909\n3910\n3911\n3912\n3913\n3914\n3915\n3916\n3917\n3918\n3919\n3920\n3921\n3922\n3923\n3924\n3925\n3926\n3927\n3928\n3929\n3930\n3931\n3932\n3933\n3934\n3935\n3936\n3937\n3938\n3939\n3940\n3941\n3942\n3943\n3944\n3945\n3946\n3947\n3948\n3949\n3950\n3951\n3952\n3953\n3954\n3955\n3956\n3957\n3958\n3959\n3960\n3961\n3962\n3963\n3964\n3965\n3966\n3967\n3968\n3969\n3970\n3971\n3972\n3973\n3974\n3975\n3976\n3977\n3978\n3979\n3980\n3981\n3982\n3983\n3984\n3985\n3986\n3987\n3988\n3989\n3990\n3991\n3992\n3993\n3994\n3995\n3996\n3997\n3998\n3999\n4000\n4001\n4002\n4003\n4004\n4005\n4006\n4007\n4008\n4009\n4010\n4011\n4012\n4013\n4014\n4015\n4016\n4017\n4018\n4019\n4020\n4021\n4022\n4023\n4024\n4025\n4026\n4027\n4028\n4029\n4030\n4031\n4032\n4033\n4034\n4035\n4036\n4037\n4038\n4039\n4040\n4041\n4042\n4043\n4044\n4045\n4046\n4047\n4048\n4049\n4050\n4051\n4052\n4053\n4054\n4055\n4056\n4057\n4058\n4059\n4060\n4061\n4062\n4063\n4064\n4065\n4066\n4067\n4068\n4069\n4070\n4071\n4072\n4073\n4074\n4075\n4076\n4077\n4078\n4079\n4080\n4081\n4082\n4083\n4084\n4085\n4086\n4087\n4088\n4089\n4090\n4091\n4092\n4093\n4094\n4095\n4096\n4097\n4098\n4099\n4100\n4101\n4102\n4103\n4104\n4105\n4106\n4107\n4108\n4109\n4110\n4111\n4112\n4113\n4114\n4115\n4116\n4117\n4118\n4119\n4120\n4121\n4122\n4123\n4124\n4125\n4126\n4127\n4128\n4129\n4130\n4131\n4132\n4133\n4134\n4135\n4136\n4137\n4138\n4139\n4140\n4141\n4142\n4143\n4144\n4145\n4146\n4147\n4148\n4149\n4150\n4151\n4152\n4153\n4154\n4155\n4156\n4157\n4158\n4159\n4160\n4161\n4162\n4163\n4164\n4165\n4166\n4167\n4168\n4169\n4170\n4171\n4172\n4173\n4174\n4175\n4176\n4177\n4178\n4179\n4180\n4181\n4182\n4183\n4184\n4185\n4186\n4187\n4188\n4189\n4190\n4191\n4192\n4193\n4194\n4195\n4196\n4197\n4198\n4199\n4200\n4201\n4202\n4203\n4204\n4205\n4206\n4207\n4208\n4209\n4210\n4211\n4212\n4213\n4214\n4215\n4216\n4217\n4218\n4219\n4220\n4221\n4222\n4223\n4224\n4225\n4226\n4227\n4228\n4229\n4230\n4231\n4232\n4233\n4234\n4235\n4236\n4237\n4238\n4239\n4240\n4241\n4242\n4243\n4244\n4245\n4246\n4247\n4248\n4249\n4250\n4251\n4252\n4253\n4254\n4255\n4256\n4257\n4258\n4259\n4260\n4261\n4262\n4263\n4264\n4265\n4266\n4267\n4268\n4269\n4270\n4271\n4272\n4273\n4274\n4275\n4276\n4277\n4278\n4279\n4280\n4281\n4282\n4283\n4284\n4285\n4286\n4287\n4288\n4289\n4290\n4291\n4292\n4293\n4294\n4295\n4296\n4297\n4298\n4299\n4300\n4301\n4302\n4303\n4304\n4305\n4306\n4307\n4308\n4309\n4310\n4311\n4312\n4313\n4314\n4315\n4316\n4317\n4318\n4319\n4320\n4321\n4322\n4323\n4324\n4325\n4326\n4327\n4328\n4329\n4330\n4331\n4332\n4333\n4334\n4335\n4336\n4337\n4338\n4339\n4340\n4341\n4342\n4343\n4344\n4345\n4346\n4347\n4348\n4349\n4350\n4351\n4352\n4353\n4354\n4355\n4356\n4357\n4358\n4359\n4360\n4361\n4362\n4363\n4364\n4365\n4366\n4367\n4368\n4369\n4370\n4371\n4372\n4373\n4374\n4375\n4376\n4377\n4378\n4379\n4380\n4381\n4382\n4383\n4384\n4385\n4386\n4387\n4388\n4389\n4390\n4391\n4392\n4393\n4394\n4395\n4396\n4397\n4398\n4399\n4400\n4401\n4402\n4403\n4404\n4405\n4406\n4407\n4408\n4409\n4410\n4411\n4412\n4413\n4414\n4415\n4416\n4417\n4418\n4419\n4420\n4421\n4422\n4423\n4424\n4425\n4426\n4427\n4428\n4429\n4430\n4431\n4432\n4433\n4434\n4435\n4436\n4437\n4438\n4439\n4440\n4441\n4442\n4443\n4444\n4445\n4446\n4447\n4448\n4449\n4450\n4451\n4452\n4453\n4454\n4455\n4456\n4457\n4458\n4459\n4460\n4461\n4462\n4463\n4464\n4465\n4466\n4467\n4468\n4469\n4470\n4471\n4472\n4473\n4474\n4475\n4476\n4477\n4478\n4479\n4480\n4481\n4482\n4483\n4484\n4485\n4486\n4487\n4488\n4489\n4490\n4491\n4492\n4493\n4494\n4495\n4496\n4497\n4498\n4499\n4500\n4501\n4502\n4503\n4504\n4505\n4506\n4507\n4508\n4509\n4510\n4511\n4512\n4513\n4514\n4515\n4516\n4517\n4518\n4519\n4520\n4521\n4522\n4523\n4524\n4525\n4526\n4527\n4528\n4529\n4530\n4531\n4532\n4533\n4534\n4535\n4536\n4537\n4538\n4539\n4540\n4541\n4542\n4543\n4544\n4545\n4546\n4547\n4548\n4549\n4550\n4551\n4552\n4553\n4554\n4555\n4556\n4557\n4558\n4559\n4560\n4561\n4562\n4563\n4564\n4565\n4566\n4567\n4568\n4569\n4570\n4571\n4572\n4573\n4574\n4575\n4576\n4577\n4578\n4579\n4580\n4581\n4582\n4583\n4584\n4585\n4586\n4587\n4588\n4589\n4590\n4591\n4592\n4593\n4594\n4595\n4596\n4597\n4598\n4599\n4600\n4601\n4602\n4603\n4604\n4605\n4606\n4607\n4608\n4609\n4610\n4611\n4612\n4613\n4614\n4615\n4616\n4617\n4618\n4619\n4620\n4621\n4622\n4623\n4624\n4625\n4626\n4627\n4628\n4629\n4630\n4631\n4632\n4633\n4634\n4635\n4636\n4637\n4638\n4639\n4640\n4641\n4642\n4643\n4644\n4645\n4646\n4647\n4648\n4649\n4650\n4651\n4652\n4653\n4654\n4655\n4656\n4657\n4658\n4659\n4660\n4661\n4662\n4663\n4664\n4665\n4666\n4667\n4668\n4669\n4670\n4671\n4672\n4673\n4674\n4675\n4676\n4677\n4678\n4679\n4680\n4681\n4682\n4683\n4684\n4685\n4686\n4687\n4688\n4689\n4690\n4691\n4692\n4693\n4694\n4695\n4696\n4697\n4698\n4699\n4700\n4701\n4702\n4703\n4704\n4705\n4706\n4707\n4708\n4709\n4710\n4711\n4712\n4713\n4714\n4715\n4716\n4717\n4718\n4719\n4720\n4721\n4722\n4723\n4724\n4725\n4726\n4727\n4728\n4729\n4730\n4731\n4732\n4733\n4734\n4735\n4736\n4737\n4738\n4739\n4740\n4741\n4742\n4743\n4744\n4745\n4746\n4747\n4748\n4749\n4750\n4751\n4752\n4753\n4754\n4755\n4756\n4757\n4758\n4759\n4760\n4761\n4762\n4763\n4764\n4765\n4766\n4767\n4768\n4769\n4770\n4771\n4772\n4773\n4774\n4775\n4776\n4777\n4778\n4779\n4780\n4781\n4782\n4783\n4784\n4785\n4786\n4787\n4788\n4789\n4790\n4791\n4792\n4793\n4794\n4795\n4796\n4797\n4798\n4799\n4800\n4801\n4802\n4803\n4804\n4805\n4806\n4807\n4808\n4809\n4810\n4811\n4812\n4813\n4814\n4815\n4816\n4817\n4818\n4819\n4820\n4821\n4822\n4823\n4824\n4825\n4826\n4827\n4828\n4829\n4830\n4831\n4832\n4833\n4834\n4835\n4836\n4837\n4838\n4839\n4840\n4841\n4842\n4843\n4844\n4845\n4846\n4847\n4848\n4849\n4850\n4851\n4852\n4853\n4854\n4855\n4856\n4857\n4858\n4859\n4860\n4861\n4862\n4863\n4864\n4865\n4866\n4867\n4868\n4869\n4870\n4871\n4872\n4873\n4874\n4875\n4876\n4877\n4878\n4879\n4880\n4881\n4882\n4883\n4884\n4885\n4886\n4887\n4888\n4889\n4890\n4891\n4892\n4893\n4894\n4895\n4896\n4897\n4898\n4899\n4900\n4901\n4902\n4903\n4904\n4905\n4906\n4907\n4908\n4909\n4910\n4911\n4912\n4913\n4914\n4915\n4916\n4917\n4918\n4919\n4920\n4921\n4922\n4923\n4924\n4925\n4926\n4927\n4928\n4929\n4930\n4931\n4932\n4933\n4934\n4935\n4936\n4937\n4938\n4939\n4940\n4941\n4942\n4943\n4944\n4945\n4946\n4947\n4948\n4949\n4950\n4951\n4952\n4953\n4954\n4955\n4956\n4957\n4958\n4959\n4960\n4961\n4962\n4963\n4964\n4965\n4966\n4967\n4968\n4969\n4970\n4971\n4972\n4973\n4974\n4975\n4976\n4977\n4978\n4979\n4980\n4981\n4982\n4983\n4984\n4985\n4986\n4987\n4988\n4989\n4990\n4991\n4992\n4993\n4994\n4995\n4996\n4997\n4998\n4999\n5000\n5001\n5002\n5003\n5004\n5005\n5006\n5007\n5008\n5009\n5010\n5011\n5012\n5013\n5014\n5015\n5016\n5017\n5018\n5019\n5020\n5021\n5022\n5023\n5024\n5025\n5026\n5027\n5028\n5029\n5030\n5031\n5032\n5033\n5034\n5035\n5036\n5037\n5038\n5039\n5040\n5041\n5042\n5043\n5044\n5045\n5046\n5047\n5048\n5049\n5050\n5051\n5052\n5053\n5054\n5055\n5056\n5057\n5058\n5059\n5060\n5061\n5062\n5063\n5064\n5065\n5066\n5067\n5068\n5069\n5070\n5071\n5072\n5073\n5074\n5075\n5076\n5077\n5078\n5079\n5080\n5081\n5082\n5083\n5084\n5085\n5086\n5087\n5088\n5089\n5090\n5091\n5092\n5093\n5094\n5095\n5096\n5097\n5098\n5099\n5100\n5101\n5102\n5103\n5104\n5105\n5106\n5107\n5108\n5109\n5110\n5111\n5112\n5113\n5114\n5115\n5116\n5117\n5118\n5119\n5120\n5121\n5122\n5123\n5124\n5125\n5126\n5127\n5128\n5129\n5130\n5131\n5132\n5133\n5134\n5135\n5136\n5137\n5138\n5139\n5140\n5141\n5142\n5143\n5144\n5145\n5146\n5147\n5148\n5149\n5150\n5151\n5152\n5153\n5154\n5155\n5156\n5157\n5158\n5159\n5160\n5161\n5162\n5163\n5164\n5165\n5166\n5167\n5168\n5169\n5170\n5171\n5172\n5173\n5174\n5175\n5176\n5177\n5178\n5179\n5180\n5181\n5182\n5183\n5184\n5185\n5186\n5187\n5188\n5189\n5190\n5191\n5192\n5193\n5194\n5195\n5196\n5197\n5198\n5199\n5200\n5201\n5202\n5203\n5204\n5205\n5206\n5207\n5208\n5209\n5210\n5211\n5212\n5213\n5214\n5215\n5216\n5217\n5218\n5219\n5220\n5221\n5222\n5223\n5224\n5225\n5226\n5227\n5228\n5229\n5230\n5231\n5232\n5233\n5234\n5235\n5236\n5237\n5238\n5239\n5240\n5241\n5242\n5243\n5244\n5245\n5246\n5247\n5248\n5249\n5250\n5251\n5252\n5253\n5254\n5255\n5256\n5257\n5258\n5259\n5260\n5261\n5262\n5263\n5264\n5265\n5266\n5267\n5268\n5269\n5270\n5271\n5272\n5273\n5274\n5275\n5276\n5277\n5278\n5279\n5280\n5281\n5282\n5283\n5284\n5285\n5286\n5287\n5288\n5289\n5290\n5291\n5292\n5293\n5294\n5295\n5296\n5297\n5298\n5299\n5300\n5301\n5302\n5303\n5304\n5305\n5306\n5307\n5308\n5309\n5310\n5311\n5312\n5313\n5314\n5315\n5316\n5317\n5318\n5319\n5320\n5321\n5322\n5323\n5324\n5325\n5326\n5327\n5328\n5329\n5330\n5331\n5332\n5333\n5334\n5335\n5336\n5337\n5338\n5339\n5340\n5341\n5342\n5343\n5344\n5345\n5346\n5347\n5348\n5349\n5350\n5351\n5352\n5353\n5354\n5355\n5356\n5357\n5358\n5359\n5360\n5361\n5362\n5363\n5364\n5365\n5366\n5367\n5368\n5369\n5370\n5371\n5372\n5373\n5374\n5375\n5376\n5377\n5378\n5379\n5380\n5381\n5382\n5383\n5384\n5385\n5386\n5387\n5388\n5389\n5390\n5391\n5392\n5393\n5394\n5395\n5396\n5397\n5398\n5399\n5400\n5401\n5402\n5403\n5404\n5405\n5406\n5407\n5408\n5409\n5410\n5411\n5412\n5413\n5414\n5415\n5416\n5417\n5418\n5419\n5420\n5421\n5422\n5423\n5424\n5425\n5426\n5427\n5428\n5429\n5430\n5431\n5432\n5433\n5434\n5435\n5436\n5437\n5438\n5439\n5440\n5441\n5442\n5443\n5444\n5445\n5446\n5447\n5448\n5449\n5450\n5451\n5452\n5453\n5454\n5455\n5456\n5457\n5458\n5459\n5460\n5461\n5462\n5463\n5464\n5465\n5466\n5467\n5468\n5469\n5470\n5471\n5472\n5473\n5474\n5475\n5476\n5477\n5478\n5479\n5480\n5481\n5482\n5483\n5484\n5485\n5486\n5487\n5488\n5489\n5490\n5491\n5492\n5493\n5494\n5495\n5496\n5497\n5498\n5499\n5500\n5501\n5502\n5503\n5504\n5505\n5506\n5507\n5508\n5509\n5510\n5511\n5512\n5513\n5514\n5515\n5516\n5517\n5518\n5519\n5520\n5521\n5522\n5523\n5524\n5525\n5526\n5527\n5528\n5529\n5530\n5531\n5532\n5533\n5534\n5535\n5536\n5537\n5538\n5539\n5540\n5541\n5542\n5543\n5544\n5545\n5546\n5547\n5548\n5549\n5550\n5551\n5552\n5553\n5554\n5555\n5556\n5557\n5558\n5559\n5560\n5561\n5562\n5563\n5564\n5565\n5566\n5567\n5568\n5569\n5570\n5571\n5572\n5573\n5574\n5575\n5576\n5577\n5578\n5579\n5580\n5581\n5582\n5583\n5584\n5585\n5586\n5587\n5588\n5589\n5590\n5591\n5592\n5593\n5594\n5595\n5596\n5597\n5598\n5599\n5600\n5601\n5602\n5603\n5604\n5605\n5606\n5607\n5608\n5609\n5610\n5611\n5612\n5613\n5614\n5615\n5616\n5617\n5618\n5619\n5620\n5621\n5622\n5623\n5624\n5625\n5626\n5627\n5628\n5629\n5630\n5631\n5632\n5633\n5634\n5635\n5636\n5637\n5638\n5639\n5640\n5641\n5642\n5643\n5644\n5645\n5646\n5647\n5648\n5649\n5650\n5651\n5652\n5653\n5654\n5655\n5656\n5657\n5658\n5659\n5660\n5661\n5662\n5663\n5664\n5665\n5666\n5667\n5668\n5669\n5670\n5671\n5672\n5673\n5674\n5675\n5676\n5677\n5678\n5679\n5680\n5681\n5682\n5683\n5684\n5685\n5686\n5687\n5688\n5689\n5690\n5691\n5692\n5693\n5694\n5695\n5696\n5697\n5698\n5699\n5700\n5701\n5702\n5703\n5704\n5705\n5706\n5707\n5708\n5709\n5710\n5711\n5712\n5713\n5714\n5715\n5716\n5717\n5718\n5719\n5720\n5721\n5722\n5723\n5724\n5725\n5726\n5727\n5728\n5729\n5730\n5731\n5732\n5733\n5734\n5735\n5736\n5737\n5738\n5739\n5740\n5741\n5742\n5743\n5744\n5745\n5746\n5747\n5748\n5749\n5750\n5751\n5752\n5753\n5754\n5755\n5756\n5757\n5758\n5759\n5760\n5761\n5762\n5763\n5764\n5765\n5766\n5767\n5768\n5769\n5770\n5771\n5772\n5773\n5774\n5775\n5776\n5777\n5778\n5779\n5780\n5781\n5782\n5783\n5784\n5785\n5786\n5787\n5788\n5789\n5790\n5791\n5792\n5793\n5794\n5795\n5796\n5797\n5798\n5799\n5800\n5801\n5802\n5803\n5804\n5805\n5806\n5807\n5808\n5809\n5810\n5811\n5812\n5813\n5814\n5815\n5816\n5817\n5818\n5819\n5820\n5821\n5822\n5823\n5824\n5825\n5826\n5827\n5828\n5829\n5830\n5831\n5832\n5833\n5834\n5835\n5836\n5837\n5838\n5839\n5840\n5841\n5842\n5843\n5844\n5845\n5846\n5847\n5848\n5849\n5850\n5851\n5852\n5853\n5854\n5855\n5856\n5857\n5858\n5859\n5860\n5861\n5862\n5863\n5864\n5865\n5866\n5867\n5868\n5869\n5870\n5871\n5872\n5873\n5874\n5875\n5876\n5877\n5878\n5879\n5880\n5881\n5882\n5883\n5884\n5885\n5886\n5887\n5888\n5889\n5890\n5891\n5892\n5893\n5894\n5895\n5896\n5897\n5898\n5899\n5900\n5901\n5902\n5903\n5904\n5905\n5906\n5907\n5908\n5909\n5910\n5911\n5912\n5913\n5914\n5915\n5916\n5917\n5918\n5919\n5920\n5921\n5922\n5923\n5924\n5925\n5926\n5927\n5928\n5929\n5930\n5931\n5932\n5933\n5934\n5935\n5936\n5937\n5938\n5939\n5940\n5941\n5942\n5943\n5944\n5945\n5946\n5947\n5948\n5949\n5950\n5951\n5952\n5953\n5954\n5955\n5956\n5957\n5958\n5959\n5960\n5961\n5962\n5963\n5964\n5965\n5966\n5967\n5968\n5969\n5970\n5971\n5972\n5973\n5974\n5975\n5976\n5977\n5978\n5979\n5980\n5981\n5982\n5983\n5984\n5985\n5986\n5987\n5988\n5989\n5990\n5991\n5992\n5993\n5994\n5995\n5996\n5997\n5998\n5999\n6000\n6001\n6002\n6003\n6004\n6005\n6006\n6007\n6008\n6009\n6010\n6011\n6012\n6013\n6014\n6015\n6016\n6017\n6018\n6019\n6020\n6021\n6022\n6023\n6024\n6025\n6026\n6027\n6028\n6029\n6030\n6031\n6032\n6033\n6034\n6035\n6036\n6037\n6038\n6039\n6040\n6041\n6042\n6043\n6044\n6045\n6046\n6047\n6048\n6049\n6050\n6051\n6052\n6053\n6054\n6055\n6056\n6057\n6058\n6059\n6060\n6061\n6062\n6063\n6064\n6065\n6066\n6067\n6068\n6069\n6070\n6071\n6072\n6073\n6074\n6075\n6076\n6077\n6078\n6079\n6080\n6081\n6082\n6083\n6084\n6085\n6086\n6087\n6088\n6089\n6090\n6091\n6092\n6093\n6094\n6095\n6096\n6097\n6098\n6099\n6100\n6101\n6102\n6103\n6104\n6105\n6106\n6107\n6108\n6109\n6110\n6111\n6112\n6113\n6114\n6115\n6116\n6117\n6118\n6119\n6120\n6121\n6122\n6123\n6124\n6125\n6126\n6127\n6128\n6129\n6130\n6131\n6132\n6133\n6134\n6135\n6136\n6137\n6138\n6139\n6140\n6141\n6142\n6143\n6144\n6145\n6146\n6147\n6148\n6149\n6150\n6151\n6152\n6153\n6154\n6155\n6156\n6157\n6158\n6159\n6160\n6161\n6162\n6163\n6164\n6165\n6166\n6167\n6168\n6169\n6170\n6171\n6172\n6173\n6174\n6175\n6176\n6177\n6178\n6179\n6180\n6181\n6182\n6183\n6184\n6185\n6186\n6187\n6188\n6189\n6190\n6191\n6192\n6193\n6194\n6195\n6196\n6197\n6198\n6199\n6200\n6201\n6202\n6203\n6204\n6205\n6206\n6207\n6208\n6209\n6210\n6211\n6212\n6213\n6214\n6215\n6216\n6217\n6218\n6219\n6220\n6221\n6222\n6223\n6224\n6225\n6226\n6227\n6228\n6229\n6230\n6231\n6232\n6233\n6234\n6235\n6236\n6237\n6238\n6239\n6240\n6241\n6242\n6243\n6244\n6245\n6246\n6247\n6248\n6249\n6250\n6251\n6252\n6253\n6254\n6255\n6256\n6257\n6258\n6259\n6260\n6261\n6262\n6263\n6264\n6265\n6266\n6267\n6268\n6269\n6270\n6271\n6272\n6273\n6274\n6275\n6276\n6277\n6278\n6279\n6280\n6281\n6282\n6283\n6284\n6285\n6286\n6287\n6288\n6289\n6290\n6291\n6292\n6293\n6294\n6295\n6296\n6297\n6298\n6299\n6300\n6301\n6302\n6303\n6304\n6305\n6306\n6307\n6308\n6309\n6310\n6311\n6312\n6313\n6314\n6315\n6316\n6317\n6318\n6319\n6320\n6321\n6322\n6323\n6324\n6325\n6326\n6327\n6328\n6329\n6330\n6331\n6332\n6333\n6334\n6335\n6336\n6337\n6338\n6339\n6340\n6341\n6342\n6343\n6344\n6345\n6346\n6347\n6348\n6349\n6350\n6351\n6352\n6353\n6354\n6355\n6356\n6357\n6358\n6359\n6360\n6361\n6362\n6363\n6364\n6365\n6366\n6367\n6368\n6369\n6370\n6371\n6372\n6373\n6374\n6375\n6376\n6377\n6378\n6379\n6380\n6381\n6382\n6383\n6384\n6385\n6386\n6387\n6388\n6389\n6390\n6391\n6392\n6393\n6394\n6395\n6396\n6397\n6398\n6399\n6400\n6401\n6402\n6403\n6404\n6405\n6406\n6407\n6408\n6409\n6410\n6411\n6412\n6413\n6414\n6415\n6416\n6417\n6418\n6419\n6420\n6421\n6422\n6423\n6424\n6425\n6426\n6427\n6428\n6429\n6430\n6431\n6432\n6433\n6434\n6435\n6436\n6437\n6438\n6439\n6440\n6441\n6442\n6443\n6444\n6445\n6446\n6447\n6448\n6449\n6450\n6451\n6452\n6453\n6454\n6455\n6456\n6457\n6458\n6459\n6460\n6461\n6462\n6463\n6464\n6465\n6466\n6467\n6468\n6469\n6470\n6471\n6472\n6473\n6474\n6475\n6476\n6477\n6478\n6479\n6480\n6481\n6482\n6483\n6484\n6485\n6486\n6487\n6488\n6489\n6490\n6491\n6492\n6493\n6494\n6495\n6496\n6497\n6498\n6499\n6500\n6501\n6502\n6503\n6504\n6505\n6506\n6507\n6508\n6509\n6510\n6511\n6512\n6513\n6514\n6515\n6516\n6517\n6518\n6519\n6520\n6521\n6522\n6523\n6524\n6525\n6526\n6527\n6528\n6529\n6530\n6531\n6532\n6533\n6534\n6535\n6536\n6537\n6538\n6539\n6540\n6541\n6542\n6543\n6544\n6545\n6546\n6547\n6548\n6549\n6550\n6551\n6552\n6553\n6554\n6555\n6556\n6557\n6558\n6559\n6560\n6561\n6562\n6563\n6564\n6565\n6566\n6567\n6568\n6569\n6570\n6571\n6572\n6573\n6574\n6575\n6576\n6577\n6578\n6579\n6580\n6581\n6582\n6583\n6584\n6585\n6586\n6587\n6588\n6589\n6590\n6591\n6592\n6593\n6594\n6595\n6596\n6597\n6598\n6599\n6600\n6601\n6602\n6603\n6604\n6605\n6606\n6607\n6608\n6609\n6610\n6611\n6612\n6613\n6614\n6615\n6616\n6617\n6618\n6619\n6620\n6621\n6622\n6623\n6624\n6625\n6626\n6627\n6628\n6629\n6630\n6631\n6632\n6633\n6634\n6635\n6636\n6637\n6638\n6639\n6640\n6641\n6642\n6643\n6644\n6645\n6646\n6647\n6648\n6649\n6650\n6651\n6652\n6653\n6654\n6655\n6656\n6657\n6658\n6659\n6660\n6661\n6662\n6663\n6664\n6665\n6666\n6667\n6668\n6669\n6670\n6671\n6672\n6673\n6674\n6675\n6676\n6677\n6678\n6679\n6680\n6681\n6682\n6683\n6684\n6685\n6686\n6687\n6688\n6689\n6690\n6691\n6692\n6693\n6694\n6695\n6696\n6697\n6698\n6699\n6700\n6701\n6702\n6703\n6704\n6705\n6706\n6707\n6708\n6709\n6710\n6711\n6712\n6713\n6714\n6715\n6716\n6717\n6718\n6719\n6720\n6721\n6722\n6723\n6724\n6725\n6726\n6727\n6728\n6729\n6730\n6731\n6732\n6733\n6734\n6735\n6736\n6737\n6738\n6739\n6740\n6741\n6742\n6743\n6744\n6745\n6746\n6747\n6748\n6749\n6750\n6751\n6752\n6753\n6754\n6755\n6756\n6757\n6758\n6759\n6760\n6761\n6762\n6763\n6764\n6765\n6766\n6767\n6768\n6769\n6770\n6771\n6772\n6773\n6774\n6775\n6776\n6777\n6778\n6779\n6780\n6781\n6782\n6783\n6784\n6785\n6786\n6787\n6788\n6789\n6790\n6791\n6792\n6793\n6794\n6795\n6796\n6797\n6798\n6799\n6800\n6801\n6802\n6803\n6804\n6805\n6806\n6807\n6808\n6809\n6810\n6811\n6812\n6813\n6814\n6815\n6816\n6817\n6818\n6819\n6820\n6821\n6822\n6823\n6824\n6825\n6826\n6827\n6828\n6829\n6830\n6831\n6832\n6833\n6834\n6835\n6836\n6837\n6838\n6839\n6840\n6841\n6842\n6843\n6844\n6845\n6846\n6847\n6848\n6849\n6850\n6851\n6852\n6853\n6854\n6855\n6856\n6857\n6858\n6859\n6860\n6861\n6862\n6863\n6864\n6865\n6866\n6867\n6868\n6869\n6870\n6871\n6872\n6873\n6874\n6875\n6876\n6877\n6878\n6879\n6880\n6881\n6882\n6883\n6884\n6885\n6886\n6887\n6888\n6889\n6890\n6891\n6892\n6893\n6894\n6895\n6896\n6897\n6898\n6899\n6900\n6901\n6902\n6903\n6904\n6905\n6906\n6907\n6908\n6909\n6910\n6911\n6912\n6913\n6914\n6915\n6916\n6917\n6918\n6919\n6920\n6921\n6922\n6923\n6924\n6925\n6926\n6927\n6928\n6929\n6930\n6931\n6932\n6933\n6934\n6935\n6936\n6937\n6938\n6939\n6940\n6941\n6942\n6943\n6944\n6945\n6946\n6947\n6948\n6949\n6950\n6951\n6952\n6953\n6954\n6955\n6956\n6957\n6958\n6959\n6960\n6961\n6962\n6963\n6964\n6965\n6966\n6967\n6968\n6969\n6970\n6971\n6972\n6973\n6974\n6975\n6976\n6977\n6978\n6979\n6980\n6981\n6982\n6983\n6984\n6985\n6986\n6987\n6988\n6989\n6990\n6991\n6992\n6993\n6994\n6995\n6996\n6997\n6998\n6999\n7000\n7001\n7002\n7003\n7004\n7005\n7006\n7007\n7008\n7009\n7010\n7011\n7012\n7013\n7014\n7015\n7016\n7017\n7018\n7019\n7020\n7021\n7022\n7023\n7024\n7025\n7026\n7027\n7028\n7029\n7030\n7031\n7032\n7033\n7034\n7035\n7036\n7037\n7038\n7039\n7040\n7041\n7042\n7043\n7044\n7045\n7046\n7047\n7048\n7049\n7050\n7051\n7052\n7053\n7054\n7055\n7056\n7057\n7058\n7059\n7060\n7061\n7062\n7063\n7064\n7065\n7066\n7067\n7068\n7069\n7070\n7071\n7072\n7073\n7074\n7075\n7076\n7077\n7078\n7079\n7080\n7081\n7082\n7083\n7084\n7085\n7086\n7087\n7088\n7089\n7090\n7091\n7092\n7093\n7094\n7095\n7096\n7097\n7098\n7099\n7100\n7101\n7102\n7103\n7104\n7105\n7106\n7107\n7108\n7109\n7110\n7111\n7112\n7113\n7114\n7115\n7116\n7117\n7118\n7119\n7120\n7121\n7122\n7123\n7124\n7125\n7126\n7127\n7128\n7129\n7130\n7131\n7132\n7133\n7134\n7135\n7136\n7137\n7138\n7139\n7140\n7141\n7142\n7143\n7144\n7145\n7146\n7147\n7148\n7149\n7150\n7151\n7152\n7153\n7154\n7155\n7156\n7157\n7158\n7159\n7160\n7161\n7162\n7163\n7164\n7165\n7166\n7167\n7168\n7169\n7170\n7171\n7172\n7173\n7174\n7175\n7176\n7177\n7178\n7179\n7180\n7181\n7182\n7183\n7184\n7185\n7186\n7187\n7188\n7189\n7190\n7191\n7192\n7193\n7194\n7195\n7196\n7197\n7198\n7199\n7200\n7201\n7202\n7203\n7204\n7205\n7206\n7207\n7208\n7209\n7210\n7211\n7212\n7213\n7214\n7215\n7216\n7217\n7218\n7219\n7220\n7221\n7222\n7223\n7224\n7225\n7226\n7227\n7228\n7229\n7230\n7231\n7232\n7233\n7234\n7235\n7236\n7237\n7238\n7239\n7240\n7241\n7242\n7243\n7244\n7245\n7246\n7247\n7248\n7249\n7250\n7251\n7252\n7253\n7254\n7255\n7256\n7257\n7258\n7259\n7260\n7261\n7262\n7263\n7264\n7265\n7266\n7267\n7268\n7269\n7270\n7271\n7272\n7273\n7274\n7275\n7276\n7277\n7278\n7279\n7280\n7281\n7282\n7283\n7284\n7285\n7286\n7287\n7288\n7289\n7290\n7291\n7292\n7293\n7294\n7295\n7296\n7297\n7298\n7299\n7300\n7301\n7302\n7303\n7304\n7305\n7306\n7307\n7308\n7309\n7310\n7311\n7312\n7313\n7314\n7315\n7316\n7317\n7318\n7319\n7320\n7321\n7322\n7323\n7324\n7325\n7326\n7327\n7328\n7329\n7330\n7331\n7332\n7333\n7334\n7335\n7336\n7337\n7338\n7339\n7340\n7341\n7342\n7343\n7344\n7345\n7346\n7347\n7348\n7349\n7350\n7351\n7352\n7353\n7354\n7355\n7356\n7357\n7358\n7359\n7360\n7361\n7362\n7363\n7364\n7365\n7366\n7367\n7368\n7369\n7370\n7371\n7372\n7373\n7374\n7375\n7376\n7377\n7378\n7379\n7380\n7381\n7382\n7383\n7384\n7385\n7386\n7387\n7388\n7389\n7390\n7391\n7392\n7393\n7394\n7395\n7396\n7397\n7398\n7399\n7400\n7401\n7402\n7403\n7404\n7405\n7406\n7407\n7408\n7409\n7410\n7411\n7412\n7413\n7414\n7415\n7416\n7417\n7418\n7419\n7420\n7421\n7422\n7423\n7424\n7425\n7426\n7427\n7428\n7429\n7430\n7431\n7432\n7433\n7434\n7435\n7436\n7437\n7438\n7439\n7440\n7441\n7442\n7443\n7444\n7445\n7446\n7447\n7448\n7449\n7450\n7451\n7452\n7453\n7454\n7455\n7456\n7457\n7458\n7459\n7460\n7461\n7462\n7463\n7464\n7465\n7466\n7467\n7468\n7469\n7470\n7471\n7472\n7473\n7474\n7475\n7476\n7477\n7478\n7479\n7480\n7481\n7482\n7483\n7484\n7485\n7486\n7487\n7488\n7489\n7490\n7491\n7492\n7493\n7494\n7495\n7496\n7497\n7498\n7499\n7500\n7501\n7502\n7503\n7504\n7505\n7506\n7507\n7508\n7509\n7510\n7511\n7512\n7513\n7514\n7515\n7516\n7517\n7518\n7519\n7520\n7521\n7522\n7523\n7524\n7525\n7526\n7527\n7528\n7529\n7530\n7531\n7532\n7533\n7534\n7535\n7536\n7537\n7538\n7539\n7540\n7541\n7542\n7543\n7544\n7545\n7546\n7547\n7548\n7549\n7550\n7551\n7552\n7553\n7554\n7555\n7556\n7557\n7558\n7559\n7560\n7561\n7562\n7563\n7564\n7565\n7566\n7567\n7568\n7569\n7570\n7571\n7572\n7573\n7574\n7575\n7576\n7577\n7578\n7579\n7580\n7581\n7582\n7583\n7584\n7585\n7586\n7587\n7588\n7589\n7590\n7591\n7592\n7593\n7594\n7595\n7596\n7597\n7598\n7599\n7600\n7601\n7602\n7603\n7604\n7605\n7606\n7607\n7608\n7609\n7610\n7611\n7612\n7613\n7614\n7615\n7616\n7617\n7618\n7619\n7620\n7621\n7622\n7623\n7624\n7625\n7626\n7627\n7628\n7629\n7630\n7631\n7632\n7633\n7634\n7635\n7636\n7637\n7638\n7639\n7640\n7641\n7642\n7643\n7644\n7645\n7646\n7647\n7648\n7649\n7650\n7651\n7652\n7653\n7654\n7655\n7656\n7657\n7658\n7659\n7660\n7661\n7662\n7663\n7664\n7665\n7666\n7667\n7668\n7669\n7670\n7671\n7672\n7673\n7674\n7675\n7676\n7677\n7678\n7679\n7680\n7681\n7682\n7683\n7684\n7685\n7686\n7687\n7688\n7689\n7690\n7691\n7692\n7693\n7694\n7695\n7696\n7697\n7698\n7699\n7700\n7701\n7702\n7703\n7704\n7705\n7706\n7707\n7708\n7709\n7710\n7711\n7712\n7713\n7714\n7715\n7716\n7717\n7718\n7719\n7720\n7721\n7722\n7723\n7724\n7725\n7726\n7727\n7728\n7729\n7730\n7731\n7732\n7733\n7734\n7735\n7736\n7737\n7738\n7739\n7740\n7741\n7742\n7743\n7744\n7745\n7746\n7747\n7748\n7749\n7750\n7751\n7752\n7753\n7754\n7755\n7756\n7757\n7758\n7759\n7760\n7761\n7762\n7763\n7764\n7765\n7766\n7767\n7768\n7769\n7770\n7771\n7772\n7773\n7774\n7775\n7776\n7777\n7778\n7779\n7780\n7781\n7782\n7783\n7784\n7785\n7786\n7787\n7788\n7789\n7790\n7791\n7792\n7793\n7794\n7795\n7796\n7797\n7798\n7799\n7800\n7801\n7802\n7803\n7804\n7805\n7806\n7807\n7808\n7809\n7810\n7811\n7812\n7813\n7814\n7815\n7816\n7817\n7818\n7819\n7820\n7821\n7822\n7823\n7824\n7825\n7826\n7827\n7828\n7829\n7830\n7831\n7832\n7833\n7834\n7835\n7836\n7837\n7838\n7839\n7840\n7841\n7842\n7843\n7844\n7845\n7846\n7847\n7848\n7849\n7850\n7851\n7852\n7853\n7854\n7855\n7856\n7857\n7858\n7859\n7860\n7861\n7862\n7863\n7864\n7865\n7866\n7867\n7868\n7869\n7870\n7871\n7872\n7873\n7874\n7875\n7876\n7877\n7878\n7879\n7880\n7881\n7882\n7883\n7884\n7885\n7886\n7887\n7888\n7889\n7890\n7891\n7892\n7893\n7894\n7895\n7896\n7897\n7898\n7899\n7900\n7901\n7902\n7903\n7904\n7905\n7906\n7907\n7908\n7909\n7910\n7911\n7912\n7913\n7914\n7915\n7916\n7917\n7918\n7919\n7920\n7921\n7922\n7923\n7924\n7925\n7926\n7927\n7928\n7929\n7930\n7931\n7932\n7933\n7934\n7935\n7936\n7937\n7938\n7939\n7940\n7941\n7942\n7943\n7944\n7945\n7946\n7947\n7948\n7949\n7950\n7951\n7952\n7953\n7954\n7955\n7956\n7957\n7958\n7959\n7960\n7961\n7962\n7963\n7964\n7965\n7966\n7967\n7968\n7969\n7970\n7971\n7972\n7973\n7974\n7975\n7976\n7977\n7978\n7979\n7980\n7981\n7982\n7983\n7984\n7985\n7986\n7987\n7988\n7989\n7990\n7991\n7992\n7993\n7994\n7995\n7996\n7997\n7998\n7999\n8000\n8001\n8002\n8003\n8004\n8005\n8006\n8007\n8008\n8009\n8010\n8011\n8012\n8013\n8014\n8015\n8016\n8017\n8018\n8019\n8020\n8021\n8022\n8023\n8024\n8025\n8026\n8027\n8028\n8029\n8030\n8031\n8032\n8033\n8034\n8035\n8036\n8037\n8038\n8039\n8040\n8041\n8042\n8043\n8044\n8045\n8046\n8047\n8048\n8049\n8050\n8051\n8052\n8053\n8054\n8055\n8056\n8057\n8058\n8059\n8060\n8061\n8062\n8063\n8064\n8065\n8066\n8067\n8068\n8069\n8070\n8071\n8072\n8073\n8074\n8075\n8076\n8077\n8078\n8079\n8080\n8081\n8082\n8083\n8084\n8085\n8086\n8087\n8088\n8089\n8090\n8091\n8092\n8093\n8094\n8095\n8096\n8097\n8098\n8099\n8100\n8101\n8102\n8103\n8104\n8105\n8106\n8107\n8108\n8109\n8110\n8111\n8112\n8113\n8114\n8115\n8116\n8117\n8118\n8119\n8120\n8121\n8122\n8123\n8124\n8125\n8126\n8127\n8128\n8129\n8130\n8131\n8132\n8133\n8134\n8135\n8136\n8137\n8138\n8139\n8140\n8141\n8142\n8143\n8144\n8145\n8146\n8147\n8148\n8149\n8150\n8151\n8152\n8153\n8154\n8155\n8156\n8157\n8158\n8159\n8160\n8161\n8162\n8163\n8164\n8165\n8166\n8167\n8168\n8169\n8170\n8171\n8172\n8173\n8174\n8175\n8176\n8177\n8178\n8179\n8180\n8181\n8182\n8183\n8184\n8185\n8186\n8187\n8188\n8189\n8190\n8191\n8192\n8193\n8194\n8195\n8196\n8197\n8198\n8199\n8200\n8201\n8202\n8203\n8204\n8205\n8206\n8207\n8208\n8209\n8210\n8211\n8212\n8213\n8214\n8215\n8216\n8217\n8218\n8219\n8220\n8221\n8222\n8223\n8224\n8225\n8226\n8227\n8228\n8229\n8230\n8231\n8232\n8233\n8234\n8235\n8236\n8237\n8238\n8239\n8240\n8241\n8242\n8243\n8244\n8245\n8246\n8247\n8248\n8249\n8250\n8251\n8252\n8253\n8254\n8255\n8256\n8257\n8258\n8259\n8260\n8261\n8262\n8263\n8264\n8265\n8266\n8267\n8268\n8269\n8270\n8271\n8272\n8273\n8274\n8275\n8276\n8277\n8278\n8279\n8280\n8281\n8282\n8283\n8284\n8285\n8286\n8287\n8288\n8289\n8290\n8291\n8292\n8293\n8294\n8295\n8296\n8297\n8298\n8299\n8300\n8301\n8302\n8303\n8304\n8305\n8306\n8307\n8308\n8309\n8310\n8311\n8312\n8313\n8314\n8315\n8316\n8317\n8318\n8319\n8320\n8321\n8322\n8323\n8324\n8325\n8326\n8327\n8328\n8329\n8330\n8331\n8332\n8333\n8334\n8335\n8336\n8337\n8338\n8339\n8340\n8341\n8342\n8343\n8344\n8345\n8346\n8347\n8348\n8349\n8350\n8351\n8352\n8353\n8354\n8355\n8356\n8357\n8358\n8359\n8360\n8361\n8362\n8363\n8364\n8365\n8366\n8367\n8368\n8369\n8370\n8371\n8372\n8373\n8374\n8375\n8376\n8377\n8378\n8379\n8380\n8381\n8382\n8383\n8384\n8385\n8386\n8387\n8388\n8389\n8390\n8391\n8392\n8393\n8394\n8395\n8396\n8397\n8398\n8399\n8400\n8401\n8402\n8403\n8404\n8405\n8406\n8407\n8408\n8409\n8410\n8411\n8412\n8413\n8414\n8415\n8416\n8417\n8418\n8419\n8420\n8421\n8422\n8423\n8424\n8425\n8426\n8427\n8428\n8429\n8430\n8431\n8432\n8433\n8434\n8435\n8436\n8437\n8438\n8439\n8440\n8441\n8442\n8443\n8444\n8445\n8446\n8447\n8448\n8449\n8450\n8451\n8452\n8453\n8454\n8455\n8456\n8457\n8458\n8459\n8460\n8461\n8462\n8463\n8464\n8465\n8466\n8467\n8468\n8469\n8470\n8471\n8472\n8473\n8474\n8475\n8476\n8477\n8478\n8479\n8480\n8481\n8482\n8483\n8484\n8485\n8486\n8487\n8488\n8489\n8490\n8491\n8492\n8493\n8494\n8495\n8496\n8497\n8498\n8499\n8500\n8501\n8502\n8503\n8504\n8505\n8506\n8507\n8508\n8509\n8510\n8511\n8512\n8513\n8514\n8515\n8516\n8517\n8518\n8519\n8520\n8521\n8522\n8523\n8524\n8525\n8526\n8527\n8528\n8529\n8530\n8531\n8532\n8533\n8534\n8535\n8536\n8537\n8538\n8539\n8540\n8541\n8542\n8543\n8544\n8545\n8546\n8547\n8548\n8549\n8550\n8551\n8552\n8553\n8554\n8555\n8556\n8557\n8558\n8559\n8560\n8561\n8562\n8563\n8564\n8565\n8566\n8567\n8568\n8569\n8570\n8571\n8572\n8573\n8574\n8575\n8576\n8577\n8578\n8579\n8580\n8581\n8582\n8583\n8584\n8585\n8586\n8587\n8588\n8589\n8590\n8591\n8592\n8593\n8594\n8595\n8596\n8597\n8598\n8599\n8600\n8601\n8602\n8603\n8604\n8605\n8606\n8607\n8608\n8609\n8610\n8611\n8612\n8613\n8614\n8615\n8616\n8617\n8618\n8619\n8620\n8621\n8622\n8623\n8624\n8625\n8626\n8627\n8628\n8629\n8630\n8631\n8632\n8633\n8634\n8635\n8636\n8637\n8638\n8639\n8640\n8641\n8642\n8643\n8644\n8645\n8646\n8647\n8648\n8649\n8650\n8651\n8652\n8653\n8654\n8655\n8656\n8657\n8658\n8659\n8660\n8661\n8662\n8663\n8664\n8665\n8666\n8667\n8668\n8669\n8670\n8671\n8672\n8673\n8674\n8675\n8676\n8677\n8678\n8679\n8680\n8681\n8682\n8683\n8684\n8685\n8686\n8687\n8688\n8689\n8690\n8691\n8692\n8693\n8694\n8695\n8696\n8697\n8698\n8699\n8700\n8701\n8702\n8703\n8704\n8705\n8706\n8707\n8708\n8709\n8710\n8711\n8712\n8713\n8714\n8715\n8716\n8717\n8718\n8719\n8720\n8721\n8722\n8723\n8724\n8725\n8726\n8727\n8728\n8729\n8730\n8731\n8732\n8733\n8734\n8735\n8736\n8737\n8738\n8739\n8740\n8741\n8742\n8743\n8744\n8745\n8746\n8747\n8748\n8749\n8750\n8751\n8752\n8753\n8754\n8755\n8756\n8757\n8758\n8759\n8760\n8761\n8762\n8763\n8764\n8765\n8766\n8767\n8768\n8769\n8770\n8771\n8772\n8773\n8774\n8775\n8776\n8777\n8778\n8779\n8780\n8781\n8782\n8783\n8784\n8785\n8786\n8787\n8788\n8789\n8790\n8791\n8792\n8793\n8794\n8795\n8796\n8797\n8798\n8799\n8800\n8801\n8802\n8803\n8804\n8805\n8806\n8807\n8808\n8809\n8810\n8811\n8812\n8813\n8814\n8815\n8816\n8817\n8818\n8819\n8820\n8821\n8822\n8823\n8824\n8825\n8826\n8827\n8828\n8829\n8830\n8831\n8832\n8833\n8834\n8835\n8836\n8837\n8838\n8839\n8840\n8841\n8842\n8843\n8844\n8845\n8846\n8847\n8848\n8849\n8850\n8851\n8852\n8853\n8854\n8855\n8856\n8857\n8858\n8859\n8860\n8861\n8862\n8863\n8864\n8865\n8866\n8867\n8868\n8869\n8870\n8871\n8872\n8873\n8874\n8875\n8876\n8877\n8878\n8879\n8880\n8881\n8882\n8883\n8884\n8885\n8886\n8887\n8888\n8889\n8890\n8891\n8892\n8893\n8894\n8895\n8896\n8897\n8898\n8899\n8900\n8901\n8902\n8903\n8904\n8905\n8906\n8907\n8908\n8909\n8910\n8911\n8912\n8913\n8914\n8915\n8916\n8917\n8918\n8919\n8920\n8921\n8922\n8923\n8924\n8925\n8926\n8927\n8928\n8929\n8930\n8931\n8932\n8933\n8934\n8935\n8936\n8937\n8938\n8939\n8940\n8941\n8942\n8943\n8944\n8945\n8946\n8947\n8948\n8949\n8950\n8951\n8952\n8953\n8954\n8955\n8956\n8957\n8958\n8959\n8960\n8961\n8962\n8963\n8964\n8965\n8966\n8967\n8968\n8969\n8970\n8971\n8972\n8973\n8974\n8975\n8976\n8977\n8978\n8979\n8980\n8981\n8982\n8983\n8984\n8985\n8986\n8987\n8988\n8989\n8990\n8991\n8992\n8993\n8994\n8995\n8996\n8997\n8998\n8999\n9000\n9001\n9002\n9003\n9004\n9005\n9006\n9007\n9008\n9009\n9010\n9011\n9012\n9013\n9014\n9015\n9016\n9017\n9018\n9019\n9020\n9021\n9022\n9023\n9024\n9025\n9026\n9027\n9028\n9029\n9030\n9031\n9032\n9033\n9034\n9035\n9036\n9037\n9038\n9039\n9040\n9041\n9042\n9043\n9044\n9045\n9046\n9047\n9048\n9049\n9050\n9051\n9052\n9053\n9054\n9055\n9056\n9057\n9058\n9059\n9060\n9061\n9062\n9063\n9064\n9065\n9066\n9067\n9068\n9069\n9070\n9071\n9072\n9073\n9074\n9075\n9076\n9077\n9078\n9079\n9080\n9081\n9082\n9083\n9084\n9085\n9086\n9087\n9088\n9089\n9090\n9091\n9092\n9093\n9094\n9095\n9096\n9097\n9098\n9099\n9100\n9101\n9102\n9103\n9104\n9105\n9106\n9107\n9108\n9109\n9110\n9111\n9112\n9113\n9114\n9115\n9116\n9117\n9118\n9119\n9120\n9121\n9122\n9123\n9124\n9125\n9126\n9127\n9128\n9129\n9130\n9131\n9132\n9133\n9134\n9135\n9136\n9137\n9138\n9139\n9140\n9141\n9142\n9143\n9144\n9145\n9146\n9147\n9148\n9149\n9150\n9151\n9152\n9153\n9154\n9155\n9156\n9157\n9158\n9159\n9160\n9161\n9162\n9163\n9164\n9165\n9166\n9167\n9168\n9169\n9170\n9171\n9172\n9173\n9174\n9175\n9176\n9177\n9178\n9179\n9180\n9181\n9182\n9183\n9184\n9185\n9186\n9187\n9188\n9189\n9190\n9191\n9192\n9193\n9194\n9195\n9196\n9197\n9198\n9199\n9200\n9201\n9202\n9203\n9204\n9205\n9206\n9207\n9208\n9209\n9210\n9211\n9212\n9213\n9214\n9215\n9216\n9217\n9218\n9219\n9220\n9221\n9222\n9223\n9224\n9225\n9226\n9227\n9228\n9229\n9230\n9231\n9232\n9233\n9234\n9235\n9236\n9237\n9238\n9239\n9240\n9241\n9242\n9243\n9244\n9245\n9246\n9247\n9248\n9249\n9250\n9251\n9252\n9253\n9254\n9255\n9256\n9257\n9258\n9259\n9260\n9261\n9262\n9263\n9264\n9265\n9266\n9267\n9268\n9269\n9270\n9271\n9272\n9273\n9274\n9275\n9276\n9277\n9278\n9279\n9280\n9281\n9282\n9283\n9284\n9285\n9286\n9287\n9288\n9289\n9290\n9291\n9292\n9293\n9294\n9295\n9296\n9297\n9298\n9299\n9300\n9301\n9302\n9303\n9304\n9305\n9306\n9307\n9308\n9309\n9310\n9311\n9312\n9313\n9314\n9315\n9316\n9317\n9318\n9319\n9320\n9321\n9322\n9323\n9324\n9325\n9326\n9327\n9328\n9329\n9330\n9331\n9332\n9333\n9334\n9335\n9336\n9337\n9338\n9339\n9340\n9341\n9342\n9343\n9344\n9345\n9346\n9347\n9348\n9349\n9350\n9351\n9352\n9353\n9354\n9355\n9356\n9357\n9358\n9359\n9360\n9361\n9362\n9363\n9364\n9365\n9366\n9367\n9368\n9369\n9370\n9371\n9372\n9373\n9374\n9375\n9376\n9377\n9378\n9379\n9380\n9381\n9382\n9383\n9384\n9385\n9386\n9387\n9388\n9389\n9390\n9391\n9392\n9393\n9394\n9395\n9396\n9397\n9398\n9399\n9400\n9401\n9402\n9403\n9404\n9405\n9406\n9407\n9408\n9409\n9410\n9411\n9412\n9413\n9414\n9415\n9416\n9417\n9418\n9419\n9420\n9421\n9422\n9423\n9424\n9425\n9426\n9427\n9428\n9429\n9430\n9431\n9432\n9433\n9434\n9435\n9436\n9437\n9438\n9439\n9440\n9441\n9442\n9443\n9444\n9445\n9446\n9447\n9448\n9449\n9450\n9451\n9452\n9453\n9454\n9455\n9456\n9457\n9458\n9459\n9460\n9461\n9462\n9463\n9464\n9465\n9466\n9467\n9468\n9469\n9470\n9471\n9472\n9473\n9474\n9475\n9476\n9477\n9478\n9479\n9480\n9481\n9482\n9483\n9484\n9485\n9486\n9487\n9488\n9489\n9490\n9491\n9492\n9493\n9494\n9495\n9496\n9497\n9498\n9499\n9500\n9501\n9502\n9503\n9504\n9505\n9506\n9507\n9508\n9509\n9510\n9511\n9512\n9513\n9514\n9515\n9516\n9517\n9518\n9519\n9520\n9521\n9522\n9523\n9524\n9525\n9526\n9527\n9528\n9529\n9530\n9531\n9532\n9533\n9534\n9535\n9536\n9537\n9538\n9539\n9540\n9541\n9542\n9543\n9544\n9545\n9546\n9547\n9548\n9549\n9550\n9551\n9552\n9553\n9554\n9555\n9556\n9557\n9558\n9559\n9560\n9561\n9562\n9563\n9564\n9565\n9566\n9567\n9568\n9569\n9570\n9571\n9572\n9573\n9574\n9575\n9576\n9577\n9578\n9579\n9580\n9581\n9582\n9583\n9584\n9585\n9586\n9587\n9588\n9589\n9590\n9591\n9592\n9593\n9594\n9595\n9596\n9597\n9598\n9599\n9600\n9601\n9602\n9603\n9604\n9605\n9606\n9607\n9608\n9609\n9610\n9611\n9612\n9613\n9614\n9615\n9616\n9617\n9618\n9619\n9620\n9621\n9622\n9623\n9624\n9625\n9626\n9627\n9628\n9629\n9630\n9631\n9632\n9633\n9634\n9635\n9636\n9637\n9638\n9639\n9640\n9641\n9642\n9643\n9644\n9645\n9646\n9647\n9648\n9649\n9650\n9651\n9652\n9653\n9654\n9655\n9656\n9657\n9658\n9659\n9660\n9661\n9662\n9663\n9664\n9665\n9666\n9667\n9668\n9669\n9670\n9671\n9672\n9673\n9674\n9675\n9676\n9677\n9678\n9679\n9680\n9681\n9682\n9683\n9684\n9685\n9686\n9687\n9688\n9689\n9690\n9691\n9692\n9693\n9694\n9695\n9696\n9697\n9698\n9699\n9700\n9701\n9702\n9703\n9704\n9705\n9706\n9707\n9708\n9709\n9710\n9711\n9712\n9713\n9714\n9715\n9716\n9717\n9718\n9719\n9720\n9721\n9722\n9723\n9724\n9725\n9726\n9727\n9728\n9729\n9730\n9731\n9732\n9733\n9734\n9735\n9736\n9737\n9738\n9739\n9740\n9741\n9742\n9743\n9744\n9745\n9746\n9747\n9748\n9749\n9750\n9751\n9752\n9753\n9754\n9755\n9756\n9757\n9758\n9759\n9760\n9761\n9762\n9763\n9764\n9765\n9766\n9767\n9768\n9769\n9770\n9771\n9772\n9773\n9774\n9775\n9776\n9777\n9778\n9779\n9780\n9781\n9782\n9783\n9784\n9785\n9786\n9787\n9788\n9789\n9790\n9791\n9792\n9793\n9794\n9795\n9796\n9797\n9798\n9799\n9800\n9801\n9802\n9803\n9804\n9805\n9806\n9807\n9808\n9809\n9810\n9811\n9812\n9813\n9814\n9815\n9816\n9817\n9818\n9819\n9820\n9821\n9822\n9823\n9824\n9825\n9826\n9827\n9828\n9829\n9830\n9831\n9832\n9833\n9834\n9835\n9836\n9837\n9838\n9839\n9840\n9841\n9842\n9843\n9844\n9845\n9846\n9847\n9848\n9849\n9850\n9851\n9852\n9853\n9854\n9855\n9856\n9857\n9858\n9859\n9860\n9861\n9862\n9863\n9864\n9865\n9866\n9867\n9868\n9869\n9870\n9871\n9872\n9873\n9874\n9875\n9876\n9877\n9878\n9879\n9880\n9881\n9882\n9883\n9884\n9885\n9886\n9887\n9888\n9889\n9890\n9891\n9892\n9893\n9894\n9895\n9896\n9897\n9898\n9899\n9900\n9901\n9902\n9903\n9904\n9905\n9906\n9907\n9908\n9909\n9910\n9911\n9912\n9913\n9914\n9915\n9916\n9917\n9918\n9919\n9920\n9921\n9922\n9923\n9924\n9925\n9926\n9927\n9928\n9929\n9930\n9931\n9932\n9933\n9934\n9935\n9936\n9937\n9938\n9939\n9940\n9941\n9942\n9943\n9944\n9945\n9946\n9947\n9948\n9949\n9950\n9951\n9952\n9953\n9954\n9955\n9956\n9957\n9958\n9959\n9960\n9961\n9962\n9963\n9964\n9965\n9966\n9967\n9968\n9969\n9970\n9971\n9972\n9973\n9974\n9975\n9976\n9977\n9978\n9979\n9980\n9981\n9982\n9983\n9984\n9985\n9986\n9987\n9988\n9989\n9990\n9991\n9992\n9993\n9994\n9995\n9996\n9997\n9998\n9999\n10000\n10001\n10002\n10003\n10004\n10005\n10006\n10007\n10008\n10009\n10010\n10011\n10012\n10013\n10014\n10015\n10016\n10017\n10018\n10019\n10020\n10021\n10022\n10023\n10024\n10025\n10026\n10027\n10028\n10029\n10030\n10031\n10032\n10033\n10034\n10035\n10036\n10037\n10038\n10039\n10040\n10041\n10042\n10043\n10044\n10045\n10046\n10047\n10048\n10049\n10050\n10051\n10052\n10053\n10054\n10055\n10056\n10057\n10058\n10059\n10060\n10061\n10062\n10063\n10064\n10065\n10066\n10067\n10068\n10069\n10070\n10071\n10072\n10073\n10074\n10075\n10076\n10077\n10078\n10079\n10080\n10081\n10082\n10083\n10084\n10085\n10086\n10087\n10088\n10089\n10090\n10091\n10092\n10093\n10094\n10095\n10096\n10097\n10098\n10099\n10100\n10101\n10102\n10103\n10104\n10105\n10106\n10107\n10108\n10109\n10110\n10111\n10112\n10113\n10114\n10115\n10116\n10117\n10118\n10119\n10120\n10121\n10122\n10123\n10124\n10125\n10126\n10127\n10128\n10129\n10130\n10131\n10132\n10133\n10134\n10135\n10136\n10137\n10138\n10139\n10140\n10141\n10142\n10143\n10144\n10145\n10146\n10147\n10148\n10149\n10150\n10151\n10152\n10153\n10154\n10155\n10156\n10157\n10158\n10159\n10160\n10161\n10162\n10163\n10164\n10165\n10166\n10167\n10168\n10169\n10170\n10171\n10172\n10173\n10174\n10175\n10176\n10177\n10178\n10179\n10180\n10181\n10182\n10183\n10184\n10185\n10186\n10187\n10188\n10189\n10190\n10191\n10192\n10193\n10194\n10195\n10196\n10197\n10198\n10199\n10200\n10201\n10202\n10203\n10204\n10205\n10206\n10207\n10208\n10209\n10210\n10211\n10212\n10213\n10214\n10215\n10216\n10217\n10218\n10219\n10220\n10221\n10222\n10223\n10224\n10225\n10226\n10227\n10228\n10229\n10230\n10231\n10232\n10233\n10234\n10235\n10236\n10237\n10238\n10239\n10240\n10241\n10242\n10243\n10244\n10245\n10246\n10247\n10248\n10249\n10250\n10251\n10252\n10253\n10254\n10255\n10256\n10257\n10258\n10259\n10260\n10261\n10262\n10263\n10264\n10265\n10266\n10267\n10268\n10269\n10270\n10271\n10272\n10273\n10274\n10275\n10276\n10277\n10278\n10279\n10280\n10281\n10282\n10283\n10284\n10285\n10286\n10287\n10288\n10289\n10290\n10291\n10292\n10293\n10294\n10295\n10296\n10297\n10298\n10299\n10300\n10301\n10302\n10303\n10304\n10305\n10306\n10307\n10308\n10309\n10310\n10311\n10312\n10313\n10314\n10315\n10316\n10317\n10318\n10319\n10320\n10321\n10322\n10323\n10324\n10325\n10326\n10327\n10328\n10329\n10330\n10331\n10332\n10333\n10334\n10335\n10336\n10337\n10338\n10339\n10340\n10341\n10342\n10343\n10344\n10345\n10346\n10347\n10348\n10349\n10350\n10351\n10352\n10353\n10354\n10355\n10356\n10357\n10358\n10359\n10360\n10361\n10362\n10363\n10364\n10365\n10366\n10367\n10368\n10369\n10370\n10371\n10372\n10373\n10374\n10375\n10376\n10377\n10378\n10379\n10380\n10381\n10382\n10383\n10384\n10385\n10386\n10387\n10388\n10389\n10390\n10391\n10392\n10393\n10394\n10395\n10396\n10397\n10398\n10399\n10400\n10401\n10402\n10403\n10404\n10405\n10406\n10407\n10408\n10409\n10410\n10411\n10412\n10413\n10414\n10415\n10416\n10417\n10418\n10419\n10420\n10421\n10422\n10423\n10424\n10425\n10426\n10427\n10428\n10429\n10430\n10431\n10432\n10433\n10434\n10435\n10436\n10437\n10438\n10439\n10440\n10441\n10442\n10443\n10444\n10445\n10446\n10447\n10448\n10449\n10450\n10451\n10452\n10453\n10454\n10455\n10456\n10457\n10458\n10459\n10460\n10461\n10462\n10463\n10464\n10465\n10466\n10467\n10468\n10469\n10470\n10471\n10472\n10473\n10474\n10475\n10476\n10477\n10478\n10479\n10480\n10481\n10482\n10483\n10484\n10485\n10486\n10487\n10488\n10489\n10490\n10491\n10492\n10493\n10494\n10495\n10496\n10497\n10498\n10499\n10500\n10501\n10502\n10503\n10504\n10505\n10506\n10507\n10508\n10509\n10510\n10511\n10512\n10513\n10514\n10515\n10516\n10517\n10518\n10519\n10520\n10521\n10522\n10523\n10524\n10525\n10526\n10527\n10528\n10529\n10530\n10531\n10532\n10533\n10534\n10535\n10536\n10537\n10538\n10539\n10540\n10541\n10542\n10543\n10544\n10545\n10546\n10547\n10548\n10549\n10550\n10551\n10552\n10553\n10554\n10555\n10556\n10557\n10558\n10559\n10560\n10561\n10562\n10563\n10564\n10565\n10566\n10567\n10568\n10569\n10570\n10571\n10572\n10573\n10574\n10575\n10576\n10577\n10578\n10579\n10580\n10581\n10582\n10583\n10584\n10585\n10586\n10587\n10588\n10589\n10590\n10591\n10592\n10593\n10594\n10595\n10596\n10597\n10598\n10599\n10600\n10601\n10602\n10603\n10604\n10605\n10606\n10607\n10608\n10609\n10610\n10611\n10612\n10613\n10614\n10615\n10616\n10617\n10618\n10619\n10620\n10621\n10622\n10623\n10624\n10625\n10626\n10627\n10628\n10629\n10630\n10631\n10632\n10633\n10634\n10635\n10636\n10637\n10638\n10639\n10640\n10641\n10642\n10643\n10644\n10645\n10646\n10647\n10648\n10649\n10650\n10651\n10652\n10653\n10654\n10655\n10656\n10657\n10658\n10659\n10660\n10661\n10662\n10663\n10664\n10665\n10666\n10667\n10668\n10669\n10670\n10671\n10672\n10673\n10674\n10675\n10676\n10677\n10678\n10679\n10680\n10681\n10682\n10683\n10684\n10685\n10686\n10687\n10688\n10689\n10690\n10691\n10692\n10693\n10694\n10695\n10696\n10697\n10698\n10699\n10700\n10701\n10702\n10703\n10704\n10705\n10706\n10707\n10708\n10709\n10710\n10711\n10712\n10713\n10714\n10715\n10716\n10717\n10718\n10719\n10720\n10721\n10722\n10723\n10724\n10725\n10726\n10727\n10728\n10729\n10730\n10731\n10732\n10733\n10734\n10735\n10736\n10737\n10738\n10739\n10740\n10741\n10742\n10743\n10744\n10745\n10746\n10747\n10748\n10749\n10750\n10751\n10752\n10753\n10754\n10755\n10756\n10757\n10758\n10759\n10760\n10761\n10762\n10763\n10764\n10765\n10766\n10767\n10768\n10769\n10770\n10771\n10772\n10773\n10774\n10775\n10776\n10777\n10778\n10779\n10780\n10781\n10782\n10783\n10784\n10785\n10786\n10787\n10788\n10789\n10790\n10791\n10792\n10793\n10794\n10795\n10796\n10797\n10798\n10799\n10800\n10801\n10802\n10803\n10804\n10805\n10806\n10807\n10808\n10809\n10810\n10811\n10812\n10813\n10814\n10815\n10816\n10817\n10818\n10819\n10820\n10821\n10822\n10823\n10824\n10825\n10826\n10827\n10828\n10829\n10830\n10831\n10832\n10833\n10834\n10835\n10836\n10837\n10838\n10839\n10840\n10841\n10842\n10843\n10844\n10845\n10846\n10847\n10848\n10849\n10850\n10851\n10852\n10853\n10854\n10855\n10856\n10857\n10858\n10859\n10860\n10861\n10862\n10863\n10864\n10865\n10866\n10867\n10868\n10869\n10870\n10871\n10872\n10873\n10874\n10875\n10876\n10877\n10878\n10879\n10880\n10881\n10882\n10883\n10884\n10885\n10886\n10887\n10888\n10889\n10890\n10891\n10892\n10893\n10894\n10895\n10896\n10897\n10898\n10899\n10900\n10901\n10902\n10903\n10904\n10905\n10906\n10907\n10908\n10909\n10910\n10911\n10912\n10913\n10914\n10915\n10916\n10917\n10918\n10919\n10920\n10921\n10922\n10923\n10924\n10925\n10926\n10927\n10928\n10929\n10930\n10931\n10932\n10933\n10934\n10935\n10936\n10937\n10938\n10939\n10940\n10941\n10942\n10943\n10944\n10945\n10946\n10947\n10948\n10949\n10950\n10951\n10952\n10953\n10954\n10955\n10956\n10957\n10958\n10959\n10960\n10961\n10962\n10963\n10964\n10965\n10966\n10967\n10968\n10969\n10970\n10971\n10972\n10973\n10974\n10975\n10976\n10977\n10978\n10979\n10980\n10981\n10982\n10983\n10984\n10985\n10986\n10987\n10988\n10989\n10990\n10991\n10992\n10993\n10994\n10995\n10996\n10997\n10998\n10999\n11000\n11001\n11002\n11003\n11004\n11005\n11006\n11007\n11008\n11009\n11010\n11011\n11012\n11013\n11014\n11015\n11016\n11017\n11018\n11019\n11020\n11021\n11022\n11023\n11024\n11025\n11026\n11027\n11028\n11029\n11030\n11031\n11032\n11033\n11034\n11035\n11036\n11037\n11038\n11039\n11040\n11041\n11042\n11043\n11044\n11045\n11046\n11047\n11048\n11049\n11050\n11051\n11052\n11053\n11054\n11055\n11056\n11057\n11058\n11059\n11060\n11061\n11062\n11063\n11064\n11065\n11066\n11067\n11068\n11069\n11070\n11071\n11072\n11073\n11074\n11075\n11076\n11077\n11078\n11079\n11080\n11081\n11082\n11083\n11084\n11085\n11086\n11087\n11088\n11089\n11090\n11091\n11092\n11093\n11094\n11095\n11096\n11097\n11098\n11099\n11100\n11101\n11102\n11103\n11104\n11105\n11106\n11107\n11108\n11109\n11110\n11111\n11112\n11113\n11114\n11115\n11116\n11117\n11118\n11119\n11120\n11121\n11122\n11123\n11124\n11125\n11126\n11127\n11128\n11129\n11130\n11131\n11132\n11133\n11134\n11135\n11136\n11137\n11138\n11139\n11140\n11141\n11142\n11143\n11144\n11145\n11146\n11147\n11148\n11149\n11150\n11151\n11152\n11153\n11154\n11155\n11156\n11157\n11158\n11159\n11160\n11161\n11162\n11163\n11164\n11165\n11166\n11167\n11168\n11169\n11170\n11171\n11172\n11173\n11174\n11175\n11176\n11177\n11178\n11179\n11180\n11181\n11182\n11183\n11184\n11185\n11186\n11187\n11188\n11189\n11190\n11191\n11192\n11193\n11194\n11195\n11196\n11197\n11198\n11199\n11200\n11201\n11202\n11203\n11204\n11205\n11206\n11207\n11208\n11209\n11210\n11211\n11212\n11213\n11214\n11215\n11216\n11217\n11218\n11219\n11220\n11221\n11222\n11223\n11224\n11225\n11226\n11227\n11228\n11229\n11230\n11231\n11232\n11233\n11234\n11235\n11236\n11237\n11238\n11239\n11240\n11241\n11242\n11243\n11244\n11245\n11246\n11247\n11248\n11249\n11250\n11251\n11252\n11253\n11254\n11255\n11256\n11257\n11258\n11259\n11260\n11261\n11262\n11263\n11264\n11265\n11266\n11267\n11268\n11269\n11270\n11271\n11272\n11273\n11274\n11275\n11276\n11277\n11278\n11279\n11280\n11281\n11282\n11283\n11284\n11285\n11286\n11287\n11288\n11289\n11290\n11291\n11292\n11293\n11294\n11295\n11296\n11297\n11298\n11299\n11300\n11301\n11302\n11303\n11304\n11305\n11306\n11307\n11308\n11309\n11310\n11311\n11312\n11313\n11314\n11315\n11316\n11317\n11318\n11319\n11320\n11321\n11322\n11323\n11324\n11325\n11326\n11327\n11328\n11329\n11330\n11331\n11332\n11333\n11334\n11335\n11336\n11337\n11338\n11339\n11340\n11341\n11342\n11343\n11344\n11345\n11346\n11347\n11348\n11349\n11350\n11351\n11352\n11353\n11354\n11355\n11356\n11357\n11358\n11359\n11360\n11361\n11362\n11363\n11364\n11365\n11366\n11367\n11368\n11369\n11370\n11371\n11372\n11373\n11374\n11375\n11376\n11377\n11378\n11379\n11380\n11381\n11382\n11383\n11384\n11385\n11386\n11387\n11388\n11389\n11390\n11391\n11392\n11393\n11394\n11395\n11396\n11397\n11398\n11399\n11400\n11401\n11402\n11403\n11404\n11405\n11406\n11407\n11408\n11409\n11410\n11411\n11412\n11413\n11414\n11415\n11416\n11417\n11418\n11419\n11420\n11421\n11422\n11423\n11424\n11425\n11426\n11427\n11428\n11429\n11430\n11431\n11432\n11433\n11434\n11435\n11436\n11437\n11438\n11439\n11440\n11441\n11442\n11443\n11444\n11445\n11446\n11447\n11448\n11449\n11450\n11451\n11452\n11453\n11454\n11455\n11456\n11457\n11458\n11459\n11460\n11461\n11462\n11463\n11464\n11465\n11466\n11467\n11468\n11469\n11470\n11471\n11472\n11473\n11474\n11475\n11476\n11477\n11478\n11479\n11480\n11481\n11482\n11483\n11484\n11485\n11486\n11487\n11488\n11489\n11490\n11491\n11492\n11493\n11494\n11495\n11496\n11497\n11498\n11499\n11500\n11501\n11502\n11503\n11504\n11505\n11506\n11507\n11508\n11509\n11510\n11511\n11512\n11513\n11514\n11515\n11516\n11517\n11518\n11519\n11520\n11521\n11522\n11523\n11524\n11525\n11526\n11527\n11528\n11529\n11530\n11531\n11532\n11533\n11534\n11535\n11536\n11537\n11538\n11539\n11540\n11541\n11542\n11543\n11544\n11545\n11546\n11547\n11548\n11549\n11550\n11551\n11552\n11553\n11554\n11555\n11556\n11557\n11558\n11559\n11560\n11561\n11562\n11563\n11564\n11565\n11566\n11567\n11568\n11569\n11570\n11571\n11572\n11573\n11574\n11575\n11576\n11577\n11578\n11579\n11580\n11581\n11582\n11583\n11584\n11585\n11586\n11587\n11588\n11589\n11590\n11591\n11592\n11593\n11594\n11595\n11596\n11597\n11598\n11599\n11600\n11601\n11602\n11603\n11604\n11605\n11606\n11607\n11608\n11609\n11610\n11611\n11612\n11613\n11614\n11615\n11616\n11617\n11618\n11619\n11620\n11621\n11622\n11623\n11624\n11625\n11626\n11627\n11628\n11629\n11630\n11631\n11632\n11633\n11634\n11635\n11636\n11637\n11638\n11639\n11640\n11641\n11642\n11643\n11644\n11645\n11646\n11647\n11648\n11649\n11650\n11651\n11652\n11653\n11654\n11655\n11656\n11657\n11658\n11659\n11660\n11661\n11662\n11663\n11664\n11665\n11666\n11667\n11668\n11669\n11670\n11671\n11672\n11673\n11674\n11675\n11676\n11677\n11678\n11679\n11680\n11681\n11682\n11683\n11684\n11685\n11686\n11687\n11688\n11689\n11690\n11691\n11692\n11693\n11694\n11695\n11696\n11697\n11698\n11699\n11700\n11701\n11702\n11703\n11704\n11705\n11706\n11707\n11708\n11709\n11710\n11711\n11712\n11713\n11714\n11715\n11716\n11717\n11718\n11719\n11720\n11721\n11722\n11723\n11724\n11725\n11726\n11727\n11728\n11729\n11730\n11731\n11732\n11733\n11734\n11735\n11736\n11737\n11738\n11739\n11740\n11741\n11742\n11743\n11744\n11745\n11746\n11747\n11748\n11749\n11750\n11751\n11752\n11753\n11754\n11755\n11756\n11757\n11758\n11759\n11760\n11761\n11762\n11763\n11764\n11765\n11766\n11767\n11768\n11769\n11770\n11771\n11772\n11773\n11774\n11775\n11776\n11777\n11778\n11779\n11780\n11781\n11782\n11783\n11784\n11785\n11786\n11787\n11788\n11789\n11790\n11791\n11792\n11793\n11794\n11795\n11796\n11797\n11798\n11799\n11800\n11801\n11802\n11803\n11804\n11805\n11806\n11807\n11808\n11809\n11810\n11811\n11812\n11813\n11814\n11815\n11816\n11817\n11818\n11819\n11820\n11821\n11822\n11823\n11824\n11825\n11826\n11827\n11828\n11829\n11830\n11831\n11832\n11833\n11834\n11835\n11836\n11837\n11838\n11839\n11840\n11841\n11842\n11843\n11844\n11845\n11846\n11847\n11848\n11849\n11850\n11851\n11852\n11853\n11854\n11855\n11856\n11857\n11858\n11859\n11860\n11861\n11862\n11863\n11864\n11865\n11866\n11867\n11868\n11869\n11870\n11871\n11872\n11873\n11874\n11875\n11876\n11877\n11878\n11879\n11880\n11881\n11882\n11883\n11884\n11885\n11886\n11887\n11888\n11889\n11890\n11891\n11892\n11893\n11894\n11895\n11896\n11897\n11898\n11899\n11900\n11901\n11902\n11903\n11904\n11905\n11906\n11907\n11908\n11909\n11910\n11911\n11912\n11913\n11914\n11915\n11916\n11917\n11918\n11919\n11920\n11921\n11922\n11923\n11924\n11925\n11926\n11927\n11928\n11929\n11930\n11931\n11932\n11933\n11934\n11935\n11936\n11937\n11938\n11939\n11940\n11941\n11942\n11943\n11944\n11945\n11946\n11947\n11948\n11949\n11950\n11951\n11952\n11953\n11954\n11955\n11956\n11957\n11958\n11959\n11960\n11961\n11962\n11963\n11964\n11965\n11966\n11967\n11968\n11969\n11970\n11971\n11972\n11973\n11974\n11975\n11976\n11977\n11978\n11979\n11980\n11981\n11982\n11983\n11984\n11985\n11986\n11987\n11988\n11989\n11990\n11991\n11992\n11993\n11994\n11995\n11996\n11997\n11998\n11999\n12000\n12001\n12002\n12003\n12004\n12005\n12006\n12007\n12008\n12009\n12010\n12011\n12012\n12013\n12014\n12015\n12016\n12017\n12018\n12019\n12020\n12021\n12022\n12023\n12024\n12025\n12026\n12027\n12028\n12029\n12030\n12031\n12032\n12033\n12034\n12035\n12036\n12037\n12038\n12039\n12040\n12041\n12042\n12043\n12044\n12045\n12046\n12047\n12048\n12049\n12050\n12051\n12052\n12053\n12054\n12055\n12056\n12057\n12058\n12059\n12060\n12061\n12062\n12063\n12064\n12065\n12066\n12067\n12068\n12069\n12070\n12071\n12072\n12073\n12074\n12075\n12076\n12077\n12078\n12079\n12080\n12081\n12082\n12083\n12084\n12085\n12086\n12087\n12088\n12089\n12090\n12091\n12092\n12093\n12094\n12095\n12096\n12097\n12098\n12099\n12100\n12101\n12102\n12103\n12104\n12105\n12106\n12107\n12108\n12109\n12110\n12111\n12112\n12113\n12114\n12115\n12116\n12117\n12118\n12119\n12120\n12121\n12122\n12123\n12124\n12125\n12126\n12127\n12128\n12129\n12130\n12131\n12132\n12133\n12134\n12135\n12136\n12137\n12138\n12139\n12140\n12141\n12142\n12143\n12144\n12145\n12146\n12147\n12148\n12149\n12150\n12151\n12152\n12153\n12154\n12155\n12156\n12157\n12158\n12159\n12160\n12161\n12162\n12163\n12164\n12165\n12166\n12167\n12168\n12169\n12170\n12171\n12172\n12173\n12174\n12175\n12176\n12177\n12178\n12179\n12180\n12181\n12182\n12183\n12184\n12185\n12186\n12187\n12188\n12189\n12190\n12191\n12192\n12193\n12194\n12195\n12196\n12197\n12198\n12199\n12200\n12201\n12202\n12203\n12204\n12205\n12206\n12207\n12208\n12209\n12210\n12211\n12212\n12213\n12214\n12215\n12216\n12217\n12218\n12219\n12220\n12221\n12222\n12223\n12224\n12225\n12226\n12227\n12228\n12229\n12230\n12231\n12232\n12233\n12234\n12235\n12236\n12237\n12238\n12239\n12240\n12241\n12242\n12243\n12244\n12245\n12246\n12247\n12248\n12249\n12250\n12251\n12252\n12253\n12254\n12255\n12256\n12257\n12258\n12259\n12260\n12261\n12262\n12263\n12264\n12265\n12266\n12267\n12268\n12269\n12270\n12271\n12272\n12273\n12274\n12275\n12276\n12277\n12278\n12279\n12280\n12281\n12282\n12283\n12284\n12285\n12286\n12287\n12288\n12289\n12290\n12291\n12292\n12293\n12294\n12295\n12296\n12297\n12298\n12299\n12300\n12301\n12302\n12303\n12304\n12305\n12306\n12307\n12308\n12309\n12310\n12311\n12312\n12313\n12314\n12315\n12316\n12317\n12318\n12319\n12320\n12321\n12322\n12323\n12324\n12325\n12326\n12327\n12328\n12329\n12330\n12331\n12332\n12333\n12334\n12335\n12336\n12337\n12338\n12339\n12340\n12341\n12342\n12343\n12344\n12345\n12346\n12347\n12348\n12349\n12350\n12351\n12352\n12353\n12354\n12355\n12356\n12357\n12358\n12359\n12360\n12361\n12362\n12363\n12364\n12365\n12366\n12367\n12368\n12369\n12370\n12371\n12372\n12373\n12374\n12375\n12376\n12377\n12378\n12379\n12380\n12381\n12382\n12383\n12384\n12385\n12386\n12387\n12388\n12389\n12390\n12391\n12392\n12393\n12394\n12395\n12396\n12397\n12398\n12399\n12400\n12401\n12402\n12403\n12404\n12405\n12406\n12407\n12408\n12409\n12410\n12411\n12412\n12413\n12414\n12415\n12416\n12417\n12418\n12419\n12420\n12421\n12422\n12423\n12424\n12425\n12426\n12427\n12428\n12429\n12430\n12431\n12432\n12433\n12434\n12435\n12436\n12437\n12438\n12439\n12440\n12441\n12442\n12443\n12444\n12445\n12446\n12447\n12448\n12449\n12450\n12451\n12452\n12453\n12454\n12455\n12456\n12457\n12458\n12459\n12460\n12461\n12462\n12463\n12464\n12465\n12466\n12467\n12468\n12469\n12470\n12471\n12472\n12473\n12474\n12475\n12476\n12477\n12478\n12479\n12480\n12481\n12482\n12483\n12484\n12485\n12486\n12487\n12488\n12489\n12490\n12491\n12492\n12493\n12494\n12495\n12496\n12497\n12498\n12499\n12500\n12501\n12502\n12503\n12504\n12505\n12506\n12507\n12508\n12509\n12510\n12511\n12512\n12513\n12514\n12515\n12516\n12517\n12518\n12519\n12520\n12521\n12522\n12523\n12524\n12525\n12526\n12527\n12528\n12529\n12530\n12531\n12532\n12533\n12534\n12535\n12536\n12537\n12538\n12539\n12540\n12541\n12542\n12543\n12544\n12545\n12546\n12547\n12548\n12549\n12550\n12551\n12552\n12553\n12554\n12555\n12556\n12557\n12558\n12559\n12560\n12561\n12562\n12563\n12564\n12565\n12566\n12567\n12568\n12569\n12570\n12571\n12572\n12573\n12574\n12575\n12576\n12577\n12578\n12579\n12580\n12581\n12582\n12583\n12584\n12585\n12586\n12587\n12588\n12589\n12590\n12591\n12592\n12593\n12594\n12595\n12596\n12597\n12598\n12599\n12600\n12601\n12602\n12603\n12604\n12605\n12606\n12607\n12608\n12609\n12610\n12611\n12612\n12613\n12614\n12615\n12616\n12617\n12618\n12619\n12620\n12621\n12622\n12623\n12624\n12625\n12626\n12627\n12628\n12629\n12630\n12631\n12632\n12633\n12634\n12635\n12636\n12637\n12638\n12639\n12640\n12641\n12642\n12643\n12644\n12645\n12646\n12647\n12648\n12649\n12650\n12651\n12652\n12653\n12654\n12655\n12656\n12657\n12658\n12659\n12660\n12661\n12662\n12663\n12664\n12665\n12666\n12667\n12668\n12669\n12670\n12671\n12672\n12673\n12674\n12675\n12676\n12677\n12678\n12679\n12680\n12681\n12682\n12683\n12684\n12685\n12686\n12687\n12688\n12689\n12690\n12691\n12692\n12693\n12694\n12695\n12696\n12697\n12698\n12699\n12700\n12701\n12702\n12703\n12704\n12705\n12706\n12707\n12708\n12709\n12710\n12711\n12712\n12713\n12714\n12715\n12716\n12717\n12718\n12719\n12720\n12721\n12722\n12723\n12724\n12725\n12726\n12727\n12728\n12729\n12730\n12731\n12732\n12733\n12734\n12735\n12736\n12737\n12738\n12739\n12740\n12741\n12742\n12743\n12744\n12745\n12746\n12747\n12748\n12749\n12750\n12751\n12752\n12753\n12754\n12755\n12756\n12757\n12758\n12759\n12760\n12761\n12762\n12763\n12764\n12765\n12766\n12767\n12768\n12769\n12770\n12771\n12772\n12773\n12774\n12775\n12776\n12777\n12778\n12779\n12780\n12781\n12782\n12783\n12784\n12785\n12786\n12787\n12788\n12789\n12790\n12791\n12792\n12793\n12794\n12795\n12796\n12797\n12798\n12799\n12800\n12801\n12802\n12803\n12804\n12805\n12806\n12807\n12808\n12809\n12810\n12811\n12812\n12813\n12814\n12815\n12816\n12817\n12818\n12819\n12820\n12821\n12822\n12823\n12824\n12825\n12826\n12827\n12828\n12829\n12830\n12831\n12832\n12833\n12834\n12835\n12836\n12837\n12838\n12839\n12840\n12841\n12842\n12843\n12844\n12845\n12846\n12847\n12848\n12849\n12850\n12851\n12852\n12853\n12854\n12855\n12856\n12857\n12858\n12859\n12860\n12861\n12862\n12863\n12864\n12865\n12866\n12867\n12868\n12869\n12870\n12871\n12872\n12873\n12874\n12875\n12876\n12877\n12878\n12879\n12880\n12881\n12882\n12883\n12884\n12885\n12886\n12887\n12888\n12889\n12890\n12891\n12892\n12893\n12894\n12895\n12896\n12897\n12898\n12899\n12900\n12901\n12902\n12903\n12904\n12905\n12906\n12907\n12908\n12909\n12910\n12911\n12912\n12913\n12914\n12915\n12916\n12917\n12918\n12919\n12920\n12921\n12922\n12923\n12924\n12925\n12926\n12927\n12928\n12929\n12930\n12931\n12932\n12933\n12934\n12935\n12936\n12937\n12938\n12939\n12940\n12941\n12942\n12943\n12944\n12945\n12946\n12947\n12948\n12949\n12950\n12951\n12952\n12953\n12954\n12955\n12956\n12957\n12958\n12959\n12960\n12961\n12962\n12963\n12964\n12965\n12966\n12967\n12968\n12969\n12970\n12971\n12972\n12973\n12974\n12975\n12976\n12977\n12978\n12979\n12980\n12981\n12982\n12983\n12984\n12985\n12986\n12987\n12988\n12989\n12990\n12991\n12992\n12993\n12994\n12995\n12996\n12997\n12998\n12999\n13000\n13001\n13002\n13003\n13004\n13005\n13006\n13007\n13008\n13009\n13010\n13011\n13012\n13013\n13014\n13015\n13016\n13017\n13018\n13019\n13020\n13021\n13022\n13023\n13024\n13025\n13026\n13027\n13028\n13029\n13030\n13031\n13032\n13033\n13034\n13035\n13036\n13037\n13038\n13039\n13040\n13041\n13042\n13043\n13044\n13045\n13046\n13047\n13048\n13049\n13050\n13051\n13052\n13053\n13054\n13055\n13056\n13057\n13058\n13059\n13060\n13061\n13062\n13063\n13064\n13065\n13066\n13067\n13068\n13069\n13070\n13071\n13072\n13073\n13074\n13075\n13076\n13077\n13078\n13079\n13080\n13081\n13082\n13083\n13084\n13085\n13086\n13087\n13088\n13089\n13090\n13091\n13092\n13093\n13094\n13095\n13096\n13097\n13098\n13099\n13100\n13101\n13102\n13103\n13104\n13105\n13106\n13107\n13108\n13109\n13110\n13111\n13112\n13113\n13114\n13115\n13116\n13117\n13118\n13119\n13120\n13121\n13122\n13123\n13124\n13125\n13126\n13127\n13128\n13129\n13130\n13131\n13132\n13133\n13134\n13135\n13136\n13137\n13138\n13139\n13140\n13141\n13142\n13143\n13144\n13145\n13146\n13147\n13148\n13149\n13150\n13151\n13152\n13153\n13154\n13155\n13156\n13157\n13158\n13159\n13160\n13161\n13162\n13163\n13164\n13165\n13166\n13167\n13168\n13169\n13170\n13171\n13172\n13173\n13174\n13175\n13176\n13177\n13178\n13179\n13180\n13181\n13182\n13183\n13184\n13185\n13186\n13187\n13188\n13189\n13190\n13191\n13192\n13193\n13194\n13195\n13196\n13197\n13198\n13199\n13200\n13201\n13202\n13203\n13204\n13205\n13206\n13207\n13208\n13209\n13210\n13211\n13212\n13213\n13214\n13215\n13216\n13217\n13218\n13219\n13220\n13221\n13222\n13223\n13224\n13225\n13226\n13227\n13228\n13229\n13230\n13231\n13232\n13233\n13234\n13235\n13236\n13237\n13238\n13239\n13240\n13241\n13242\n13243\n13244\n13245\n13246\n13247\n13248\n13249\n13250\n13251\n13252\n13253\n13254\n13255\n13256\n13257\n13258\n13259\n13260\n13261\n13262\n13263\n13264\n13265\n13266\n13267\n13268\n13269\n13270\n13271\n13272\n13273\n13274\n13275\n13276\n13277\n13278\n13279\n13280\n13281\n13282\n13283\n13284\n13285\n13286\n13287\n13288\n13289\n13290\n13291\n13292\n13293\n13294\n13295\n13296\n13297\n13298\n13299\n13300\n13301\n13302\n13303\n13304\n13305\n13306\n13307\n13308\n13309\n13310\n13311\n13312\n13313\n13314\n13315\n13316\n13317\n13318\n13319\n13320\n13321\n13322\n13323\n13324\n13325\n13326\n13327\n13328\n13329\n13330\n13331\n13332\n13333\n13334\n13335\n13336\n13337\n13338\n13339\n13340\n13341\n13342\n13343\n13344\n13345\n13346\n13347\n13348\n13349\n13350\n13351\n13352\n13353\n13354\n13355\n13356\n13357\n13358\n13359\n13360\n13361\n13362\n13363\n13364\n13365\n13366\n13367\n13368\n13369\n13370\n13371\n13372\n13373\n13374\n13375\n13376\n13377\n13378\n13379\n13380\n13381\n13382\n13383\n13384\n13385\n13386\n13387\n13388\n13389\n13390\n13391\n13392\n13393\n13394\n13395\n13396\n13397\n13398\n13399\n13400\n13401\n13402\n13403\n13404\n13405\n13406\n13407\n13408\n13409\n13410\n13411\n13412\n13413\n13414\n13415\n13416\n13417\n13418\n13419\n13420\n13421\n13422\n13423\n13424\n13425\n13426\n13427\n13428\n13429\n13430\n13431\n13432\n13433\n13434\n13435\n13436\n13437\n13438\n13439\n13440\n13441\n13442\n13443\n13444\n13445\n13446\n13447\n13448\n13449\n13450\n13451\n13452\n13453\n13454\n13455\n13456\n13457\n13458\n13459\n13460\n13461\n13462\n13463\n13464\n13465\n13466\n13467\n13468\n13469\n13470\n13471\n13472\n13473\n13474\n13475\n13476\n13477\n13478\n13479\n13480\n13481\n13482\n13483\n13484\n13485\n13486\n13487\n13488\n13489\n13490\n13491\n13492\n13493\n13494\n13495\n13496\n13497\n13498\n13499\n13500\n13501\n13502\n13503\n13504\n13505\n13506\n13507\n13508\n13509\n13510\n13511\n13512\n13513\n13514\n13515\n13516\n13517\n13518\n13519\n13520\n13521\n13522\n13523\n13524\n13525\n13526\n13527\n13528\n13529\n13530\n13531\n13532\n13533\n13534\n13535\n13536\n13537\n13538\n13539\n13540\n13541\n13542\n13543\n13544\n13545\n13546\n13547\n13548\n13549\n13550\n13551\n13552\n13553\n13554\n13555\n13556\n13557\n13558\n13559\n13560\n13561\n13562\n13563\n13564\n13565\n13566\n13567\n13568\n13569\n13570\n13571\n13572\n13573\n13574\n13575\n13576\n13577\n13578\n13579\n13580\n13581\n13582\n13583\n13584\n13585\n13586\n13587\n13588\n13589\n13590\n13591\n13592\n13593\n13594\n13595\n13596\n13597\n13598\n13599\n13600\n13601\n13602\n13603\n13604\n13605\n13606\n13607\n13608\n13609\n13610\n13611\n13612\n13613\n13614\n13615\n13616\n13617\n13618\n13619\n13620\n13621\n13622\n13623\n13624\n13625\n13626\n13627\n13628\n13629\n13630\n13631\n13632\n13633\n13634\n13635\n13636\n13637\n13638\n13639\n13640\n13641\n13642\n13643\n13644\n13645\n13646\n13647\n13648\n13649\n13650\n13651\n13652\n13653\n13654\n13655\n13656\n13657\n13658\n13659\n13660\n13661\n13662\n13663\n13664\n13665\n13666\n13667\n13668\n13669\n13670\n13671\n13672\n13673\n13674\n13675\n13676\n13677\n13678\n13679\n13680\n13681\n13682\n13683\n13684\n13685\n13686\n13687\n13688\n13689\n13690\n13691\n13692\n13693\n13694\n13695\n13696\n13697\n13698\n13699\n13700\n13701\n13702\n13703\n13704\n13705\n13706\n13707\n13708\n13709\n13710\n13711\n13712\n13713\n13714\n13715\n13716\n13717\n13718\n13719\n13720\n13721\n13722\n13723\n13724\n13725\n13726\n13727\n13728\n13729\n13730\n13731\n13732\n13733\n13734\n13735\n13736\n13737\n13738\n13739\n13740\n13741\n13742\n13743\n13744\n13745\n13746\n13747\n13748\n13749\n13750\n13751\n13752\n13753\n13754\n13755\n13756\n13757\n13758\n13759\n13760\n13761\n13762\n13763\n13764\n13765\n13766\n13767\n13768\n13769\n13770\n13771\n13772\n13773\n13774\n13775\n13776\n13777\n13778\n13779\n13780\n13781\n13782\n13783\n13784\n13785\n13786\n13787\n13788\n13789\n13790\n13791\n13792\n13793\n13794\n13795\n13796\n13797\n13798\n13799\n13800\n13801\n13802\n13803\n13804\n13805\n13806\n13807\n13808\n13809\n13810\n13811\n13812\n13813\n13814\n13815\n13816\n13817\n13818\n13819\n13820\n13821\n13822\n13823\n13824\n13825\n13826\n13827\n13828\n13829\n13830\n13831\n13832\n13833\n13834\n13835\n13836\n13837\n13838\n13839\n13840\n13841\n13842\n13843\n13844\n13845\n13846\n13847\n13848\n13849\n13850\n13851\n13852\n13853\n13854\n13855\n13856\n13857\n13858\n13859\n13860\n13861\n13862\n13863\n13864\n13865\n13866\n13867\n13868\n13869\n13870\n13871\n13872\n13873\n13874\n13875\n13876\n13877\n13878\n13879\n13880\n13881\n13882\n13883\n13884\n13885\n13886\n13887\n13888\n13889\n13890\n13891\n13892\n13893\n13894\n13895\n13896\n13897\n13898\n13899\n13900\n13901\n13902\n13903\n13904\n13905\n13906\n13907\n13908\n13909\n13910\n13911\n13912\n13913\n13914\n13915\n13916\n13917\n13918\n13919\n13920\n13921\n13922\n13923\n13924\n13925\n13926\n13927\n13928\n13929\n13930\n13931\n13932\n13933\n13934\n13935\n13936\n13937\n13938\n13939\n13940\n13941\n13942\n13943\n13944\n13945\n13946\n13947\n13948\n13949\n13950\n13951\n13952\n13953\n13954\n13955\n13956\n13957\n13958\n13959\n13960\n13961\n13962\n13963\n13964\n13965\n13966\n13967\n13968\n13969\n13970\n13971\n13972\n13973\n13974\n13975\n13976\n13977\n13978\n13979\n13980\n13981\n13982\n13983\n13984\n13985\n13986\n13987\n13988\n13989\n13990\n13991\n13992\n13993\n13994\n13995\n13996\n13997\n13998\n13999\n14000\n14001\n14002\n14003\n14004\n14005\n14006\n14007\n14008\n14009\n14010\n14011\n14012\n14013\n14014\n14015\n14016\n14017\n14018\n14019\n14020\n14021\n14022\n14023\n14024\n14025\n14026\n14027\n14028\n14029\n14030\n14031\n14032\n14033\n14034\n14035\n14036\n14037\n14038\n14039\n14040\n14041\n14042\n14043\n14044\n14045\n14046\n14047\n14048\n14049\n14050\n14051\n14052\n14053\n14054\n14055\n14056\n14057\n14058\n14059\n14060\n14061\n14062\n14063\n14064\n14065\n14066\n14067\n14068\n14069\n14070\n14071\n14072\n14073\n14074\n14075\n14076\n14077\n14078\n14079\n14080\n14081\n14082\n14083\n14084\n14085\n14086\n14087\n14088\n14089\n14090\n14091\n14092\n14093\n14094\n14095\n14096\n14097\n14098\n14099\n14100\n14101\n14102\n14103\n14104\n14105\n14106\n14107\n14108\n14109\n14110\n14111\n14112\n14113\n14114\n14115\n14116\n14117\n14118\n14119\n14120\n14121\n14122\n14123\n14124\n14125\n14126\n14127\n14128\n14129\n14130\n14131\n14132\n14133\n14134\n14135\n14136\n14137\n14138\n14139\n14140\n14141\n14142\n14143\n14144\n14145\n14146\n14147\n14148\n14149\n14150\n14151\n14152\n14153\n14154\n14155\n14156\n14157\n14158\n14159\n14160\n14161\n14162\n14163\n14164\n14165\n14166\n14167\n14168\n14169\n14170\n14171\n14172\n14173\n14174\n14175\n14176\n14177\n14178\n14179\n14180\n14181\n14182\n14183\n14184\n14185\n14186\n14187\n14188\n14189\n14190\n14191\n14192\n14193\n14194\n14195\n14196\n14197\n14198\n14199\n14200\n14201\n14202\n14203\n14204\n14205\n14206\n14207\n14208\n14209\n14210\n14211\n14212\n14213\n14214\n14215\n14216\n14217\n14218\n14219\n14220\n14221\n14222\n14223\n14224\n14225\n14226\n14227\n14228\n14229\n14230\n14231\n14232\n14233\n14234\n14235\n14236\n14237\n14238\n14239\n14240\n14241\n14242\n14243\n14244\n14245\n14246\n14247\n14248\n14249\n14250\n14251\n14252\n14253\n14254\n14255\n14256\n14257\n14258\n14259\n14260\n14261\n14262\n14263\n14264\n14265\n14266\n14267\n14268\n14269\n14270\n14271\n14272\n14273\n14274\n14275\n14276\n14277\n14278\n14279\n14280\n14281\n14282\n14283\n14284\n14285\n14286\n14287\n14288\n14289\n14290\n14291\n14292\n14293\n14294\n14295\n14296\n14297\n14298\n14299\n14300\n14301\n14302\n14303\n14304\n14305\n14306\n14307\n14308\n14309\n14310\n14311\n14312\n14313\n14314\n14315\n14316\n14317\n14318\n14319\n14320\n14321\n14322\n14323\n14324\n14325\n14326\n14327\n14328\n14329\n14330\n14331\n14332\n14333\n14334\n14335\n14336\n14337\n14338\n14339\n14340\n14341\n14342\n14343\n14344\n14345\n14346\n14347\n14348\n14349\n14350\n14351\n14352\n14353\n14354\n14355\n14356\n14357\n14358\n14359\n14360\n14361\n14362\n14363\n14364\n14365\n14366\n14367\n14368\n14369\n14370\n14371\n14372\n14373\n14374\n14375\n14376\n14377\n14378\n14379\n14380\n14381\n14382\n14383\n14384\n14385\n14386\n14387\n14388\n14389\n14390\n14391\n14392\n14393\n14394\n14395\n14396\n14397\n14398\n14399\n14400\n14401\n14402\n14403\n14404\n14405\n14406\n14407\n14408\n14409\n14410\n14411\n14412\n14413\n14414\n14415\n14416\n14417\n14418\n14419\n14420\n14421\n14422\n14423\n14424\n14425\n14426\n14427\n14428\n14429\n14430\n14431\n14432\n14433\n14434\n14435\n14436\n14437\n14438\n14439\n14440\n14441\n14442\n14443\n14444\n14445\n14446\n14447\n14448\n14449\n14450\n14451\n14452\n14453\n14454\n14455\n14456\n14457\n14458\n14459\n14460\n14461\n14462\n14463\n14464\n14465\n14466\n14467\n14468\n14469\n14470\n14471\n14472\n14473\n14474\n14475\n14476\n14477\n14478\n14479\n14480\n14481\n14482\n14483\n14484\n14485\n14486\n14487\n14488\n14489\n14490\n14491\n14492\n14493\n14494\n14495\n14496\n14497\n14498\n14499\n14500\n14501\n14502\n14503\n14504\n14505\n14506\n14507\n14508\n14509\n14510\n14511\n14512\n14513\n14514\n14515\n14516\n14517\n14518\n14519\n14520\n14521\n14522\n14523\n14524\n14525\n14526\n14527\n14528\n14529\n14530\n14531\n14532\n14533\n14534\n14535\n14536\n14537\n14538\n14539\n14540\n14541\n14542\n14543\n14544\n14545\n14546\n14547\n14548\n14549\n14550\n14551\n14552\n14553\n14554\n14555\n14556\n14557\n14558\n14559\n14560\n14561\n14562\n14563\n14564\n14565\n14566\n14567\n14568\n14569\n14570\n14571\n14572\n14573\n14574\n14575\n14576\n14577\n14578\n14579\n14580\n14581\n14582\n14583\n14584\n14585\n14586\n14587\n14588\n14589\n14590\n14591\n14592\n14593\n14594\n14595\n14596\n14597\n14598\n14599\n14600\n14601\n14602\n14603\n14604\n14605\n14606\n14607\n14608\n14609\n14610\n14611\n14612\n14613\n14614\n14615\n14616\n14617\n14618\n14619\n14620\n14621\n14622\n14623\n14624\n14625\n14626\n14627\n14628\n14629\n14630\n14631\n14632\n14633\n14634\n14635\n14636\n14637\n14638\n14639\n14640\n14641\n14642\n14643\n14644\n14645\n14646\n14647\n14648\n14649\n14650\n14651\n14652\n14653\n14654\n14655\n14656\n14657\n14658\n14659\n14660\n14661\n14662\n14663\n14664\n14665\n14666\n14667\n14668\n14669\n14670\n14671\n14672\n14673\n14674\n14675\n14676\n14677\n14678\n14679\n14680\n14681\n14682\n14683\n14684\n14685\n14686\n14687\n14688\n14689\n14690\n14691\n14692\n14693\n14694\n14695\n14696\n14697\n14698\n14699\n14700\n14701\n14702\n14703\n14704\n14705\n14706\n14707\n14708\n14709\n14710\n14711\n14712\n14713\n14714\n14715\n14716\n14717\n14718\n14719\n14720\n14721\n14722\n14723\n14724\n14725\n14726\n14727\n14728\n14729\n14730\n14731\n14732\n14733\n14734\n14735\n14736\n14737\n14738\n14739\n14740\n14741\n14742\n14743\n14744\n14745\n14746\n14747\n14748\n14749\n14750\n14751\n14752\n14753\n14754\n14755\n14756\n14757\n14758\n14759\n14760\n14761\n14762\n14763\n14764\n14765\n14766\n14767\n14768\n14769\n14770\n14771\n14772\n14773\n14774\n14775\n14776\n14777\n14778\n14779\n14780\n14781\n14782\n14783\n14784\n14785\n14786\n14787\n14788\n14789\n14790\n14791\n14792\n14793\n14794\n14795\n14796\n14797\n14798\n14799\n14800\n14801\n14802\n14803\n14804\n14805\n14806\n14807\n14808\n14809\n14810\n14811\n14812\n14813\n14814\n14815\n14816\n14817\n14818\n14819\n14820\n14821\n14822\n14823\n14824\n14825\n14826\n14827\n14828\n14829\n14830\n14831\n14832\n14833\n14834\n14835\n14836\n14837\n14838\n14839\n14840\n14841\n14842\n14843\n14844\n14845\n14846\n14847\n14848\n14849\n14850\n14851\n14852\n14853\n14854\n14855\n14856\n14857\n14858\n14859\n14860\n14861\n14862\n14863\n14864\n14865\n14866\n14867\n14868\n14869\n14870\n14871\n14872\n14873\n14874\n14875\n14876\n14877\n14878\n14879\n14880\n14881\n14882\n14883\n14884\n14885\n14886\n14887\n14888\n14889\n14890\n14891\n14892\n14893\n14894\n14895\n14896\n14897\n14898\n14899\n14900\n14901\n14902\n14903\n14904\n14905\n14906\n14907\n14908\n14909\n14910\n14911\n14912\n14913\n14914\n14915\n14916\n14917\n14918\n14919\n14920\n14921\n14922\n14923\n14924\n14925\n14926\n14927\n14928\n14929\n14930\n14931\n14932\n14933\n14934\n14935\n14936\n14937\n14938\n14939\n14940\n14941\n14942\n14943\n14944\n14945\n14946\n14947\n14948\n14949\n14950\n14951\n14952\n14953\n14954\n14955\n14956\n14957\n14958\n14959\n14960\n14961\n14962\n14963\n14964\n14965\n14966\n14967\n14968\n14969\n14970\n14971\n14972\n14973\n14974\n14975\n14976\n14977\n14978\n14979\n14980\n14981\n14982\n14983\n14984\n14985\n14986\n14987\n14988\n14989\n14990\n14991\n14992\n14993\n14994\n14995\n14996\n14997\n14998\n14999\n15000\n15001\n15002\n15003\n15004\n15005\n15006\n15007\n15008\n15009\n15010\n15011\n15012\n15013\n15014\n15015\n15016\n15017\n15018\n15019\n15020\n15021\n15022\n15023\n15024\n15025\n15026\n15027\n15028\n15029\n15030\n15031\n15032\n15033\n15034\n15035\n15036\n15037\n15038\n15039\n15040\n15041\n15042\n15043\n15044\n15045\n15046\n15047\n15048\n15049\n15050\n15051\n15052\n15053\n15054\n15055\n15056\n15057\n15058\n15059\n15060\n15061\n15062\n15063\n15064\n15065\n15066\n15067\n15068\n15069\n15070\n15071\n15072\n15073\n15074\n15075\n15076\n15077\n15078\n15079\n15080\n15081\n15082\n15083\n15084\n15085\n15086\n15087\n15088\n15089\n15090\n15091\n15092\n15093\n15094\n15095\n15096\n15097\n15098\n15099\n15100\n15101\n15102\n15103\n15104\n15105\n15106\n15107\n15108\n15109\n15110\n15111\n15112\n15113\n15114\n15115\n15116\n15117\n15118\n15119\n15120\n15121\n15122\n15123\n15124\n15125\n15126\n15127\n15128\n15129\n15130\n15131\n15132\n15133\n15134\n15135\n15136\n15137\n15138\n15139\n15140\n15141\n15142\n15143\n15144\n15145\n15146\n15147\n15148\n15149\n15150\n15151\n15152\n15153\n15154\n15155\n15156\n15157\n15158\n15159\n15160\n15161\n15162\n15163\n15164\n15165\n15166\n15167\n15168\n15169\n15170\n15171\n15172\n15173\n15174\n15175\n15176\n15177\n15178\n15179\n15180\n15181\n15182\n15183\n15184\n15185\n15186\n15187\n15188\n15189\n15190\n15191\n15192\n15193\n15194\n15195\n15196\n15197\n15198\n15199\n15200\n15201\n15202\n15203\n15204\n15205\n15206\n15207\n15208\n15209\n15210\n15211\n15212\n15213\n15214\n15215\n15216\n15217\n15218\n15219\n15220\n15221\n15222\n15223\n15224\n15225\n15226\n15227\n15228\n15229\n15230\n15231\n15232\n15233\n15234\n15235\n15236\n15237\n15238\n15239\n15240\n15241\n15242\n15243\n15244\n15245\n15246\n15247\n15248\n15249\n15250\n15251\n15252\n15253\n15254\n15255\n15256\n15257\n15258\n15259\n15260\n15261\n15262\n15263\n15264\n15265\n15266\n15267\n15268\n15269\n15270\n15271\n15272\n15273\n15274\n15275\n15276\n15277\n15278\n15279\n15280\n15281\n15282\n15283\n15284\n15285\n15286\n15287\n15288\n15289\n15290\n15291\n15292\n15293\n15294\n15295\n15296\n15297\n15298\n15299\n15300\n15301\n15302\n15303\n15304\n15305\n15306\n15307\n15308\n15309\n15310\n15311\n15312\n15313\n15314\n15315\n15316\n15317\n15318\n15319\n15320\n15321\n15322\n15323\n15324\n15325\n15326\n15327\n15328\n15329\n15330\n15331\n15332\n15333\n15334\n15335\n15336\n15337\n15338\n15339\n15340\n15341\n15342\n15343\n15344\n15345\n15346\n15347\n15348\n15349\n15350\n15351\n15352\n15353\n15354\n15355\n15356\n15357\n15358\n15359\n15360\n15361\n15362\n15363\n15364\n15365\n15366\n15367\n15368\n15369\n15370\n15371\n15372\n15373\n15374\n15375\n15376\n15377\n15378\n15379\n15380\n15381\n15382\n15383\n15384\n15385\n15386\n15387\n15388\n15389\n15390\n15391\n15392\n15393\n15394\n15395\n15396\n15397\n15398\n15399\n15400\n15401\n15402\n15403\n15404\n15405\n15406\n15407\n15408\n15409\n15410\n15411\n15412\n15413\n15414\n15415\n15416\n15417\n15418\n15419\n15420\n15421\n15422\n15423\n15424\n15425\n15426\n15427\n15428\n15429\n15430\n15431\n15432\n15433\n15434\n15435\n15436\n15437\n15438\n15439\n15440\n15441\n15442\n15443\n15444\n15445\n15446\n15447\n15448\n15449\n15450\n15451\n15452\n15453\n15454\n15455\n15456\n15457\n15458\n15459\n15460\n15461\n15462\n15463\n15464\n15465\n15466\n15467\n15468\n15469\n15470\n15471\n15472\n15473\n15474\n15475\n15476\n15477\n15478\n15479\n15480\n15481\n15482\n15483\n15484\n15485\n15486\n15487\n15488\n15489\n15490\n15491\n15492\n15493\n15494\n15495\n15496\n15497\n15498\n15499\n15500\n15501\n15502\n15503\n15504\n15505\n15506\n15507\n15508\n15509\n15510\n15511\n15512\n15513\n15514\n15515\n15516\n15517\n15518\n15519\n15520\n15521\n15522\n15523\n15524\n15525\n15526\n15527\n15528\n15529\n15530\n15531\n15532\n15533\n15534\n15535\n15536\n15537\n15538\n15539\n15540\n15541\n15542\n15543\n15544\n15545\n15546\n15547\n15548\n15549\n15550\n15551\n15552\n15553\n15554\n15555\n15556\n15557\n15558\n15559\n15560\n15561\n15562\n15563\n15564\n15565\n15566\n15567\n15568\n15569\n15570\n15571\n15572\n15573\n15574\n15575\n15576\n15577\n15578\n15579\n15580\n15581\n15582\n15583\n15584\n15585\n15586\n15587\n15588\n15589\n15590\n15591\n15592\n15593\n15594\n15595\n15596\n15597\n15598\n15599\n15600\n15601\n15602\n15603\n15604\n15605\n15606\n15607\n15608\n15609\n15610\n15611\n15612\n15613\n15614\n15615\n15616\n15617\n15618\n15619\n15620\n15621\n15622\n15623\n15624\n15625\n15626\n15627\n15628\n15629\n15630\n15631\n15632\n15633\n15634\n15635\n15636\n15637\n15638\n15639\n15640\n15641\n15642\n15643\n15644\n15645\n15646\n15647\n15648\n15649\n15650\n15651\n15652\n15653\n15654\n15655\n15656\n15657\n15658\n15659\n15660\n15661\n15662\n15663\n15664\n15665\n15666\n15667\n15668\n15669\n15670\n15671\n15672\n15673\n15674\n15675\n15676\n15677\n15678\n15679\n15680\n15681\n15682\n15683\n15684\n15685\n15686\n15687\n15688\n15689\n15690\n15691\n15692\n15693\n15694\n15695\n15696\n15697\n15698\n15699\n15700\n15701\n15702\n15703\n15704\n15705\n15706\n15707\n15708\n15709\n15710\n15711\n15712\n15713\n15714\n15715\n15716\n15717\n15718\n15719\n15720\n15721\n15722\n15723\n15724\n15725\n15726\n15727\n15728\n15729\n15730\n15731\n15732\n15733\n15734\n15735\n15736\n15737\n15738\n15739\n15740\n15741\n15742\n15743\n15744\n15745\n15746\n15747\n15748\n15749\n15750\n15751\n15752\n15753\n15754\n15755\n15756\n15757\n15758\n15759\n15760\n15761\n15762\n15763\n15764\n15765\n15766\n15767\n15768\n15769\n15770\n15771\n15772\n15773\n15774\n15775\n15776\n15777\n15778\n15779\n15780\n15781\n15782\n15783\n15784\n15785\n15786\n15787\n15788\n15789\n15790\n15791\n15792\n15793\n15794\n15795\n15796\n15797\n15798\n15799\n15800\n15801\n15802\n15803\n15804\n15805\n15806\n15807\n15808\n15809\n15810\n15811\n15812\n15813\n15814\n15815\n15816\n15817\n15818\n15819\n15820\n15821\n15822\n15823\n15824\n15825\n15826\n15827\n15828\n15829\n15830\n15831\n15832\n15833\n15834\n15835\n15836\n15837\n15838\n15839\n15840\n15841\n15842\n15843\n15844\n15845\n15846\n15847\n15848\n15849\n15850\n15851\n15852\n15853\n15854\n15855\n15856\n15857\n15858\n15859\n15860\n15861\n15862\n15863\n15864\n15865\n15866\n15867\n15868\n15869\n15870\n15871\n15872\n15873\n15874\n15875\n15876\n15877\n15878\n15879\n15880\n15881\n15882\n15883\n15884\n15885\n15886\n15887\n15888\n15889\n15890\n15891\n15892\n15893\n15894\n15895\n15896\n15897\n15898\n15899\n15900\n15901\n15902\n15903\n15904\n15905\n15906\n15907\n15908\n15909\n15910\n15911\n15912\n15913\n15914\n15915\n15916\n15917\n15918\n15919\n15920\n15921\n15922\n15923\n15924\n15925\n15926\n15927\n15928\n15929\n15930\n15931\n15932\n15933\n15934\n15935\n15936\n15937\n15938\n15939\n15940\n15941\n15942\n15943\n15944\n15945\n15946\n15947\n15948\n15949\n15950\n15951\n15952\n15953\n15954\n15955\n15956\n15957\n15958\n15959\n15960\n15961\n15962\n15963\n15964\n15965\n15966\n15967\n15968\n15969\n15970\n15971\n15972\n15973\n15974\n15975\n15976\n15977\n15978\n15979\n15980\n15981\n15982\n15983\n15984\n15985\n15986\n15987\n15988\n15989\n15990\n15991\n15992\n15993\n15994\n15995\n15996\n15997\n15998\n15999\n16000\n16001\n16002\n16003\n16004\n16005\n16006\n16007\n16008\n16009\n16010\n16011\n16012\n16013\n16014\n16015\n16016\n16017\n16018\n16019\n16020\n16021\n16022\n16023\n16024\n16025\n16026\n16027\n16028\n16029\n16030\n16031\n16032\n16033\n16034\n16035\n16036\n16037\n16038\n16039\n16040\n16041\n16042\n16043\n16044\n16045\n16046\n16047\n16048\n16049\n16050\n16051\n16052\n16053\n16054\n16055\n16056\n16057\n16058\n16059\n16060\n16061\n16062\n16063\n16064\n16065\n16066\n16067\n16068\n16069\n16070\n16071\n16072\n16073\n16074\n16075\n16076\n16077\n16078\n16079\n16080\n16081\n16082\n16083\n16084\n16085\n16086\n16087\n16088\n16089\n16090\n16091\n16092\n16093\n16094\n16095\n16096\n16097\n16098\n16099\n16100\n16101\n16102\n16103\n16104\n16105\n16106\n16107\n16108\n16109\n16110\n16111\n16112\n16113\n16114\n16115\n16116\n16117\n16118\n16119\n16120\n16121\n16122\n16123\n16124\n16125\n16126\n16127\n16128\n16129\n16130\n16131\n16132\n16133\n16134\n16135\n16136\n16137\n16138\n16139\n16140\n16141\n16142\n16143\n16144\n16145\n16146\n16147\n16148\n16149\n16150\n16151\n16152\n16153\n16154\n16155\n16156\n16157\n16158\n16159\n16160\n16161\n16162\n16163\n16164\n16165\n16166\n16167\n16168\n16169\n16170\n16171\n16172\n16173\n16174\n16175\n16176\n16177\n16178\n16179\n16180\n16181\n16182\n16183\n16184\n16185\n16186\n16187\n16188\n16189\n16190\n16191\n16192\n16193\n16194\n16195\n16196\n16197\n16198\n16199\n16200\n16201\n16202\n16203\n16204\n16205\n16206\n16207\n16208\n16209\n16210\n16211\n16212\n16213\n16214\n16215\n16216\n16217\n16218\n16219\n16220\n16221\n16222\n16223\n16224\n16225\n16226\n16227\n16228\n16229\n16230\n16231\n16232\n16233\n16234\n16235\n16236\n16237\n16238\n16239\n16240\n16241\n16242\n16243\n16244\n16245\n16246\n16247\n16248\n16249\n16250\n16251\n16252\n16253\n16254\n16255\n16256\n16257\n16258\n16259\n16260\n16261\n16262\n16263\n16264\n16265\n16266\n16267\n16268\n16269\n16270\n16271\n16272\n16273\n16274\n16275\n16276\n16277\n16278\n16279\n16280\n16281\n16282\n16283\n16284\n16285\n16286\n16287\n16288\n16289\n16290\n16291\n16292\n16293\n16294\n16295\n16296\n16297\n16298\n16299\n16300\n16301\n16302\n16303\n16304\n16305\n16306\n16307\n16308\n16309\n16310\n16311\n16312\n16313\n16314\n16315\n16316\n16317\n16318\n16319\n16320\n16321\n16322\n16323\n16324\n16325\n16326\n16327\n16328\n16329\n16330\n16331\n16332\n16333\n16334\n16335\n16336\n16337\n16338\n16339\n16340\n16341\n16342\n16343\n16344\n16345\n16346\n16347\n16348\n16349\n16350\n16351\n16352\n16353\n16354\n16355\n16356\n16357\n16358\n16359\n16360\n16361\n16362\n16363\n16364\n16365\n16366\n16367\n16368\n16369\n16370\n16371\n16372\n16373\n16374\n16375\n16376\n16377\n16378\n16379\n16380\n16381\n16382\n16383\n16384\n16385\n16386\n16387\n16388\n16389\n16390\n16391\n16392\n16393\n16394\n16395\n16396\n16397\n16398\n16399\n16400\n16401\n16402\n16403\n16404\n16405\n16406\n16407\n16408\n16409\n16410\n16411\n16412\n16413\n16414\n16415\n16416\n16417\n16418\n16419\n16420\n16421\n16422\n16423\n16424\n16425\n16426\n16427\n16428\n16429\n16430\n16431\n16432\n16433\n16434\n16435\n16436\n16437\n16438\n16439\n16440\n16441\n16442\n16443\n16444\n16445\n16446\n16447\n16448\n16449\n16450\n16451\n16452\n16453\n16454\n16455\n16456\n16457\n16458\n16459\n16460\n16461\n16462\n16463\n16464\n16465\n16466\n16467\n16468\n16469\n16470\n16471\n16472\n16473\n16474\n16475\n16476\n16477\n16478\n16479\n16480\n16481\n16482\n16483\n16484\n16485\n16486\n16487\n16488\n16489\n16490\n16491\n16492\n16493\n16494\n16495\n16496\n16497\n16498\n16499\n16500\n16501\n16502\n16503\n16504\n16505\n16506\n16507\n16508\n16509\n16510\n16511\n16512\n16513\n16514\n16515\n16516\n16517\n16518\n16519\n16520\n16521\n16522\n16523\n16524\n16525\n16526\n16527\n16528\n16529\n16530\n16531\n16532\n16533\n16534\n16535\n16536\n16537\n16538\n16539\n16540\n16541\n16542\n16543\n16544\n16545\n16546\n16547\n16548\n16549\n16550\n16551\n16552\n16553\n16554\n16555\n16556\n16557\n16558\n16559\n16560\n16561\n16562\n16563\n16564\n16565\n16566\n16567\n16568\n16569\n16570\n16571\n16572\n16573\n16574\n16575\n16576\n16577\n16578\n16579\n16580\n16581\n16582\n16583\n16584\n16585\n16586\n16587\n16588\n16589\n16590\n16591\n16592\n16593\n16594\n16595\n16596\n16597\n16598\n16599\n16600\n16601\n16602\n16603\n16604\n16605\n16606\n16607\n16608\n16609\n16610\n16611\n16612\n16613\n16614\n16615\n16616\n16617\n16618\n16619\n16620\n16621\n16622\n16623\n16624\n16625\n16626\n16627\n16628\n16629\n16630\n16631\n16632\n16633\n16634\n16635\n16636\n16637\n16638\n16639\n16640\n16641\n16642\n16643\n16644\n16645\n16646\n16647\n16648\n16649\n16650\n16651\n16652\n16653\n16654\n16655\n16656\n16657\n16658\n16659\n16660\n16661\n16662\n16663\n16664\n16665\n16666\n16667\n16668\n16669\n16670\n16671\n16672\n16673\n16674\n16675\n16676\n16677\n16678\n16679\n16680\n16681\n16682\n16683\n16684\n16685\n16686\n16687\n16688\n16689\n16690\n16691\n16692\n16693\n16694\n16695\n16696\n16697\n16698\n16699\n16700\n16701\n16702\n16703\n16704\n16705\n16706\n16707\n16708\n16709\n16710\n16711\n16712\n16713\n16714\n16715\n16716\n16717\n16718\n16719\n16720\n16721\n16722\n16723\n16724\n16725\n16726\n16727\n16728\n16729\n16730\n16731\n16732\n16733\n16734\n16735\n16736\n16737\n16738\n16739\n16740\n16741\n16742\n16743\n16744\n16745\n16746\n16747\n16748\n16749\n16750\n16751\n16752\n16753\n16754\n16755\n16756\n16757\n16758\n16759\n16760\n16761\n16762\n16763\n16764\n16765\n16766\n16767\n16768\n16769\n16770\n16771\n16772\n16773\n16774\n16775\n16776\n16777\n16778\n16779\n16780\n16781\n16782\n16783\n16784\n16785\n16786\n16787\n16788\n16789\n16790\n16791\n16792\n16793\n16794\n16795\n16796\n16797\n16798\n16799\n16800\n16801\n16802\n16803\n16804\n16805\n16806\n16807\n16808\n16809\n16810\n16811\n16812\n16813\n16814\n16815\n16816\n16817\n16818\n16819\n16820\n16821\n16822\n16823\n16824\n16825\n16826\n16827\n16828\n16829\n16830\n16831\n16832\n16833\n16834\n16835\n16836\n16837\n16838\n16839\n16840\n16841\n16842\n16843\n16844\n16845\n16846\n16847\n16848\n16849\n16850\n16851\n16852\n16853\n16854\n16855\n16856\n16857\n16858\n16859\n16860\n16861\n16862\n16863\n16864\n16865\n16866\n16867\n16868\n16869\n16870\n16871\n16872\n16873\n16874\n16875\n16876\n16877\n16878\n16879\n16880\n16881\n16882\n16883\n16884\n16885\n16886\n16887\n16888\n16889\n16890\n16891\n16892\n16893\n16894\n16895\n16896\n16897\n16898\n16899\n16900\n16901\n16902\n16903\n16904\n16905\n16906\n16907\n16908\n16909\n16910\n16911\n16912\n16913\n16914\n16915\n16916\n16917\n16918\n16919\n16920\n16921\n16922\n16923\n16924\n16925\n16926\n16927\n16928\n16929\n16930\n16931\n16932\n16933\n16934\n16935\n16936\n16937\n16938\n16939\n16940\n16941\n16942\n16943\n16944\n16945\n16946\n16947\n16948\n16949\n16950\n16951\n16952\n16953\n16954\n16955\n16956\n16957\n16958\n16959\n16960\n16961\n16962\n16963\n16964\n16965\n16966\n16967\n16968\n16969\n16970\n16971\n16972\n16973\n16974\n16975\n16976\n16977\n16978\n16979\n16980\n16981\n16982\n16983\n16984\n16985\n16986\n16987\n16988\n16989\n16990\n16991\n16992\n16993\n16994\n16995\n16996\n16997\n16998\n16999\n17000\n17001\n17002\n17003\n17004\n17005\n17006\n17007\n17008\n17009\n17010\n17011\n17012\n17013\n17014\n17015\n17016\n17017\n17018\n17019\n17020\n17021\n17022\n17023\n17024\n17025\n17026\n17027\n17028\n17029\n17030\n17031\n17032\n17033\n17034\n17035\n17036\n17037\n17038\n17039\n17040\n17041\n17042\n17043\n17044\n17045\n17046\n17047\n17048\n17049\n17050\n17051\n17052\n17053\n17054\n17055\n17056\n17057\n17058\n17059\n17060\n17061\n17062\n17063\n17064\n17065\n17066\n17067\n17068\n17069\n17070\n17071\n17072\n17073\n17074\n17075\n17076\n17077\n17078\n17079\n17080\n17081\n17082\n17083\n17084\n17085\n17086\n17087\n17088\n17089\n17090\n17091\n17092\n17093\n17094\n17095\n17096\n17097\n17098\n17099\n17100\n17101\n17102\n17103\n17104\n17105\n17106\n17107\n17108\n17109\n17110\n17111\n17112\n17113\n17114\n17115\n17116\n17117\n17118\n17119\n17120\n17121\n17122\n17123\n17124\n17125\n17126\n17127\n17128\n17129\n17130\n17131\n17132\n17133\n17134\n17135\n17136\n17137\n17138\n17139\n17140\n17141\n17142\n17143\n17144\n17145\n17146\n17147\n17148\n17149\n17150\n17151\n17152\n17153\n17154\n17155\n17156\n17157\n17158\n17159\n17160\n17161\n17162\n17163\n17164\n17165\n17166\n17167\n17168\n17169\n17170\n17171\n17172\n17173\n17174\n17175\n17176\n17177\n17178\n17179\n17180\n17181\n17182\n17183\n17184\n17185\n17186\n17187\n17188\n17189\n17190\n17191\n17192\n17193\n17194\n17195\n17196\n17197\n17198\n17199\n17200\n17201\n17202\n17203\n17204\n17205\n17206\n17207\n17208\n17209\n17210\n17211\n17212\n17213\n17214\n17215\n17216\n17217\n17218\n17219\n17220\n17221\n17222\n17223\n17224\n17225\n17226\n17227\n17228\n17229\n17230\n17231\n17232\n17233\n17234\n17235\n17236\n17237\n17238\n17239\n17240\n17241\n17242\n17243\n17244\n17245\n17246\n17247\n17248\n17249\n17250\n17251\n17252\n17253\n17254\n17255\n17256\n17257\n17258\n17259\n17260\n17261\n17262\n17263\n17264\n17265\n17266\n17267\n17268\n17269\n17270\n17271\n17272\n17273\n17274\n17275\n17276\n17277\n17278\n17279\n17280\n17281\n17282\n17283\n17284\n17285\n17286\n17287\n17288\n17289\n17290\n17291\n17292\n17293\n17294\n17295\n17296\n17297\n17298\n17299\n17300\n17301\n17302\n17303\n17304\n17305\n17306\n17307\n17308\n17309\n17310\n17311\n17312\n17313\n17314\n17315\n17316\n17317\n17318\n17319\n17320\n17321\n17322\n17323\n17324\n17325\n17326\n17327\n17328\n17329\n17330\n17331\n17332\n17333\n17334\n17335\n17336\n17337\n17338\n17339\n17340\n17341\n17342\n17343\n17344\n17345\n17346\n17347\n17348\n17349\n17350\n17351\n17352\n17353\n17354\n17355\n17356\n17357\n17358\n17359\n17360\n17361\n17362\n17363\n17364\n17365\n17366\n17367\n17368\n17369\n17370\n17371\n17372\n17373\n17374\n17375\n17376\n17377\n17378\n17379\n17380\n17381\n17382\n17383\n17384\n17385\n17386\n17387\n17388\n17389\n17390\n17391\n17392\n17393\n17394\n17395\n17396\n17397\n17398\n17399\n17400\n17401\n17402\n17403\n17404\n17405\n17406\n17407\n17408\n17409\n17410\n17411\n17412\n17413\n17414\n17415\n17416\n17417\n17418\n17419\n17420\n17421\n17422\n17423\n17424\n17425\n17426\n17427\n17428\n17429\n17430\n17431\n17432\n17433\n17434\n17435\n17436\n17437\n17438\n17439\n17440\n17441\n17442\n17443\n17444\n17445\n17446\n17447\n17448\n17449\n17450\n17451\n17452\n17453\n17454\n17455\n17456\n17457\n17458\n17459\n17460\n17461\n17462\n17463\n17464\n17465\n17466\n17467\n17468\n17469\n17470\n17471\n17472\n17473\n17474\n17475\n17476\n17477\n17478\n17479\n17480\n17481\n17482\n17483\n17484\n17485\n17486\n17487\n17488\n17489\n17490\n17491\n17492\n17493\n17494\n17495\n17496\n17497\n17498\n17499\n17500\n17501\n17502\n17503\n17504\n17505\n17506\n17507\n17508\n17509\n17510\n17511\n17512\n17513\n17514\n17515\n17516\n17517\n17518\n17519\n17520\n17521\n17522\n17523\n17524\n17525\n17526\n17527\n17528\n17529\n17530\n17531\n17532\n17533\n17534\n17535\n17536\n17537\n17538\n17539\n17540\n17541\n17542\n17543\n17544\n17545\n17546\n17547\n17548\n17549\n17550\n17551\n17552\n17553\n17554\n17555\n17556\n17557\n17558\n17559\n17560\n17561\n17562\n17563\n17564\n17565\n17566\n17567\n17568\n17569\n17570\n17571\n17572\n17573\n17574\n17575\n17576\n17577\n17578\n17579\n17580\n17581\n17582\n17583\n17584\n17585\n17586\n17587\n17588\n17589\n17590\n17591\n17592\n17593\n17594\n17595\n17596\n17597\n17598\n17599\n17600\n17601\n17602\n17603\n17604\n17605\n17606\n17607\n17608\n17609\n17610\n17611\n17612\n17613\n17614\n17615\n17616\n17617\n17618\n17619\n17620\n17621\n17622\n17623\n17624\n17625\n17626\n17627\n17628\n17629\n17630\n17631\n17632\n17633\n17634\n17635\n17636\n17637\n17638\n17639\n17640\n17641\n17642\n17643\n17644\n17645\n17646\n17647\n17648\n17649\n17650\n17651\n17652\n17653\n17654\n17655\n17656\n17657\n17658\n17659\n17660\n17661\n17662\n17663\n17664\n17665\n17666\n17667\n17668\n17669\n17670\n17671\n17672\n17673\n17674\n17675\n17676\n17677\n17678\n17679\n17680\n17681\n17682\n17683\n17684\n17685\n17686\n17687\n17688\n17689\n17690\n17691\n17692\n17693\n17694\n17695\n17696\n17697\n17698\n17699\n17700\n17701\n17702\n17703\n17704\n17705\n17706\n17707\n17708\n17709\n17710\n17711\n17712\n17713\n17714\n17715\n17716\n17717\n17718\n17719\n17720\n17721\n17722\n17723\n17724\n17725\n17726\n17727\n17728\n17729\n17730\n17731\n17732\n17733\n17734\n17735\n17736\n17737\n17738\n17739\n17740\n17741\n17742\n17743\n17744\n17745\n17746\n17747\n17748\n17749\n17750\n17751\n17752\n17753\n17754\n17755\n17756\n17757\n17758\n17759\n17760\n17761\n17762\n17763\n17764\n17765\n17766\n17767\n17768\n17769\n17770\n17771\n17772\n17773\n17774\n17775\n17776\n17777\n17778\n17779\n17780\n17781\n17782\n17783\n17784\n17785\n17786\n17787\n17788\n17789\n17790\n17791\n17792\n17793\n17794\n17795\n17796\n17797\n17798\n17799\n17800\n17801\n17802\n17803\n17804\n17805\n17806\n17807\n17808\n17809\n17810\n17811\n17812\n17813\n17814\n17815\n17816\n17817\n17818\n17819\n17820\n17821\n17822\n17823\n17824\n17825\n17826\n17827\n17828\n17829\n17830\n17831\n17832\n17833\n17834\n17835\n17836\n17837\n17838\n17839\n17840\n17841\n17842\n17843\n17844\n17845\n17846\n17847\n17848\n17849\n17850\n17851\n17852\n17853\n17854\n17855\n17856\n17857\n17858\n17859\n17860\n17861\n17862\n17863\n17864\n17865\n17866\n17867\n17868\n17869\n17870\n17871\n17872\n17873\n17874\n17875\n17876\n17877\n17878\n17879\n17880\n17881\n17882\n17883\n17884\n17885\n17886\n17887\n17888\n17889\n17890\n17891\n17892\n17893\n17894\n17895\n17896\n17897\n17898\n17899\n17900\n17901\n17902\n17903\n17904\n17905\n17906\n17907\n17908\n17909\n17910\n17911\n17912\n17913\n17914\n17915\n17916\n17917\n17918\n17919\n17920\n17921\n17922\n17923\n17924\n17925\n17926\n17927\n17928\n17929\n17930\n17931\n17932\n17933\n17934\n17935\n17936\n17937\n17938\n17939\n17940\n17941\n17942\n17943\n17944\n17945\n17946\n17947\n17948\n17949\n17950\n17951\n17952\n17953\n17954\n17955\n17956\n17957\n17958\n17959\n17960\n17961\n17962\n17963\n17964\n17965\n17966\n17967\n17968\n17969\n17970\n17971\n17972\n17973\n17974\n17975\n17976\n17977\n17978\n17979\n17980\n17981\n17982\n17983\n17984\n17985\n17986\n17987\n17988\n17989\n17990\n17991\n17992\n17993\n17994\n17995\n17996\n17997\n17998\n17999\n18000\n18001\n18002\n18003\n18004\n18005\n18006\n18007\n18008\n18009\n18010\n18011\n18012\n18013\n18014\n18015\n18016\n18017\n18018\n18019\n18020\n18021\n18022\n18023\n18024\n18025\n18026\n18027\n18028\n18029\n18030\n18031\n18032\n18033\n18034\n18035\n18036\n18037\n18038\n18039\n18040\n18041\n18042\n18043\n18044\n18045\n18046\n18047\n18048\n18049\n18050\n18051\n18052\n18053\n18054\n18055\n18056\n18057\n18058\n18059\n18060\n18061\n18062\n18063\n18064\n18065\n18066\n18067\n18068\n18069\n18070\n18071\n18072\n18073\n18074\n18075\n18076\n18077\n18078\n18079\n18080\n18081\n18082\n18083\n18084\n18085\n18086\n18087\n18088\n18089\n18090\n18091\n18092\n18093\n18094\n18095\n18096\n18097\n18098\n18099\n18100\n18101\n18102\n18103\n18104\n18105\n18106\n18107\n18108\n18109\n18110\n18111\n18112\n18113\n18114\n18115\n18116\n18117\n18118\n18119\n18120\n18121\n18122\n18123\n18124\n18125\n18126\n18127\n18128\n18129\n18130\n18131\n18132\n18133\n18134\n18135\n18136\n18137\n18138\n18139\n18140\n18141\n18142\n18143\n18144\n18145\n18146\n18147\n18148\n18149\n18150\n18151\n18152\n18153\n18154\n18155\n18156\n18157\n18158\n18159\n18160\n18161\n18162\n18163\n18164\n18165\n18166\n18167\n18168\n18169\n18170\n18171\n18172\n18173\n18174\n18175\n18176\n18177\n18178\n18179\n18180\n18181\n18182\n18183\n18184\n18185\n18186\n18187\n18188\n18189\n18190\n18191\n18192\n18193\n18194\n18195\n18196\n18197\n18198\n18199\n18200\n18201\n18202\n18203\n18204\n18205\n18206\n18207\n18208\n18209\n18210\n18211\n18212\n18213\n18214\n18215\n18216\n18217\n18218\n18219\n18220\n18221\n18222\n18223\n18224\n18225\n18226\n18227\n18228\n18229\n18230\n18231\n18232\n18233\n18234\n18235\n18236\n18237\n18238\n18239\n18240\n18241\n18242\n18243\n18244\n18245\n18246\n18247\n18248\n18249\n18250\n18251\n18252\n18253\n18254\n18255\n18256\n18257\n18258\n18259\n18260\n18261\n18262\n18263\n18264\n18265\n18266\n18267\n18268\n18269\n18270\n18271\n18272\n18273\n18274\n18275\n18276\n18277\n18278\n18279\n18280\n18281\n18282\n18283\n18284\n18285\n18286\n18287\n18288\n18289\n18290\n18291\n18292\n18293\n18294\n18295\n18296\n18297\n18298\n18299\n18300\n18301\n18302\n18303\n18304\n18305\n18306\n18307\n18308\n18309\n18310\n18311\n18312\n18313\n18314\n18315\n18316\n18317\n18318\n18319\n18320\n18321\n18322\n18323\n18324\n18325\n18326\n18327\n18328\n18329\n18330\n18331\n18332\n18333\n18334\n18335\n18336\n18337\n18338\n18339\n18340\n18341\n18342\n18343\n18344\n18345\n18346\n18347\n18348\n18349\n18350\n18351\n18352\n18353\n18354\n18355\n18356\n18357\n18358\n18359\n18360\n18361\n18362\n18363\n18364\n18365\n18366\n18367\n18368\n18369\n18370\n18371\n18372\n18373\n18374\n18375\n18376\n18377\n18378\n18379\n18380\n18381\n18382\n18383\n18384\n18385\n18386\n18387\n18388\n18389\n18390\n18391\n18392\n18393\n18394\n18395\n18396\n18397\n18398\n18399\n18400\n18401\n18402\n18403\n18404\n18405\n18406\n18407\n18408\n18409\n18410\n18411\n18412\n18413\n18414\n18415\n18416\n18417\n18418\n18419\n18420\n18421\n18422\n18423\n18424\n18425\n18426\n18427\n18428\n18429\n18430\n18431\n18432\n18433\n18434\n18435\n18436\n18437\n18438\n18439\n18440\n18441\n18442\n18443\n18444\n18445\n18446\n18447\n18448\n18449\n18450\n18451\n18452\n18453\n18454\n18455\n18456\n18457\n18458\n18459\n18460\n18461\n18462\n18463\n18464\n18465\n18466\n18467\n18468\n18469\n18470\n18471\n18472\n18473\n18474\n18475\n18476\n18477\n18478\n18479\n18480\n18481\n18482\n18483\n18484\n18485\n18486\n18487\n18488\n18489\n18490\n18491\n18492\n18493\n18494\n18495\n18496\n18497\n18498\n18499\n18500\n18501\n18502\n18503\n18504\n18505\n18506\n18507\n18508\n18509\n18510\n18511\n18512\n18513\n18514\n18515\n18516\n18517\n18518\n18519\n18520\n18521\n18522\n18523\n18524\n18525\n18526\n18527\n18528\n18529\n18530\n18531\n18532\n18533\n18534\n18535\n18536\n18537\n18538\n18539\n18540\n18541\n18542\n18543\n18544\n18545\n18546\n18547\n18548\n18549\n18550\n18551\n18552\n18553\n18554\n18555\n18556\n18557\n18558\n18559\n18560\n18561\n18562\n18563\n18564\n18565\n18566\n18567\n18568\n18569\n18570\n18571\n18572\n18573\n18574\n18575\n18576\n18577\n18578\n18579\n18580\n18581\n18582\n18583\n18584\n18585\n18586\n18587\n18588\n18589\n18590\n18591\n18592\n18593\n18594\n18595\n18596\n18597\n18598\n18599\n18600\n18601\n18602\n18603\n18604\n18605\n18606\n18607\n18608\n18609\n18610\n18611\n18612\n18613\n18614\n18615\n18616\n18617\n18618\n18619\n18620\n18621\n18622\n18623\n18624\n18625\n18626\n18627\n18628\n18629\n18630\n18631\n18632\n18633\n18634\n18635\n18636\n18637\n18638\n18639\n18640\n18641\n18642\n18643\n18644\n18645\n18646\n18647\n18648\n18649\n18650\n18651\n18652\n18653\n18654\n18655\n18656\n18657\n18658\n18659\n18660\n18661\n18662\n18663\n18664\n18665\n18666\n18667\n18668\n18669\n18670\n18671\n18672\n18673\n18674\n18675\n18676\n18677\n18678\n18679\n18680\n18681\n18682\n18683\n18684\n18685\n18686\n18687\n18688\n18689\n18690\n18691\n18692\n18693\n18694\n18695\n18696\n18697\n18698\n18699\n18700\n18701\n18702\n18703\n18704\n18705\n18706\n18707\n18708\n18709\n18710\n18711\n18712\n18713\n18714\n18715\n18716\n18717\n18718\n18719\n18720\n18721\n18722\n18723\n18724\n18725\n18726\n18727\n18728\n18729\n18730\n18731\n18732\n18733\n18734\n18735\n18736\n18737\n18738\n18739\n18740\n18741\n18742\n18743\n18744\n18745\n18746\n18747\n18748\n18749\n18750\n18751\n18752\n18753\n18754\n18755\n18756\n18757\n18758\n18759\n18760\n18761\n18762\n18763\n18764\n18765\n18766\n18767\n18768\n18769\n18770\n18771\n18772\n18773\n18774\n18775\n18776\n18777\n18778\n18779\n18780\n18781\n18782\n18783\n18784\n18785\n18786\n18787\n18788\n18789\n18790\n18791\n18792\n18793\n18794\n18795\n18796\n18797\n18798\n18799\n18800\n18801\n18802\n18803\n18804\n18805\n18806\n18807\n18808\n18809\n18810\n18811\n18812\n18813\n18814\n18815\n18816\n18817\n18818\n18819\n18820\n18821\n18822\n18823\n18824\n18825\n18826\n18827\n18828\n18829\n18830\n18831\n18832\n18833\n18834\n18835\n18836\n18837\n18838\n18839\n18840\n18841\n18842\n18843\n18844\n18845\n18846\n18847\n18848\n18849\n18850\n18851\n18852\n18853\n18854\n18855\n18856\n18857\n18858\n18859\n18860\n18861\n18862\n18863\n18864\n18865\n18866\n18867\n18868\n18869\n18870\n18871\n18872\n18873\n18874\n18875\n18876\n18877\n18878\n18879\n18880\n18881\n18882\n18883\n18884\n18885\n18886\n18887\n18888\n18889\n18890\n18891\n18892\n18893\n18894\n18895\n18896\n18897\n18898\n18899\n18900\n18901\n18902\n18903\n18904\n18905\n18906\n18907\n18908\n18909\n18910\n18911\n18912\n18913\n18914\n18915\n18916\n18917\n18918\n18919\n18920\n18921\n18922\n18923\n18924\n18925\n18926\n18927\n18928\n18929\n18930\n18931\n18932\n18933\n18934\n18935\n18936\n18937\n18938\n18939\n18940\n18941\n18942\n18943\n18944\n18945\n18946\n18947\n18948\n18949\n18950\n18951\n18952\n18953\n18954\n18955\n18956\n18957\n18958\n18959\n18960\n18961\n18962\n18963\n18964\n18965\n18966\n18967\n18968\n18969\n18970\n18971\n18972\n18973\n18974\n18975\n18976\n18977\n18978\n18979\n18980\n18981\n18982\n18983\n18984\n18985\n18986\n18987\n18988\n18989\n18990\n18991\n18992\n18993\n18994\n18995\n18996\n18997\n18998\n18999\n19000\n19001\n19002\n19003\n19004\n19005\n19006\n19007\n19008\n19009\n19010\n19011\n19012\n19013\n19014\n19015\n19016\n19017\n19018\n19019\n19020\n19021\n19022\n19023\n19024\n19025\n19026\n19027\n19028\n19029\n19030\n19031\n19032\n19033\n19034\n19035\n19036\n19037\n19038\n19039\n19040\n19041\n19042\n19043\n19044\n19045\n19046\n19047\n19048\n19049\n19050\n19051\n19052\n19053\n19054\n19055\n19056\n19057\n19058\n19059\n19060\n19061\n19062\n19063\n19064\n19065\n19066\n19067\n19068\n19069\n19070\n19071\n19072\n19073\n19074\n19075\n19076\n19077\n19078\n19079\n19080\n19081\n19082\n19083\n19084\n19085\n19086\n19087\n19088\n19089\n19090\n19091\n19092\n19093\n19094\n19095\n19096\n19097\n19098\n19099\n19100\n19101\n19102\n19103\n19104\n19105\n19106\n19107\n19108\n19109\n19110\n19111\n19112\n19113\n19114\n19115\n19116\n19117\n19118\n19119\n19120\n19121\n19122\n19123\n19124\n19125\n19126\n19127\n19128\n19129\n19130\n19131\n19132\n19133\n19134\n19135\n19136\n19137\n19138\n19139\n19140\n19141\n19142\n19143\n19144\n19145\n19146\n19147\n19148\n19149\n19150\n19151\n19152\n19153\n19154\n19155\n19156\n19157\n19158\n19159\n19160\n19161\n19162\n19163\n19164\n19165\n19166\n19167\n19168\n19169\n19170\n19171\n19172\n19173\n19174\n19175\n19176\n19177\n19178\n19179\n19180\n19181\n19182\n19183\n19184\n19185\n19186\n19187\n19188\n19189\n19190\n19191\n19192\n19193\n19194\n19195\n19196\n19197\n19198\n19199\n19200\n19201\n19202\n19203\n19204\n19205\n19206\n19207\n19208\n19209\n19210\n19211\n19212\n19213\n19214\n19215\n19216\n19217\n19218\n19219\n19220\n19221\n19222\n19223\n19224\n19225\n19226\n19227\n19228\n19229\n19230\n19231\n19232\n19233\n19234\n19235\n19236\n19237\n19238\n19239\n19240\n19241\n19242\n19243\n19244\n19245\n19246\n19247\n19248\n19249\n19250\n19251\n19252\n19253\n19254\n19255\n19256\n19257\n19258\n19259\n19260\n19261\n19262\n19263\n19264\n19265\n19266\n19267\n19268\n19269\n19270\n19271\n19272\n19273\n19274\n19275\n19276\n19277\n19278\n19279\n19280\n19281\n19282\n19283\n19284\n19285\n19286\n19287\n19288\n19289\n19290\n19291\n19292\n19293\n19294\n19295\n19296\n19297\n19298\n19299\n19300\n19301\n19302\n19303\n19304\n19305\n19306\n19307\n19308\n19309\n19310\n19311\n19312\n19313\n19314\n19315\n19316\n19317\n19318\n19319\n19320\n19321\n19322\n19323\n19324\n19325\n19326\n19327\n19328\n19329\n19330\n19331\n19332\n19333\n19334\n19335\n19336\n19337\n19338\n19339\n19340\n19341\n19342\n19343\n19344\n19345\n19346\n19347\n19348\n19349\n19350\n19351\n19352\n19353\n19354\n19355\n19356\n19357\n19358\n19359\n19360\n19361\n19362\n19363\n19364\n19365\n19366\n19367\n19368\n19369\n19370\n19371\n19372\n19373\n19374\n19375\n19376\n19377\n19378\n19379\n19380\n19381\n19382\n19383\n19384\n19385\n19386\n19387\n19388\n19389\n19390\n19391\n19392\n19393\n19394\n19395\n19396\n19397\n19398\n19399\n19400\n19401\n19402\n19403\n19404\n19405\n19406\n19407\n19408\n19409\n19410\n19411\n19412\n19413\n19414\n19415\n19416\n19417\n19418\n19419\n19420\n19421\n19422\n19423\n19424\n19425\n19426\n19427\n19428\n19429\n19430\n19431\n19432\n19433\n19434\n19435\n19436\n19437\n19438\n19439\n19440\n19441\n19442\n19443\n19444\n19445\n19446\n19447\n19448\n19449\n19450\n19451\n19452\n19453\n19454\n19455\n19456\n19457\n19458\n19459\n19460\n19461\n19462\n19463\n19464\n19465\n19466\n19467\n19468\n19469\n19470\n19471\n19472\n19473\n19474\n19475\n19476\n19477\n19478\n19479\n19480\n19481\n19482\n19483\n19484\n19485\n19486\n19487\n19488\n19489\n19490\n19491\n19492\n19493\n19494\n19495\n19496\n19497\n19498\n19499\n19500\n19501\n19502\n19503\n19504\n19505\n19506\n19507\n19508\n19509\n19510\n19511\n19512\n19513\n19514\n19515\n19516\n19517\n19518\n19519\n19520\n19521\n19522\n19523\n19524\n19525\n19526\n19527\n19528\n19529\n19530\n19531\n19532\n19533\n19534\n19535\n19536\n19537\n19538\n19539\n19540\n19541\n19542\n19543\n19544\n19545\n19546\n19547\n19548\n19549\n19550\n19551\n19552\n19553\n19554\n19555\n19556\n19557\n19558\n19559\n19560\n19561\n19562\n19563\n19564\n19565\n19566\n19567\n19568\n19569\n19570\n19571\n19572\n19573\n19574\n19575\n19576\n19577\n19578\n19579\n19580\n19581\n19582\n19583\n19584\n19585\n19586\n19587\n19588\n19589\n19590\n19591\n19592\n19593\n19594\n19595\n19596\n19597\n19598\n19599\n19600\n19601\n19602\n19603\n19604\n19605\n19606\n19607\n19608\n19609\n19610\n19611\n19612\n19613\n19614\n19615\n19616\n19617\n19618\n19619\n19620\n19621\n19622\n19623\n19624\n19625\n19626\n19627\n19628\n19629\n19630\n19631\n19632\n19633\n19634\n19635\n19636\n19637\n19638\n19639\n19640\n19641\n19642\n19643\n19644\n19645\n19646\n19647\n19648\n19649\n19650\n19651\n19652\n19653\n19654\n19655\n19656\n19657\n19658\n19659\n19660\n19661\n19662\n19663\n19664\n19665\n19666\n19667\n19668\n19669\n19670\n19671\n19672\n19673\n19674\n19675\n19676\n19677\n19678\n19679\n19680\n19681\n19682\n19683\n19684\n19685\n19686\n19687\n19688\n19689\n19690\n19691\n19692\n19693\n19694\n19695\n19696\n19697\n19698\n19699\n19700\n19701\n19702\n19703\n19704\n19705\n19706\n19707\n19708\n19709\n19710\n19711\n19712\n19713\n19714\n19715\n19716\n19717\n19718\n19719\n19720\n19721\n19722\n19723\n19724\n19725\n19726\n19727\n19728\n19729\n19730\n19731\n19732\n19733\n19734\n19735\n19736\n19737\n19738\n19739\n19740\n19741\n19742\n19743\n19744\n19745\n19746\n19747\n19748\n19749\n19750\n19751\n19752\n19753\n19754\n19755\n19756\n19757\n19758\n19759\n19760\n19761\n19762\n19763\n19764\n19765\n19766\n19767\n19768\n19769\n19770\n19771\n19772\n19773\n19774\n19775\n19776\n19777\n19778\n19779\n19780\n19781\n19782\n19783\n19784\n19785\n19786\n19787\n19788\n19789\n19790\n19791\n19792\n19793\n19794\n19795\n19796\n19797\n19798\n19799\n19800\n19801\n19802\n19803\n19804\n19805\n19806\n19807\n19808\n19809\n19810\n19811\n19812\n19813\n19814\n19815\n19816\n19817\n19818\n19819\n19820\n19821\n19822\n19823\n19824\n19825\n19826\n19827\n19828\n19829\n19830\n19831\n19832\n19833\n19834\n19835\n19836\n19837\n19838\n19839\n19840\n19841\n19842\n19843\n19844\n19845\n19846\n19847\n19848\n19849\n19850\n19851\n19852\n19853\n19854\n19855\n19856\n19857\n19858\n19859\n19860\n19861\n19862\n19863\n19864\n19865\n19866\n19867\n19868\n19869\n19870\n19871\n19872\n19873\n19874\n19875\n19876\n19877\n19878\n19879\n19880\n19881\n19882\n19883\n19884\n19885\n19886\n19887\n19888\n19889\n19890\n19891\n19892\n19893\n19894\n19895\n19896\n19897\n19898\n19899\n19900\n19901\n19902\n19903\n19904\n19905\n19906\n19907\n19908\n19909\n19910\n19911\n19912\n19913\n19914\n19915\n19916\n19917\n19918\n19919\n19920\n19921\n19922\n19923\n19924\n19925\n19926\n19927\n19928\n19929\n19930\n19931\n19932\n19933\n19934\n19935\n19936\n19937\n19938\n19939\n19940\n19941\n19942\n19943\n19944\n19945\n19946\n19947\n19948\n19949\n19950\n19951\n19952\n19953\n19954\n19955\n19956\n19957\n19958\n19959\n19960\n19961\n19962\n19963\n19964\n19965\n19966\n19967\n19968\n19969\n19970\n19971\n19972\n19973\n19974\n19975\n19976\n19977\n19978\n19979\n19980\n19981\n19982\n19983\n19984\n19985\n19986\n19987\n19988\n19989\n19990\n19991\n19992\n19993\n19994\n19995\n19996\n19997\n19998\n19999\n20000\n20001\n20002\n20003\n20004\n20005\n20006\n20007\n20008\n20009\n20010\n20011\n20012\n20013\n20014\n20015\n20016\n20017\n20018\n20019\n20020\n20021\n20022\n20023\n20024\n20025\n20026\n20027\n20028\n20029\n20030\n20031\n20032\n20033\n20034\n20035\n20036\n20037\n20038\n20039\n20040\n20041\n20042\n20043\n20044\n20045\n20046\n20047\n20048\n20049\n20050\n20051\n20052\n20053\n20054\n20055\n20056\n20057\n20058\n20059\n20060\n20061\n20062\n20063\n20064\n20065\n20066\n20067\n20068\n20069\n20070\n20071\n20072\n20073\n20074\n20075\n20076\n20077\n20078\n20079\n20080\n20081\n20082\n20083\n20084\n20085\n20086\n20087\n20088\n20089\n20090\n20091\n20092\n20093\n20094\n20095\n20096\n20097\n20098\n20099\n20100\n20101\n20102\n20103\n20104\n20105\n20106\n20107\n20108\n20109\n20110\n20111\n20112\n20113\n20114\n20115\n20116\n20117\n20118\n20119\n20120\n20121\n20122\n20123\n20124\n20125\n20126\n20127\n20128\n20129\n20130\n20131\n20132\n20133\n20134\n20135\n20136\n20137\n20138\n20139\n20140\n20141\n20142\n20143\n20144\n20145\n20146\n20147\n20148\n20149\n20150\n20151\n20152\n20153\n20154\n20155\n20156\n20157\n20158\n20159\n20160\n20161\n20162\n20163\n20164\n20165\n20166\n20167\n20168\n20169\n20170\n20171\n20172\n20173\n20174\n20175\n20176\n20177\n20178\n20179\n20180\n20181\n20182\n20183\n20184\n20185\n20186\n20187\n20188\n20189\n20190\n20191\n20192\n20193\n20194\n20195\n20196\n20197\n20198\n20199\n20200\n20201\n20202\n20203\n20204\n20205\n20206\n20207\n20208\n20209\n20210\n20211\n20212\n20213\n20214\n20215\n20216\n20217\n20218\n20219\n20220\n20221\n20222\n20223\n20224\n20225\n20226\n20227\n20228\n20229\n20230\n20231\n20232\n20233\n20234\n20235\n20236\n20237\n20238\n20239\n20240\n20241\n20242\n20243\n20244\n20245\n20246\n20247\n20248\n20249\n20250\n20251\n20252\n20253\n20254\n20255\n20256\n20257\n20258\n20259\n20260\n20261\n20262\n20263\n20264\n20265\n20266\n20267\n20268\n20269\n20270\n20271\n20272\n20273\n20274\n20275\n20276\n20277\n20278\n20279\n20280\n20281\n20282\n20283\n20284\n20285\n20286\n20287\n20288\n20289\n20290\n20291\n20292\n20293\n20294\n20295\n20296\n20297\n20298\n20299\n20300\n20301\n20302\n20303\n20304\n20305\n20306\n20307\n20308\n20309\n20310\n20311\n20312\n20313\n20314\n20315\n20316\n20317\n20318\n20319\n20320\n20321\n20322\n20323\n20324\n20325\n20326\n20327\n20328\n20329\n20330\n20331\n20332\n20333\n20334\n20335\n20336\n20337\n20338\n20339\n20340\n20341\n20342\n20343\n20344\n20345\n20346\n20347\n20348\n20349\n20350\n20351\n20352\n20353\n20354\n20355\n20356\n20357\n20358\n20359\n20360\n20361\n20362\n20363\n20364\n20365\n20366\n20367\n20368\n20369\n20370\n20371\n20372\n20373\n20374\n20375\n20376\n20377\n20378\n20379\n20380\n20381\n20382\n20383\n20384\n20385\n20386\n20387\n20388\n20389\n20390\n20391\n20392\n20393\n20394\n20395\n20396\n20397\n20398\n20399\n20400\n20401\n20402\n20403\n20404\n20405\n20406\n20407\n20408\n20409\n20410\n20411\n20412\n20413\n20414\n20415\n20416\n20417\n20418\n20419\n20420\n20421\n20422\n20423\n20424\n20425\n20426\n20427\n20428\n20429\n20430\n20431\n20432\n20433\n20434\n20435\n20436\n20437\n20438\n20439\n20440\n20441\n20442\n20443\n20444\n20445\n20446\n20447\n20448\n20449\n20450\n20451\n20452\n20453\n20454\n20455\n20456\n20457\n20458\n20459\n20460\n20461\n20462\n20463\n20464\n20465\n20466\n20467\n20468\n20469\n20470\n20471\n20472\n20473\n20474\n20475\n20476\n20477\n20478\n20479\n20480\n20481\n20482\n20483\n20484\n20485\n20486\n20487\n20488\n20489\n20490\n20491\n20492\n20493\n20494\n20495\n20496\n20497\n20498\n20499\n20500\n20501\n20502\n20503\n20504\n20505\n20506\n20507\n20508\n20509\n20510\n20511\n20512\n20513\n20514\n20515\n20516\n20517\n20518\n20519\n20520\n20521\n20522\n20523\n20524\n20525\n20526\n20527\n20528\n20529\n20530\n20531\n20532\n20533\n20534\n20535\n20536\n20537\n20538\n20539\n20540\n20541\n20542\n20543\n20544\n20545\n20546\n20547\n20548\n20549\n20550\n20551\n20552\n20553\n20554\n20555\n20556\n20557\n20558\n20559\n20560\n20561\n20562\n20563\n20564\n20565\n20566\n20567\n20568\n20569\n20570\n20571\n20572\n20573\n20574\n20575\n20576\n20577\n20578\n20579\n20580\n20581\n20582\n20583\n20584\n20585\n20586\n20587\n20588\n20589\n20590\n20591\n20592\n20593\n20594\n20595\n20596\n20597\n20598\n20599\n20600\n20601\n20602\n20603\n20604\n20605\n20606\n20607\n20608\n20609\n20610\n20611\n20612\n20613\n20614\n20615\n20616\n20617\n20618\n20619\n20620\n20621\n20622\n20623\n20624\n20625\n20626\n20627\n20628\n20629\n20630\n20631\n20632\n20633\n20634\n20635\n20636\n20637\n20638\n20639\n20640\n20641\n20642\n20643\n20644\n20645\n20646\n20647\n20648\n20649\n20650\n20651\n20652\n20653\n20654\n20655\n20656\n20657\n20658\n20659\n20660\n20661\n20662\n20663\n20664\n20665\n20666\n20667\n20668\n20669\n20670\n20671\n20672\n20673\n20674\n20675\n20676\n20677\n20678\n20679\n20680\n20681\n20682\n20683\n20684\n20685\n20686\n20687\n20688\n20689\n20690\n20691\n20692\n20693\n20694\n20695\n20696\n20697\n20698\n20699\n20700\n20701\n20702\n20703\n20704\n20705\n20706\n20707\n20708\n20709\n20710\n20711\n20712\n20713\n20714\n20715\n20716\n20717\n20718\n20719\n20720\n20721\n20722\n20723\n20724\n20725\n20726\n20727\n20728\n20729\n20730\n20731\n20732\n20733\n20734\n20735\n20736\n20737\n20738\n20739\n20740\n20741\n20742\n20743\n20744\n20745\n20746\n20747\n20748\n20749\n20750\n20751\n20752\n20753\n20754\n20755\n20756\n20757\n20758\n20759\n20760\n20761\n20762\n20763\n20764\n20765\n20766\n20767\n20768\n20769\n20770\n20771\n20772\n20773\n20774\n20775\n20776\n20777\n20778\n20779\n20780\n20781\n20782\n20783\n20784\n20785\n20786\n20787\n20788\n20789\n20790\n20791\n20792\n20793\n20794\n20795\n20796\n20797\n20798\n20799\n20800\n20801\n20802\n20803\n20804\n20805\n20806\n20807\n20808\n20809\n20810\n20811\n20812\n20813\n20814\n20815\n20816\n20817\n20818\n20819\n20820\n20821\n20822\n20823\n20824\n20825\n20826\n20827\n20828\n20829\n20830\n20831\n20832\n20833\n20834\n20835\n20836\n20837\n20838\n20839\n20840\n20841\n20842\n20843\n20844\n20845\n20846\n20847\n20848\n20849\n20850\n20851\n20852\n20853\n20854\n20855\n20856\n20857\n20858\n20859\n20860\n20861\n20862\n20863\n20864\n20865\n20866\n20867\n20868\n20869\n20870\n20871\n20872\n20873\n20874\n20875\n20876\n20877\n20878\n20879\n20880\n20881\n20882\n20883\n20884\n20885\n20886\n20887\n20888\n20889\n20890\n20891\n20892\n20893\n20894\n20895\n20896\n20897\n20898\n20899\n20900\n20901\n20902\n20903\n20904\n20905\n20906\n20907\n20908\n20909\n20910\n20911\n20912\n20913\n20914\n20915\n20916\n20917\n20918\n20919\n20920\n20921\n20922\n20923\n20924\n20925\n20926\n20927\n20928\n20929\n20930\n20931\n20932\n20933\n20934\n20935\n20936\n20937\n20938\n20939\n20940\n20941\n20942\n20943\n20944\n20945\n20946\n20947\n20948\n20949\n20950\n20951\n20952\n20953\n20954\n20955\n20956\n20957\n20958\n20959\n20960\n20961\n20962\n20963\n20964\n20965\n20966\n20967\n20968\n20969\n20970\n20971\n20972\n20973\n20974\n20975\n20976\n20977\n20978\n20979\n20980\n20981\n20982\n20983\n20984\n20985\n20986\n20987\n20988\n20989\n20990\n20991\n20992\n20993\n20994\n20995\n20996\n20997\n20998\n20999\n21000\n21001\n21002\n21003\n21004\n21005\n21006\n21007\n21008\n21009\n21010\n21011\n21012\n21013\n21014\n21015\n21016\n21017\n21018\n21019\n21020\n21021\n21022\n21023\n21024\n21025\n21026\n21027\n21028\n21029\n21030\n21031\n21032\n21033\n21034\n21035\n21036\n21037\n21038\n21039\n21040\n21041\n21042\n21043\n21044\n21045\n21046\n21047\n21048\n21049\n21050\n21051\n21052\n21053\n21054\n21055\n21056\n21057\n21058\n21059\n21060\n21061\n21062\n21063\n21064\n21065\n21066\n21067\n21068\n21069\n21070\n21071\n21072\n21073\n21074\n21075\n21076\n21077\n21078\n21079\n21080\n21081\n21082\n21083\n21084\n21085\n21086\n21087\n21088\n21089\n21090\n21091\n21092\n21093\n21094\n21095\n21096\n21097\n21098\n21099\n21100\n21101\n21102\n21103\n21104\n21105\n21106\n21107\n21108\n21109\n21110\n21111\n21112\n21113\n21114\n21115\n21116\n21117\n21118\n21119\n21120\n21121\n21122\n21123\n21124\n21125\n21126\n21127\n21128\n21129\n21130\n21131\n21132\n21133\n21134\n21135\n21136\n21137\n21138\n21139\n21140\n21141\n21142\n21143\n21144\n21145\n21146\n21147\n21148\n21149\n21150\n21151\n21152\n21153\n21154\n21155\n21156\n21157\n21158\n21159\n21160\n21161\n21162\n21163\n21164\n21165\n21166\n21167\n21168\n21169\n21170\n21171\n21172\n21173\n21174\n21175\n21176\n21177\n21178\n21179\n21180\n21181\n21182\n21183\n21184\n21185\n21186\n21187\n21188\n21189\n21190\n21191\n21192\n21193\n21194\n21195\n21196\n21197\n21198\n21199\n21200\n21201\n21202\n21203\n21204\n21205\n21206\n21207\n21208\n21209\n21210\n21211\n21212\n21213\n21214\n21215\n21216\n21217\n21218\n21219\n21220\n21221\n21222\n21223\n21224\n21225\n21226\n21227\n21228\n21229\n21230\n21231\n21232\n21233\n21234\n21235\n21236\n21237\n21238\n21239\n21240\n21241\n21242\n21243\n21244\n21245\n21246\n21247\n21248\n21249\n21250\n21251\n21252\n21253\n21254\n21255\n21256\n21257\n21258\n21259\n21260\n21261\n21262\n21263\n21264\n21265\n21266\n21267\n21268\n21269\n21270\n21271\n21272\n21273\n21274\n21275\n21276\n21277\n21278\n21279\n21280\n21281\n21282\n21283\n21284\n21285\n21286\n21287\n21288\n21289\n21290\n21291\n21292\n21293\n21294\n21295\n21296\n21297\n21298\n21299\n21300\n21301\n21302\n21303\n21304\n21305\n21306\n21307\n21308\n21309\n21310\n21311\n21312\n21313\n21314\n21315\n21316\n21317\n21318\n21319\n21320\n21321\n21322\n21323\n21324\n21325\n21326\n21327\n21328\n21329\n21330\n21331\n21332\n21333\n21334\n21335\n21336\n21337\n21338\n21339\n21340\n21341\n21342\n21343\n21344\n21345\n21346\n21347\n21348\n21349\n21350\n21351\n21352\n21353\n21354\n21355\n21356\n21357\n21358\n21359\n21360\n21361\n21362\n21363\n21364\n21365\n21366\n21367\n21368\n21369\n21370\n21371\n21372\n21373\n21374\n21375\n21376\n21377\n21378\n21379\n21380\n21381\n21382\n21383\n21384\n21385\n21386\n21387\n21388\n21389\n21390\n21391\n21392\n21393\n21394\n21395\n21396\n21397\n21398\n21399\n21400\n21401\n21402\n21403\n21404\n21405\n21406\n21407\n21408\n21409\n21410\n21411\n21412\n21413\n21414\n21415\n21416\n21417\n21418\n21419\n21420\n21421\n21422\n21423\n21424\n21425\n21426\n21427\n21428\n21429\n21430\n21431\n21432\n21433\n21434\n21435\n21436\n21437\n21438\n21439\n21440\n21441\n21442\n21443\n21444\n21445\n21446\n21447\n21448\n21449\n21450\n21451\n21452\n21453\n21454\n21455\n21456\n21457\n21458\n21459\n21460\n21461\n21462\n21463\n21464\n21465\n21466\n21467\n21468\n21469\n21470\n21471\n21472\n21473\n21474\n21475\n21476\n21477\n21478\n21479\n21480\n21481\n21482\n21483\n21484\n21485\n21486\n21487\n21488\n21489\n21490\n21491\n21492\n21493\n21494\n21495\n21496\n21497\n21498\n21499\n21500\n21501\n21502\n21503\n21504\n21505\n21506\n21507\n21508\n21509\n21510\n21511\n21512\n21513\n21514\n21515\n21516\n21517\n21518\n21519\n21520\n21521\n21522\n21523\n21524\n21525\n21526\n21527\n21528\n21529\n21530\n21531\n21532\n21533\n21534\n21535\n21536\n21537\n21538\n21539\n21540\n21541\n21542\n21543\n21544\n21545\n21546\n21547\n21548\n21549\n21550\n21551\n21552\n21553\n21554\n21555\n21556\n21557\n21558\n21559\n21560\n21561\n21562\n21563\n21564\n21565\n21566\n21567\n21568\n21569\n21570\n21571\n21572\n21573\n21574\n21575\n21576\n21577\n21578\n21579\n21580\n21581\n21582\n21583\n21584\n21585\n21586\n21587\n21588\n21589\n21590\n21591\n21592\n21593\n21594\n21595\n21596\n21597\n21598\n21599\n21600\n21601\n21602\n21603\n21604\n21605\n21606\n21607\n21608\n21609\n21610\n21611\n21612\n21613\n21614\n21615\n21616\n21617\n21618\n21619\n21620\n21621\n21622\n21623\n21624\n21625\n21626\n21627\n21628\n21629\n21630\n21631\n21632\n21633\n21634\n21635\n21636\n21637\n21638\n21639\n21640\n21641\n21642\n21643\n21644\n21645\n21646\n21647\n21648\n21649\n21650\n21651\n21652\n21653\n21654\n21655\n21656\n21657\n21658\n21659\n21660\n21661\n21662\n21663\n21664\n21665\n21666\n21667\n21668\n21669\n21670\n21671\n21672\n21673\n21674\n21675\n21676\n21677\n21678\n21679\n21680\n21681\n21682\n21683\n21684\n21685\n21686\n21687\n21688\n21689\n21690\n21691\n21692\n21693\n21694\n21695\n21696\n21697\n21698\n21699\n21700\n21701\n21702\n21703\n21704\n21705\n21706\n21707\n21708\n21709\n21710\n21711\n21712\n21713\n21714\n21715\n21716\n21717\n21718\n21719\n21720\n21721\n21722\n21723\n21724\n21725\n21726\n21727\n21728\n21729\n21730\n21731\n21732\n21733\n21734\n21735\n21736\n21737\n21738\n21739\n21740\n21741\n21742\n21743\n21744\n21745\n21746\n21747\n21748\n21749\n21750\n21751\n21752\n21753\n21754\n21755\n21756\n21757\n21758\n21759\n21760\n21761\n21762\n21763\n21764\n21765\n21766\n21767\n21768\n21769\n21770\n21771\n21772\n21773\n21774\n21775\n21776\n21777\n21778\n21779\n21780\n21781\n21782\n21783\n21784\n21785\n21786\n21787\n21788\n21789\n21790\n21791\n21792\n21793\n21794\n21795\n21796\n21797\n21798\n21799\n21800\n21801\n21802\n21803\n21804\n21805\n21806\n21807\n21808\n21809\n21810\n21811\n21812\n21813\n21814\n21815\n21816\n21817\n21818\n21819\n21820\n21821\n21822\n21823\n21824\n21825\n21826\n21827\n21828\n21829\n21830\n21831\n21832\n21833\n21834\n21835\n21836\n21837\n21838\n21839\n21840\n21841\n21842\n21843\n21844\n21845\n21846\n21847\n21848\n21849\n21850\n21851\n21852\n21853\n21854\n21855\n21856\n21857\n21858\n21859\n21860\n21861\n21862\n21863\n21864\n21865\n21866\n21867\n21868\n21869\n21870\n21871\n21872\n21873\n21874\n21875\n21876\n21877\n21878\n21879\n21880\n21881\n21882\n21883\n21884\n21885\n21886\n21887\n21888\n21889\n21890\n21891\n21892\n21893\n21894\n21895\n21896\n21897\n21898\n21899\n21900\n21901\n21902\n21903\n21904\n21905\n21906\n21907\n21908\n21909\n21910\n21911\n21912\n21913\n21914\n21915\n21916\n21917\n21918\n21919\n21920\n21921\n21922\n21923\n21924\n21925\n21926\n21927\n21928\n21929\n21930\n21931\n21932\n21933\n21934\n21935\n21936\n21937\n21938\n21939\n21940\n21941\n21942\n21943\n21944\n21945\n21946\n21947\n21948\n21949\n21950\n21951\n21952\n21953\n21954\n21955\n21956\n21957\n21958\n21959\n21960\n21961\n21962\n21963\n21964\n21965\n21966\n21967\n21968\n21969\n21970\n21971\n21972\n21973\n21974\n21975\n21976\n21977\n21978\n21979\n21980\n21981\n21982\n21983\n21984\n21985\n21986\n21987\n21988\n21989\n21990\n21991\n21992\n21993\n21994\n21995\n21996\n21997\n21998\n21999\n22000\n22001\n22002\n22003\n22004\n22005\n22006\n22007\n22008\n22009\n22010\n22011\n22012\n22013\n22014\n22015\n22016\n22017\n22018\n22019\n22020\n22021\n22022\n22023\n22024\n22025\n22026\n22027\n22028\n22029\n22030\n22031\n22032\n22033\n22034\n22035\n22036\n22037\n22038\n22039\n22040\n22041\n22042\n22043\n22044\n22045\n22046\n22047\n22048\n22049\n22050\n22051\n22052\n22053\n22054\n22055\n22056\n22057\n22058\n22059\n22060\n22061\n22062\n22063\n22064\n22065\n22066\n22067\n22068\n22069\n22070\n22071\n22072\n22073\n22074\n22075\n22076\n22077\n22078\n22079\n22080\n22081\n22082\n22083\n22084\n22085\n22086\n22087\n22088\n22089\n22090\n22091\n22092\n22093\n22094\n22095\n22096\n22097\n22098\n22099\n22100\n22101\n22102\n22103\n22104\n22105\n22106\n22107\n22108\n22109\n22110\n22111\n22112\n22113\n22114\n22115\n22116\n22117\n22118\n22119\n22120\n22121\n22122\n22123\n22124\n22125\n22126\n22127\n22128\n22129\n22130\n22131\n22132\n22133\n22134\n22135\n22136\n22137\n22138\n22139\n22140\n22141\n22142\n22143\n22144\n22145\n22146\n22147\n22148\n22149\n22150\n22151\n22152\n22153\n22154\n22155\n22156\n22157\n22158\n22159\n22160\n22161\n22162\n22163\n22164\n22165\n22166\n22167\n22168\n22169\n22170\n22171\n22172\n22173\n22174\n22175\n22176\n22177\n22178\n22179\n22180\n22181\n22182\n22183\n22184\n22185\n22186\n22187\n22188\n22189\n22190\n22191\n22192\n22193\n22194\n22195\n22196\n22197\n22198\n22199\n22200\n22201\n22202\n22203\n22204\n22205\n22206\n22207\n22208\n22209\n22210\n22211\n22212\n22213\n22214\n22215\n22216\n22217\n22218\n22219\n22220\n22221\n22222\n22223\n22224\n22225\n22226\n22227\n22228\n22229\n22230\n22231\n22232\n22233\n22234\n22235\n22236\n22237\n22238\n22239\n22240\n22241\n22242\n22243\n22244\n22245\n22246\n22247\n22248\n22249\n22250\n22251\n22252\n22253\n22254\n22255\n22256\n22257\n22258\n22259\n22260\n22261\n22262\n22263\n22264\n22265\n22266\n22267\n22268\n22269\n22270\n22271\n22272\n22273\n22274\n22275\n22276\n22277\n22278\n22279\n22280\n22281\n22282\n22283\n22284\n22285\n22286\n22287\n22288\n22289\n22290\n22291\n22292\n22293\n22294\n22295\n22296\n22297\n22298\n22299\n22300\n22301\n22302\n22303\n22304\n22305\n22306\n22307\n22308\n22309\n22310\n22311\n22312\n22313\n22314\n22315\n22316\n22317\n22318\n22319\n22320\n22321\n22322\n22323\n22324\n22325\n22326\n22327\n22328\n22329\n22330\n22331\n22332\n22333\n22334\n22335\n22336\n22337\n22338\n22339\n22340\n22341\n22342\n22343\n22344\n22345\n22346\n22347\n22348\n22349\n22350\n22351\n22352\n22353\n22354\n22355\n22356\n22357\n22358\n22359\n22360\n22361\n22362\n22363\n22364\n22365\n22366\n22367\n22368\n22369\n22370\n22371\n22372\n22373\n22374\n22375\n22376\n22377\n22378\n22379\n22380\n22381\n22382\n22383\n22384\n22385\n22386\n22387\n22388\n22389\n22390\n22391\n22392\n22393\n22394\n22395\n22396\n22397\n22398\n22399\n22400\n22401\n22402\n22403\n22404\n22405\n22406\n22407\n22408\n22409\n22410\n22411\n22412\n22413\n22414\n22415\n22416\n22417\n22418\n22419\n22420\n22421\n22422\n22423\n22424\n22425\n22426\n22427\n22428\n22429\n22430\n22431\n22432\n22433\n22434\n22435\n22436\n22437\n22438\n22439\n22440\n22441\n22442\n22443\n22444\n22445\n22446\n22447\n22448\n22449\n22450\n22451\n22452\n22453\n22454\n22455\n22456\n22457\n22458\n22459\n22460\n22461\n22462\n22463\n22464\n22465\n22466\n22467\n22468\n22469\n22470\n22471\n22472\n22473\n22474\n22475\n22476\n22477\n22478\n22479\n22480\n22481\n22482\n22483\n22484\n22485\n22486\n22487\n22488\n22489\n22490\n22491\n22492\n22493\n22494\n22495\n22496\n22497\n22498\n22499\n22500\n22501\n22502\n22503\n22504\n22505\n22506\n22507\n22508\n22509\n22510\n22511\n22512\n22513\n22514\n22515\n22516\n22517\n22518\n22519\n22520\n22521\n22522\n22523\n22524\n22525\n22526\n22527\n22528\n22529\n22530\n22531\n22532\n22533\n22534\n22535\n22536\n22537\n22538\n22539\n22540\n22541\n22542\n22543\n22544\n22545\n22546\n22547\n22548\n22549\n22550\n22551\n22552\n22553\n22554\n22555\n22556\n22557\n22558\n22559\n22560\n22561\n22562\n22563\n22564\n22565\n22566\n22567\n22568\n22569\n22570\n22571\n22572\n22573\n22574\n22575\n22576\n22577\n22578\n22579\n22580\n22581\n22582\n22583\n22584\n22585\n22586\n22587\n22588\n22589\n22590\n22591\n22592\n22593\n22594\n22595\n22596\n22597\n22598\n22599\n22600\n22601\n22602\n22603\n22604\n22605\n22606\n22607\n22608\n22609\n22610\n22611\n22612\n22613\n22614\n22615\n22616\n22617\n22618\n22619\n22620\n22621\n22622\n22623\n22624\n22625\n22626\n22627\n22628\n22629\n22630\n22631\n22632\n22633\n22634\n22635\n22636\n22637\n22638\n22639\n22640\n22641\n22642\n22643\n22644\n22645\n22646\n22647\n22648\n22649\n22650\n22651\n22652\n22653\n22654\n22655\n22656\n22657\n22658\n22659\n22660\n22661\n22662\n22663\n22664\n22665\n22666\n22667\n22668\n22669\n22670\n22671\n22672\n22673\n22674\n22675\n22676\n22677\n22678\n22679\n22680\n22681\n22682\n22683\n22684\n22685\n22686\n22687\n22688\n22689\n22690\n22691\n22692\n22693\n22694\n22695\n22696\n22697\n22698\n22699\n22700\n22701\n22702\n22703\n22704\n22705\n22706\n22707\n22708\n22709\n22710\n22711\n22712\n22713\n22714\n22715\n22716\n22717\n22718\n22719\n22720\n22721\n22722\n22723\n22724\n22725\n22726\n22727\n22728\n22729\n22730\n22731\n22732\n22733\n22734\n22735\n22736\n22737\n22738\n22739\n22740\n22741\n22742\n22743\n22744\n22745\n22746\n22747\n22748\n22749\n22750\n22751\n22752\n22753\n22754\n22755\n22756\n22757\n22758\n22759\n22760\n22761\n22762\n22763\n22764\n22765\n22766\n22767\n22768\n22769\n22770\n22771\n22772\n22773\n22774\n22775\n22776\n22777\n22778\n22779\n22780\n22781\n22782\n22783\n22784\n22785\n22786\n22787\n22788\n22789\n22790\n22791\n22792\n22793\n22794\n22795\n22796\n22797\n22798\n22799\n22800\n22801\n22802\n22803\n22804\n22805\n22806\n22807\n22808\n22809\n22810\n22811\n22812\n22813\n22814\n22815\n22816\n22817\n22818\n22819\n22820\n22821\n22822\n22823\n22824\n22825\n22826\n22827\n22828\n22829\n22830\n22831\n22832\n22833\n22834\n22835\n22836\n22837\n22838\n22839\n22840\n22841\n22842\n22843\n22844\n22845\n22846\n22847\n22848\n22849\n22850\n22851\n22852\n22853\n22854\n22855\n22856\n22857\n22858\n22859\n22860\n22861\n22862\n22863\n22864\n22865\n22866\n22867\n22868\n22869\n22870\n22871\n22872\n22873\n22874\n22875\n22876\n22877\n22878\n22879\n22880\n22881\n22882\n22883\n22884\n22885\n22886\n22887\n22888\n22889\n22890\n22891\n22892\n22893\n22894\n22895\n22896\n22897\n22898\n22899\n22900\n22901\n22902\n22903\n22904\n22905\n22906\n22907\n22908\n22909\n22910\n22911\n22912\n22913\n22914\n22915\n22916\n22917\n22918\n22919\n22920\n22921\n22922\n22923\n22924\n22925\n22926\n22927\n22928\n22929\n22930\n22931\n22932\n22933\n22934\n22935\n22936\n22937\n22938\n22939\n22940\n22941\n22942\n22943\n22944\n22945\n22946\n22947\n22948\n22949\n22950\n22951\n22952\n22953\n22954\n22955\n22956\n22957\n22958\n22959\n22960\n22961\n22962\n22963\n22964\n22965\n22966\n22967\n22968\n22969\n22970\n22971\n22972\n22973\n22974\n22975\n22976\n22977\n22978\n22979\n22980\n22981\n22982\n22983\n22984\n22985\n22986\n22987\n22988\n22989\n22990\n22991\n22992\n22993\n22994\n22995\n22996\n22997\n22998\n22999\n23000\n23001\n23002\n23003\n23004\n23005\n23006\n23007\n23008\n23009\n23010\n23011\n23012\n23013\n23014\n23015\n23016\n23017\n23018\n23019\n23020\n23021\n23022\n23023\n23024\n23025\n23026\n23027\n23028\n23029\n23030\n23031\n23032\n23033\n23034\n23035\n23036\n23037\n23038\n23039\n23040\n23041\n23042\n23043\n23044\n23045\n23046\n23047\n23048\n23049\n23050\n23051\n23052\n23053\n23054\n23055\n23056\n23057\n23058\n23059\n23060\n23061\n23062\n23063\n23064\n23065\n23066\n23067\n23068\n23069\n23070\n23071\n23072\n23073\n23074\n23075\n23076\n23077\n23078\n23079\n23080\n23081\n23082\n23083\n23084\n23085\n23086\n23087\n23088\n23089\n23090\n23091\n23092\n23093\n23094\n23095\n23096\n23097\n23098\n23099\n23100\n23101\n23102\n23103\n23104\n23105\n23106\n23107\n23108\n23109\n23110\n23111\n23112\n23113\n23114\n23115\n23116\n23117\n23118\n23119\n23120\n23121\n23122\n23123\n23124\n23125\n23126\n23127\n23128\n23129\n23130\n23131\n23132\n23133\n23134\n23135\n23136\n23137\n23138\n23139\n23140\n23141\n23142\n23143\n23144\n23145\n23146\n23147\n23148\n23149\n23150\n23151\n23152\n23153\n23154\n23155\n23156\n23157\n23158\n23159\n23160\n23161\n23162\n23163\n23164\n23165\n23166\n23167\n23168\n23169\n23170\n23171\n23172\n23173\n23174\n23175\n23176\n23177\n23178\n23179\n23180\n23181\n23182\n23183\n23184\n23185\n23186\n23187\n23188\n23189\n23190\n23191\n23192\n23193\n23194\n23195\n23196\n23197\n23198\n23199\n23200\n23201\n23202\n23203\n23204\n23205\n23206\n23207\n23208\n23209\n23210\n23211\n23212\n23213\n23214\n23215\n23216\n23217\n23218\n23219\n23220\n23221\n23222\n23223\n23224\n23225\n23226\n23227\n23228\n23229\n23230\n23231\n23232\n23233\n23234\n23235\n23236\n23237\n23238\n23239\n23240\n23241\n23242\n23243\n23244\n23245\n23246\n23247\n23248\n23249\n23250\n23251\n23252\n23253\n23254\n23255\n23256\n23257\n23258\n23259\n23260\n23261\n23262\n23263\n23264\n23265\n23266\n23267\n23268\n23269\n23270\n23271\n23272\n23273\n23274\n23275\n23276\n23277\n23278\n23279\n23280\n23281\n23282\n23283\n23284\n23285\n23286\n23287\n23288\n23289\n23290\n23291\n23292\n23293\n23294\n23295\n23296\n23297\n23298\n23299\n23300\n23301\n23302\n23303\n23304\n23305\n23306\n23307\n23308\n23309\n23310\n23311\n23312\n23313\n23314\n23315\n23316\n23317\n23318\n23319\n23320\n23321\n23322\n23323\n23324\n23325\n23326\n23327\n23328\n23329\n23330\n23331\n23332\n23333\n23334\n23335\n23336\n23337\n23338\n23339\n23340\n23341\n23342\n23343\n23344\n23345\n23346\n23347\n23348\n23349\n23350\n23351\n23352\n23353\n23354\n23355\n23356\n23357\n23358\n23359\n23360\n23361\n23362\n23363\n23364\n23365\n23366\n23367\n23368\n23369\n23370\n23371\n23372\n23373\n23374\n23375\n23376\n23377\n23378\n23379\n23380\n23381\n23382\n23383\n23384\n23385\n23386\n23387\n23388\n23389\n23390\n23391\n23392\n23393\n23394\n23395\n23396\n23397\n23398\n23399\n23400\n23401\n23402\n23403\n23404\n23405\n23406\n23407\n23408\n23409\n23410\n23411\n23412\n23413\n23414\n23415\n23416\n23417\n23418\n23419\n23420\n23421\n23422\n23423\n23424\n23425\n23426\n23427\n23428\n23429\n23430\n23431\n23432\n23433\n23434\n23435\n23436\n23437\n23438\n23439\n23440\n23441\n23442\n23443\n23444\n23445\n23446\n23447\n23448\n23449\n23450\n23451\n23452\n23453\n23454\n23455\n23456\n23457\n23458\n23459\n23460\n23461\n23462\n23463\n23464\n23465\n23466\n23467\n23468\n23469\n23470\n23471\n23472\n23473\n23474\n23475\n23476\n23477\n23478\n23479\n23480\n23481\n23482\n23483\n23484\n23485\n23486\n23487\n23488\n23489\n23490\n23491\n23492\n23493\n23494\n23495\n23496\n23497\n23498\n23499\n23500\n23501\n23502\n23503\n23504\n23505\n23506\n23507\n23508\n23509\n23510\n23511\n23512\n23513\n23514\n23515\n23516\n23517\n23518\n23519\n23520\n23521\n23522\n23523\n23524\n23525\n23526\n23527\n23528\n23529\n23530\n23531\n23532\n23533\n23534\n23535\n23536\n23537\n23538\n23539\n23540\n23541\n23542\n23543\n23544\n23545\n23546\n23547\n23548\n23549\n23550\n23551\n23552\n23553\n23554\n23555\n23556\n23557\n23558\n23559\n23560\n23561\n23562\n23563\n23564\n23565\n23566\n23567\n23568\n23569\n23570\n23571\n23572\n23573\n23574\n23575\n23576\n23577\n23578\n23579\n23580\n23581\n23582\n23583\n23584\n23585\n23586\n23587\n23588\n23589\n23590\n23591\n23592\n23593\n23594\n23595\n23596\n23597\n23598\n23599\n23600\n23601\n23602\n23603\n23604\n23605\n23606\n23607\n23608\n23609\n23610\n23611\n23612\n23613\n23614\n23615\n23616\n23617\n23618\n23619\n23620\n23621\n23622\n23623\n23624\n23625\n23626\n23627\n23628\n23629\n23630\n23631\n23632\n23633\n23634\n23635\n23636\n23637\n23638\n23639\n23640\n23641\n23642\n23643\n23644\n23645\n23646\n23647\n23648\n23649\n23650\n23651\n23652\n23653\n23654\n23655\n23656\n23657\n23658\n23659\n23660\n23661\n23662\n23663\n23664\n23665\n23666\n23667\n23668\n23669\n23670\n23671\n23672\n23673\n23674\n23675\n23676\n23677\n23678\n23679\n23680\n23681\n23682\n23683\n23684\n23685\n23686\n23687\n23688\n23689\n23690\n23691\n23692\n23693\n23694\n23695\n23696\n23697\n23698\n23699\n23700\n23701\n23702\n23703\n23704\n23705\n23706\n23707\n23708\n23709\n23710\n23711\n23712\n23713\n23714\n23715\n23716\n23717\n23718\n23719\n23720\n23721\n23722\n23723\n23724\n23725\n23726\n23727\n23728\n23729\n23730\n23731\n23732\n23733\n23734\n23735\n23736\n23737\n23738\n23739\n23740\n23741\n23742\n23743\n23744\n23745\n23746\n23747\n23748\n23749\n23750\n23751\n23752\n23753\n23754\n23755\n23756\n23757\n23758\n23759\n23760\n23761\n23762\n23763\n23764\n23765\n23766\n23767\n23768\n23769\n23770\n23771\n23772\n23773\n23774\n23775\n23776\n23777\n23778\n23779\n23780\n23781\n23782\n23783\n23784\n23785\n23786\n23787\n23788\n23789\n23790\n23791\n23792\n23793\n23794\n23795\n23796\n23797\n23798\n23799\n23800\n23801\n23802\n23803\n23804\n23805\n23806\n23807\n23808\n23809\n23810\n23811\n23812\n23813\n23814\n23815\n23816\n23817\n23818\n23819\n23820\n23821\n23822\n23823\n23824\n23825\n23826\n23827\n23828\n23829\n23830\n23831\n23832\n23833\n23834\n23835\n23836\n23837\n23838\n23839\n23840\n23841\n23842\n23843\n23844\n23845\n23846\n23847\n23848\n23849\n23850\n23851\n23852\n23853\n23854\n23855\n23856\n23857\n23858\n23859\n23860\n23861\n23862\n23863\n23864\n23865\n23866\n23867\n23868\n23869\n23870\n23871\n23872\n23873\n23874\n23875\n23876\n23877\n23878\n23879\n23880\n23881\n23882\n23883\n23884\n23885\n23886\n23887\n23888\n23889\n23890\n23891\n23892\n23893\n23894\n23895\n23896\n23897\n23898\n23899\n23900\n23901\n23902\n23903\n23904\n23905\n23906\n23907\n23908\n23909\n23910\n23911\n23912\n23913\n23914\n23915\n23916\n23917\n23918\n23919\n23920\n23921\n23922\n23923\n23924\n23925\n23926\n23927\n23928\n23929\n23930\n23931\n23932\n23933\n23934\n23935\n23936\n23937\n23938\n23939\n23940\n23941\n23942\n23943\n23944\n23945\n23946\n23947\n23948\n23949\n23950\n23951\n23952\n23953\n23954\n23955\n23956\n23957\n23958\n23959\n23960\n23961\n23962\n23963\n23964\n23965\n23966\n23967\n23968\n23969\n23970\n23971\n23972\n23973\n23974\n23975\n23976\n23977\n23978\n23979\n23980\n23981\n23982\n23983\n23984\n23985\n23986\n23987\n23988\n23989\n23990\n23991\n23992\n23993\n23994\n23995\n23996\n23997\n23998\n23999\n24000\n24001\n24002\n24003\n24004\n24005\n24006\n24007\n24008\n24009\n24010\n24011\n24012\n24013\n24014\n24015\n24016\n24017\n24018\n24019\n24020\n24021\n24022\n24023\n24024\n24025\n24026\n24027\n24028\n24029\n24030\n24031\n24032\n24033\n24034\n24035\n24036\n24037\n24038\n24039\n24040\n24041\n24042\n24043\n24044\n24045\n24046\n24047\n24048\n24049\n24050\n24051\n24052\n24053\n24054\n24055\n24056\n24057\n24058\n24059\n24060\n24061\n24062\n24063\n24064\n24065\n24066\n24067\n24068\n24069\n24070\n24071\n24072\n24073\n24074\n24075\n24076\n24077\n24078\n24079\n24080\n24081\n24082\n24083\n24084\n24085\n24086\n24087\n24088\n24089\n24090\n24091\n24092\n24093\n24094\n24095\n24096\n24097\n24098\n24099\n24100\n24101\n24102\n24103\n24104\n24105\n24106\n24107\n24108\n24109\n24110\n24111\n24112\n24113\n24114\n24115\n24116\n24117\n24118\n24119\n24120\n24121\n24122\n24123\n24124\n24125\n24126\n24127\n24128\n24129\n24130\n24131\n24132\n24133\n24134\n24135\n24136\n24137\n24138\n24139\n24140\n24141\n24142\n24143\n24144\n24145\n24146\n24147\n24148\n24149\n24150\n24151\n24152\n24153\n24154\n24155\n24156\n24157\n24158\n24159\n24160\n24161\n24162\n24163\n24164\n24165\n24166\n24167\n24168\n24169\n24170\n24171\n24172\n24173\n24174\n24175\n24176\n24177\n24178\n24179\n24180\n24181\n24182\n24183\n24184\n24185\n24186\n24187\n24188\n24189\n24190\n24191\n24192\n24193\n24194\n24195\n24196\n24197\n24198\n24199\n24200\n24201\n24202\n24203\n24204\n24205\n24206\n24207\n24208\n24209\n24210\n24211\n24212\n24213\n24214\n24215\n24216\n24217\n24218\n24219\n24220\n24221\n24222\n24223\n24224\n24225\n24226\n24227\n24228\n24229\n24230\n24231\n24232\n24233\n24234\n24235\n24236\n24237\n24238\n24239\n24240\n24241\n24242\n24243\n24244\n24245\n24246\n24247\n24248\n24249\n24250\n24251\n24252\n24253\n24254\n24255\n24256\n24257\n24258\n24259\n24260\n24261\n24262\n24263\n24264\n24265\n24266\n24267\n24268\n24269\n24270\n24271\n24272\n24273\n24274\n24275\n24276\n24277\n24278\n24279\n24280\n24281\n24282\n24283\n24284\n24285\n24286\n24287\n24288\n24289\n24290\n24291\n24292\n24293\n24294\n24295\n24296\n24297\n24298\n24299\n24300\n24301\n24302\n24303\n24304\n24305\n24306\n24307\n24308\n24309\n24310\n24311\n24312\n24313\n24314\n24315\n24316\n24317\n24318\n24319\n24320\n24321\n24322\n24323\n24324\n24325\n24326\n24327\n24328\n24329\n24330\n24331\n24332\n24333\n24334\n24335\n24336\n24337\n24338\n24339\n24340\n24341\n24342\n24343\n24344\n24345\n24346\n24347\n24348\n24349\n24350\n24351\n24352\n24353\n24354\n24355\n24356\n24357\n24358\n24359\n24360\n24361\n24362\n24363\n24364\n24365\n24366\n24367\n24368\n24369\n24370\n24371\n24372\n24373\n24374\n24375\n24376\n24377\n24378\n24379\n24380\n24381\n24382\n24383\n24384\n24385\n24386\n24387\n24388\n24389\n24390\n24391\n24392\n24393\n24394\n24395\n24396\n24397\n24398\n24399\n24400\n24401\n24402\n24403\n24404\n24405\n24406\n24407\n24408\n24409\n24410\n24411\n24412\n24413\n24414\n24415\n24416\n24417\n24418\n24419\n24420\n24421\n24422\n24423\n24424\n24425\n24426\n24427\n24428\n24429\n24430\n24431\n24432\n24433\n24434\n24435\n24436\n24437\n24438\n24439\n24440\n24441\n24442\n24443\n24444\n24445\n24446\n24447\n24448\n24449\n24450\n24451\n24452\n24453\n24454\n24455\n24456\n24457\n24458\n24459\n24460\n24461\n24462\n24463\n24464\n24465\n24466\n24467\n24468\n24469\n24470\n24471\n24472\n24473\n24474\n24475\n24476\n24477\n24478\n24479\n24480\n24481\n24482\n24483\n24484\n24485\n24486\n24487\n24488\n24489\n24490\n24491\n24492\n24493\n24494\n24495\n24496\n24497\n24498\n24499\n24500\n24501\n24502\n24503\n24504\n24505\n24506\n24507\n24508\n24509\n24510\n24511\n24512\n24513\n24514\n24515\n24516\n24517\n24518\n24519\n24520\n24521\n24522\n24523\n24524\n24525\n24526\n24527\n24528\n24529\n24530\n24531\n24532\n24533\n24534\n24535\n24536\n24537\n24538\n24539\n24540\n24541\n24542\n24543\n24544\n24545\n24546\n24547\n24548\n24549\n24550\n24551\n24552\n24553\n24554\n24555\n24556\n24557\n24558\n24559\n24560\n24561\n24562\n24563\n24564\n24565\n24566\n24567\n24568\n24569\n24570\n24571\n24572\n24573\n24574\n24575\n24576\n24577\n24578\n24579\n24580\n24581\n24582\n24583\n24584\n24585\n24586\n24587\n24588\n24589\n24590\n24591\n24592\n24593\n24594\n24595\n24596\n24597\n24598\n24599\n24600\n24601\n24602\n24603\n24604\n24605\n24606\n24607\n24608\n24609\n24610\n24611\n24612\n24613\n24614\n24615\n24616\n24617\n24618\n24619\n24620\n24621\n24622\n24623\n24624\n24625\n24626\n24627\n24628\n24629\n24630\n24631\n24632\n24633\n24634\n24635\n24636\n24637\n24638\n24639\n24640\n24641\n24642\n24643\n24644\n24645\n24646\n24647\n24648\n24649\n24650\n24651\n24652\n24653\n24654\n24655\n24656\n24657\n24658\n24659\n24660\n24661\n24662\n24663\n24664\n24665\n24666\n24667\n24668\n24669\n24670\n24671\n24672\n24673\n24674\n24675\n24676\n24677\n24678\n24679\n24680\n24681\n24682\n24683\n24684\n24685\n24686\n24687\n24688\n24689\n24690\n24691\n24692\n24693\n24694\n24695\n24696\n24697\n24698\n24699\n24700\n24701\n24702\n24703\n24704\n24705\n24706\n24707\n24708\n24709\n24710\n24711\n24712\n24713\n24714\n24715\n24716\n24717\n24718\n24719\n24720\n24721\n24722\n24723\n24724\n24725\n24726\n24727\n24728\n24729\n24730\n24731\n24732\n24733\n24734\n24735\n24736\n24737\n24738\n24739\n24740\n24741\n24742\n24743\n24744\n24745\n24746\n24747\n24748\n24749\n24750\n24751\n24752\n24753\n24754\n24755\n24756\n24757\n24758\n24759\n24760\n24761\n24762\n24763\n24764\n24765\n24766\n24767\n24768\n24769\n24770\n24771\n24772\n24773\n24774\n24775\n24776\n24777\n24778\n24779\n24780\n24781\n24782\n24783\n24784\n24785\n24786\n24787\n24788\n24789\n24790\n24791\n24792\n24793\n24794\n24795\n24796\n24797\n24798\n24799\n24800\n24801\n24802\n24803\n24804\n24805\n24806\n24807\n24808\n24809\n24810\n24811\n24812\n24813\n24814\n24815\n24816\n24817\n24818\n24819\n24820\n24821\n24822\n24823\n24824\n24825\n24826\n24827\n24828\n24829\n24830\n24831\n24832\n24833\n24834\n24835\n24836\n24837\n24838\n24839\n24840\n24841\n24842\n24843\n24844\n24845\n24846\n24847\n24848\n24849\n24850\n24851\n24852\n24853\n24854\n24855\n24856\n24857\n24858\n24859\n24860\n24861\n24862\n24863\n24864\n24865\n24866\n24867\n24868\n24869\n24870\n24871\n24872\n24873\n24874\n24875\n24876\n24877\n24878\n24879\n24880\n24881\n24882\n24883\n24884\n24885\n24886\n24887\n24888\n24889\n24890\n24891\n24892\n24893\n24894\n24895\n24896\n24897\n24898\n24899\n24900\n24901\n24902\n24903\n24904\n24905\n24906\n24907\n24908\n24909\n24910\n24911\n24912\n24913\n24914\n24915\n24916\n24917\n24918\n24919\n24920\n24921\n24922\n24923\n24924\n24925\n24926\n24927\n24928\n24929\n24930\n24931\n24932\n24933\n24934\n24935\n24936\n24937\n24938\n24939\n24940\n24941\n24942\n24943\n24944\n24945\n24946\n24947\n24948\n24949\n24950\n24951\n24952\n24953\n24954\n24955\n24956\n24957\n24958\n24959\n24960\n24961\n24962\n24963\n24964\n24965\n24966\n24967\n24968\n24969\n24970\n24971\n24972\n24973\n24974\n24975\n24976\n24977\n24978\n24979\n24980\n24981\n24982\n24983\n24984\n24985\n24986\n24987\n24988\n24989\n24990\n24991\n24992\n24993\n24994\n24995\n24996\n24997\n24998\n24999\n25000\n25001\n25002\n25003\n25004\n25005\n25006\n25007\n25008\n25009\n25010\n25011\n25012\n25013\n25014\n25015\n25016\n25017\n25018\n25019\n25020\n25021\n25022\n25023\n25024\n25025\n25026\n25027\n25028\n25029\n25030\n25031\n25032\n25033\n25034\n25035\n25036\n25037\n25038\n25039\n25040\n25041\n25042\n25043\n25044\n25045\n25046\n25047\n25048\n25049\n25050\n25051\n25052\n25053\n25054\n25055\n25056\n25057\n25058\n25059\n25060\n25061\n25062\n25063\n25064\n25065\n25066\n25067\n25068\n25069\n25070\n25071\n25072\n25073\n25074\n25075\n25076\n25077\n25078\n25079\n25080\n25081\n25082\n25083\n25084\n25085\n25086\n25087\n25088\n25089\n25090\n25091\n25092\n25093\n25094\n25095\n25096\n25097\n25098\n25099\n25100\n25101\n25102\n25103\n25104\n25105\n25106\n25107\n25108\n25109\n25110\n25111\n25112\n25113\n25114\n25115\n25116\n25117\n25118\n25119\n25120\n25121\n25122\n25123\n25124\n25125\n25126\n25127\n25128\n25129\n25130\n25131\n25132\n25133\n25134\n25135\n25136\n25137\n25138\n25139\n25140\n25141\n25142\n25143\n25144\n25145\n25146\n25147\n25148\n25149\n25150\n25151\n25152\n25153\n25154\n25155\n25156\n25157\n25158\n25159\n25160\n25161\n25162\n25163\n25164\n25165\n25166\n25167\n25168\n25169\n25170\n25171\n25172\n25173\n25174\n25175\n25176\n25177\n25178\n25179\n25180\n25181\n25182\n25183\n25184\n25185\n25186\n25187\n25188\n25189\n25190\n25191\n25192\n25193\n25194\n25195\n25196\n25197\n25198\n25199\n25200\n25201\n25202\n25203\n25204\n25205\n25206\n25207\n25208\n25209\n25210\n25211\n25212\n25213\n25214\n25215\n25216\n25217\n25218\n25219\n25220\n25221\n25222\n25223\n25224\n25225\n25226\n25227\n25228\n25229\n25230\n25231\n25232\n25233\n25234\n25235\n25236\n25237\n25238\n25239\n25240\n25241\n25242\n25243\n25244\n25245\n25246\n25247\n25248\n25249\n25250\n25251\n25252\n25253\n25254\n25255\n25256\n25257\n25258\n25259\n25260\n25261\n25262\n25263\n25264\n25265\n25266\n25267\n25268\n25269\n25270\n25271\n25272\n25273\n25274\n25275\n25276\n25277\n25278\n25279\n25280\n25281\n25282\n25283\n25284\n25285\n25286\n25287\n25288\n25289\n25290\n25291\n25292\n25293\n25294\n25295\n25296\n25297\n25298\n25299\n25300\n25301\n25302\n25303\n25304\n25305\n25306\n25307\n25308\n25309\n25310\n25311\n25312\n25313\n25314\n25315\n25316\n25317\n25318\n25319\n25320\n25321\n25322\n25323\n25324\n25325\n25326\n25327\n25328\n25329\n25330\n25331\n25332\n25333\n25334\n25335\n25336\n25337\n25338\n25339\n25340\n25341\n25342\n25343\n25344\n25345\n25346\n25347\n25348\n25349\n25350\n25351\n25352\n25353\n25354\n25355\n25356\n25357\n25358\n25359\n25360\n25361\n25362\n25363\n25364\n25365\n25366\n25367\n25368\n25369\n25370\n25371\n25372\n25373\n25374\n25375\n25376\n25377\n25378\n25379\n25380\n25381\n25382\n25383\n25384\n25385\n25386\n25387\n25388\n25389\n25390\n25391\n25392\n25393\n25394\n25395\n25396\n25397\n25398\n25399\n25400\n25401\n25402\n25403\n25404\n25405\n25406\n25407\n25408\n25409\n25410\n25411\n25412\n25413\n25414\n25415\n25416\n25417\n25418\n25419\n25420\n25421\n25422\n25423\n25424\n25425\n25426\n25427\n25428\n25429\n25430\n25431\n25432\n25433\n25434\n25435\n25436\n25437\n25438\n25439\n25440\n25441\n25442\n25443\n25444\n25445\n25446\n25447\n25448\n25449\n25450\n25451\n25452\n25453\n25454\n25455\n25456\n25457\n25458\n25459\n25460\n25461\n25462\n25463\n25464\n25465\n25466\n25467\n25468\n25469\n25470\n25471\n25472\n25473\n25474\n25475\n25476\n25477\n25478\n25479\n25480\n25481\n25482\n25483\n25484\n25485\n25486\n25487\n25488\n25489\n25490\n25491\n25492\n25493\n25494\n25495\n25496\n25497\n25498\n25499\n25500\n25501\n25502\n25503\n25504\n25505\n25506\n25507\n25508\n25509\n25510\n25511\n25512\n25513\n25514\n25515\n25516\n25517\n25518\n25519\n25520\n25521\n25522\n25523\n25524\n25525\n25526\n25527\n25528\n25529\n25530\n25531\n25532\n25533\n25534\n25535\n25536\n25537\n25538\n25539\n25540\n25541\n25542\n25543\n25544\n25545\n25546\n25547\n25548\n25549\n25550\n25551\n25552\n25553\n25554\n25555\n25556\n25557\n25558\n25559\n25560\n25561\n25562\n25563\n25564\n25565\n25566\n25567\n25568\n25569\n25570\n25571\n25572\n25573\n25574\n25575\n25576\n25577\n25578\n25579\n25580\n25581\n25582\n25583\n25584\n25585\n25586\n25587\n25588\n25589\n25590\n25591\n25592\n25593\n25594\n25595\n25596\n25597\n25598\n25599\n25600\n25601\n25602\n25603\n25604\n25605\n25606\n25607\n25608\n25609\n25610\n25611\n25612\n25613\n25614\n25615\n25616\n25617\n25618\n25619\n25620\n25621\n25622\n25623\n25624\n25625\n25626\n25627\n25628\n25629\n25630\n25631\n25632\n25633\n25634\n25635\n25636\n25637\n25638\n25639\n25640\n25641\n25642\n25643\n25644\n25645\n25646\n25647\n25648\n25649\n25650\n25651\n25652\n25653\n25654\n25655\n25656\n25657\n25658\n25659\n25660\n25661\n25662\n25663\n25664\n25665\n25666\n25667\n25668\n25669\n25670\n25671\n25672\n25673\n25674\n25675\n25676\n25677\n25678\n25679\n25680\n25681\n25682\n25683\n25684\n25685\n25686\n25687\n25688\n25689\n25690\n25691\n25692\n25693\n25694\n25695\n25696\n25697\n25698\n25699\n25700\n25701\n25702\n25703\n25704\n25705\n25706\n25707\n25708\n25709\n25710\n25711\n25712\n25713\n25714\n25715\n25716\n25717\n25718\n25719\n25720\n25721\n25722\n25723\n25724\n25725\n25726\n25727\n25728\n25729\n25730\n25731\n25732\n25733\n25734\n25735\n25736\n25737\n25738\n25739\n25740\n25741\n25742\n25743\n25744\n25745\n25746\n25747\n25748\n25749\n25750\n25751\n25752\n25753\n25754\n25755\n25756\n25757\n25758\n25759\n25760\n25761\n25762\n25763\n25764\n25765\n25766\n25767\n25768\n25769\n25770\n25771\n25772\n25773\n25774\n25775\n25776\n25777\n25778\n25779\n25780\n25781\n25782\n25783\n25784\n25785\n25786\n25787\n25788\n25789\n25790\n25791\n25792\n25793\n25794\n25795\n25796\n25797\n25798\n25799\n25800\n25801\n25802\n25803\n25804\n25805\n25806\n25807\n25808\n25809\n25810\n25811\n25812\n25813\n25814\n25815\n25816\n25817\n25818\n25819\n25820\n25821\n25822\n25823\n25824\n25825\n25826\n25827\n25828\n25829\n25830\n25831\n25832\n25833\n25834\n25835\n25836\n25837\n25838\n25839\n25840\n25841\n25842\n25843\n25844\n25845\n25846\n25847\n25848\n25849\n25850\n25851\n25852\n25853\n25854\n25855\n25856\n25857\n25858\n25859\n25860\n25861\n25862\n25863\n25864\n25865\n25866\n25867\n25868\n25869\n25870\n25871\n25872\n25873\n25874\n25875\n25876\n25877\n25878\n25879\n25880\n25881\n25882\n25883\n25884\n25885\n25886\n25887\n25888\n25889\n25890\n25891\n25892\n25893\n25894\n25895\n25896\n25897\n25898\n25899\n25900\n25901\n25902\n25903\n25904\n25905\n25906\n25907\n25908\n25909\n25910\n25911\n25912\n25913\n25914\n25915\n25916\n25917\n25918\n25919\n25920\n25921\n25922\n25923\n25924\n25925\n25926\n25927\n25928\n25929\n25930\n25931\n25932\n25933\n25934\n25935\n25936\n25937\n25938\n25939\n25940\n25941\n25942\n25943\n25944\n25945\n25946\n25947\n25948\n25949\n25950\n25951\n25952\n25953\n25954\n25955\n25956\n25957\n25958\n25959\n25960\n25961\n25962\n25963\n25964\n25965\n25966\n25967\n25968\n25969\n25970\n25971\n25972\n25973\n25974\n25975\n25976\n25977\n25978\n25979\n25980\n25981\n25982\n25983\n25984\n25985\n25986\n25987\n25988\n25989\n25990\n25991\n25992\n25993\n25994\n25995\n25996\n25997\n25998\n25999\n26000\n26001\n26002\n26003\n26004\n26005\n26006\n26007\n26008\n26009\n26010\n26011\n26012\n26013\n26014\n26015\n26016\n26017\n26018\n26019\n26020\n26021\n26022\n26023\n26024\n26025\n26026\n26027\n26028\n26029\n26030\n26031\n26032\n26033\n26034\n26035\n26036\n26037\n26038\n26039\n26040\n26041\n26042\n26043\n26044\n26045\n26046\n26047\n26048\n26049\n26050\n26051\n26052\n26053\n26054\n26055\n26056\n26057\n26058\n26059\n26060\n26061\n26062\n26063\n26064\n26065\n26066\n26067\n26068\n26069\n26070\n26071\n26072\n26073\n26074\n26075\n26076\n26077\n26078\n26079\n26080\n26081\n26082\n26083\n26084\n26085\n26086\n26087\n26088\n26089\n26090\n26091\n26092\n26093\n26094\n26095\n26096\n26097\n26098\n26099\n26100\n26101\n26102\n26103\n26104\n26105\n26106\n26107\n26108\n26109\n26110\n26111\n26112\n26113\n26114\n26115\n26116\n26117\n26118\n26119\n26120\n26121\n26122\n26123\n26124\n26125\n26126\n26127\n26128\n26129\n26130\n26131\n26132\n26133\n26134\n26135\n26136\n26137\n26138\n26139\n26140\n26141\n26142\n26143\n26144\n26145\n26146\n26147\n26148\n26149\n26150\n26151\n26152\n26153\n26154\n26155\n26156\n26157\n26158\n26159\n26160\n26161\n26162\n26163\n26164\n26165\n26166\n26167\n26168\n26169\n26170\n26171\n26172\n26173\n26174\n26175\n26176\n26177\n26178\n26179\n26180\n26181\n26182\n26183\n26184\n26185\n26186\n26187\n26188\n26189\n26190\n26191\n26192\n26193\n26194\n26195\n26196\n26197\n26198\n26199\n26200\n26201\n26202\n26203\n26204\n26205\n26206\n26207\n26208\n26209\n26210\n26211\n26212\n26213\n26214\n26215\n26216\n26217\n26218\n26219\n26220\n26221\n26222\n26223\n26224\n26225\n26226\n26227\n26228\n26229\n26230\n26231\n26232\n26233\n26234\n26235\n26236\n26237\n26238\n26239\n26240\n26241\n26242\n26243\n26244\n26245\n26246\n26247\n26248\n26249\n26250\n26251\n26252\n26253\n26254\n26255\n26256\n26257\n26258\n26259\n26260\n26261\n26262\n26263\n26264\n26265\n26266\n26267\n26268\n26269\n26270\n26271\n26272\n26273\n26274\n26275\n26276\n26277\n26278\n26279\n26280\n26281\n26282\n26283\n26284\n26285\n26286\n26287\n26288\n26289\n26290\n26291\n26292\n26293\n26294\n26295\n26296\n26297\n26298\n26299\n26300\n26301\n26302\n26303\n26304\n26305\n26306\n26307\n26308\n26309\n26310\n26311\n26312\n26313\n26314\n26315\n26316\n26317\n26318\n26319\n26320\n26321\n26322\n26323\n26324\n26325\n26326\n26327\n26328\n26329\n26330\n26331\n26332\n26333\n26334\n26335\n26336\n26337\n26338\n26339\n26340\n26341\n26342\n26343\n26344\n26345\n26346\n26347\n26348\n26349\n26350\n26351\n26352\n26353\n26354\n26355\n26356\n26357\n26358\n26359\n26360\n26361\n26362\n26363\n26364\n26365\n26366\n26367\n26368\n26369\n26370\n26371\n26372\n26373\n26374\n26375\n26376\n26377\n26378\n26379\n26380\n26381\n26382\n26383\n26384\n26385\n26386\n26387\n26388\n26389\n26390\n26391\n26392\n26393\n26394\n26395\n26396\n26397\n26398\n26399\n26400\n26401\n26402\n26403\n26404\n26405\n26406\n26407\n26408\n26409\n26410\n26411\n26412\n26413\n26414\n26415\n26416\n26417\n26418\n26419\n26420\n26421\n26422\n26423\n26424\n26425\n26426\n26427\n26428\n26429\n26430\n26431\n26432\n26433\n26434\n26435\n26436\n26437\n26438\n26439\n26440\n26441\n26442\n26443\n26444\n26445\n26446\n26447\n26448\n26449\n26450\n26451\n26452\n26453\n26454\n26455\n26456\n26457\n26458\n26459\n26460\n26461\n26462\n26463\n26464\n26465\n26466\n26467\n26468\n26469\n26470\n26471\n26472\n26473\n26474\n26475\n26476\n26477\n26478\n26479\n26480\n26481\n26482\n26483\n26484\n26485\n26486\n26487\n26488\n26489\n26490\n26491\n26492\n26493\n26494\n26495\n26496\n26497\n26498\n26499\n26500\n26501\n26502\n26503\n26504\n26505\n26506\n26507\n26508\n26509\n26510\n26511\n26512\n26513\n26514\n26515\n26516\n26517\n26518\n26519\n26520\n26521\n26522\n26523\n26524\n26525\n26526\n26527\n26528\n26529\n26530\n26531\n26532\n26533\n26534\n26535\n26536\n26537\n26538\n26539\n26540\n26541\n26542\n26543\n26544\n26545\n26546\n26547\n26548\n26549\n26550\n26551\n26552\n26553\n26554\n26555\n26556\n26557\n26558\n26559\n26560\n26561\n26562\n26563\n26564\n26565\n26566\n26567\n26568\n26569\n26570\n26571\n26572\n26573\n26574\n26575\n26576\n26577\n26578\n26579\n26580\n26581\n26582\n26583\n26584\n26585\n26586\n26587\n26588\n26589\n26590\n26591\n26592\n26593\n26594\n26595\n26596\n26597\n26598\n26599\n26600\n26601\n26602\n26603\n26604\n26605\n26606\n26607\n26608\n26609\n26610\n26611\n26612\n26613\n26614\n26615\n26616\n26617\n26618\n26619\n26620\n26621\n26622\n26623\n26624\n26625\n26626\n26627\n26628\n26629\n26630\n26631\n26632\n26633\n26634\n26635\n26636\n26637\n26638\n26639\n26640\n26641\n26642\n26643\n26644\n26645\n26646\n26647\n26648\n26649\n26650\n26651\n26652\n26653\n26654\n26655\n26656\n26657\n26658\n26659\n26660\n26661\n26662\n26663\n26664\n26665\n26666\n26667\n26668\n26669\n26670\n26671\n26672\n26673\n26674\n26675\n26676\n26677\n26678\n26679\n26680\n26681\n26682\n26683\n26684\n26685\n26686\n26687\n26688\n26689\n26690\n26691\n26692\n26693\n26694\n26695\n26696\n26697\n26698\n26699\n26700\n26701\n26702\n26703\n26704\n26705\n26706\n26707\n26708\n26709\n26710\n26711\n26712\n26713\n26714\n26715\n26716\n26717\n26718\n26719\n26720\n26721\n26722\n26723\n26724\n26725\n26726\n26727\n26728\n26729\n26730\n26731\n26732\n26733\n26734\n26735\n26736\n26737\n26738\n26739\n26740\n26741\n26742\n26743\n26744\n26745\n26746\n26747\n26748\n26749\n26750\n26751\n26752\n26753\n26754\n26755\n26756\n26757\n26758\n26759\n26760\n26761\n26762\n26763\n26764\n26765\n26766\n26767\n26768\n26769\n26770\n26771\n26772\n26773\n26774\n26775\n26776\n26777\n26778\n26779\n26780\n26781\n26782\n26783\n26784\n26785\n26786\n26787\n26788\n26789\n26790\n26791\n26792\n26793\n26794\n26795\n26796\n26797\n26798\n26799\n26800\n26801\n26802\n26803\n26804\n26805\n26806\n26807\n26808\n26809\n26810\n26811\n26812\n26813\n26814\n26815\n26816\n26817\n26818\n26819\n26820\n26821\n26822\n26823\n26824\n26825\n26826\n26827\n26828\n26829\n26830\n26831\n26832\n26833\n26834\n26835\n26836\n26837\n26838\n26839\n26840\n26841\n26842\n26843\n26844\n26845\n26846\n26847\n26848\n26849\n26850\n26851\n26852\n26853\n26854\n26855\n26856\n26857\n26858\n26859\n26860\n26861\n26862\n26863\n26864\n26865\n26866\n26867\n26868\n26869\n26870\n26871\n26872\n26873\n26874\n26875\n26876\n26877\n26878\n26879\n26880\n26881\n26882\n26883\n26884\n26885\n26886\n26887\n26888\n26889\n26890\n26891\n26892\n26893\n26894\n26895\n26896\n26897\n26898\n26899\n26900\n26901\n26902\n26903\n26904\n26905\n26906\n26907\n26908\n26909\n26910\n26911\n26912\n26913\n26914\n26915\n26916\n26917\n26918\n26919\n26920\n26921\n26922\n26923\n26924\n26925\n26926\n26927\n26928\n26929\n26930\n26931\n26932\n26933\n26934\n26935\n26936\n26937\n26938\n26939\n26940\n26941\n26942\n26943\n26944\n26945\n26946\n26947\n26948\n26949\n26950\n26951\n26952\n26953\n26954\n26955\n26956\n26957\n26958\n26959\n26960\n26961\n26962\n26963\n26964\n26965\n26966\n26967\n26968\n26969\n26970\n26971\n26972\n26973\n26974\n26975\n26976\n26977\n26978\n26979\n26980\n26981\n26982\n26983\n26984\n26985\n26986\n26987\n26988\n26989\n26990\n26991\n26992\n26993\n26994\n26995\n26996\n26997\n26998\n26999\n27000\n27001\n27002\n27003\n27004\n27005\n27006\n27007\n27008\n27009\n27010\n27011\n27012\n27013\n27014\n27015\n27016\n27017\n27018\n27019\n27020\n27021\n27022\n27023\n27024\n27025\n27026\n27027\n27028\n27029\n27030\n27031\n27032\n27033\n27034\n27035\n27036\n27037\n27038\n27039\n27040\n27041\n27042\n27043\n27044\n27045\n27046\n27047\n27048\n27049\n27050\n27051\n27052\n27053\n27054\n27055\n27056\n27057\n27058\n27059\n27060\n27061\n27062\n27063\n27064\n27065\n27066\n27067\n27068\n27069\n27070\n27071\n27072\n27073\n27074\n27075\n27076\n27077\n27078\n27079\n27080\n27081\n27082\n27083\n27084\n27085\n27086\n27087\n27088\n27089\n27090\n27091\n27092\n27093\n27094\n27095\n27096\n27097\n27098\n27099\n27100\n27101\n27102\n27103\n27104\n27105\n27106\n27107\n27108\n27109\n27110\n27111\n27112\n27113\n27114\n27115\n27116\n27117\n27118\n27119\n27120\n27121\n27122\n27123\n27124\n27125\n27126\n27127\n27128\n27129\n27130\n27131\n27132\n27133\n27134\n27135\n27136\n27137\n27138\n27139\n27140\n27141\n27142\n27143\n27144\n27145\n27146\n27147\n27148\n27149\n27150\n27151\n27152\n27153\n27154\n27155\n27156\n27157\n27158\n27159\n27160\n27161\n27162\n27163\n27164\n27165\n27166\n27167\n27168\n27169\n27170\n27171\n27172\n27173\n27174\n27175\n27176\n27177\n27178\n27179\n27180\n27181\n27182\n27183\n27184\n27185\n27186\n27187\n27188\n27189\n27190\n27191\n27192\n27193\n27194\n27195\n27196\n27197\n27198\n27199\n27200\n27201\n27202\n27203\n27204\n27205\n27206\n27207\n27208\n27209\n27210\n27211\n27212\n27213\n27214\n27215\n27216\n27217\n27218\n27219\n27220\n27221\n27222\n27223\n27224\n27225\n27226\n27227\n27228\n27229\n27230\n27231\n27232\n27233\n27234\n27235\n27236\n27237\n27238\n27239\n27240\n27241\n27242\n27243\n27244\n27245\n27246\n27247\n27248\n27249\n27250\n27251\n27252\n27253\n27254\n27255\n27256\n27257\n27258\n27259\n27260\n27261\n27262\n27263\n27264\n27265\n27266\n27267\n27268\n27269\n27270\n27271\n27272\n27273\n27274\n27275\n27276\n27277\n27278\n27279\n27280\n27281\n27282\n27283\n27284\n27285\n27286\n27287\n27288\n27289\n27290\n27291\n27292\n27293\n27294\n27295\n27296\n27297\n27298\n27299\n27300\n27301\n27302\n27303\n27304\n27305\n27306\n27307\n27308\n27309\n27310\n27311\n27312\n27313\n27314\n27315\n27316\n27317\n27318\n27319\n27320\n27321\n27322\n27323\n27324\n27325\n27326\n27327\n27328\n27329\n27330\n27331\n27332\n27333\n27334\n27335\n27336\n27337\n27338\n27339\n27340\n27341\n27342\n27343\n27344\n27345\n27346\n27347\n27348\n27349\n27350\n27351\n27352\n27353\n27354\n27355\n27356\n27357\n27358\n27359\n27360\n27361\n27362\n27363\n27364\n27365\n27366\n27367\n27368\n27369\n27370\n27371\n27372\n27373\n27374\n27375\n27376\n27377\n27378\n27379\n27380\n27381\n27382\n27383\n27384\n27385\n27386\n27387\n27388\n27389\n27390\n27391\n27392\n27393\n27394\n27395\n27396\n27397\n27398\n27399\n27400\n27401\n27402\n27403\n27404\n27405\n27406\n27407\n27408\n27409\n27410\n27411\n27412\n27413\n27414\n27415\n27416\n27417\n27418\n27419\n27420\n27421\n27422\n27423\n27424\n27425\n27426\n27427\n27428\n27429\n27430\n27431\n27432\n27433\n27434\n27435\n27436\n27437\n27438\n27439\n27440\n27441\n27442\n27443\n27444\n27445\n27446\n27447\n27448\n27449\n27450\n27451\n27452\n27453\n27454\n27455\n27456\n27457\n27458\n27459\n27460\n27461\n27462\n27463\n27464\n27465\n27466\n27467\n27468\n27469\n27470\n27471\n27472\n27473\n27474\n27475\n27476\n27477\n27478\n27479\n27480\n27481\n27482\n27483\n27484\n27485\n27486\n27487\n27488\n27489\n27490\n27491\n27492\n27493\n27494\n27495\n27496\n27497\n27498\n27499\n27500\n27501\n27502\n27503\n27504\n27505\n27506\n27507\n27508\n27509\n27510\n27511\n27512\n27513\n27514\n27515\n27516\n27517\n27518\n27519\n27520\n27521\n27522\n27523\n27524\n27525\n27526\n27527\n27528\n27529\n27530\n27531\n27532\n27533\n27534\n27535\n27536\n27537\n27538\n27539\n27540\n27541\n27542\n27543\n27544\n27545\n27546\n27547\n27548\n27549\n27550\n27551\n27552\n27553\n27554\n27555\n27556\n27557\n27558\n27559\n27560\n27561\n27562\n27563\n27564\n27565\n27566\n27567\n27568\n27569\n27570\n27571\n27572\n27573\n27574\n27575\n27576\n27577\n27578\n27579\n27580\n27581\n27582\n27583\n27584\n27585\n27586\n27587\n27588\n27589\n27590\n27591\n27592\n27593\n27594\n27595\n27596\n27597\n27598\n27599\n27600\n27601\n27602\n27603\n27604\n27605\n27606\n27607\n27608\n27609\n27610\n27611\n27612\n27613\n27614\n27615\n27616\n27617\n27618\n27619\n27620\n27621\n27622\n27623\n27624\n27625\n27626\n27627\n27628\n27629\n27630\n27631\n27632\n27633\n27634\n27635\n27636\n27637\n27638\n27639\n27640\n27641\n27642\n27643\n27644\n27645\n27646\n27647\n27648\n27649\n27650\n27651\n27652\n27653\n27654\n27655\n27656\n27657\n27658\n27659\n27660\n27661\n27662\n27663\n27664\n27665\n27666\n27667\n27668\n27669\n27670\n27671\n27672\n27673\n27674\n27675\n27676\n27677\n27678\n27679\n27680\n27681\n27682\n27683\n27684\n27685\n27686\n27687\n27688\n27689\n27690\n27691\n27692\n27693\n27694\n27695\n27696\n27697\n27698\n27699\n27700\n27701\n27702\n27703\n27704\n27705\n27706\n27707\n27708\n27709\n27710\n27711\n27712\n27713\n27714\n27715\n27716\n27717\n27718\n27719\n27720\n27721\n27722\n27723\n27724\n27725\n27726\n27727\n27728\n27729\n27730\n27731\n27732\n27733\n27734\n27735\n27736\n27737\n27738\n27739\n27740\n27741\n27742\n27743\n27744\n27745\n27746\n27747\n27748\n27749\n27750\n27751\n27752\n27753\n27754\n27755\n27756\n27757\n27758\n27759\n27760\n27761\n27762\n27763\n27764\n27765\n27766\n27767\n27768\n27769\n27770\n27771\n27772\n27773\n27774\n27775\n27776\n27777\n27778\n27779\n27780\n27781\n27782\n27783\n27784\n27785\n27786\n27787\n27788\n27789\n27790\n27791\n27792\n27793\n27794\n27795\n27796\n27797\n27798\n27799\n27800\n27801\n27802\n27803\n27804\n27805\n27806\n27807\n27808\n27809\n27810\n27811\n27812\n27813\n27814\n27815\n27816\n27817\n27818\n27819\n27820\n27821\n27822\n27823\n27824\n27825\n27826\n27827\n27828\n27829\n27830\n27831\n27832\n27833\n27834\n27835\n27836\n27837\n27838\n27839\n27840\n27841\n27842\n27843\n27844\n27845\n27846\n27847\n27848\n27849\n27850\n27851\n27852\n27853\n27854\n27855\n27856\n27857\n27858\n27859\n27860\n27861\n27862\n27863\n27864\n27865\n27866\n27867\n27868\n27869\n27870\n27871\n27872\n27873\n27874\n27875\n27876\n27877\n27878\n27879\n27880\n27881\n27882\n27883\n27884\n27885\n27886\n27887\n27888\n27889\n27890\n27891\n27892\n27893\n27894\n27895\n27896\n27897\n27898\n27899\n27900\n27901\n27902\n27903\n27904\n27905\n27906\n27907\n27908\n27909\n27910\n27911\n27912\n27913\n27914\n27915\n27916\n27917\n27918\n27919\n27920\n27921\n27922\n27923\n27924\n27925\n27926\n27927\n27928\n27929\n27930\n27931\n27932\n27933\n27934\n27935\n27936\n27937\n27938\n27939\n27940\n27941\n27942\n27943\n27944\n27945\n27946\n27947\n27948\n27949\n27950\n27951\n27952\n27953\n27954\n27955\n27956\n27957\n27958\n27959\n27960\n27961\n27962\n27963\n27964\n27965\n27966\n27967\n27968\n27969\n27970\n27971\n27972\n27973\n27974\n27975\n27976\n27977\n27978\n27979\n27980\n27981\n27982\n27983\n27984\n27985\n27986\n27987\n27988\n27989\n27990\n27991\n27992\n27993\n27994\n27995\n27996\n27997\n27998\n27999\n28000\n28001\n28002\n28003\n28004\n28005\n28006\n28007\n28008\n28009\n28010\n28011\n28012\n28013\n28014\n28015\n28016\n28017\n28018\n28019\n28020\n28021\n28022\n28023\n28024\n28025\n28026\n28027\n28028\n28029\n28030\n28031\n28032\n28033\n28034\n28035\n28036\n28037\n28038\n28039\n28040\n28041\n28042\n28043\n28044\n28045\n28046\n28047\n28048\n28049\n28050\n28051\n28052\n28053\n28054\n28055\n28056\n28057\n28058\n28059\n28060\n28061\n28062\n28063\n28064\n28065\n28066\n28067\n28068\n28069\n28070\n28071\n28072\n28073\n28074\n28075\n28076\n28077\n28078\n28079\n28080\n28081\n28082\n28083\n28084\n28085\n28086\n28087\n28088\n28089\n28090\n28091\n28092\n28093\n28094\n28095\n28096\n28097\n28098\n28099\n28100\n28101\n28102\n28103\n28104\n28105\n28106\n28107\n28108\n28109\n28110\n28111\n28112\n28113\n28114\n28115\n28116\n28117\n28118\n28119\n28120\n28121\n28122\n28123\n28124\n28125\n28126\n28127\n28128\n28129\n28130\n28131\n28132\n28133\n28134\n28135\n28136\n28137\n28138\n28139\n28140\n28141\n28142\n28143\n28144\n28145\n28146\n28147\n28148\n28149\n28150\n28151\n28152\n28153\n28154\n28155\n28156\n28157\n28158\n28159\n28160\n28161\n28162\n28163\n28164\n28165\n28166\n28167\n28168\n28169\n28170\n28171\n28172\n28173\n28174\n28175\n28176\n28177\n28178\n28179\n28180\n28181\n28182\n28183\n28184\n28185\n28186\n28187\n28188\n28189\n28190\n28191\n28192\n28193\n28194\n28195\n28196\n28197\n28198\n28199\n28200\n28201\n28202\n28203\n28204\n28205\n28206\n28207\n28208\n28209\n28210\n28211\n28212\n28213\n28214\n28215\n28216\n28217\n28218\n28219\n28220\n28221\n28222\n28223\n28224\n28225\n28226\n28227\n28228\n28229\n28230\n28231\n28232\n28233\n28234\n28235\n28236\n28237\n28238\n28239\n28240\n28241\n28242\n28243\n28244\n28245\n28246\n28247\n28248\n28249\n28250\n28251\n28252\n28253\n28254\n28255\n28256\n28257\n28258\n28259\n28260\n28261\n28262\n28263\n28264\n28265\n28266\n28267\n28268\n28269\n28270\n28271\n28272\n28273\n28274\n28275\n28276\n28277\n28278\n28279\n28280\n28281\n28282\n28283\n28284\n28285\n28286\n28287\n28288\n28289\n28290\n28291\n28292\n28293\n28294\n28295\n28296\n28297\n28298\n28299\n28300\n28301\n28302\n28303\n28304\n28305\n28306\n28307\n28308\n28309\n28310\n28311\n28312\n28313\n28314\n28315\n28316\n28317\n28318\n28319\n28320\n28321\n28322\n28323\n28324\n28325\n28326\n28327\n28328\n28329\n28330\n28331\n28332\n28333\n28334\n28335\n28336\n28337\n28338\n28339\n28340\n28341\n28342\n28343\n28344\n28345\n28346\n28347\n28348\n28349\n28350\n28351\n28352\n28353\n28354\n28355\n28356\n28357\n28358\n28359\n28360\n28361\n28362\n28363\n28364\n28365\n28366\n28367\n28368\n28369\n28370\n28371\n28372\n28373\n28374\n28375\n28376\n28377\n28378\n28379\n28380\n28381\n28382\n28383\n28384\n28385\n28386\n28387\n28388\n28389\n28390\n28391\n28392\n28393\n28394\n28395\n28396\n28397\n28398\n28399\n28400\n28401\n28402\n28403\n28404\n28405\n28406\n28407\n28408\n28409\n28410\n28411\n28412\n28413\n28414\n28415\n28416\n28417\n28418\n28419\n28420\n28421\n28422\n28423\n28424\n28425\n28426\n28427\n28428\n28429\n28430\n28431\n28432\n28433\n28434\n28435\n28436\n28437\n28438\n28439\n28440\n28441\n28442\n28443\n28444\n28445\n28446\n28447\n28448\n28449\n28450\n28451\n28452\n28453\n28454\n28455\n28456\n28457\n28458\n28459\n28460\n28461\n28462\n28463\n28464\n28465\n28466\n28467\n28468\n28469\n28470\n28471\n28472\n28473\n28474\n28475\n28476\n28477\n28478\n28479\n28480\n28481\n28482\n28483\n28484\n28485\n28486\n28487\n28488\n28489\n28490\n28491\n28492\n28493\n28494\n28495\n28496\n28497\n28498\n28499\n28500\n28501\n28502\n28503\n28504\n28505\n28506\n28507\n28508\n28509\n28510\n28511\n28512\n28513\n28514\n28515\n28516\n28517\n28518\n28519\n28520\n28521\n28522\n28523\n28524\n28525\n28526\n28527\n28528\n28529\n28530\n28531\n28532\n28533\n28534\n28535\n28536\n28537\n28538\n28539\n28540\n28541\n28542\n28543\n28544\n28545\n28546\n28547\n28548\n28549\n28550\n28551\n28552\n28553\n28554\n28555\n28556\n28557\n28558\n28559\n28560\n28561\n28562\n28563\n28564\n28565\n28566\n28567\n28568\n28569\n28570\n28571\n28572\n28573\n28574\n28575\n28576\n28577\n28578\n28579\n28580\n28581\n28582\n28583\n28584\n28585\n28586\n28587\n28588\n28589\n28590\n28591\n28592\n28593\n28594\n28595\n28596\n28597\n28598\n28599\n28600\n28601\n28602\n28603\n28604\n28605\n28606\n28607\n28608\n28609\n28610\n28611\n28612\n28613\n28614\n28615\n28616\n28617\n28618\n28619\n28620\n28621\n28622\n28623\n28624\n28625\n28626\n28627\n28628\n28629\n28630\n28631\n28632\n28633\n28634\n28635\n28636\n28637\n28638\n28639\n28640\n28641\n28642\n28643\n28644\n28645\n28646\n28647\n28648\n28649\n28650\n28651\n28652\n28653\n28654\n28655\n28656\n28657\n28658\n28659\n28660\n28661\n28662\n28663\n28664\n28665\n28666\n28667\n28668\n28669\n28670\n28671\n28672\n28673\n28674\n28675\n28676\n28677\n28678\n28679\n28680\n28681\n28682\n28683\n28684\n28685\n28686\n28687\n28688\n28689\n28690\n28691\n28692\n28693\n28694\n28695\n28696\n28697\n28698\n28699\n28700\n28701\n28702\n28703\n28704\n28705\n28706\n28707\n28708\n28709\n28710\n28711\n28712\n28713\n28714\n28715\n28716\n28717\n28718\n28719\n28720\n28721\n28722\n28723\n28724\n28725\n28726\n28727\n28728\n28729\n28730\n28731\n28732\n28733\n28734\n28735\n28736\n28737\n28738\n28739\n28740\n28741\n28742\n28743\n28744\n28745\n28746\n28747\n28748\n28749\n28750\n28751\n28752\n28753\n28754\n28755\n28756\n28757\n28758\n28759\n28760\n28761\n28762\n28763\n28764\n28765\n28766\n28767\n28768\n28769\n28770\n28771\n28772\n28773\n28774\n28775\n28776\n28777\n28778\n28779\n28780\n28781\n28782\n28783\n28784\n28785\n28786\n28787\n28788\n28789\n28790\n28791\n28792\n28793\n28794\n28795\n28796\n28797\n28798\n28799\n28800\n28801\n28802\n28803\n28804\n28805\n28806\n28807\n28808\n28809\n28810\n28811\n28812\n28813\n28814\n28815\n28816\n28817\n28818\n28819\n28820\n28821\n28822\n28823\n28824\n28825\n28826\n28827\n28828\n28829\n28830\n28831\n28832\n28833\n28834\n28835\n28836\n28837\n28838\n28839\n28840\n28841\n28842\n28843\n28844\n28845\n28846\n28847\n28848\n28849\n28850\n28851\n28852\n28853\n28854\n28855\n28856\n28857\n28858\n28859\n28860\n28861\n28862\n28863\n28864\n28865\n28866\n28867\n28868\n28869\n28870\n28871\n28872\n28873\n28874\n28875\n28876\n28877\n28878\n28879\n28880\n28881\n28882\n28883\n28884\n28885\n28886\n28887\n28888\n28889\n28890\n28891\n28892\n28893\n28894\n28895\n28896\n28897\n28898\n28899\n28900\n28901\n28902\n28903\n28904\n28905\n28906\n28907\n28908\n28909\n28910\n28911\n28912\n28913\n28914\n28915\n28916\n28917\n28918\n28919\n28920\n28921\n28922\n28923\n28924\n28925\n28926\n28927\n28928\n28929\n28930\n28931\n28932\n28933\n28934\n28935\n28936\n28937\n28938\n28939\n28940\n28941\n28942\n28943\n28944\n28945\n28946\n28947\n28948\n28949\n28950\n28951\n28952\n28953\n28954\n28955\n28956\n28957\n28958\n28959\n28960\n28961\n28962\n28963\n28964\n28965\n28966\n28967\n28968\n28969\n28970\n28971\n28972\n28973\n28974\n28975\n28976\n28977\n28978\n28979\n28980\n28981\n28982\n28983\n28984\n28985\n28986\n28987\n28988\n28989\n28990\n28991\n28992\n28993\n28994\n28995\n28996\n28997\n28998\n28999\n29000\n29001\n29002\n29003\n29004\n29005\n29006\n29007\n29008\n29009\n29010\n29011\n29012\n29013\n29014\n29015\n29016\n29017\n29018\n29019\n29020\n29021\n29022\n29023\n29024\n29025\n29026\n29027\n29028\n29029\n29030\n29031\n29032\n29033\n29034\n29035\n29036\n29037\n29038\n29039\n29040\n29041\n29042\n29043\n29044\n29045\n29046\n29047\n29048\n29049\n29050\n29051\n29052\n29053\n29054\n29055\n29056\n29057\n29058\n29059\n29060\n29061\n29062\n29063\n29064\n29065\n29066\n29067\n29068\n29069\n29070\n29071\n29072\n29073\n29074\n29075\n29076\n29077\n29078\n29079\n29080\n29081\n29082\n29083\n29084\n29085\n29086\n29087\n29088\n29089\n29090\n29091\n29092\n29093\n29094\n29095\n29096\n29097\n29098\n29099\n29100\n29101\n29102\n29103\n29104\n29105\n29106\n29107\n29108\n29109\n29110\n29111\n29112\n29113\n29114\n29115\n29116\n29117\n29118\n29119\n29120\n29121\n29122\n29123\n29124\n29125\n29126\n29127\n29128\n29129\n29130\n29131\n29132\n29133\n29134\n29135\n29136\n29137\n29138\n29139\n29140\n29141\n29142\n29143\n29144\n29145\n29146\n29147\n29148\n29149\n29150\n29151\n29152\n29153\n29154\n29155\n29156\n29157\n29158\n29159\n29160\n29161\n29162\n29163\n29164\n29165\n29166\n29167\n29168\n29169\n29170\n29171\n29172\n29173\n29174\n29175\n29176\n29177\n29178\n29179\n29180\n29181\n29182\n29183\n29184\n29185\n29186\n29187\n29188\n29189\n29190\n29191\n29192\n29193\n29194\n29195\n29196\n29197\n29198\n29199\n29200\n29201\n29202\n29203\n29204\n29205\n29206\n29207\n29208\n29209\n29210\n29211\n29212\n29213\n29214\n29215\n29216\n29217\n29218\n29219\n29220\n29221\n29222\n29223\n29224\n29225\n29226\n29227\n29228\n29229\n29230\n29231\n29232\n29233\n29234\n29235\n29236\n29237\n29238\n29239\n29240\n29241\n29242\n29243\n29244\n29245\n29246\n29247\n29248\n29249\n29250\n29251\n29252\n29253\n29254\n29255\n29256\n29257\n29258\n29259\n29260\n29261\n29262\n29263\n29264\n29265\n29266\n29267\n29268\n29269\n29270\n29271\n29272\n29273\n29274\n29275\n29276\n29277\n29278\n29279\n29280\n29281\n29282\n29283\n29284\n29285\n29286\n29287\n29288\n29289\n29290\n29291\n29292\n29293\n29294\n29295\n29296\n29297\n29298\n29299\n29300\n29301\n29302\n29303\n29304\n29305\n29306\n29307\n29308\n29309\n29310\n29311\n29312\n29313\n29314\n29315\n29316\n29317\n29318\n29319\n29320\n29321\n29322\n29323\n29324\n29325\n29326\n29327\n29328\n29329\n29330\n29331\n29332\n29333\n29334\n29335\n29336\n29337\n29338\n29339\n29340\n29341\n29342\n29343\n29344\n29345\n29346\n29347\n29348\n29349\n29350\n29351\n29352\n29353\n29354\n29355\n29356\n29357\n29358\n29359\n29360\n29361\n29362\n29363\n29364\n29365\n29366\n29367\n29368\n29369\n29370\n29371\n29372\n29373\n29374\n29375\n29376\n29377\n29378\n29379\n29380\n29381\n29382\n29383\n29384\n29385\n29386\n29387\n29388\n29389\n29390\n29391\n29392\n29393\n29394\n29395\n29396\n29397\n29398\n29399\n29400\n29401\n29402\n29403\n29404\n29405\n29406\n29407\n29408\n29409\n29410\n29411\n29412\n29413\n29414\n29415\n29416\n29417\n29418\n29419\n29420\n29421\n29422\n29423\n29424\n29425\n29426\n29427\n29428\n29429\n29430\n29431\n29432\n29433\n29434\n29435\n29436\n29437\n29438\n29439\n29440\n29441\n29442\n29443\n29444\n29445\n29446\n29447\n29448\n29449\n29450\n29451\n29452\n29453\n29454\n29455\n29456\n29457\n29458\n29459\n29460\n29461\n29462\n29463\n29464\n29465\n29466\n29467\n29468\n29469\n29470\n29471\n29472\n29473\n29474\n29475\n29476\n29477\n29478\n29479\n29480\n29481\n29482\n29483\n29484\n29485\n29486\n29487\n29488\n29489\n29490\n29491\n29492\n29493\n29494\n29495\n29496\n29497\n29498\n29499\n29500\n29501\n29502\n29503\n29504\n29505\n29506\n29507\n29508\n29509\n29510\n29511\n29512\n29513\n29514\n29515\n29516\n29517\n29518\n29519\n29520\n29521\n29522\n29523\n29524\n29525\n29526\n29527\n29528\n29529\n29530\n29531\n29532\n29533\n29534\n29535\n29536\n29537\n29538\n29539\n29540\n29541\n29542\n29543\n29544\n29545\n29546\n29547\n29548\n29549\n29550\n29551\n29552\n29553\n29554\n29555\n29556\n29557\n29558\n29559\n29560\n29561\n29562\n29563\n29564\n29565\n29566\n29567\n29568\n29569\n29570\n29571\n29572\n29573\n29574\n29575\n29576\n29577\n29578\n29579\n29580\n29581\n29582\n29583\n29584\n29585\n29586\n29587\n29588\n29589\n29590\n29591\n29592\n29593\n29594\n29595\n29596\n29597\n29598\n29599\n29600\n29601\n29602\n29603\n29604\n29605\n29606\n29607\n29608\n29609\n29610\n29611\n29612\n29613\n29614\n29615\n29616\n29617\n29618\n29619\n29620\n29621\n29622\n29623\n29624\n29625\n29626\n29627\n29628\n29629\n29630\n29631\n29632\n29633\n29634\n29635\n29636\n29637\n29638\n29639\n29640\n29641\n29642\n29643\n29644\n29645\n29646\n29647\n29648\n29649\n29650\n29651\n29652\n29653\n29654\n29655\n29656\n29657\n29658\n29659\n29660\n29661\n29662\n29663\n29664\n29665\n29666\n29667\n29668\n29669\n29670\n29671\n29672\n29673\n29674\n29675\n29676\n29677\n29678\n29679\n29680\n29681\n29682\n29683\n29684\n29685\n29686\n29687\n29688\n29689\n29690\n29691\n29692\n29693\n29694\n29695\n29696\n29697\n29698\n29699\n29700\n29701\n29702\n29703\n29704\n29705\n29706\n29707\n29708\n29709\n29710\n29711\n29712\n29713\n29714\n29715\n29716\n29717\n29718\n29719\n29720\n29721\n29722\n29723\n29724\n29725\n29726\n29727\n29728\n29729\n29730\n29731\n29732\n29733\n29734\n29735\n29736\n29737\n29738\n29739\n29740\n29741\n29742\n29743\n29744\n29745\n29746\n29747\n29748\n29749\n29750\n29751\n29752\n29753\n29754\n29755\n29756\n29757\n29758\n29759\n29760\n29761\n29762\n29763\n29764\n29765\n29766\n29767\n29768\n29769\n29770\n29771\n29772\n29773\n29774\n29775\n29776\n29777\n29778\n29779\n29780\n29781\n29782\n29783\n29784\n29785\n29786\n29787\n29788\n29789\n29790\n29791\n29792\n29793\n29794\n29795\n29796\n29797\n29798\n29799\n29800\n29801\n29802\n29803\n29804\n29805\n29806\n29807\n29808\n29809\n29810\n29811\n29812\n29813\n29814\n29815\n29816\n29817\n29818\n29819\n29820\n29821\n29822\n29823\n29824\n29825\n29826\n29827\n29828\n29829\n29830\n29831\n29832\n29833\n29834\n29835\n29836\n29837\n29838\n29839\n29840\n29841\n29842\n29843\n29844\n29845\n29846\n29847\n29848\n29849\n29850\n29851\n29852\n29853\n29854\n29855\n29856\n29857\n29858\n29859\n29860\n29861\n29862\n29863\n29864\n29865\n29866\n29867\n29868\n29869\n29870\n29871\n29872\n29873\n29874\n29875\n29876\n29877\n29878\n29879\n29880\n29881\n29882\n29883\n29884\n29885\n29886\n29887\n29888\n29889\n29890\n29891\n29892\n29893\n29894\n29895\n29896\n29897\n29898\n29899\n29900\n29901\n29902\n29903\n29904\n29905\n29906\n29907\n29908\n29909\n29910\n29911\n29912\n29913\n29914\n29915\n29916\n29917\n29918\n29919\n29920\n29921\n29922\n29923\n29924\n29925\n29926\n29927\n29928\n29929\n29930\n29931\n29932\n29933\n29934\n29935\n29936\n29937\n29938\n29939\n29940\n29941\n29942\n29943\n29944\n29945\n29946\n29947\n29948\n29949\n29950\n29951\n29952\n29953\n29954\n29955\n29956\n29957\n29958\n29959\n29960\n29961\n29962\n29963\n29964\n29965\n29966\n29967\n29968\n29969\n29970\n29971\n29972\n29973\n29974\n29975\n29976\n29977\n29978\n29979\n29980\n29981\n29982\n29983\n29984\n29985\n29986\n29987\n29988\n29989\n29990\n29991\n29992\n29993\n29994\n29995\n29996\n29997\n29998\n29999' \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test11.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test11.arff new file mode 100644 index 0000000000000000000000000000000000000000..5e26109bf5785ad8b6f03d2c35cd4ecb48507c9d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test11.arff @@ -0,0 +1,11 @@ +@RELATION test11 + +@ATTRIBUTE attr0 REAL +@ATTRIBUTE attr1 REAL +@ATTRIBUTE attr2 REAL +@ATTRIBUTE attr3 REAL +@ATTRIBUTE class { class0, class1, class2, class3 } +@DATA +0.1, 0.2, 0.3, 0.4,class1 +-0.1, -0.2, -0.3, -0.4,class2 +1, 2, 3, 4,class3 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test2.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test2.arff new file mode 100644 index 0000000000000000000000000000000000000000..07d0ef26481f0facc3c687fd56c4e9a907786716 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test2.arff @@ -0,0 +1,15 @@ +@RELATION test2 + +@ATTRIBUTE attr0 REAL +@ATTRIBUTE attr1 real +@ATTRIBUTE attr2 integer +@ATTRIBUTE attr3 Integer +@ATTRIBUTE attr4 Numeric +@ATTRIBUTE attr5 numeric +@ATTRIBUTE attr6 string +@ATTRIBUTE attr7 STRING +@ATTRIBUTE attr8 {bla} +@ATTRIBUTE attr9 {bla, bla} + +@DATA +0.1, 0.2, 0.3, 0.4,class1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test3.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test3.arff new file mode 100644 index 0000000000000000000000000000000000000000..bb1b440c2a219137492be75ca778cb8ab39aee90 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test3.arff @@ -0,0 +1,6 @@ +@RELATION test3 + +@ATTRIBUTE attr0 crap + +@DATA +0.1, 0.2, 0.3, 0.4,class1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test4.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test4.arff new file mode 100644 index 0000000000000000000000000000000000000000..a76898886aefb6d4667b218cf1db3a263af24324 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test4.arff @@ -0,0 +1,11 @@ +@RELATION test5 + +@ATTRIBUTE attr0 REAL +@ATTRIBUTE attr1 REAL +@ATTRIBUTE attr2 REAL +@ATTRIBUTE attr3 REAL +@ATTRIBUTE class {class0, class1, class2, class3} +@DATA +0.1, 0.2, 0.3, 0.4,class1 +-0.1, -0.2, -0.3, -0.4,class2 +1, 2, 3, 4,class3 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test5.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test5.arff new file mode 100644 index 0000000000000000000000000000000000000000..af405d41baf8a58058bb53019b464e7209f65c25 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test5.arff @@ -0,0 +1,26 @@ +@RELATION test4 + +@ATTRIBUTE attr0 REAL +@ATTRIBUTE attr1 REAL +@ATTRIBUTE attr2 REAL +@ATTRIBUTE attr3 REAL +@ATTRIBUTE class {class0, class1, class2, class3} + +@DATA + +% lsdflkjhaksjdhf + +% lsdflkjhaksjdhf + +0.1, 0.2, 0.3, 0.4,class1 +% laksjdhf + +% lsdflkjhaksjdhf +-0.1, -0.2, -0.3, -0.4,class2 + +% lsdflkjhaksjdhf +% lsdflkjhaksjdhf + +% lsdflkjhaksjdhf + +1, 2, 3, 4,class3 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test6.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test6.arff new file mode 100644 index 0000000000000000000000000000000000000000..eb1963ea069ccc6489ebdf5d17ec0826c4d3a949 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test6.arff @@ -0,0 +1,12 @@ +@RELATION test6 + +@ATTRIBUTE attr0 REAL +@ATTRIBUTE attr1 REAL +@ATTRIBUTE attr2 REAL +@ATTRIBUTE attr3 REAL +@ATTRIBUTE class {C} + +@DATA +0.1, 0.2, 0.3, 0.4,C +-0.1, -0.2, -0.3, -0.4,C +1, 2, 3, 4,C diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test7.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test7.arff new file mode 100644 index 0000000000000000000000000000000000000000..ebfed767bd928a17ae2caef6a1561b9c68db8783 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test7.arff @@ -0,0 +1,15 @@ +@RELATION test7 + +@ATTRIBUTE attr_year DATE yyyy +@ATTRIBUTE attr_month DATE yyyy-MM +@ATTRIBUTE attr_date DATE yyyy-MM-dd +@ATTRIBUTE attr_datetime_local DATE "yyyy-MM-dd HH:mm" +@ATTRIBUTE attr_datetime_missing DATE "yyyy-MM-dd HH:mm" + +@DATA +1999,1999-01,1999-01-31,"1999-01-31 00:01",? +2004,2004-12,2004-12-01,"2004-12-01 23:59","2004-12-01 23:59" +1817,1817-04,1817-04-28,"1817-04-28 13:00",? +2100,2100-09,2100-09-10,"2100-09-10 12:00",? +2013,2013-11,2013-11-30,"2013-11-30 04:55","2013-11-30 04:55" +1631,1631-10,1631-10-15,"1631-10-15 20:04","1631-10-15 20:04" \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test8.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test8.arff new file mode 100644 index 0000000000000000000000000000000000000000..d03687cfd4bdf3b26d7d1868eb123bc38b7140a5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test8.arff @@ -0,0 +1,12 @@ +@RELATION test8 + +@ATTRIBUTE attr_datetime_utc DATE "yyyy-MM-dd HH:mm Z" +@ATTRIBUTE attr_datetime_full DATE "yy-MM-dd HH:mm:ss z" + +@DATA +"1999-01-31 00:01 UTC","99-01-31 00:01:08 +0430" +"2004-12-01 23:59 UTC","04-12-01 23:59:59 -0800" +"1817-04-28 13:00 UTC","17-04-28 13:00:33 +1000" +"2100-09-10 12:00 UTC","21-09-10 12:00:21 -0300" +"2013-11-30 04:55 UTC","13-11-30 04:55:48 -1100" +"1631-10-15 20:04 UTC","31-10-15 20:04:10 +0000" \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test9.arff b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test9.arff new file mode 100644 index 0000000000000000000000000000000000000000..6e12f761b3dd1f56488b84660b676302ac8dd6b3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/data/test9.arff @@ -0,0 +1,14 @@ +@RELATION test9 + +@ATTRIBUTE attr_date_number RELATIONAL + @ATTRIBUTE attr_date DATE "yyyy-MM-dd" + @ATTRIBUTE attr_number INTEGER +@END attr_date_number + +@DATA +"1999-01-31 1\n1935-11-27 10" +"2004-12-01 2\n1942-08-13 20" +"1817-04-28 3" +"2100-09-10 4\n1957-04-17 40\n1721-01-14 400" +"2013-11-30 5" +"1631-10-15 6" \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/test_arffread.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/test_arffread.py new file mode 100644 index 0000000000000000000000000000000000000000..62ac0ad52fb99684e6469b6cc13dcc165b3bb633 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/arff/tests/test_arffread.py @@ -0,0 +1,421 @@ +import datetime +import os +import sys +from os.path import join as pjoin + +from io import StringIO + +import numpy as np + +from numpy.testing import (assert_array_almost_equal, + assert_array_equal, assert_equal, assert_) +from pytest import raises as assert_raises + +from scipy.io.arff import loadarff +from scipy.io.arff._arffread import read_header, ParseArffError + + +data_path = pjoin(os.path.dirname(__file__), 'data') + +test1 = pjoin(data_path, 'test1.arff') +test2 = pjoin(data_path, 'test2.arff') +test3 = pjoin(data_path, 'test3.arff') + +test4 = pjoin(data_path, 'test4.arff') +test5 = pjoin(data_path, 'test5.arff') +test6 = pjoin(data_path, 'test6.arff') +test7 = pjoin(data_path, 'test7.arff') +test8 = pjoin(data_path, 'test8.arff') +test9 = pjoin(data_path, 'test9.arff') +test10 = pjoin(data_path, 'test10.arff') +test11 = pjoin(data_path, 'test11.arff') +test_quoted_nominal = pjoin(data_path, 'quoted_nominal.arff') +test_quoted_nominal_spaces = pjoin(data_path, 'quoted_nominal_spaces.arff') + +expect4_data = [(0.1, 0.2, 0.3, 0.4, 'class1'), + (-0.1, -0.2, -0.3, -0.4, 'class2'), + (1, 2, 3, 4, 'class3')] +expected_types = ['numeric', 'numeric', 'numeric', 'numeric', 'nominal'] + +missing = pjoin(data_path, 'missing.arff') +expect_missing_raw = np.array([[1, 5], [2, 4], [np.nan, np.nan]]) +expect_missing = np.empty(3, [('yop', float), ('yap', float)]) +expect_missing['yop'] = expect_missing_raw[:, 0] +expect_missing['yap'] = expect_missing_raw[:, 1] + + +class TestData: + def test1(self): + # Parsing trivial file with nothing. + self._test(test4) + + def test2(self): + # Parsing trivial file with some comments in the data section. + self._test(test5) + + def test3(self): + # Parsing trivial file with nominal attribute of 1 character. + self._test(test6) + + def test4(self): + # Parsing trivial file with trailing spaces in attribute declaration. + self._test(test11) + + def _test(self, test_file): + data, meta = loadarff(test_file) + for i in range(len(data)): + for j in range(4): + assert_array_almost_equal(expect4_data[i][j], data[i][j]) + assert_equal(meta.types(), expected_types) + + def test_filelike(self): + # Test reading from file-like object (StringIO) + with open(test1) as f1: + data1, meta1 = loadarff(f1) + with open(test1) as f2: + data2, meta2 = loadarff(StringIO(f2.read())) + assert_(data1 == data2) + assert_(repr(meta1) == repr(meta2)) + + def test_path(self): + # Test reading from `pathlib.Path` object + from pathlib import Path + + with open(test1) as f1: + data1, meta1 = loadarff(f1) + + data2, meta2 = loadarff(Path(test1)) + + assert_(data1 == data2) + assert_(repr(meta1) == repr(meta2)) + + +class TestMissingData: + def test_missing(self): + data, meta = loadarff(missing) + for i in ['yop', 'yap']: + assert_array_almost_equal(data[i], expect_missing[i]) + + +class TestNoData: + def test_nodata(self): + # The file nodata.arff has no data in the @DATA section. + # Reading it should result in an array with length 0. + nodata_filename = os.path.join(data_path, 'nodata.arff') + data, meta = loadarff(nodata_filename) + if sys.byteorder == 'big': + end = '>' + else: + end = '<' + expected_dtype = np.dtype([('sepallength', f'{end}f8'), + ('sepalwidth', f'{end}f8'), + ('petallength', f'{end}f8'), + ('petalwidth', f'{end}f8'), + ('class', 'S15')]) + assert_equal(data.dtype, expected_dtype) + assert_equal(data.size, 0) + + +class TestHeader: + def test_type_parsing(self): + # Test parsing type of attribute from their value. + with open(test2) as ofile: + rel, attrs = read_header(ofile) + + expected = ['numeric', 'numeric', 'numeric', 'numeric', 'numeric', + 'numeric', 'string', 'string', 'nominal', 'nominal'] + + for i in range(len(attrs)): + assert_(attrs[i].type_name == expected[i]) + + def test_badtype_parsing(self): + # Test parsing wrong type of attribute from their value. + def badtype_read(): + with open(test3) as ofile: + _, _ = read_header(ofile) + + assert_raises(ParseArffError, badtype_read) + + def test_fullheader1(self): + # Parsing trivial header with nothing. + with open(test1) as ofile: + rel, attrs = read_header(ofile) + + # Test relation + assert_(rel == 'test1') + + # Test numerical attributes + assert_(len(attrs) == 5) + for i in range(4): + assert_(attrs[i].name == f'attr{i}') + assert_(attrs[i].type_name == 'numeric') + + # Test nominal attribute + assert_(attrs[4].name == 'class') + assert_(attrs[4].values == ('class0', 'class1', 'class2', 'class3')) + + def test_dateheader(self): + with open(test7) as ofile: + rel, attrs = read_header(ofile) + + assert_(rel == 'test7') + + assert_(len(attrs) == 5) + + assert_(attrs[0].name == 'attr_year') + assert_(attrs[0].date_format == '%Y') + + assert_(attrs[1].name == 'attr_month') + assert_(attrs[1].date_format == '%Y-%m') + + assert_(attrs[2].name == 'attr_date') + assert_(attrs[2].date_format == '%Y-%m-%d') + + assert_(attrs[3].name == 'attr_datetime_local') + assert_(attrs[3].date_format == '%Y-%m-%d %H:%M') + + assert_(attrs[4].name == 'attr_datetime_missing') + assert_(attrs[4].date_format == '%Y-%m-%d %H:%M') + + def test_dateheader_unsupported(self): + def read_dateheader_unsupported(): + with open(test8) as ofile: + _, _ = read_header(ofile) + + assert_raises(ValueError, read_dateheader_unsupported) + + +class TestDateAttribute: + def setup_method(self): + self.data, self.meta = loadarff(test7) + + def test_year_attribute(self): + expected = np.array([ + '1999', + '2004', + '1817', + '2100', + '2013', + '1631' + ], dtype='datetime64[Y]') + + assert_array_equal(self.data["attr_year"], expected) + + def test_month_attribute(self): + expected = np.array([ + '1999-01', + '2004-12', + '1817-04', + '2100-09', + '2013-11', + '1631-10' + ], dtype='datetime64[M]') + + assert_array_equal(self.data["attr_month"], expected) + + def test_date_attribute(self): + expected = np.array([ + '1999-01-31', + '2004-12-01', + '1817-04-28', + '2100-09-10', + '2013-11-30', + '1631-10-15' + ], dtype='datetime64[D]') + + assert_array_equal(self.data["attr_date"], expected) + + def test_datetime_local_attribute(self): + expected = np.array([ + datetime.datetime(year=1999, month=1, day=31, hour=0, minute=1), + datetime.datetime(year=2004, month=12, day=1, hour=23, minute=59), + datetime.datetime(year=1817, month=4, day=28, hour=13, minute=0), + datetime.datetime(year=2100, month=9, day=10, hour=12, minute=0), + datetime.datetime(year=2013, month=11, day=30, hour=4, minute=55), + datetime.datetime(year=1631, month=10, day=15, hour=20, minute=4) + ], dtype='datetime64[m]') + + assert_array_equal(self.data["attr_datetime_local"], expected) + + def test_datetime_missing(self): + expected = np.array([ + 'nat', + '2004-12-01T23:59', + 'nat', + 'nat', + '2013-11-30T04:55', + '1631-10-15T20:04' + ], dtype='datetime64[m]') + + assert_array_equal(self.data["attr_datetime_missing"], expected) + + def test_datetime_timezone(self): + assert_raises(ParseArffError, loadarff, test8) + + +class TestRelationalAttribute: + def setup_method(self): + self.data, self.meta = loadarff(test9) + + def test_attributes(self): + assert_equal(len(self.meta._attributes), 1) + + relational = list(self.meta._attributes.values())[0] + + assert_equal(relational.name, 'attr_date_number') + assert_equal(relational.type_name, 'relational') + assert_equal(len(relational.attributes), 2) + assert_equal(relational.attributes[0].name, + 'attr_date') + assert_equal(relational.attributes[0].type_name, + 'date') + assert_equal(relational.attributes[1].name, + 'attr_number') + assert_equal(relational.attributes[1].type_name, + 'numeric') + + def test_data(self): + dtype_instance = [('attr_date', 'datetime64[D]'), + ('attr_number', np.float64)] + + expected = [ + np.array([('1999-01-31', 1), ('1935-11-27', 10)], + dtype=dtype_instance), + np.array([('2004-12-01', 2), ('1942-08-13', 20)], + dtype=dtype_instance), + np.array([('1817-04-28', 3)], + dtype=dtype_instance), + np.array([('2100-09-10', 4), ('1957-04-17', 40), + ('1721-01-14', 400)], + dtype=dtype_instance), + np.array([('2013-11-30', 5)], + dtype=dtype_instance), + np.array([('1631-10-15', 6)], + dtype=dtype_instance) + ] + + for i in range(len(self.data["attr_date_number"])): + assert_array_equal(self.data["attr_date_number"][i], + expected[i]) + + +class TestRelationalAttributeLong: + def setup_method(self): + self.data, self.meta = loadarff(test10) + + def test_attributes(self): + assert_equal(len(self.meta._attributes), 1) + + relational = list(self.meta._attributes.values())[0] + + assert_equal(relational.name, 'attr_relational') + assert_equal(relational.type_name, 'relational') + assert_equal(len(relational.attributes), 1) + assert_equal(relational.attributes[0].name, + 'attr_number') + assert_equal(relational.attributes[0].type_name, 'numeric') + + def test_data(self): + dtype_instance = [('attr_number', np.float64)] + + expected = np.array([(n,) for n in range(30000)], + dtype=dtype_instance) + + assert_array_equal(self.data["attr_relational"][0], + expected) + + +class TestQuotedNominal: + """ + Regression test for issue #10232: + + Exception in loadarff with quoted nominal attributes. + """ + + def setup_method(self): + self.data, self.meta = loadarff(test_quoted_nominal) + + def test_attributes(self): + assert_equal(len(self.meta._attributes), 2) + + age, smoker = self.meta._attributes.values() + + assert_equal(age.name, 'age') + assert_equal(age.type_name, 'numeric') + assert_equal(smoker.name, 'smoker') + assert_equal(smoker.type_name, 'nominal') + assert_equal(smoker.values, ['yes', 'no']) + + def test_data(self): + + age_dtype_instance = np.float64 + smoker_dtype_instance = '' (big endian) + +''' +import sys + +__all__ = [ + 'aliases', 'native_code', 'swapped_code', + 'sys_is_le', 'to_numpy_code' +] + +sys_is_le = sys.byteorder == 'little' +native_code = sys_is_le and '<' or '>' +swapped_code = sys_is_le and '>' or '<' + +aliases = {'little': ('little', '<', 'l', 'le'), + 'big': ('big', '>', 'b', 'be'), + 'native': ('native', '='), + 'swapped': ('swapped', 'S')} + + +def to_numpy_code(code): + """ + Convert various order codings to NumPy format. + + Parameters + ---------- + code : str + The code to convert. It is converted to lower case before parsing. + Legal values are: + 'little', 'big', 'l', 'b', 'le', 'be', '<', '>', 'native', '=', + 'swapped', 's'. + + Returns + ------- + out_code : {'<', '>'} + Here '<' is the numpy dtype code for little endian, + and '>' is the code for big endian. + + Examples + -------- + >>> import sys + >>> from scipy.io.matlab._byteordercodes import to_numpy_code + >>> sys_is_le = (sys.byteorder == 'little') + >>> sys_is_le + True + >>> to_numpy_code('big') + '>' + >>> to_numpy_code('little') + '<' + >>> nc = to_numpy_code('native') + >>> nc == '<' if sys_is_le else nc == '>' + True + >>> sc = to_numpy_code('swapped') + >>> sc == '>' if sys_is_le else sc == '<' + True + + """ + code = code.lower() + if code is None: + return native_code + if code in aliases['little']: + return '<' + elif code in aliases['big']: + return '>' + elif code in aliases['native']: + return native_code + elif code in aliases['swapped']: + return swapped_code + else: + raise ValueError( + f'We cannot handle byte order {code}') diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d021ab75d55a835fd8150aa930be5172fe6679 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio.py @@ -0,0 +1,377 @@ +""" +Module for reading and writing matlab (TM) .mat files +""" +# Authors: Travis Oliphant, Matthew Brett + +from contextlib import contextmanager + +from ._miobase import _get_matfile_version, docfiller +from ._mio4 import MatFile4Reader, MatFile4Writer +from ._mio5 import MatFile5Reader, MatFile5Writer + +__all__ = ['loadmat', 'savemat', 'whosmat'] + + +@contextmanager +def _open_file_context(file_like, appendmat, mode='rb'): + f, opened = _open_file(file_like, appendmat, mode) + try: + yield f + finally: + if opened: + f.close() + + +def _open_file(file_like, appendmat, mode='rb'): + """ + Open `file_like` and return as file-like object. First, check if object is + already file-like; if so, return it as-is. Otherwise, try to pass it + to open(). If that fails, and `file_like` is a string, and `appendmat` is true, + append '.mat' and try again. + """ + reqs = {'read'} if set(mode) & set('r+') else set() + if set(mode) & set('wax+'): + reqs.add('write') + if reqs.issubset(dir(file_like)): + return file_like, False + + try: + return open(file_like, mode), True + except OSError as e: + # Probably "not found" + if isinstance(file_like, str): + if appendmat and not file_like.endswith('.mat'): + file_like += '.mat' + return open(file_like, mode), True + else: + raise OSError( + 'Reader needs file name or open file-like object' + ) from e + + +@docfiller +def mat_reader_factory(file_name, appendmat=True, **kwargs): + """ + Create reader for matlab .mat format files. + + Parameters + ---------- + %(file_arg)s + %(append_arg)s + %(load_args)s + %(struct_arg)s + + Returns + ------- + matreader : MatFileReader object + Initialized instance of MatFileReader class matching the mat file + type detected in `filename`. + file_opened : bool + Whether the file was opened by this routine. + + """ + byte_stream, file_opened = _open_file(file_name, appendmat) + mjv, mnv = _get_matfile_version(byte_stream) + if mjv == 0: + return MatFile4Reader(byte_stream, **kwargs), file_opened + elif mjv == 1: + return MatFile5Reader(byte_stream, **kwargs), file_opened + elif mjv == 2: + raise NotImplementedError('Please use HDF reader for matlab v7.3 ' + 'files, e.g. h5py') + else: + raise TypeError(f'Did not recognize version {mjv}') + + +@docfiller +def loadmat(file_name, mdict=None, appendmat=True, *, spmatrix=True, **kwargs): + """ + Load MATLAB file. + + Parameters + ---------- + file_name : str + Name of the mat file (do not need .mat extension if + appendmat==True). Can also pass open file-like object. + mdict : dict, optional + Dictionary in which to insert matfile variables. + appendmat : bool, optional + True to append the .mat extension to the end of the given + filename, if not already present. Default is True. + spmatrix : bool, optional (default: True) + If ``True``, return sparse matrix. Otherwise return sparse array. + Format is `COO` for MatFile 4 and `CSC` for MatFile 5. + Only relevant for sparse variables. + byte_order : str or None, optional + None by default, implying byte order guessed from mat + file. Otherwise can be one of ('native', '=', 'little', '<', + 'BIG', '>'). + mat_dtype : bool, optional + If True, return arrays in same dtype as would be loaded into + MATLAB (instead of the dtype with which they are saved). + squeeze_me : bool, optional + Whether to squeeze unit matrix dimensions or not. + chars_as_strings : bool, optional + Whether to convert char arrays to string arrays. + matlab_compatible : bool, optional + Returns matrices as would be loaded by MATLAB (implies + squeeze_me=False, chars_as_strings=False, mat_dtype=True, + struct_as_record=True). + struct_as_record : bool, optional + Whether to load MATLAB structs as NumPy record arrays, or as + old-style NumPy arrays with dtype=object. Setting this flag to + False replicates the behavior of scipy version 0.7.x (returning + NumPy object arrays). The default setting is True, because it + allows easier round-trip load and save of MATLAB files. + verify_compressed_data_integrity : bool, optional + Whether the length of compressed sequences in the MATLAB file + should be checked, to ensure that they are not longer than we expect. + It is advisable to enable this (the default) because overlong + compressed sequences in MATLAB files generally indicate that the + files have experienced some sort of corruption. + variable_names : None or sequence + If None (the default) - read all variables in file. Otherwise, + `variable_names` should be a sequence of strings, giving names of the + MATLAB variables to read from the file. The reader will skip any + variable with a name not in this sequence, possibly saving some read + processing. + simplify_cells : False, optional + If True, return a simplified dict structure (which is useful if the mat + file contains cell arrays). Note that this only affects the structure + of the result and not its contents (which is identical for both output + structures). If True, this automatically sets `struct_as_record` to + False and `squeeze_me` to True, which is required to simplify cells. + uint16_codec : str, optional + The codec to use for decoding characters, which are stored as uint16 + values. The default uses the system encoding, but this can be manually + set to other values such as 'ascii', 'latin1', and 'utf-8'. This + parameter is relevant only for files stored as v6 and above, and not + for files stored as v4. + + Returns + ------- + mat_dict : dict + dictionary with variable names as keys, and loaded matrices as values. + + Notes + ----- + v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported. + + You will need an HDF5 Python library to read MATLAB 7.3 format mat + files. Because SciPy does not supply one, we do not implement the + HDF5 / 7.3 interface here. + + Examples + -------- + >>> from os.path import dirname, join as pjoin + >>> import scipy.io as sio + + Get the filename for an example .mat file from the tests/data directory. + + >>> data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data') + >>> mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat') + + Load the .mat file contents. + + >>> mat_contents = sio.loadmat(mat_fname, spmatrix=False) + + The result is a dictionary, one key/value pair for each variable: + + >>> sorted(mat_contents.keys()) + ['__globals__', '__header__', '__version__', 'testdouble'] + >>> mat_contents['testdouble'] + array([[0. , 0.78539816, 1.57079633, 2.35619449, 3.14159265, + 3.92699082, 4.71238898, 5.49778714, 6.28318531]]) + + By default SciPy reads MATLAB structs as structured NumPy arrays where the + dtype fields are of type `object` and the names correspond to the MATLAB + struct field names. This can be disabled by setting the optional argument + `struct_as_record=False`. + + Get the filename for an example .mat file that contains a MATLAB struct + called `teststruct` and load the contents. + + >>> matstruct_fname = pjoin(data_dir, 'teststruct_7.4_GLNX86.mat') + >>> matstruct_contents = sio.loadmat(matstruct_fname) + >>> teststruct = matstruct_contents['teststruct'] + >>> teststruct.dtype + dtype([('stringfield', 'O'), ('doublefield', 'O'), ('complexfield', 'O')]) + + The size of the structured array is the size of the MATLAB struct, not the + number of elements in any particular field. The shape defaults to 2-D + unless the optional argument `squeeze_me=True`, in which case all length 1 + dimensions are removed. + + >>> teststruct.size + 1 + >>> teststruct.shape + (1, 1) + + Get the 'stringfield' of the first element in the MATLAB struct. + + >>> teststruct[0, 0]['stringfield'] + array(['Rats live on no evil star.'], + dtype='>> teststruct['doublefield'][0, 0] + array([[ 1.41421356, 2.71828183, 3.14159265]]) + + Load the MATLAB struct, squeezing out length 1 dimensions, and get the item + from the 'complexfield'. + + >>> matstruct_squeezed = sio.loadmat(matstruct_fname, squeeze_me=True) + >>> matstruct_squeezed['teststruct'].shape + () + >>> matstruct_squeezed['teststruct']['complexfield'].shape + () + >>> matstruct_squeezed['teststruct']['complexfield'].item() + array([ 1.41421356+1.41421356j, 2.71828183+2.71828183j, + 3.14159265+3.14159265j]) + """ + variable_names = kwargs.pop('variable_names', None) + with _open_file_context(file_name, appendmat) as f: + MR, _ = mat_reader_factory(f, **kwargs) + matfile_dict = MR.get_variables(variable_names) + if spmatrix: + from scipy.sparse import issparse, coo_matrix, csc_matrix + for name, var in list(matfile_dict.items()): + if issparse(var): + fmt_matrix = coo_matrix if var.format == "coo" else csc_matrix + matfile_dict[name] = fmt_matrix(var) + + if mdict is not None: + mdict.update(matfile_dict) + else: + mdict = matfile_dict + + return mdict + + +@docfiller +def savemat(file_name, mdict, + appendmat=True, + format='5', + long_field_names=False, + do_compression=False, + oned_as='row'): + """ + Save a dictionary of names and arrays into a MATLAB-style .mat file. + + This saves the array objects in the given dictionary to a MATLAB- + style .mat file. + + Parameters + ---------- + file_name : str or file-like object + Name of the .mat file (.mat extension not needed if ``appendmat == + True``). + Can also pass open file_like object. + mdict : dict + Dictionary from which to save matfile variables. Note that if this dict + has a key starting with ``_`` or a sub-dict has a key starting with ``_`` + or a digit, these key's items will not be saved in the mat file and + `MatWriteWarning` will be issued. + appendmat : bool, optional + True (the default) to append the .mat extension to the end of the + given filename, if not already present. + format : {'5', '4'}, string, optional + '5' (the default) for MATLAB 5 and up (to 7.2), + '4' for MATLAB 4 .mat files. + long_field_names : bool, optional + False (the default) - maximum field name length in a structure is + 31 characters which is the documented maximum length. + True - maximum field name length in a structure is 63 characters + which works for MATLAB 7.6+. + do_compression : bool, optional + Whether or not to compress matrices on write. Default is False. + oned_as : {'row', 'column'}, optional + If 'column', write 1-D NumPy arrays as column vectors. + If 'row', write 1-D NumPy arrays as row vectors. + + Examples + -------- + >>> from scipy.io import savemat + >>> import numpy as np + >>> a = np.arange(20) + >>> mdic = {"a": a, "label": "experiment"} + >>> mdic + {'a': array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19]), + 'label': 'experiment'} + >>> savemat("matlab_matrix.mat", mdic) + """ + with _open_file_context(file_name, appendmat, 'wb') as file_stream: + if format == '4': + if long_field_names: + message = "Long field names are not available for version 4 files" + raise ValueError(message) + MW = MatFile4Writer(file_stream, oned_as) + elif format == '5': + MW = MatFile5Writer(file_stream, + do_compression=do_compression, + unicode_strings=True, + long_field_names=long_field_names, + oned_as=oned_as) + else: + raise ValueError("Format should be '4' or '5'") + MW.put_variables(mdict) + + +@docfiller +def whosmat(file_name, appendmat=True, **kwargs): + """ + List variables inside a MATLAB file. + + Parameters + ---------- + %(file_arg)s + %(append_arg)s + %(load_args)s + %(struct_arg)s + + Returns + ------- + variables : list of tuples + A list of tuples, where each tuple holds the matrix name (a string), + its shape (tuple of ints), and its data class (a string). + Possible data classes are: int8, uint8, int16, uint16, int32, uint32, + int64, uint64, single, double, cell, struct, object, char, sparse, + function, opaque, logical, unknown. + + Notes + ----- + v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported. + + You will need an HDF5 python library to read matlab 7.3 format mat + files (e.g. h5py). Because SciPy does not supply one, we do not implement the + HDF5 / 7.3 interface here. + + .. versionadded:: 0.12.0 + + Examples + -------- + >>> from io import BytesIO + >>> import numpy as np + >>> from scipy.io import savemat, whosmat + + Create some arrays, and use `savemat` to write them to a ``BytesIO`` + instance. + + >>> a = np.array([[10, 20, 30], [11, 21, 31]], dtype=np.int32) + >>> b = np.geomspace(1, 10, 5) + >>> f = BytesIO() + >>> savemat(f, {'a': a, 'b': b}) + + Use `whosmat` to inspect ``f``. Each tuple in the output list gives + the name, shape and data type of the array in ``f``. + + >>> whosmat(f) + [('a', (2, 3), 'int32'), ('b', (1, 5), 'double')] + + """ + with _open_file_context(file_name, appendmat) as f: + ML, file_opened = mat_reader_factory(f, **kwargs) + variables = ML.list_variables() + return variables diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio4.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio4.py new file mode 100644 index 0000000000000000000000000000000000000000..edce30ee3c85ca22e3660952bc4558ba12edac16 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio4.py @@ -0,0 +1,632 @@ +''' Classes for read / write of matlab (TM) 4 files +''' +import sys +import warnings +import math +from operator import mul + +import numpy as np + +import scipy.sparse + +from ._miobase import (MatFileReader, docfiller, matdims, read_dtype, + convert_dtypes, arr_to_chars, arr_dtype_number) + +from ._mio_utils import squeeze_element, chars_to_strings +from functools import reduce + + +__all__ = [ + 'MatFile4Reader', 'MatFile4Writer', 'SYS_LITTLE_ENDIAN', + 'VarHeader4', 'VarReader4', 'VarWriter4', 'arr_to_2d', 'mclass_info', + 'mdtypes_template', 'miDOUBLE', 'miINT16', 'miINT32', 'miSINGLE', + 'miUINT16', 'miUINT8', 'mxCHAR_CLASS', 'mxFULL_CLASS', 'mxSPARSE_CLASS', + 'np_to_mtypes', 'order_codes' +] + + +SYS_LITTLE_ENDIAN = sys.byteorder == 'little' + +miDOUBLE = 0 +miSINGLE = 1 +miINT32 = 2 +miINT16 = 3 +miUINT16 = 4 +miUINT8 = 5 + +mdtypes_template = { + miDOUBLE: 'f8', + miSINGLE: 'f4', + miINT32: 'i4', + miINT16: 'i2', + miUINT16: 'u2', + miUINT8: 'u1', + 'header': [('mopt', 'i4'), + ('mrows', 'i4'), + ('ncols', 'i4'), + ('imagf', 'i4'), + ('namlen', 'i4')], + 'U1': 'U1', + } + +np_to_mtypes = { + 'f8': miDOUBLE, + 'c32': miDOUBLE, + 'c24': miDOUBLE, + 'c16': miDOUBLE, + 'f4': miSINGLE, + 'c8': miSINGLE, + 'i4': miINT32, + 'i2': miINT16, + 'u2': miUINT16, + 'u1': miUINT8, + 'S1': miUINT8, + } + +# matrix classes +mxFULL_CLASS = 0 +mxCHAR_CLASS = 1 +mxSPARSE_CLASS = 2 + +order_codes = { + 0: '<', + 1: '>', + 2: 'VAX D-float', # ! + 3: 'VAX G-float', + 4: 'Cray', # !! + } + +mclass_info = { + mxFULL_CLASS: 'double', + mxCHAR_CLASS: 'char', + mxSPARSE_CLASS: 'sparse', + } + + +_MAX_INTP = np.iinfo(np.intp).max + + +class VarHeader4: + # Mat4 variables never logical or global + is_logical = False + is_global = False + + def __init__(self, + name, + dtype, + mclass, + dims, + is_complex): + self.name = name + self.dtype = dtype + self.mclass = mclass + self.dims = dims + self.is_complex = is_complex + + +class VarReader4: + ''' Class to read matlab 4 variables ''' + + def __init__(self, file_reader): + self.file_reader = file_reader + self.mat_stream = file_reader.mat_stream + self.dtypes = file_reader.dtypes + self.chars_as_strings = file_reader.chars_as_strings + self.squeeze_me = file_reader.squeeze_me + + def read_header(self): + ''' Read and return header for variable ''' + data = read_dtype(self.mat_stream, self.dtypes['header']) + name = self.mat_stream.read(int(data['namlen'])).strip(b'\x00') + if data['mopt'] < 0 or data['mopt'] > 5000: + raise ValueError('Mat 4 mopt wrong format, byteswapping problem?') + M, rest = divmod(data['mopt'], 1000) # order code + if M not in (0, 1): + warnings.warn(f"We do not support byte ordering '{order_codes[M]}';" + " returned data may be corrupt", + UserWarning, stacklevel=3) + O, rest = divmod(rest, 100) # unused, should be 0 + if O != 0: + raise ValueError('O in MOPT integer should be 0, wrong format?') + P, rest = divmod(rest, 10) # data type code e.g miDOUBLE (see above) + T = rest # matrix type code e.g., mxFULL_CLASS (see above) + dims = (data['mrows'], data['ncols']) + is_complex = data['imagf'] == 1 + dtype = self.dtypes[P] + return VarHeader4( + name, + dtype, + T, + dims, + is_complex) + + def array_from_header(self, hdr, process=True): + mclass = hdr.mclass + if mclass == mxFULL_CLASS: + arr = self.read_full_array(hdr) + elif mclass == mxCHAR_CLASS: + arr = self.read_char_array(hdr) + if process and self.chars_as_strings: + arr = chars_to_strings(arr) + elif mclass == mxSPARSE_CLASS: + # no current processing (below) makes sense for sparse + return self.read_sparse_array(hdr) + else: + raise TypeError(f'No reader for class code {mclass}') + if process and self.squeeze_me: + return squeeze_element(arr) + return arr + + def read_sub_array(self, hdr, copy=True): + ''' Mat4 read using header `hdr` dtype and dims + + Parameters + ---------- + hdr : object + object with attributes ``dtype``, ``dims``. dtype is assumed to be + the correct endianness + copy : bool, optional + copies array before return if True (default True) + (buffer is usually read only) + + Returns + ------- + arr : ndarray + of dtype given by `hdr` ``dtype`` and shape given by `hdr` ``dims`` + ''' + dt = hdr.dtype + # Fast product for large (>2GB) arrays. + num_bytes = reduce(mul, hdr.dims, np.int64(dt.itemsize)) + if num_bytes > _MAX_INTP: + raise ValueError( + f"Variable '{hdr.name.decode('latin1')}' has byte length " + f"longer than largest possible NumPy array on this platform.") + buffer = self.mat_stream.read(num_bytes) + if len(buffer) != num_bytes: + raise ValueError( + f"Not enough bytes to read matrix " + f"'{hdr.name.decode('latin1')}'; is this a badly-formed file? " + f"Consider listing matrices with `whosmat` and loading named " + f"matrices with `variable_names` kwarg to `loadmat`") + arr = np.ndarray(shape=hdr.dims, + dtype=dt, + buffer=buffer, + order='F') + if copy: + arr = arr.copy() + return arr + + def read_full_array(self, hdr): + ''' Full (rather than sparse) matrix getter + + Read matrix (array) can be real or complex + + Parameters + ---------- + hdr : ``VarHeader4`` instance + + Returns + ------- + arr : ndarray + complex array if ``hdr.is_complex`` is True, otherwise a real + numeric array + ''' + if hdr.is_complex: + # avoid array copy to save memory + res = self.read_sub_array(hdr, copy=False) + res_j = self.read_sub_array(hdr, copy=False) + return res + (res_j * 1j) + return self.read_sub_array(hdr) + + def read_char_array(self, hdr): + ''' latin-1 text matrix (char matrix) reader + + Parameters + ---------- + hdr : ``VarHeader4`` instance + + Returns + ------- + arr : ndarray + with dtype 'U1', shape given by `hdr` ``dims`` + ''' + arr = self.read_sub_array(hdr).astype(np.uint8) + S = arr.tobytes().decode('latin-1') + return np.ndarray(shape=hdr.dims, + dtype=np.dtype('U1'), + buffer=np.array(S)).copy() + + def read_sparse_array(self, hdr): + ''' Read and return sparse matrix type + + Parameters + ---------- + hdr : ``VarHeader4`` instance + + Returns + ------- + arr : coo_array + with dtype ``float`` and shape read from the sparse array data + + Notes + ----- + MATLAB 4 real sparse arrays are saved in a N+1 by 3 array format, where + N is the number of non-zero values. Column 1 values [0:N] are the + (1-based) row indices of the each non-zero value, column 2 [0:N] are the + column indices, column 3 [0:N] are the (real) values. The last values + [-1,0:2] of the rows, column indices are shape[0] and shape[1] + respectively of the output matrix. The last value for the values column + is a padding 0. mrows and ncols values from the header give the shape of + the stored matrix, here [N+1, 3]. Complex data are saved as a 4 column + matrix, where the fourth column contains the imaginary component; the + last value is again 0. Complex sparse data do *not* have the header + ``imagf`` field set to True; the fact that the data are complex is only + detectable because there are 4 storage columns. + ''' + res = self.read_sub_array(hdr) + tmp = res[:-1,:] + # All numbers are float64 in Matlab, but SciPy sparse expects int shape + dims = (int(res[-1,0]), int(res[-1,1])) + I = np.ascontiguousarray(tmp[:,0],dtype='intc') # fixes byte order also + J = np.ascontiguousarray(tmp[:,1],dtype='intc') + I -= 1 # for 1-based indexing + J -= 1 + if res.shape[1] == 3: + V = np.ascontiguousarray(tmp[:,2],dtype='float') + else: + V = np.ascontiguousarray(tmp[:,2],dtype='complex') + V.imag = tmp[:,3] + return scipy.sparse.coo_array((V,(I,J)), dims) + + def shape_from_header(self, hdr): + '''Read the shape of the array described by the header. + The file position after this call is unspecified. + ''' + mclass = hdr.mclass + if mclass == mxFULL_CLASS: + shape = tuple(map(int, hdr.dims)) + elif mclass == mxCHAR_CLASS: + shape = tuple(map(int, hdr.dims)) + if self.chars_as_strings: + shape = shape[:-1] + elif mclass == mxSPARSE_CLASS: + dt = hdr.dtype + dims = hdr.dims + + if not (len(dims) == 2 and dims[0] >= 1 and dims[1] >= 1): + return () + + # Read only the row and column counts + self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1) + rows = np.ndarray(shape=(), dtype=dt, + buffer=self.mat_stream.read(dt.itemsize)) + self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1) + cols = np.ndarray(shape=(), dtype=dt, + buffer=self.mat_stream.read(dt.itemsize)) + + shape = (int(rows), int(cols)) + else: + raise TypeError(f'No reader for class code {mclass}') + + if self.squeeze_me: + shape = tuple([x for x in shape if x != 1]) + return shape + + +class MatFile4Reader(MatFileReader): + ''' Reader for Mat4 files ''' + @docfiller + def __init__(self, mat_stream, *args, **kwargs): + ''' Initialize matlab 4 file reader + + %(matstream_arg)s + %(load_args)s + ''' + super().__init__(mat_stream, *args, **kwargs) + self._matrix_reader = None + + def guess_byte_order(self): + self.mat_stream.seek(0) + mopt = read_dtype(self.mat_stream, np.dtype('i4')) + self.mat_stream.seek(0) + if mopt == 0: + return '<' + if mopt < 0 or mopt > 5000: + # Number must have been byteswapped + return SYS_LITTLE_ENDIAN and '>' or '<' + # Not byteswapped + return SYS_LITTLE_ENDIAN and '<' or '>' + + def initialize_read(self): + ''' Run when beginning read of variables + + Sets up readers from parameters in `self` + ''' + self.dtypes = convert_dtypes(mdtypes_template, self.byte_order) + self._matrix_reader = VarReader4(self) + + def read_var_header(self): + ''' Read and return header, next position + + Parameters + ---------- + None + + Returns + ------- + header : object + object that can be passed to self.read_var_array, and that + has attributes ``name`` and ``is_global`` + next_position : int + position in stream of next variable + ''' + hdr = self._matrix_reader.read_header() + # Fast product for large (>2GB) arrays. + remaining_bytes = reduce(mul, hdr.dims, np.int64(hdr.dtype.itemsize)) + if hdr.is_complex and not hdr.mclass == mxSPARSE_CLASS: + remaining_bytes *= 2 + next_position = self.mat_stream.tell() + remaining_bytes + return hdr, next_position + + def read_var_array(self, header, process=True): + ''' Read array, given `header` + + Parameters + ---------- + header : header object + object with fields defining variable header + process : {True, False}, optional + If True, apply recursive post-processing during loading of array. + + Returns + ------- + arr : array + array with post-processing applied or not according to + `process`. + ''' + return self._matrix_reader.array_from_header(header, process) + + def get_variables(self, variable_names=None): + ''' get variables from stream as dictionary + + Parameters + ---------- + variable_names : None or str or sequence of str, optional + variable name, or sequence of variable names to get from Mat file / + file stream. If None, then get all variables in file. + ''' + if isinstance(variable_names, str): + variable_names = [variable_names] + elif variable_names is not None: + variable_names = list(variable_names) + self.mat_stream.seek(0) + # set up variable reader + self.initialize_read() + mdict = {} + while not self.end_of_stream(): + hdr, next_position = self.read_var_header() + name = 'None' if hdr.name is None else hdr.name.decode('latin1') + if variable_names is not None and name not in variable_names: + self.mat_stream.seek(next_position) + continue + mdict[name] = self.read_var_array(hdr) + self.mat_stream.seek(next_position) + if variable_names is not None: + variable_names.remove(name) + if len(variable_names) == 0: + break + return mdict + + def list_variables(self): + ''' list variables from stream ''' + self.mat_stream.seek(0) + # set up variable reader + self.initialize_read() + vars = [] + while not self.end_of_stream(): + hdr, next_position = self.read_var_header() + name = 'None' if hdr.name is None else hdr.name.decode('latin1') + shape = self._matrix_reader.shape_from_header(hdr) + info = mclass_info.get(hdr.mclass, 'unknown') + vars.append((name, shape, info)) + + self.mat_stream.seek(next_position) + return vars + + +def arr_to_2d(arr, oned_as='row'): + ''' Make ``arr`` exactly two dimensional + + If `arr` has more than 2 dimensions, raise a ValueError + + Parameters + ---------- + arr : array + oned_as : {'row', 'column'}, optional + Whether to reshape 1-D vectors as row vectors or column vectors. + See documentation for ``matdims`` for more detail + + Returns + ------- + arr2d : array + 2-D version of the array + ''' + dims = matdims(arr, oned_as) + if len(dims) > 2: + raise ValueError('Matlab 4 files cannot save arrays with more than ' + '2 dimensions') + return arr.reshape(dims) + + +class VarWriter4: + def __init__(self, file_writer): + self.file_stream = file_writer.file_stream + self.oned_as = file_writer.oned_as + + def write_bytes(self, arr): + self.file_stream.write(arr.tobytes(order='F')) + + def write_string(self, s): + self.file_stream.write(s) + + def write_header(self, name, shape, P=miDOUBLE, T=mxFULL_CLASS, imagf=0): + ''' Write header for given data options + + Parameters + ---------- + name : str + name of variable + shape : sequence + Shape of array as it will be read in matlab + P : int, optional + code for mat4 data type, one of ``miDOUBLE, miSINGLE, miINT32, + miINT16, miUINT16, miUINT8`` + T : int, optional + code for mat4 matrix class, one of ``mxFULL_CLASS, mxCHAR_CLASS, + mxSPARSE_CLASS`` + imagf : int, optional + flag indicating complex + ''' + header = np.empty((), mdtypes_template['header']) + M = not SYS_LITTLE_ENDIAN + O = 0 + header['mopt'] = (M * 1000 + + O * 100 + + P * 10 + + T) + header['mrows'] = shape[0] + header['ncols'] = shape[1] + header['imagf'] = imagf + header['namlen'] = len(name) + 1 + self.write_bytes(header) + data = name + '\0' + self.write_string(data.encode('latin1')) + + def write(self, arr, name): + ''' Write matrix `arr`, with name `name` + + Parameters + ---------- + arr : array_like + array to write + name : str + name in matlab workspace + ''' + # we need to catch sparse first, because np.asarray returns an + # an object array for scipy.sparse + if scipy.sparse.issparse(arr): + self.write_sparse(arr, name) + return + arr = np.asarray(arr) + dt = arr.dtype + if not dt.isnative: + arr = arr.astype(dt.newbyteorder('=')) + dtt = dt.type + if dtt is np.object_: + raise TypeError('Cannot save object arrays in Mat4') + elif dtt is np.void: + raise TypeError('Cannot save void type arrays') + elif dtt in (np.str_, np.bytes_): + self.write_char(arr, name) + return + self.write_numeric(arr, name) + + def write_numeric(self, arr, name): + arr = arr_to_2d(arr, self.oned_as) + imagf = arr.dtype.kind == 'c' + try: + P = np_to_mtypes[arr.dtype.str[1:]] + except KeyError: + if imagf: + arr = arr.astype('c128') + else: + arr = arr.astype('f8') + P = miDOUBLE + self.write_header(name, + arr.shape, + P=P, + T=mxFULL_CLASS, + imagf=imagf) + if imagf: + self.write_bytes(arr.real) + self.write_bytes(arr.imag) + else: + self.write_bytes(arr) + + def write_char(self, arr, name): + if arr.dtype.type == np.str_ and arr.dtype.itemsize != np.dtype('U1').itemsize: + arr = arr_to_chars(arr) + arr = arr_to_2d(arr, self.oned_as) + dims = arr.shape + self.write_header( + name, + dims, + P=miUINT8, + T=mxCHAR_CLASS) + if arr.dtype.kind == 'U': + # Recode unicode to latin1 + n_chars = math.prod(dims) + st_arr = np.ndarray(shape=(), + dtype=arr_dtype_number(arr, n_chars), + buffer=arr) + st = st_arr.item().encode('latin-1') + arr = np.ndarray(shape=dims, dtype='S1', buffer=st) + self.write_bytes(arr) + + def write_sparse(self, arr, name): + ''' Sparse matrices are 2-D + + See docstring for VarReader4.read_sparse_array + ''' + A = arr.tocoo() # convert to sparse COO format (ijv) + imagf = A.dtype.kind == 'c' + ijv = np.zeros((A.nnz + 1, 3+imagf), dtype='f8') + ijv[:-1,0] = A.row + ijv[:-1,1] = A.col + ijv[:-1,0:2] += 1 # 1 based indexing + if imagf: + ijv[:-1,2] = A.data.real + ijv[:-1,3] = A.data.imag + else: + ijv[:-1,2] = A.data + ijv[-1,0:2] = A.shape + self.write_header( + name, + ijv.shape, + P=miDOUBLE, + T=mxSPARSE_CLASS) + self.write_bytes(ijv) + + +class MatFile4Writer: + ''' Class for writing matlab 4 format files ''' + def __init__(self, file_stream, oned_as=None): + self.file_stream = file_stream + if oned_as is None: + oned_as = 'row' + self.oned_as = oned_as + self._matrix_writer = None + + def put_variables(self, mdict, write_header=None): + ''' Write variables in `mdict` to stream + + Parameters + ---------- + mdict : mapping + mapping with method ``items`` return name, contents pairs + where ``name`` which will appeak in the matlab workspace in + file load, and ``contents`` is something writeable to a + matlab file, such as a NumPy array. + write_header : {None, True, False} + If True, then write the matlab file header before writing the + variables. If None (the default) then write the file header + if we are at position 0 in the stream. By setting False + here, and setting the stream position to the end of the file, + you can append variables to a matlab file + ''' + # there is no header for a matlab 4 mat file, so we ignore the + # ``write_header`` input argument. It's there for compatibility + # with the matlab 5 version of this method + self._matrix_writer = VarWriter4(self) + for name, var in mdict.items(): + self._matrix_writer.write(var, name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5.py new file mode 100644 index 0000000000000000000000000000000000000000..c251d972a3746d5045db93f0b938bf3cb4793dd8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5.py @@ -0,0 +1,901 @@ +''' Classes for read / write of matlab (TM) 5 files + +The matfile specification last found here: + +https://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf + +(as of December 5 2008) + +================================= + Note on functions and mat files +================================= + +The document above does not give any hints as to the storage of matlab +function handles, or anonymous function handles. I had, therefore, to +guess the format of matlab arrays of ``mxFUNCTION_CLASS`` and +``mxOPAQUE_CLASS`` by looking at example mat files. + +``mxFUNCTION_CLASS`` stores all types of matlab functions. It seems to +contain a struct matrix with a set pattern of fields. For anonymous +functions, a sub-fields of one of these fields seems to contain the +well-named ``mxOPAQUE_CLASS``. This seems to contain: + +* array flags as for any matlab matrix +* 3 int8 strings +* a matrix + +It seems that whenever the mat file contains a ``mxOPAQUE_CLASS`` +instance, there is also an un-named matrix (name == '') at the end of +the mat file. I'll call this the ``__function_workspace__`` matrix. + +When I saved two anonymous functions in a mat file, or appended another +anonymous function to the mat file, there was still only one +``__function_workspace__`` un-named matrix at the end, but larger than +that for a mat file with a single anonymous function, suggesting that +the workspaces for the two functions had been merged. + +The ``__function_workspace__`` matrix appears to be of double class +(``mxCLASS_DOUBLE``), but stored as uint8, the memory for which is in +the format of a mini .mat file, without the first 124 bytes of the file +header (the description and the subsystem_offset), but with the version +U2 bytes, and the S2 endian test bytes. There follow 4 zero bytes, +presumably for 8 byte padding, and then a series of ``miMATRIX`` +entries, as in a standard mat file. The ``miMATRIX`` entries appear to +be series of un-named (name == '') matrices, and may also contain arrays +of this same mini-mat format. + +I guess that: + +* saving an anonymous function back to a mat file will need the + associated ``__function_workspace__`` matrix saved as well for the + anonymous function to work correctly. +* appending to a mat file that has a ``__function_workspace__`` would + involve first pulling off this workspace, appending, checking whether + there were any more anonymous functions appended, and then somehow + merging the relevant workspaces, and saving at the end of the mat + file. + +The mat files I was playing with are in ``tests/data``: + +* sqr.mat +* parabola.mat +* some_functions.mat + +See ``tests/test_mio.py:test_mio_funcs.py`` for the debugging +script I was working with. + +Small fragments of current code adapted from matfile.py by Heiko +Henkelmann; parts of the code for simplify_cells=True adapted from +http://blog.nephics.com/2019/08/28/better-loadmat-for-scipy/. +''' + +import math +import os +import time +import sys +import zlib + +from io import BytesIO + +import warnings + +import numpy as np + +import scipy.sparse + +from ._byteordercodes import native_code, swapped_code + +from ._miobase import (MatFileReader, docfiller, matdims, read_dtype, + arr_to_chars, arr_dtype_number, MatWriteError, + MatReadError, MatReadWarning, MatWriteWarning) + +# Reader object for matlab 5 format variables +from ._mio5_utils import VarReader5 + +# Constants and helper objects +from ._mio5_params import (MatlabObject, MatlabFunction, MDTYPES, NP_TO_MTYPES, + NP_TO_MXTYPES, miCOMPRESSED, miMATRIX, miINT8, + miUTF8, miUINT32, mxCELL_CLASS, mxSTRUCT_CLASS, + mxOBJECT_CLASS, mxCHAR_CLASS, mxSPARSE_CLASS, + mxDOUBLE_CLASS, mclass_info, mat_struct) + +from ._streams import ZlibInputStream + + +def _has_struct(elem): + """Determine if elem is an array and if first array item is a struct.""" + return (isinstance(elem, np.ndarray) and (elem.size > 0) and (elem.ndim > 0) and + isinstance(elem[0], mat_struct)) + + +def _inspect_cell_array(ndarray): + """Construct lists from cell arrays (loaded as numpy ndarrays), recursing + into items if they contain mat_struct objects.""" + elem_list = [] + for sub_elem in ndarray: + if isinstance(sub_elem, mat_struct): + elem_list.append(_matstruct_to_dict(sub_elem)) + elif _has_struct(sub_elem): + elem_list.append(_inspect_cell_array(sub_elem)) + else: + elem_list.append(sub_elem) + return elem_list + + +def _matstruct_to_dict(matobj): + """Construct nested dicts from mat_struct objects.""" + d = {} + for f in matobj._fieldnames: + elem = matobj.__dict__[f] + if isinstance(elem, mat_struct): + d[f] = _matstruct_to_dict(elem) + elif _has_struct(elem): + d[f] = _inspect_cell_array(elem) + else: + d[f] = elem + return d + + +def _simplify_cells(d): + """Convert mat objects in dict to nested dicts.""" + for key in d: + if isinstance(d[key], mat_struct): + d[key] = _matstruct_to_dict(d[key]) + elif _has_struct(d[key]): + d[key] = _inspect_cell_array(d[key]) + return d + + +class MatFile5Reader(MatFileReader): + ''' Reader for Mat 5 mat files + Adds the following attribute to base class + + uint16_codec - char codec to use for uint16 char arrays + (defaults to system default codec) + + Uses variable reader that has the following standard interface (see + abstract class in ``miobase``:: + + __init__(self, file_reader) + read_header(self) + array_from_header(self) + + and added interface:: + + set_stream(self, stream) + read_full_tag(self) + + ''' + @docfiller + def __init__(self, + mat_stream, + byte_order=None, + mat_dtype=False, + squeeze_me=False, + chars_as_strings=True, + matlab_compatible=False, + struct_as_record=True, + verify_compressed_data_integrity=True, + uint16_codec=None, + simplify_cells=False): + '''Initializer for matlab 5 file format reader + + %(matstream_arg)s + %(load_args)s + %(struct_arg)s + uint16_codec : {None, string} + Set codec to use for uint16 char arrays (e.g., 'utf-8'). + Use system default codec if None + ''' + super().__init__( + mat_stream, + byte_order, + mat_dtype, + squeeze_me, + chars_as_strings, + matlab_compatible, + struct_as_record, + verify_compressed_data_integrity, + simplify_cells) + # Set uint16 codec + if not uint16_codec: + uint16_codec = sys.getdefaultencoding() + self.uint16_codec = uint16_codec + # placeholders for readers - see initialize_read method + self._file_reader = None + self._matrix_reader = None + + def guess_byte_order(self): + ''' Guess byte order. + Sets stream pointer to 0''' + self.mat_stream.seek(126) + mi = self.mat_stream.read(2) + self.mat_stream.seek(0) + return mi == b'IM' and '<' or '>' + + def read_file_header(self): + ''' Read in mat 5 file header ''' + hdict = {} + hdr_dtype = MDTYPES[self.byte_order]['dtypes']['file_header'] + hdr = read_dtype(self.mat_stream, hdr_dtype) + hdict['__header__'] = hdr['description'].item().strip(b' \t\n\000') + v_major = hdr['version'] >> 8 + v_minor = hdr['version'] & 0xFF + hdict['__version__'] = f'{v_major}.{v_minor}' + return hdict + + def initialize_read(self): + ''' Run when beginning read of variables + + Sets up readers from parameters in `self` + ''' + # reader for top level stream. We need this extra top-level + # reader because we use the matrix_reader object to contain + # compressed matrices (so they have their own stream) + self._file_reader = VarReader5(self) + # reader for matrix streams + self._matrix_reader = VarReader5(self) + + def read_var_header(self): + ''' Read header, return header, next position + + Header has to define at least .name and .is_global + + Parameters + ---------- + None + + Returns + ------- + header : object + object that can be passed to self.read_var_array, and that + has attributes .name and .is_global + next_position : int + position in stream of next variable + ''' + mdtype, byte_count = self._file_reader.read_full_tag() + if not byte_count > 0: + raise ValueError("Did not read any bytes") + next_pos = self.mat_stream.tell() + byte_count + if mdtype == miCOMPRESSED: + # Make new stream from compressed data + stream = ZlibInputStream(self.mat_stream, byte_count) + self._matrix_reader.set_stream(stream) + check_stream_limit = self.verify_compressed_data_integrity + mdtype, byte_count = self._matrix_reader.read_full_tag() + else: + check_stream_limit = False + self._matrix_reader.set_stream(self.mat_stream) + if not mdtype == miMATRIX: + raise TypeError(f'Expecting miMATRIX type here, got {mdtype}') + header = self._matrix_reader.read_header(check_stream_limit) + return header, next_pos + + def read_var_array(self, header, process=True): + ''' Read array, given `header` + + Parameters + ---------- + header : header object + object with fields defining variable header + process : {True, False} bool, optional + If True, apply recursive post-processing during loading of + array. + + Returns + ------- + arr : array + array with post-processing applied or not according to + `process`. + ''' + return self._matrix_reader.array_from_header(header, process) + + def get_variables(self, variable_names=None): + ''' get variables from stream as dictionary + + variable_names - optional list of variable names to get + + If variable_names is None, then get all variables in file + ''' + if isinstance(variable_names, str): + variable_names = [variable_names] + elif variable_names is not None: + variable_names = list(variable_names) + + self.mat_stream.seek(0) + # Here we pass all the parameters in self to the reading objects + self.initialize_read() + mdict = self.read_file_header() + mdict['__globals__'] = [] + while not self.end_of_stream(): + hdr, next_position = self.read_var_header() + name = 'None' if hdr.name is None else hdr.name.decode('latin1') + if name in mdict: + msg = ( + f'Duplicate variable name "{name}" in stream' + " - replacing previous with new\nConsider" + "scipy.io.matlab.varmats_from_mat to split " + "file into single variable files" + ) + warnings.warn(msg, MatReadWarning, stacklevel=2) + if name == '': + # can only be a matlab 7 function workspace + name = '__function_workspace__' + # We want to keep this raw because mat_dtype processing + # will break the format (uint8 as mxDOUBLE_CLASS) + process = False + else: + process = True + if variable_names is not None and name not in variable_names: + self.mat_stream.seek(next_position) + continue + try: + res = self.read_var_array(hdr, process) + except MatReadError as err: + warnings.warn( + f'Unreadable variable "{name}", because "{err}"', + Warning, stacklevel=2) + res = f"Read error: {err}" + self.mat_stream.seek(next_position) + mdict[name] = res + if hdr.is_global: + mdict['__globals__'].append(name) + if variable_names is not None: + variable_names.remove(name) + if len(variable_names) == 0: + break + if self.simplify_cells: + return _simplify_cells(mdict) + else: + return mdict + + def list_variables(self): + ''' list variables from stream ''' + self.mat_stream.seek(0) + # Here we pass all the parameters in self to the reading objects + self.initialize_read() + self.read_file_header() + vars = [] + while not self.end_of_stream(): + hdr, next_position = self.read_var_header() + name = 'None' if hdr.name is None else hdr.name.decode('latin1') + if name == '': + # can only be a matlab 7 function workspace + name = '__function_workspace__' + + shape = self._matrix_reader.shape_from_header(hdr) + if hdr.is_logical: + info = 'logical' + else: + info = mclass_info.get(hdr.mclass, 'unknown') + vars.append((name, shape, info)) + + self.mat_stream.seek(next_position) + return vars + + +def varmats_from_mat(file_obj): + """ Pull variables out of mat 5 file as a sequence of mat file objects + + This can be useful with a difficult mat file, containing unreadable + variables. This routine pulls the variables out in raw form and puts them, + unread, back into a file stream for saving or reading. Another use is the + pathological case where there is more than one variable of the same name in + the file; this routine returns the duplicates, whereas the standard reader + will overwrite duplicates in the returned dictionary. + + The file pointer in `file_obj` will be undefined. File pointers for the + returned file-like objects are set at 0. + + Parameters + ---------- + file_obj : file-like + file object containing mat file + + Returns + ------- + named_mats : list + list contains tuples of (name, BytesIO) where BytesIO is a file-like + object containing mat file contents as for a single variable. The + BytesIO contains a string with the original header and a single var. If + ``var_file_obj`` is an individual BytesIO instance, then save as a mat + file with something like ``open('test.mat', + 'wb').write(var_file_obj.read())`` + + Examples + -------- + >>> import scipy.io + >>> import numpy as np + >>> from io import BytesIO + >>> from scipy.io.matlab._mio5 import varmats_from_mat + >>> mat_fileobj = BytesIO() + >>> scipy.io.savemat(mat_fileobj, {'b': np.arange(10), 'a': 'a string'}) + >>> varmats = varmats_from_mat(mat_fileobj) + >>> sorted([name for name, str_obj in varmats]) + ['a', 'b'] + """ + rdr = MatFile5Reader(file_obj) + file_obj.seek(0) + # Raw read of top-level file header + hdr_len = MDTYPES[native_code]['dtypes']['file_header'].itemsize + raw_hdr = file_obj.read(hdr_len) + # Initialize variable reading + file_obj.seek(0) + rdr.initialize_read() + rdr.read_file_header() + next_position = file_obj.tell() + named_mats = [] + while not rdr.end_of_stream(): + start_position = next_position + hdr, next_position = rdr.read_var_header() + name = 'None' if hdr.name is None else hdr.name.decode('latin1') + # Read raw variable string + file_obj.seek(start_position) + byte_count = next_position - start_position + var_str = file_obj.read(byte_count) + # write to stringio object + out_obj = BytesIO() + out_obj.write(raw_hdr) + out_obj.write(var_str) + out_obj.seek(0) + named_mats.append((name, out_obj)) + return named_mats + + +class EmptyStructMarker: + """ Class to indicate presence of empty matlab struct on output """ + + +def to_writeable(source): + ''' Convert input object ``source`` to something we can write + + Parameters + ---------- + source : object + + Returns + ------- + arr : None or ndarray or EmptyStructMarker + If `source` cannot be converted to something we can write to a matfile, + return None. If `source` is equivalent to an empty dictionary, return + ``EmptyStructMarker``. Otherwise return `source` converted to an + ndarray with contents for writing to matfile. + ''' + if isinstance(source, np.ndarray): + return source + if source is None: + return None + if hasattr(source, "__array__"): + return np.asarray(source) + # Objects that implement mappings + is_mapping = (hasattr(source, 'keys') and hasattr(source, 'values') and + hasattr(source, 'items')) + # Objects that don't implement mappings, but do have dicts + if isinstance(source, np.generic): + # NumPy scalars are never mappings (PyPy issue workaround) + pass + elif not is_mapping and hasattr(source, '__dict__'): + source = {key: value for key, value in source.__dict__.items() + if not key.startswith('_')} + is_mapping = True + if is_mapping: + dtype = [] + values = [] + for field, value in source.items(): + if isinstance(field, str): + if field[0] not in '_0123456789': + dtype.append((str(field), object)) + values.append(value) + else: + msg = (f"Starting field name with a underscore " + f"or a digit ({field}) is ignored") + warnings.warn(msg, MatWriteWarning, stacklevel=2) + if dtype: + return np.array([tuple(values)], dtype) + else: + return EmptyStructMarker + # Next try and convert to an array + try: + narr = np.asanyarray(source) + except ValueError: + narr = np.asanyarray(source, dtype=object) + if narr.dtype.type in (object, np.object_) and \ + narr.shape == () and narr == source: + # No interesting conversion possible + return None + return narr + + +# Native byte ordered dtypes for convenience for writers +NDT_FILE_HDR = MDTYPES[native_code]['dtypes']['file_header'] +NDT_TAG_FULL = MDTYPES[native_code]['dtypes']['tag_full'] +NDT_TAG_SMALL = MDTYPES[native_code]['dtypes']['tag_smalldata'] +NDT_ARRAY_FLAGS = MDTYPES[native_code]['dtypes']['array_flags'] + + +class VarWriter5: + ''' Generic matlab matrix writing class ''' + mat_tag = np.zeros((), NDT_TAG_FULL) + mat_tag['mdtype'] = miMATRIX + + def __init__(self, file_writer): + self.file_stream = file_writer.file_stream + self.unicode_strings = file_writer.unicode_strings + self.long_field_names = file_writer.long_field_names + self.oned_as = file_writer.oned_as + # These are used for top level writes, and unset after + self._var_name = None + self._var_is_global = False + + def write_bytes(self, arr): + self.file_stream.write(arr.tobytes(order='F')) + + def write_string(self, s): + self.file_stream.write(s) + + def write_element(self, arr, mdtype=None): + ''' write tag and data ''' + if mdtype is None: + mdtype = NP_TO_MTYPES[arr.dtype.str[1:]] + # Array needs to be in native byte order + if arr.dtype.byteorder == swapped_code: + arr = arr.byteswap().view(arr.dtype.newbyteorder()) + byte_count = arr.size*arr.itemsize + if byte_count <= 4: + self.write_smalldata_element(arr, mdtype, byte_count) + else: + self.write_regular_element(arr, mdtype, byte_count) + + def write_smalldata_element(self, arr, mdtype, byte_count): + # write tag with embedded data + tag = np.zeros((), NDT_TAG_SMALL) + tag['byte_count_mdtype'] = (byte_count << 16) + mdtype + # if arr.tobytes is < 4, the element will be zero-padded as needed. + tag['data'] = arr.tobytes(order='F') + self.write_bytes(tag) + + def write_regular_element(self, arr, mdtype, byte_count): + # write tag, data + tag = np.zeros((), NDT_TAG_FULL) + tag['mdtype'] = mdtype + tag['byte_count'] = byte_count + self.write_bytes(tag) + self.write_bytes(arr) + # pad to next 64-bit boundary + bc_mod_8 = byte_count % 8 + if bc_mod_8: + self.file_stream.write(b'\x00' * (8-bc_mod_8)) + + def write_header(self, + shape, + mclass, + is_complex=False, + is_logical=False, + nzmax=0): + ''' Write header for given data options + shape : sequence + array shape + mclass - mat5 matrix class + is_complex - True if matrix is complex + is_logical - True if matrix is logical + nzmax - max non zero elements for sparse arrays + + We get the name and the global flag from the object, and reset + them to defaults after we've used them + ''' + # get name and is_global from one-shot object store + name = self._var_name + is_global = self._var_is_global + # initialize the top-level matrix tag, store position + self._mat_tag_pos = self.file_stream.tell() + self.write_bytes(self.mat_tag) + # write array flags (complex, global, logical, class, nzmax) + af = np.zeros((), NDT_ARRAY_FLAGS) + af['data_type'] = miUINT32 + af['byte_count'] = 8 + flags = is_complex << 3 | is_global << 2 | is_logical << 1 + af['flags_class'] = mclass | flags << 8 + af['nzmax'] = nzmax + self.write_bytes(af) + # shape + self.write_element(np.array(shape, dtype='i4')) + # write name + name = np.asarray(name) + if name == '': # empty string zero-terminated + self.write_smalldata_element(name, miINT8, 0) + else: + self.write_element(name, miINT8) + # reset the one-shot store to defaults + self._var_name = '' + self._var_is_global = False + + def update_matrix_tag(self, start_pos): + curr_pos = self.file_stream.tell() + self.file_stream.seek(start_pos) + byte_count = curr_pos - start_pos - 8 + if byte_count >= 2**32: + raise MatWriteError("Matrix too large to save with Matlab " + "5 format") + self.mat_tag['byte_count'] = byte_count + self.write_bytes(self.mat_tag) + self.file_stream.seek(curr_pos) + + def write_top(self, arr, name, is_global): + """ Write variable at top level of mat file + + Parameters + ---------- + arr : array_like + array-like object to create writer for + name : str, optional + name as it will appear in matlab workspace + default is empty string + is_global : {False, True}, optional + whether variable will be global on load into matlab + """ + # these are set before the top-level header write, and unset at + # the end of the same write, because they do not apply for lower levels + self._var_is_global = is_global + self._var_name = name + # write the header and data + self.write(arr) + + def write(self, arr): + ''' Write `arr` to stream at top and sub levels + + Parameters + ---------- + arr : array_like + array-like object to create writer for + ''' + # store position, so we can update the matrix tag + mat_tag_pos = self.file_stream.tell() + # First check if these are sparse + if scipy.sparse.issparse(arr): + self.write_sparse(arr) + self.update_matrix_tag(mat_tag_pos) + return + # Try to convert things that aren't arrays + narr = to_writeable(arr) + if narr is None: + raise TypeError(f'Could not convert {arr} (type {type(arr)}) to array') + if isinstance(narr, MatlabObject): + self.write_object(narr) + elif isinstance(narr, MatlabFunction): + raise MatWriteError('Cannot write matlab functions') + elif narr is EmptyStructMarker: # empty struct array + self.write_empty_struct() + elif narr.dtype.fields: # struct array + self.write_struct(narr) + elif narr.dtype.hasobject: # cell array + self.write_cells(narr) + elif narr.dtype.kind in ('U', 'S'): + if self.unicode_strings: + codec = 'UTF8' + else: + codec = 'ascii' + self.write_char(narr, codec) + else: + self.write_numeric(narr) + self.update_matrix_tag(mat_tag_pos) + + def write_numeric(self, arr): + imagf = arr.dtype.kind == 'c' + logif = arr.dtype.kind == 'b' + try: + mclass = NP_TO_MXTYPES[arr.dtype.str[1:]] + except KeyError: + # No matching matlab type, probably complex256 / float128 / float96 + # Cast data to complex128 / float64. + if imagf: + arr = arr.astype('c128') + elif logif: + arr = arr.astype('i1') # Should only contain 0/1 + else: + arr = arr.astype('f8') + mclass = mxDOUBLE_CLASS + self.write_header(matdims(arr, self.oned_as), + mclass, + is_complex=imagf, + is_logical=logif) + if imagf: + self.write_element(arr.real) + self.write_element(arr.imag) + else: + self.write_element(arr) + + def write_char(self, arr, codec='ascii'): + ''' Write string array `arr` with given `codec` + ''' + if arr.size == 0 or np.all(arr == ''): + # This an empty string array or a string array containing + # only empty strings. Matlab cannot distinguish between a + # string array that is empty, and a string array containing + # only empty strings, because it stores strings as arrays of + # char. There is no way of having an array of char that is + # not empty, but contains an empty string. We have to + # special-case the array-with-empty-strings because even + # empty strings have zero padding, which would otherwise + # appear in matlab as a string with a space. + shape = (0,) * np.max([arr.ndim, 2]) + self.write_header(shape, mxCHAR_CLASS) + self.write_smalldata_element(arr, miUTF8, 0) + return + # non-empty string. + # + # Convert to char array + arr = arr_to_chars(arr) + # We have to write the shape directly, because we are going + # recode the characters, and the resulting stream of chars + # may have a different length + shape = arr.shape + self.write_header(shape, mxCHAR_CLASS) + if arr.dtype.kind == 'U' and arr.size: + # Make one long string from all the characters. We need to + # transpose here, because we're flattening the array, before + # we write the bytes. The bytes have to be written in + # Fortran order. + n_chars = math.prod(shape) + st_arr = np.ndarray(shape=(), + dtype=arr_dtype_number(arr, n_chars), + buffer=arr.T.copy()) # Fortran order + # Recode with codec to give byte string + st = st_arr.item().encode(codec) + # Reconstruct as 1-D byte array + arr = np.ndarray(shape=(len(st),), + dtype='S1', + buffer=st) + self.write_element(arr, mdtype=miUTF8) + + def write_sparse(self, arr): + ''' Sparse matrices are 2D + ''' + A = arr.tocsc() # convert to sparse CSC format + A.sort_indices() # MATLAB expects sorted row indices + is_complex = (A.dtype.kind == 'c') + is_logical = (A.dtype.kind == 'b') + nz = A.nnz + self.write_header(matdims(arr, self.oned_as), + mxSPARSE_CLASS, + is_complex=is_complex, + is_logical=is_logical, + # matlab won't load file with 0 nzmax + nzmax=1 if nz == 0 else nz) + self.write_element(A.indices.astype('i4')) + self.write_element(A.indptr.astype('i4')) + self.write_element(A.data.real) + if is_complex: + self.write_element(A.data.imag) + + def write_cells(self, arr): + self.write_header(matdims(arr, self.oned_as), + mxCELL_CLASS) + # loop over data, column major + A = np.atleast_2d(arr).flatten('F') + for el in A: + self.write(el) + + def write_empty_struct(self): + self.write_header((1, 1), mxSTRUCT_CLASS) + # max field name length set to 1 in an example matlab struct + self.write_element(np.array(1, dtype=np.int32)) + # Field names element is empty + self.write_element(np.array([], dtype=np.int8)) + + def write_struct(self, arr): + self.write_header(matdims(arr, self.oned_as), + mxSTRUCT_CLASS) + self._write_items(arr) + + def _write_items(self, arr): + # write fieldnames + fieldnames = [f[0] for f in arr.dtype.descr] + length = max([len(fieldname) for fieldname in fieldnames])+1 + max_length = (self.long_field_names and 64) or 32 + if length > max_length: + raise ValueError( + f"Field names are restricted to {max_length - 1} characters" + ) + self.write_element(np.array([length], dtype='i4')) + self.write_element(np.array(fieldnames, dtype=f'S{length}'), mdtype=miINT8) + A = np.atleast_2d(arr).flatten('F') + for el in A: + for f in fieldnames: + self.write(el[f]) + + def write_object(self, arr): + '''Same as writing structs, except different mx class, and extra + classname element after header + ''' + self.write_header(matdims(arr, self.oned_as), + mxOBJECT_CLASS) + self.write_element(np.array(arr.classname, dtype='S'), + mdtype=miINT8) + self._write_items(arr) + + +class MatFile5Writer: + ''' Class for writing mat5 files ''' + + @docfiller + def __init__(self, file_stream, + do_compression=False, + unicode_strings=False, + global_vars=None, + long_field_names=False, + oned_as='row'): + ''' Initialize writer for matlab 5 format files + + Parameters + ---------- + %(do_compression)s + %(unicode_strings)s + global_vars : None or sequence of strings, optional + Names of variables to be marked as global for matlab + %(long_fields)s + %(oned_as)s + ''' + self.file_stream = file_stream + self.do_compression = do_compression + self.unicode_strings = unicode_strings + if global_vars: + self.global_vars = global_vars + else: + self.global_vars = [] + self.long_field_names = long_field_names + self.oned_as = oned_as + self._matrix_writer = None + + def write_file_header(self): + # write header + hdr = np.zeros((), NDT_FILE_HDR) + hdr['description'] = (f'MATLAB 5.0 MAT-file Platform: {os.name}, ' + f'Created on: {time.asctime()}') + hdr['version'] = 0x0100 + hdr['endian_test'] = np.ndarray(shape=(), + dtype='S2', + buffer=np.uint16(0x4d49)) + self.file_stream.write(hdr.tobytes()) + + def put_variables(self, mdict, write_header=None): + ''' Write variables in `mdict` to stream + + Parameters + ---------- + mdict : mapping + mapping with method ``items`` returns name, contents pairs where + ``name`` which will appear in the matlab workspace in file load, and + ``contents`` is something writeable to a matlab file, such as a NumPy + array. + write_header : {None, True, False}, optional + If True, then write the matlab file header before writing the + variables. If None (the default) then write the file header + if we are at position 0 in the stream. By setting False + here, and setting the stream position to the end of the file, + you can append variables to a matlab file + ''' + # write header if requested, or None and start of file + if write_header is None: + write_header = self.file_stream.tell() == 0 + if write_header: + self.write_file_header() + self._matrix_writer = VarWriter5(self) + for name, var in mdict.items(): + if name[0] == '_': + msg = (f"Starting field name with a " + f"underscore ({name}) is ignored") + warnings.warn(msg, MatWriteWarning, stacklevel=2) + continue + is_global = name in self.global_vars + if self.do_compression: + stream = BytesIO() + self._matrix_writer.file_stream = stream + self._matrix_writer.write_top(var, name.encode('latin1'), is_global) + out_str = zlib.compress(stream.getvalue()) + tag = np.empty((), NDT_TAG_FULL) + tag['mdtype'] = miCOMPRESSED + tag['byte_count'] = len(out_str) + self.file_stream.write(tag.tobytes()) + self.file_stream.write(out_str) + else: # not compressing + self._matrix_writer.write_top(var, name.encode('latin1'), is_global) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5_params.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5_params.py new file mode 100644 index 0000000000000000000000000000000000000000..e2e55a13c87665401c3d2c3f5657bcea3237298e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5_params.py @@ -0,0 +1,281 @@ +''' Constants and classes for matlab 5 read and write + +See also mio5_utils.pyx where these same constants arise as c enums. + +If you make changes in this file, don't forget to change mio5_utils.pyx +''' +import numpy as np + +from ._miobase import convert_dtypes + + +__all__ = [ + 'MDTYPES', 'MatlabFunction', 'MatlabObject', 'MatlabOpaque', + 'NP_TO_MTYPES', 'NP_TO_MXTYPES', 'OPAQUE_DTYPE', 'codecs_template', + 'mat_struct', 'mclass_dtypes_template', 'mclass_info', 'mdtypes_template', + 'miCOMPRESSED', 'miDOUBLE', 'miINT16', 'miINT32', 'miINT64', 'miINT8', + 'miMATRIX', 'miSINGLE', 'miUINT16', 'miUINT32', 'miUINT64', 'miUINT8', + 'miUTF16', 'miUTF32', 'miUTF8', 'mxCELL_CLASS', 'mxCHAR_CLASS', + 'mxDOUBLE_CLASS', 'mxFUNCTION_CLASS', 'mxINT16_CLASS', 'mxINT32_CLASS', + 'mxINT64_CLASS', 'mxINT8_CLASS', 'mxOBJECT_CLASS', + 'mxOBJECT_CLASS_FROM_MATRIX_H', 'mxOPAQUE_CLASS', 'mxSINGLE_CLASS', + 'mxSPARSE_CLASS', 'mxSTRUCT_CLASS', 'mxUINT16_CLASS', 'mxUINT32_CLASS', + 'mxUINT64_CLASS', 'mxUINT8_CLASS' +] +miINT8 = 1 +miUINT8 = 2 +miINT16 = 3 +miUINT16 = 4 +miINT32 = 5 +miUINT32 = 6 +miSINGLE = 7 +miDOUBLE = 9 +miINT64 = 12 +miUINT64 = 13 +miMATRIX = 14 +miCOMPRESSED = 15 +miUTF8 = 16 +miUTF16 = 17 +miUTF32 = 18 + +mxCELL_CLASS = 1 +mxSTRUCT_CLASS = 2 +# The March 2008 edition of "Matlab 7 MAT-File Format" says that +# mxOBJECT_CLASS = 3, whereas matrix.h says that mxLOGICAL = 3. +# Matlab 2008a appears to save logicals as type 9, so we assume that +# the document is correct. See type 18, below. +mxOBJECT_CLASS = 3 +mxCHAR_CLASS = 4 +mxSPARSE_CLASS = 5 +mxDOUBLE_CLASS = 6 +mxSINGLE_CLASS = 7 +mxINT8_CLASS = 8 +mxUINT8_CLASS = 9 +mxINT16_CLASS = 10 +mxUINT16_CLASS = 11 +mxINT32_CLASS = 12 +mxUINT32_CLASS = 13 +# The following are not in the March 2008 edition of "Matlab 7 +# MAT-File Format," but were guessed from matrix.h. +mxINT64_CLASS = 14 +mxUINT64_CLASS = 15 +mxFUNCTION_CLASS = 16 +# Not doing anything with these at the moment. +mxOPAQUE_CLASS = 17 # This appears to be a function workspace +# Thread 'saving/loading symbol table of annymous functions', +# octave-maintainers, April-May 2007 +# https://lists.gnu.org/archive/html/octave-maintainers/2007-04/msg00031.html +# https://lists.gnu.org/archive/html/octave-maintainers/2007-05/msg00032.html +# (Was/Deprecated: https://www-old.cae.wisc.edu/pipermail/octave-maintainers/2007-May/002824.html) +mxOBJECT_CLASS_FROM_MATRIX_H = 18 + +mdtypes_template = { + miINT8: 'i1', + miUINT8: 'u1', + miINT16: 'i2', + miUINT16: 'u2', + miINT32: 'i4', + miUINT32: 'u4', + miSINGLE: 'f4', + miDOUBLE: 'f8', + miINT64: 'i8', + miUINT64: 'u8', + miUTF8: 'u1', + miUTF16: 'u2', + miUTF32: 'u4', + 'file_header': [('description', 'S116'), + ('subsystem_offset', 'i8'), + ('version', 'u2'), + ('endian_test', 'S2')], + 'tag_full': [('mdtype', 'u4'), ('byte_count', 'u4')], + 'tag_smalldata':[('byte_count_mdtype', 'u4'), ('data', 'S4')], + 'array_flags': [('data_type', 'u4'), + ('byte_count', 'u4'), + ('flags_class','u4'), + ('nzmax', 'u4')], + 'U1': 'U1', + } + +mclass_dtypes_template = { + mxINT8_CLASS: 'i1', + mxUINT8_CLASS: 'u1', + mxINT16_CLASS: 'i2', + mxUINT16_CLASS: 'u2', + mxINT32_CLASS: 'i4', + mxUINT32_CLASS: 'u4', + mxINT64_CLASS: 'i8', + mxUINT64_CLASS: 'u8', + mxSINGLE_CLASS: 'f4', + mxDOUBLE_CLASS: 'f8', + } + +mclass_info = { + mxINT8_CLASS: 'int8', + mxUINT8_CLASS: 'uint8', + mxINT16_CLASS: 'int16', + mxUINT16_CLASS: 'uint16', + mxINT32_CLASS: 'int32', + mxUINT32_CLASS: 'uint32', + mxINT64_CLASS: 'int64', + mxUINT64_CLASS: 'uint64', + mxSINGLE_CLASS: 'single', + mxDOUBLE_CLASS: 'double', + mxCELL_CLASS: 'cell', + mxSTRUCT_CLASS: 'struct', + mxOBJECT_CLASS: 'object', + mxCHAR_CLASS: 'char', + mxSPARSE_CLASS: 'sparse', + mxFUNCTION_CLASS: 'function', + mxOPAQUE_CLASS: 'opaque', + } + +NP_TO_MTYPES = { + 'f8': miDOUBLE, + 'c32': miDOUBLE, + 'c24': miDOUBLE, + 'c16': miDOUBLE, + 'f4': miSINGLE, + 'c8': miSINGLE, + 'i8': miINT64, + 'i4': miINT32, + 'i2': miINT16, + 'i1': miINT8, + 'u8': miUINT64, + 'u4': miUINT32, + 'u2': miUINT16, + 'u1': miUINT8, + 'S1': miUINT8, + 'U1': miUTF16, + 'b1': miUINT8, # not standard but seems MATLAB uses this (gh-4022) + } + + +NP_TO_MXTYPES = { + 'f8': mxDOUBLE_CLASS, + 'c32': mxDOUBLE_CLASS, + 'c24': mxDOUBLE_CLASS, + 'c16': mxDOUBLE_CLASS, + 'f4': mxSINGLE_CLASS, + 'c8': mxSINGLE_CLASS, + 'i8': mxINT64_CLASS, + 'i4': mxINT32_CLASS, + 'i2': mxINT16_CLASS, + 'i1': mxINT8_CLASS, + 'u8': mxUINT64_CLASS, + 'u4': mxUINT32_CLASS, + 'u2': mxUINT16_CLASS, + 'u1': mxUINT8_CLASS, + 'S1': mxUINT8_CLASS, + 'b1': mxUINT8_CLASS, # not standard but seems MATLAB uses this + } + +''' Before release v7.1 (release 14) matlab (TM) used the system +default character encoding scheme padded out to 16-bits. Release 14 +and later use Unicode. When saving character data, R14 checks if it +can be encoded in 7-bit ascii, and saves in that format if so.''' + +codecs_template = { + miUTF8: {'codec': 'utf_8', 'width': 1}, + miUTF16: {'codec': 'utf_16', 'width': 2}, + miUTF32: {'codec': 'utf_32','width': 4}, + } + + +def _convert_codecs(template, byte_order): + ''' Convert codec template mapping to byte order + + Set codecs not on this system to None + + Parameters + ---------- + template : mapping + key, value are respectively codec name, and root name for codec + (without byte order suffix) + byte_order : {'<', '>'} + code for little or big endian + + Returns + ------- + codecs : dict + key, value are name, codec (as in .encode(codec)) + ''' + codecs = {} + postfix = byte_order == '<' and '_le' or '_be' + for k, v in template.items(): + codec = v['codec'] + try: + " ".encode(codec) + except LookupError: + codecs[k] = None + continue + if v['width'] > 1: + codec += postfix + codecs[k] = codec + return codecs.copy() + + +MDTYPES = {} +for _bytecode in '<>': + _def = {'dtypes': convert_dtypes(mdtypes_template, _bytecode), + 'classes': convert_dtypes(mclass_dtypes_template, _bytecode), + 'codecs': _convert_codecs(codecs_template, _bytecode)} + MDTYPES[_bytecode] = _def + + +class mat_struct: + """Placeholder for holding read data from structs. + + We use instances of this class when the user passes False as a value to the + ``struct_as_record`` parameter of the :func:`scipy.io.loadmat` function. + """ + pass + + +class MatlabObject(np.ndarray): + """Subclass of ndarray to signal this is a matlab object. + + This is a simple subclass of :class:`numpy.ndarray` meant to be used + by :func:`scipy.io.loadmat` and should not be instantiated directly. + """ + + def __new__(cls, input_array, classname=None): + # Input array is an already formed ndarray instance + # We first cast to be our class type + obj = np.asarray(input_array).view(cls) + # add the new attribute to the created instance + obj.classname = classname + # Finally, we must return the newly created object: + return obj + + def __array_finalize__(self,obj): + # reset the attribute from passed original object + self.classname = getattr(obj, 'classname', None) + # We do not need to return anything + + +class MatlabFunction(np.ndarray): + """Subclass for a MATLAB function. + + This is a simple subclass of :class:`numpy.ndarray` meant to be used + by :func:`scipy.io.loadmat` and should not be directly instantiated. + """ + + def __new__(cls, input_array): + obj = np.asarray(input_array).view(cls) + return obj + + +class MatlabOpaque(np.ndarray): + """Subclass for a MATLAB opaque matrix. + + This is a simple subclass of :class:`numpy.ndarray` meant to be used + by :func:`scipy.io.loadmat` and should not be directly instantiated. + """ + + def __new__(cls, input_array): + obj = np.asarray(input_array).view(cls) + return obj + + +OPAQUE_DTYPE = np.dtype( + [('s0', 'O'), ('s1', 'O'), ('s2', 'O'), ('arr', 'O')]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5_utils.cp311-win_amd64.dll.a b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5_utils.cp311-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..9199558ea4b182877168088f4771ae06da3c762e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio5_utils.cp311-win_amd64.dll.a differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio_utils.cp311-win_amd64.dll.a b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio_utils.cp311-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..959746b91fbb437f172514bad8780417a76beadf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio_utils.cp311-win_amd64.dll.a differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio_utils.cp311-win_amd64.pyd b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio_utils.cp311-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..9bd5c22313764c164b98feceb61b0de84ff852dc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_mio_utils.cp311-win_amd64.pyd differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_miobase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_miobase.py new file mode 100644 index 0000000000000000000000000000000000000000..e00314f269ffcecc00696f5dafe39e50763f973f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_miobase.py @@ -0,0 +1,435 @@ +# Authors: Travis Oliphant, Matthew Brett + +""" +Base classes for MATLAB file stream reading. + +MATLAB is a registered trademark of the Mathworks inc. +""" + +from typing import Final + +import numpy as np +from scipy._lib import doccer + +from . import _byteordercodes as boc + +__all__ = [ + 'MatReadError', 'MatReadWarning', 'MatWriteError', 'MatWriteWarning', +] + +class MatReadError(Exception): + """Exception indicating a read issue.""" + + +class MatWriteError(Exception): + """Exception indicating a write issue.""" + + +class MatReadWarning(UserWarning): + """Warning class for read issues.""" + +class MatWriteWarning(UserWarning): + """Warning class for write issues.""" + + +doc_dict = \ + {'file_arg': + '''file_name : str + Name of the mat file (do not need .mat extension if + appendmat==True) Can also pass open file-like object.''', + 'append_arg': + '''appendmat : bool, optional + True to append the .mat extension to the end of the given + filename, if not already present. Default is True.''', + 'load_args': + '''byte_order : str or None, optional + None by default, implying byte order guessed from mat + file. Otherwise can be one of ('native', '=', 'little', '<', + 'BIG', '>'). +mat_dtype : bool, optional + If True, return arrays in same dtype as would be loaded into + MATLAB (instead of the dtype with which they are saved). +squeeze_me : bool, optional + Whether to squeeze unit matrix dimensions or not. +chars_as_strings : bool, optional + Whether to convert char arrays to string arrays. +matlab_compatible : bool, optional + Returns matrices as would be loaded by MATLAB (implies + squeeze_me=False, chars_as_strings=False, mat_dtype=True, + struct_as_record=True).''', + 'struct_arg': + '''struct_as_record : bool, optional + Whether to load MATLAB structs as NumPy record arrays, or as + old-style NumPy arrays with dtype=object. Setting this flag to + False replicates the behavior of SciPy version 0.7.x (returning + numpy object arrays). The default setting is True, because it + allows easier round-trip load and save of MATLAB files.''', + 'matstream_arg': + '''mat_stream : file-like + Object with file API, open for reading.''', + 'long_fields': + '''long_field_names : bool, optional + * False - maximum field name length in a structure is 31 characters + which is the documented maximum length. This is the default. + * True - maximum field name length in a structure is 63 characters + which works for MATLAB 7.6''', + 'do_compression': + '''do_compression : bool, optional + Whether to compress matrices on write. Default is False.''', + 'oned_as': + '''oned_as : {'row', 'column'}, optional + If 'column', write 1-D NumPy arrays as column vectors. + If 'row', write 1D NumPy arrays as row vectors.''', + 'unicode_strings': + '''unicode_strings : bool, optional + If True, write strings as Unicode, else MATLAB usual encoding.'''} + +docfiller: Final = doccer.filldoc(doc_dict) + +''' + + Note on architecture +====================== + +There are three sets of parameters relevant for reading files. The +first are *file read parameters* - containing options that are common +for reading the whole file, and therefore every variable within that +file. At the moment these are: + +* mat_stream +* dtypes (derived from byte code) +* byte_order +* chars_as_strings +* squeeze_me +* struct_as_record (MATLAB 5 files) +* class_dtypes (derived from order code, MATLAB 5 files) +* codecs (MATLAB 5 files) +* uint16_codec (MATLAB 5 files) + +Another set of parameters are those that apply only to the current +variable being read - the *header*: + +* header related variables (different for v4 and v5 mat files) +* is_complex +* mclass +* var_stream + +With the header, we need ``next_position`` to tell us where the next +variable in the stream is. + +Then, for each element in a matrix, there can be *element read +parameters*. An element is, for example, one element in a MATLAB cell +array. At the moment, these are: + +* mat_dtype + +The file-reading object contains the *file read parameters*. The +*header* is passed around as a data object, or may be read and discarded +in a single function. The *element read parameters* - the mat_dtype in +this instance, is passed into a general post-processing function - see +``mio_utils`` for details. +''' + + +def convert_dtypes(dtype_template, order_code): + ''' Convert dtypes in mapping to given order + + Parameters + ---------- + dtype_template : mapping + mapping with values returning numpy dtype from ``np.dtype(val)`` + order_code : str + an order code suitable for using in ``dtype.newbyteorder()`` + + Returns + ------- + dtypes : mapping + mapping where values have been replaced by + ``np.dtype(val).newbyteorder(order_code)`` + + ''' + dtypes = dtype_template.copy() + for k in dtypes: + dtypes[k] = np.dtype(dtypes[k]).newbyteorder(order_code) + return dtypes + + +def read_dtype(mat_stream, a_dtype): + """ + Generic get of byte stream data of known type + + Parameters + ---------- + mat_stream : file_like object + MATLAB (tm) mat file stream + a_dtype : dtype + dtype of array to read. `a_dtype` is assumed to be correct + endianness. + + Returns + ------- + arr : ndarray + Array of dtype `a_dtype` read from stream. + + """ + num_bytes = a_dtype.itemsize + arr = np.ndarray(shape=(), + dtype=a_dtype, + buffer=mat_stream.read(num_bytes), + order='F') + return arr + + +def matfile_version(file_name, *, appendmat=True): + """ + Return major, minor tuple depending on apparent mat file type + + Where: + + #. 0,x -> version 4 format mat files + #. 1,x -> version 5 format mat files + #. 2,x -> version 7.3 format mat files (HDF format) + + Parameters + ---------- + file_name : str + Name of the mat file (do not need .mat extension if + appendmat==True). Can also pass open file-like object. + appendmat : bool, optional + True to append the .mat extension to the end of the given + filename, if not already present. Default is True. + + Returns + ------- + major_version : {0, 1, 2} + major MATLAB File format version + minor_version : int + minor MATLAB file format version + + Raises + ------ + MatReadError + If the file is empty. + ValueError + The matfile version is unknown. + + Notes + ----- + Has the side effect of setting the file read pointer to 0 + """ + from ._mio import _open_file_context + with _open_file_context(file_name, appendmat=appendmat) as fileobj: + return _get_matfile_version(fileobj) + + +get_matfile_version = matfile_version + + +_HDR_N_BYTES = 20 + + +def _get_matfile_version(fileobj): + # Mat4 files have a zero somewhere in first 4 bytes + fileobj.seek(0) + hdr_bytes = fileobj.read(_HDR_N_BYTES) + if len(hdr_bytes) < _HDR_N_BYTES: + raise MatReadError("Mat file appears to be truncated") + if hdr_bytes.count(0) == _HDR_N_BYTES: + raise MatReadError("Mat file appears to be corrupt " + f"(first {_HDR_N_BYTES} bytes == 0)") + mopt_ints = np.ndarray(shape=(4,), dtype=np.uint8, buffer=hdr_bytes[:4]) + if 0 in mopt_ints: + fileobj.seek(0) + return (0,0) + # For 5 format or 7.3 format we need to read an integer in the + # header. Bytes 124 through 128 contain a version integer and an + # endian test string + fileobj.seek(124) + tst_str = fileobj.read(4) + fileobj.seek(0) + maj_ind = int(tst_str[2] == b'I'[0]) + maj_val = int(tst_str[maj_ind]) + min_val = int(tst_str[1 - maj_ind]) + ret = (maj_val, min_val) + if maj_val in (1, 2): + return ret + raise ValueError('Unknown mat file type, version {}, {}'.format(*ret)) + + +def matdims(arr, oned_as='column'): + """ + Determine equivalent MATLAB dimensions for given array + + Parameters + ---------- + arr : ndarray + Input array + oned_as : {'column', 'row'}, optional + Whether 1-D arrays are returned as MATLAB row or column matrices. + Default is 'column'. + + Returns + ------- + dims : tuple + Shape tuple, in the form MATLAB expects it. + + Notes + ----- + We had to decide what shape a 1 dimensional array would be by + default. ``np.atleast_2d`` thinks it is a row vector. The + default for a vector in MATLAB (e.g., ``>> 1:12``) is a row vector. + + Versions of scipy up to and including 0.11 resulted (accidentally) + in 1-D arrays being read as column vectors. For the moment, we + maintain the same tradition here. + + Examples + -------- + >>> import numpy as np + >>> from scipy.io.matlab._miobase import matdims + >>> matdims(np.array(1)) # NumPy scalar + (1, 1) + >>> matdims(np.array([1])) # 1-D array, 1 element + (1, 1) + >>> matdims(np.array([1,2])) # 1-D array, 2 elements + (2, 1) + >>> matdims(np.array([[2],[3]])) # 2-D array, column vector + (2, 1) + >>> matdims(np.array([[2,3]])) # 2-D array, row vector + (1, 2) + >>> matdims(np.array([[[2,3]]])) # 3-D array, rowish vector + (1, 1, 2) + >>> matdims(np.array([])) # empty 1-D array + (0, 0) + >>> matdims(np.array([[]])) # empty 2-D array + (0, 0) + >>> matdims(np.array([[[]]])) # empty 3-D array + (0, 0, 0) + + Optional argument flips 1-D shape behavior. + + >>> matdims(np.array([1,2]), 'row') # 1-D array, 2 elements + (1, 2) + + The argument has to make sense though + + >>> matdims(np.array([1,2]), 'bizarre') + Traceback (most recent call last): + ... + ValueError: 1-D option "bizarre" is strange + + """ + shape = arr.shape + if shape == (): # scalar + return (1, 1) + if len(shape) == 1: # 1D + if shape[0] == 0: + return (0, 0) + elif oned_as == 'column': + return shape + (1,) + elif oned_as == 'row': + return (1,) + shape + else: + raise ValueError(f'1-D option "{oned_as}" is strange') + return shape + + +class MatVarReader: + ''' Abstract class defining required interface for var readers''' + def __init__(self, file_reader): + pass + + def read_header(self): + ''' Returns header ''' + pass + + def array_from_header(self, header): + ''' Reads array given header ''' + pass + + +class MatFileReader: + """ Base object for reading mat files + + To make this class functional, you will need to override the + following methods: + + matrix_getter_factory - gives object to fetch next matrix from stream + guess_byte_order - guesses file byte order from file + """ + + @docfiller + def __init__(self, mat_stream, + byte_order=None, + mat_dtype=False, + squeeze_me=False, + chars_as_strings=True, + matlab_compatible=False, + struct_as_record=True, + verify_compressed_data_integrity=True, + simplify_cells=False): + ''' + Initializer for mat file reader + + mat_stream : file-like + object with file API, open for reading + %(load_args)s + ''' + # Initialize stream + self.mat_stream = mat_stream + self.dtypes = {} + if not byte_order: + byte_order = self.guess_byte_order() + else: + byte_order = boc.to_numpy_code(byte_order) + self.byte_order = byte_order + self.struct_as_record = struct_as_record + if matlab_compatible: + self.set_matlab_compatible() + else: + self.squeeze_me = squeeze_me + self.chars_as_strings = chars_as_strings + self.mat_dtype = mat_dtype + self.verify_compressed_data_integrity = verify_compressed_data_integrity + self.simplify_cells = simplify_cells + if simplify_cells: + self.squeeze_me = True + self.struct_as_record = False + + def set_matlab_compatible(self): + ''' Sets options to return arrays as MATLAB loads them ''' + self.mat_dtype = True + self.squeeze_me = False + self.chars_as_strings = False + + def guess_byte_order(self): + ''' As we do not know what file type we have, assume native ''' + return boc.native_code + + def end_of_stream(self): + b = self.mat_stream.read(1) + curpos = self.mat_stream.tell() + self.mat_stream.seek(curpos-1) + return len(b) == 0 + + +def arr_dtype_number(arr, num): + ''' Return dtype for given number of items per element''' + return np.dtype(arr.dtype.str[:2] + str(num)) + + +def arr_to_chars(arr): + ''' Convert string array to char array ''' + dims = list(arr.shape) + if not dims: + dims = [1] + dims.append(int(arr.dtype.str[2:])) + arr = np.ndarray(shape=dims, + dtype=arr_dtype_number(arr, 1), + buffer=arr) + empties = [arr == np.array('', dtype=arr.dtype)] + if not np.any(empties): + return arr + arr = arr.copy() + arr[tuple(empties)] = ' ' + return arr diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_streams.cp311-win_amd64.dll.a b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_streams.cp311-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..11e3fb8c463d668491ee5211411e4b64375abc28 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/_streams.cp311-win_amd64.dll.a differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/byteordercodes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/byteordercodes.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7aa40acae02bfb62764bfe1cadac13122468e0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/byteordercodes.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="byteordercodes", + private_modules=["_byteordercodes"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio.py new file mode 100644 index 0000000000000000000000000000000000000000..c75bb56a01c7d6c8188b9b865af207a6a5157609 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio.py @@ -0,0 +1,16 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = ["loadmat", "savemat", "whosmat"] # noqa: F822 + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="mio", + private_modules=["_mio"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio4.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio4.py new file mode 100644 index 0000000000000000000000000000000000000000..566d873030611f0026d501a9aea31a228a678dc9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio4.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="mio4", + private_modules=["_mio4"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5.py new file mode 100644 index 0000000000000000000000000000000000000000..2c124bcb1f915d1d5f57c2e0d91b313a25755b66 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5.py @@ -0,0 +1,19 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'MatWriteError', 'MatReadError', 'MatReadWarning', 'MatlabObject', + 'MatlabFunction', 'mat_struct', 'varmats_from_mat', +] + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="mio5", + private_modules=["_mio5"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5_params.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5_params.py new file mode 100644 index 0000000000000000000000000000000000000000..37095753f173dfa2fb218f74365565e81d6d304b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5_params.py @@ -0,0 +1,18 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'MatlabFunction', 'MatlabObject', 'MatlabOpaque', 'mat_struct', +] + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="mio5_params", + private_modules=["_mio5_params"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..19198c70a3f1cead751a558ba0cb03c0ec5f70be --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio5_utils.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="mio5_utils", + private_modules=["_mio5_utils"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e535b7b62d83ed42d165c3122c61d00257b19ee9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/mio_utils.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="mio_utils", + private_modules=["_mio_utils"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/miobase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/miobase.py new file mode 100644 index 0000000000000000000000000000000000000000..482660e2765996df6c65a96ac4cd29e35da10ad5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/miobase.py @@ -0,0 +1,16 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = ["MatReadError", "MatReadWarning", "MatWriteError"] # noqa: F822 + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="miobase", + private_modules=["_miobase"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/streams.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..d495b46507e25b2302f493ef0041b9ffd36260a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/streams.py @@ -0,0 +1,16 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io.matlab` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io.matlab", module="streams", + private_modules=["_streams"], all=__all__, + attribute=name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b7e1a06a185304e769c902a413b02bdf74ed300 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_byteordercodes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_byteordercodes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..380e2b1bd5e7193cebf17856011088ab869e1450 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_byteordercodes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c90348f3646de9c5297afe0fc5b86e4c404ec017 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio5_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio5_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f96c041cd2e1737367f9db180007870222595c30 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio5_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio_funcs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio_funcs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2affe6727ca9f7b631637f97225d97559792aab6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio_funcs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32ac80bb32e94f043844f6e067833335bce694bf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_mio_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_miobase.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_miobase.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe85b70df1945509434eaf3efc6bbfea8b4b36c7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_miobase.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_pathological.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_pathological.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e23c8d07706bf6ef203a0a18227c5896d854f03 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_pathological.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_streams.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_streams.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66b02957826e22e2ee7dee246b1331a477c0faac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/__pycache__/test_streams.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat new file mode 100644 index 0000000000000000000000000000000000000000..c9ab357ec85972cf0014752a1e0ccb08ff284af9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/bad_miutf8_array_name.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/bad_miutf8_array_name.mat new file mode 100644 index 0000000000000000000000000000000000000000..a17203fbb2a7628db644b953ac7723b866a2a0a4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/bad_miutf8_array_name.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/big_endian.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/big_endian.mat new file mode 100644 index 0000000000000000000000000000000000000000..2a0c982c298fba9df96fd5a927a9c08ee12b09df Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/big_endian.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/broken_utf8.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/broken_utf8.mat new file mode 100644 index 0000000000000000000000000000000000000000..4f6323870368cd97a6294e108ffea9067cf5e69b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/broken_utf8.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat new file mode 100644 index 0000000000000000000000000000000000000000..c88cbb6f54b70d4e795de7cf43f7b46ff6d4d5ef Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat new file mode 100644 index 0000000000000000000000000000000000000000..45a2ef4e39755ea1f41aab045f18a035af58ea07 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/debigged_m4.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/debigged_m4.mat new file mode 100644 index 0000000000000000000000000000000000000000..28aad199045d0b3bf31060300aff9231ee6d9a71 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/debigged_m4.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/japanese_utf8.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/japanese_utf8.txt new file mode 100644 index 0000000000000000000000000000000000000000..1459b6b6ea635b17b5eb04c941e197f98cf04bf1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/japanese_utf8.txt @@ -0,0 +1,5 @@ +Japanese: +すべての人間は、生まれながらにして自由であり、 +かつ、尊厳と権利と について平等である。 +人間は、理性と良心とを授けられており、 +互いに同胞の精神をもって行動しなければならない。 \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/little_endian.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/little_endian.mat new file mode 100644 index 0000000000000000000000000000000000000000..df6db666dcf2b98d66e04933bd4011f649dcbe30 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/little_endian.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat new file mode 100644 index 0000000000000000000000000000000000000000..a60ad5b605a9dc6b0d85eb0a0e3e655c4955dd34 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/malformed1.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/malformed1.mat new file mode 100644 index 0000000000000000000000000000000000000000..54462e27d663770bc33ef73ed70baae65767719d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/malformed1.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat new file mode 100644 index 0000000000000000000000000000000000000000..fd2c4994578edbf31431902ecfcb601b11f60b0b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat new file mode 100644 index 0000000000000000000000000000000000000000..ccfdaa8adb7879ba852eab9ce55b602e11dad06d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat new file mode 100644 index 0000000000000000000000000000000000000000..35dcb715bca4cb7f4b0dca287648ef8ee797cd73 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/one_by_zero_char.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/one_by_zero_char.mat new file mode 100644 index 0000000000000000000000000000000000000000..07e7dca456843004dcfd9023a800ea91d309814d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/one_by_zero_char.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/parabola.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/parabola.mat new file mode 100644 index 0000000000000000000000000000000000000000..66350532a7737c475a3ae6ef1b1d8406543d890e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/parabola.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/single_empty_string.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/single_empty_string.mat new file mode 100644 index 0000000000000000000000000000000000000000..293f387719e8bdcacb075e0de5737894e5dafed3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/single_empty_string.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/some_functions.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/some_functions.mat new file mode 100644 index 0000000000000000000000000000000000000000..cc818593b48dd8d29a40a827210b54373e5acf50 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/some_functions.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/sqr.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/sqr.mat new file mode 100644 index 0000000000000000000000000000000000000000..2436d87cc5dfb6d558b841c2367bfe2363bd1b3c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/sqr.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..453712610bf46501d8dd3667ff72d8033f49d81c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..e04d27d30378655ed14634330c7a8ddcd0b98c10 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..4c0303039826af6f6caa928e505cec10ebb3fa81 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..232a051c774105176c28c9718c2cd46f1a1ee1af Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_empty_struct.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_empty_struct.mat new file mode 100644 index 0000000000000000000000000000000000000000..30c8c8ad5378be4508bd785da8b7cef38adbd13e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_empty_struct.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_mat4_le_floats.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_mat4_le_floats.mat new file mode 100644 index 0000000000000000000000000000000000000000..6643c42ddcc9579930980b7eb30e11f339638404 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_mat4_le_floats.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat new file mode 100644 index 0000000000000000000000000000000000000000..efbe3fec64ee54c9f8b3998e5035ccfa251e74ff Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testbool_8_WIN64.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testbool_8_WIN64.mat new file mode 100644 index 0000000000000000000000000000000000000000..faa30b10bc61ea4889bd9e776c0a1a079e2c2a90 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testbool_8_WIN64.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..512f7d889420a016094a903585f27acaa50bc658 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..a7633104c1e4f32fe30fd43f389d7559527c8211 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..2ac1da15873c5edac27758b6f91563d2b8aaace0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..fc893f331c985cf17b7ce9b7b8c179eaf2103659 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..4198a4f2aeb8effcccf94a9c0114539f98124179 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..2c7826eeacdb456e5290cafba343703c7596d191 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..b3b086cc31dce2de1e300a1d018b0bf5661b69f3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..316f8894c5ecc88468cfa0908c277f730e3163e8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..36621b25c08f18e4545100c6eaec015123c3bf9f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..32fcd2a93c91eff478a3ab3076e5c78e31f09bf1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..f3ecd203376c17b09d97a24aceab824dae0f91c1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..c0c083855f38e62e3a29460b745f198c9c79313d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..6a187edb1828256362617d3fe24d26cf58e7ca3b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..5dbfcf17dd0e01dc0325dd009340291158906e8d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..8e36c0c8ce62d7559b60fde454a96e8eefcbcb92 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..a003b6d866f77a25d3b8b236bc95e343221e3019 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..3106712e1099345b48dc4e4125d5e739c24b5341 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..9097bb08712d5bfccf172b0366573f503136228d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..e7dec3b81abdae8769e0ae0329948548f4038adf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..a1c93483597f364443158132b31b86693891b02a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..f29d4f9327aa906729234a38caa05ebfc50cfc30 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..8b244044cf3028df9a019a259d8fc533b80f7fb7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..adb6c28ee95d1cf8bf3bfeb72295d1a7848020f8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..6066c1e30f69b76afdb8d251ecefd8cd9e1acde5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..3698c8853b46d4a42194002523b57fddfb225908 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..164be1109d977cf7681b1ea00a5df80d5e8f8e71 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..a8735e9a23558ce86a528ceafa8f3475b053e43b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..b6fb05bb7564c863d5bb6c145fe8b06928d3805a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..eb537ab1042b0f989d49711b1a36cc508946fe55 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..cc207ed9f32095f39b7690e2dc1e2dc0d55ee8e0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..c2f0ba2ae4c8a1750cace6eae0267e9736272fc0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..b4dbd152d6e9f3d289b3c4a9792729d2735a4c5c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..fadcd2366b1867239782f073291ff327c2af3001 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..9ce65f91116f68332d1c16e21319e965541d0d73 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..9c6ba793cf41bf36447ab7a1890447fe5e939614 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..0c4729c56b6ab1e8945249a4d3144c79d8538e9e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..6d3e068977edfe6407f29404f0a7d1737f7d3eba Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..fc13642263a64874f6c2ac602be9cdcb9b788996 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..f68323b0c8eb7fc999dead349ea3bd3a6da66bd4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..83dcad34249afa543bf66dae9b836276246aab4a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..59d243c4de4fbb3fa653753e40651a6d0a4f4967 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..cdb4191c7d2eb0ac66d4f6add250e1f6a604d892 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..3b5a428501a53ae7308c7b6edc42f4881820664d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..8cef2dd7ea6df8aac26ed067a9427935b81c7ac7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..5ba4810ac67756c17b0ef3163a496e913c0b5e57 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..8964765f7bd207bfab63b4d16569cb1c3763bda7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..1dcd72e51a51abdcf48bd37f68b9927421c17cb0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsimplecell.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsimplecell.mat new file mode 100644 index 0000000000000000000000000000000000000000..2a98f48917f8f275e541eeac5ef1fe741c40bb0b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsimplecell.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..55cbd3c1b3d65630beae47832ffbcc7a6fd43354 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..194ca4d7d4d4d22be5669041a25c3ca24ae6edcb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..3e1e9a1ec916040e94c231f428725add10a2709c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..55b510762ee9b0ac04776e38f6b4bb46b0d10021 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..bdb6ce66ce79b808f044124156db4b803dab155e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..81c536d0b067b92cae1b7a2ee71824e2c5e730d9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..520e1cedb3823b859666b1fa8872e073904fd4c6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..969b7143dfff3bb817dbf70c54af8303c3b5822e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..9117dce3092e3e6a39b67da9a7ad1dcfc3ded385 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..a8a615a320f9c8db068a9120c1ceb2e49bb0ea6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..15424266a3bd4aa1e7525a8fdc4945b51d2b5ad6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..137561e1f636d7b08959e43e969a6984eb7a3b37 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..2ad75f2e17d8b3fda285490d52b426d1f27d0d95 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..6fd12d884d19df65f1534c13944e988e636166f1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..ab93994f7befe7d1505c84c238d6409bcb3d438a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..63059b84476749119f44ebefda795f85f6ab27d7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..fa687ee988ce530bca87f46235667baa30ac038b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..11afb412056ad803f0d8ac1d9dcb188d42285fdf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..75e07a0b55e008b070f41dabba7480a4e463b67a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..7d76f63643737834053f80539188c9dad75ed0cb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..954e39beb8156b460ca904ff66261d8f2fc338cb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..5086bb7acdc3773186e903000aace436c90dc565 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..6feb6e42375ebebf6dd9440ee09312204cbf1a33 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..b2ff2226223181ec5c42d36afe4f56728f25972d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..028841f9d3aae42d6cf782db14634cbe375f0a05 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..da57365926afe1e8d7dd424a6fcd5b52bc3233ac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..d1c97a7a2e1edf9683959ec36e899ef8e355073c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..c7ca09594106a765e815a55e942019d17c181270 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..8716f7e3db67d1fd479f913d12286715029ed1a4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..2c34c4d8c1477bc4859880a8d2f800073825dcd1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..c6dccc00289f61787b235f4299aa5a14ab4f6d07 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..0f6f5444b0c1e4bcd80dc0f63b28523d655b05d0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..faf9221b776eee67cd5d2971da5ba77732ef8016 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..1b7b3d7f002080839f672e4eb858bbfbddda27ec Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..d22fb57c81fc3ec9ee7e9b447a05e8a89ff1fcfe Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..76c51d01388a1770b348bc603ebfdd51bc011f0c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_byteordercodes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_byteordercodes.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd5faa965fb7f8f88bece6cdd2f463789f078e3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_byteordercodes.py @@ -0,0 +1,29 @@ +''' Tests for byteorder module ''' + +import sys + +from numpy.testing import assert_ +from pytest import raises as assert_raises + +import scipy.io.matlab._byteordercodes as sibc + + +def test_native(): + native_is_le = sys.byteorder == 'little' + assert_(sibc.sys_is_le == native_is_le) + + +def test_to_numpy(): + if sys.byteorder == 'little': + assert_(sibc.to_numpy_code('native') == '<') + assert_(sibc.to_numpy_code('swapped') == '>') + else: + assert_(sibc.to_numpy_code('native') == '>') + assert_(sibc.to_numpy_code('swapped') == '<') + assert_(sibc.to_numpy_code('native') == sibc.to_numpy_code('=')) + assert_(sibc.to_numpy_code('big') == '>') + for code in ('little', '<', 'l', 'L', 'le'): + assert_(sibc.to_numpy_code(code) == '<') + for code in ('big', '>', 'b', 'B', 'be'): + assert_(sibc.to_numpy_code(code) == '>') + assert_raises(ValueError, sibc.to_numpy_code, 'silly string') diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio.py new file mode 100644 index 0000000000000000000000000000000000000000..46f71270d96c8fa1be751c0d37db92c1eb1c9314 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio.py @@ -0,0 +1,1399 @@ +import os +from collections import OrderedDict +from os.path import join as pjoin, dirname +from glob import glob +from io import BytesIO +import re +from tempfile import mkdtemp + +import warnings +import shutil +import gzip + +from numpy.testing import (assert_array_equal, assert_array_almost_equal, + assert_equal, assert_, assert_allclose) +import pytest +from pytest import raises as assert_raises, warns as assert_warns + +import numpy as np +from numpy import array +from scipy.sparse import issparse, eye_array, coo_array, csc_array + +import scipy.io +from scipy.io.matlab import MatlabOpaque, MatlabFunction, MatlabObject +import scipy.io.matlab._byteordercodes as boc +from scipy.io.matlab._miobase import (matdims, MatWriteError, MatReadError, + matfile_version, MatWriteWarning) +from scipy.io.matlab._mio import mat_reader_factory, loadmat, savemat, whosmat +from scipy.io.matlab._mio5 import ( + MatFile5Writer, MatFile5Reader, varmats_from_mat, to_writeable, + EmptyStructMarker) +import scipy.io.matlab._mio5_params as mio5p + + +test_data_path = pjoin(dirname(__file__), 'data') +pytestmark = pytest.mark.thread_unsafe + + +def mlarr(*args, **kwargs): + """Convenience function to return matlab-compatible 2-D array.""" + arr = np.array(*args, **kwargs) + arr = arr.reshape(matdims(arr)) + return arr + + +# Define cases to test +theta = np.pi/4*np.arange(9,dtype=float).reshape(1,9) +case_table4 = [ + {'name': 'double', + 'classes': {'testdouble': 'double'}, + 'expected': {'testdouble': theta} + }] +case_table4.append( + {'name': 'string', + 'classes': {'teststring': 'char'}, + 'expected': {'teststring': + array(['"Do nine men interpret?" "Nine men," I nod.'])} + }) +case_table4.append( + {'name': 'complex', + 'classes': {'testcomplex': 'double'}, + 'expected': {'testcomplex': np.cos(theta) + 1j*np.sin(theta)} + }) +A = np.zeros((3,5)) +A[0] = list(range(1,6)) +A[:,0] = list(range(1,4)) +case_table4.append( + {'name': 'matrix', + 'classes': {'testmatrix': 'double'}, + 'expected': {'testmatrix': A}, + }) +case_table4.append( + {'name': 'sparse', + 'classes': {'testsparse': 'sparse'}, + 'expected': {'testsparse': coo_array(A)}, + }) +B = A.astype(complex) +B[0,0] += 1j +case_table4.append( + {'name': 'sparsecomplex', + 'classes': {'testsparsecomplex': 'sparse'}, + 'expected': {'testsparsecomplex': coo_array(B)}, + }) +case_table4.append( + {'name': 'multi', + 'classes': {'theta': 'double', 'a': 'double'}, + 'expected': {'theta': theta, 'a': A}, + }) +case_table4.append( + {'name': 'minus', + 'classes': {'testminus': 'double'}, + 'expected': {'testminus': mlarr(-1)}, + }) +case_table4.append( + {'name': 'onechar', + 'classes': {'testonechar': 'char'}, + 'expected': {'testonechar': array(['r'])}, + }) +# Cell arrays stored as object arrays +CA = mlarr(( # tuple for object array creation + [], + mlarr([1]), + mlarr([[1,2]]), + mlarr([[1,2,3]])), dtype=object).reshape(1,-1) +CA[0,0] = array( + ['This cell contains this string and 3 arrays of increasing length']) +case_table5 = [ + {'name': 'cell', + 'classes': {'testcell': 'cell'}, + 'expected': {'testcell': CA}}] +CAE = mlarr(( # tuple for object array creation + mlarr(1), + mlarr(2), + mlarr([]), + mlarr([]), + mlarr(3)), dtype=object).reshape(1,-1) +objarr = np.empty((1,1),dtype=object) +objarr[0,0] = mlarr(1) +case_table5.append( + {'name': 'scalarcell', + 'classes': {'testscalarcell': 'cell'}, + 'expected': {'testscalarcell': objarr} + }) +case_table5.append( + {'name': 'emptycell', + 'classes': {'testemptycell': 'cell'}, + 'expected': {'testemptycell': CAE}}) +case_table5.append( + {'name': 'stringarray', + 'classes': {'teststringarray': 'char'}, + 'expected': {'teststringarray': array( + ['one ', 'two ', 'three'])}, + }) +case_table5.append( + {'name': '3dmatrix', + 'classes': {'test3dmatrix': 'double'}, + 'expected': { + 'test3dmatrix': np.transpose(np.reshape(list(range(1,25)), (4,3,2)))} + }) +st_sub_arr = array([np.sqrt(2),np.exp(1),np.pi]).reshape(1,3) +dtype = [(n, object) for n in ['stringfield', 'doublefield', 'complexfield']] +st1 = np.zeros((1,1), dtype) +st1['stringfield'][0,0] = array(['Rats live on no evil star.']) +st1['doublefield'][0,0] = st_sub_arr +st1['complexfield'][0,0] = st_sub_arr * (1 + 1j) +case_table5.append( + {'name': 'struct', + 'classes': {'teststruct': 'struct'}, + 'expected': {'teststruct': st1} + }) +CN = np.zeros((1,2), dtype=object) +CN[0,0] = mlarr(1) +CN[0,1] = np.zeros((1,3), dtype=object) +CN[0,1][0,0] = mlarr(2, dtype=np.uint8) +CN[0,1][0,1] = mlarr([[3]], dtype=np.uint8) +CN[0,1][0,2] = np.zeros((1,2), dtype=object) +CN[0,1][0,2][0,0] = mlarr(4, dtype=np.uint8) +CN[0,1][0,2][0,1] = mlarr(5, dtype=np.uint8) +case_table5.append( + {'name': 'cellnest', + 'classes': {'testcellnest': 'cell'}, + 'expected': {'testcellnest': CN}, + }) +st2 = np.empty((1,1), dtype=[(n, object) for n in ['one', 'two']]) +st2[0,0]['one'] = mlarr(1) +st2[0,0]['two'] = np.empty((1,1), dtype=[('three', object)]) +st2[0,0]['two'][0,0]['three'] = array(['number 3']) +case_table5.append( + {'name': 'structnest', + 'classes': {'teststructnest': 'struct'}, + 'expected': {'teststructnest': st2} + }) +a = np.empty((1,2), dtype=[(n, object) for n in ['one', 'two']]) +a[0,0]['one'] = mlarr(1) +a[0,0]['two'] = mlarr(2) +a[0,1]['one'] = array(['number 1']) +a[0,1]['two'] = array(['number 2']) +case_table5.append( + {'name': 'structarr', + 'classes': {'teststructarr': 'struct'}, + 'expected': {'teststructarr': a} + }) +ODT = np.dtype([(n, object) for n in + ['expr', 'inputExpr', 'args', + 'isEmpty', 'numArgs', 'version']]) +MO = MatlabObject(np.zeros((1,1), dtype=ODT), 'inline') +m0 = MO[0,0] +m0['expr'] = array(['x']) +m0['inputExpr'] = array([' x = INLINE_INPUTS_{1};']) +m0['args'] = array(['x']) +m0['isEmpty'] = mlarr(0) +m0['numArgs'] = mlarr(1) +m0['version'] = mlarr(1) +case_table5.append( + {'name': 'object', + 'classes': {'testobject': 'object'}, + 'expected': {'testobject': MO} + }) +fp_u_str = open(pjoin(test_data_path, 'japanese_utf8.txt'), 'rb') +u_str = fp_u_str.read().decode('utf-8') +fp_u_str.close() +case_table5.append( + {'name': 'unicode', + 'classes': {'testunicode': 'char'}, + 'expected': {'testunicode': array([u_str])} + }) +case_table5.append( + {'name': 'sparse', + 'classes': {'testsparse': 'sparse'}, + 'expected': {'testsparse': coo_array(A)}, + }) +case_table5.append( + {'name': 'sparsecomplex', + 'classes': {'testsparsecomplex': 'sparse'}, + 'expected': {'testsparsecomplex': coo_array(B)}, + }) +case_table5.append( + {'name': 'bool', + 'classes': {'testbools': 'logical'}, + 'expected': {'testbools': + array([[True], [False]])}, + }) + +case_table5_rt = case_table5[:] +# Inline functions can't be concatenated in matlab, so RT only +case_table5_rt.append( + {'name': 'objectarray', + 'classes': {'testobjectarray': 'object'}, + 'expected': {'testobjectarray': np.repeat(MO, 2).reshape(1,2)}}) + + +def types_compatible(var1, var2): + """Check if types are same or compatible. + + 0-D numpy scalars are compatible with bare python scalars. + """ + type1 = type(var1) + type2 = type(var2) + if type1 is type2: + return True + if type1 is np.ndarray and var1.shape == (): + return type(var1.item()) is type2 + if type2 is np.ndarray and var2.shape == (): + return type(var2.item()) is type1 + return False + + +def _check_level(label, expected, actual): + """ Check one level of a potentially nested array """ + if issparse(expected): # allow different types of sparse matrices + assert_(issparse(actual)) + assert_array_almost_equal(actual.toarray(), + expected.toarray(), + err_msg=label, + decimal=5) + return + # Check types are as expected + assert_(types_compatible(expected, actual), + f"Expected type {type(expected)}, got {type(actual)} at {label}") + # A field in a record array may not be an ndarray + # A scalar from a record array will be type np.void + if not isinstance(expected, np.void | np.ndarray | MatlabObject): + assert_equal(expected, actual) + return + # This is an ndarray-like thing + assert_(expected.shape == actual.shape, + msg=f'Expected shape {expected.shape}, got {actual.shape} at {label}') + ex_dtype = expected.dtype + if ex_dtype.hasobject: # array of objects + if isinstance(expected, MatlabObject): + assert_equal(expected.classname, actual.classname) + for i, ev in enumerate(expected): + level_label = f"{label}, [{i}], " + _check_level(level_label, ev, actual[i]) + return + if ex_dtype.fields: # probably recarray + for fn in ex_dtype.fields: + level_label = f"{label}, field {fn}, " + _check_level(level_label, + expected[fn], actual[fn]) + return + if ex_dtype.type in (str, # string or bool + np.str_, + np.bool_): + assert_equal(actual, expected, err_msg=label) + return + # Something numeric + assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) + + +def _load_check_case(name, files, case): + for file_name in files: + matdict = loadmat(file_name, struct_as_record=True, spmatrix=False) + label = f"test {name}; file {file_name}" + for k, expected in case.items(): + k_label = f"{label}, variable {k}" + assert_(k in matdict, f"Missing key at {k_label}") + _check_level(k_label, expected, matdict[k]) + + +def _whos_check_case(name, files, case, classes): + for file_name in files: + label = f"test {name}; file {file_name}" + + whos = whosmat(file_name) + + expected_whos = [ + (k, expected.shape, classes[k]) for k, expected in case.items()] + + whos.sort() + expected_whos.sort() + assert_equal(whos, expected_whos, + f"{label}: {whos!r} != {expected_whos!r}" + ) + + +# Round trip tests +def _rt_check_case(name, expected, format): + mat_stream = BytesIO() + savemat(mat_stream, expected, format=format) + mat_stream.seek(0) + _load_check_case(name, [mat_stream], expected) + + +# generator for tests +def _cases(version, filt='test%(name)s_*.mat'): + if version == '4': + cases = case_table4 + elif version == '5': + cases = case_table5 + else: + assert version == '5_rt' + cases = case_table5_rt + for case in cases: + name = case['name'] + expected = case['expected'] + if filt is None: + files = None + else: + use_filt = pjoin(test_data_path, filt % dict(name=name)) + files = glob(use_filt) + assert len(files) > 0, \ + f"No files for test {name} using filter {filt}" + classes = case['classes'] + yield name, files, expected, classes + + +@pytest.mark.parametrize('version', ('4', '5')) +def test_load(version): + for case in _cases(version): + _load_check_case(*case[:3]) + + +@pytest.mark.parametrize('version', ('4', '5')) +def test_whos(version): + for case in _cases(version): + _whos_check_case(*case) + + +# generator for round trip tests +@pytest.mark.parametrize('version, fmts', [ + ('4', ['4', '5']), + ('5_rt', ['5']), +]) +def test_round_trip(version, fmts): + for case in _cases(version, filt=None): + for fmt in fmts: + _rt_check_case(case[0], case[2], fmt) + + +def test_gzip_simple(): + xdense = np.zeros((20,20)) + xdense[2,3] = 2.3 + xdense[4,5] = 4.5 + x = csc_array(xdense) + + name = 'gzip_test' + expected = {'x':x} + format = '4' + + tmpdir = mkdtemp() + try: + fname = pjoin(tmpdir,name) + mat_stream = gzip.open(fname, mode='wb') + savemat(mat_stream, expected, format=format) + mat_stream.close() + + mat_stream = gzip.open(fname, mode='rb') + actual = loadmat(mat_stream, struct_as_record=True, spmatrix=False) + mat_stream.close() + finally: + shutil.rmtree(tmpdir) + + assert_array_almost_equal(actual['x'].toarray(), + expected['x'].toarray(), + err_msg=repr(actual)) + + +def test_multiple_open(): + # Ticket #1039, on Windows: check that files are not left open + tmpdir = mkdtemp() + try: + x = dict(x=np.zeros((2, 2))) + + fname = pjoin(tmpdir, "a.mat") + + # Check that file is not left open + savemat(fname, x) + os.unlink(fname) + savemat(fname, x) + loadmat(fname) + os.unlink(fname) + + # Check that stream is left open + f = open(fname, 'wb') + savemat(f, x) + f.seek(0) + f.close() + + f = open(fname, 'rb') + loadmat(f) + f.seek(0) + f.close() + finally: + shutil.rmtree(tmpdir) + + +def test_mat73(): + # Check any hdf5 files raise an error + filenames = glob( + pjoin(test_data_path, 'testhdf5*.mat')) + assert_(len(filenames) > 0) + for filename in filenames: + fp = open(filename, 'rb') + assert_raises(NotImplementedError, + loadmat, + fp, + struct_as_record=True) + fp.close() + + +def test_warnings(): + # This test is an echo of the previous behavior, which was to raise a + # warning if the user triggered a search for mat files on the Python system + # path. We can remove the test in the next version after upcoming (0.13). + fname = pjoin(test_data_path, 'testdouble_7.1_GLNX86.mat') + with warnings.catch_warnings(): + warnings.simplefilter('error') + # This should not generate a warning + loadmat(fname, struct_as_record=True) + # This neither + loadmat(fname, struct_as_record=False) + + +def test_regression_653(): + # Saving a dictionary with only invalid keys used to raise an error. Now we + # save this as an empty struct in matlab space. + sio = BytesIO() + savemat(sio, {'d':{1:2}}, format='5') + back = loadmat(sio)['d'] + # Check we got an empty struct equivalent + assert_equal(back.shape, (1,1)) + assert_equal(back.dtype, np.dtype(object)) + assert_(back[0,0] is None) + + +def test_structname_len(): + # Test limit for length of field names in structs + lim = 31 + fldname = 'a' * lim + st1 = np.zeros((1,1), dtype=[(fldname, object)]) + savemat(BytesIO(), {'longstruct': st1}, format='5') + fldname = 'a' * (lim+1) + st1 = np.zeros((1,1), dtype=[(fldname, object)]) + assert_raises(ValueError, savemat, BytesIO(), + {'longstruct': st1}, format='5') + + +def test_4_and_long_field_names_incompatible(): + # Long field names option not supported in 4 + my_struct = np.zeros((1,1),dtype=[('my_fieldname',object)]) + assert_raises(ValueError, savemat, BytesIO(), + {'my_struct':my_struct}, format='4', long_field_names=True) + + +def test_long_field_names(): + # Test limit for length of field names in structs + lim = 63 + fldname = 'a' * lim + st1 = np.zeros((1,1), dtype=[(fldname, object)]) + savemat(BytesIO(), {'longstruct': st1}, format='5',long_field_names=True) + fldname = 'a' * (lim+1) + st1 = np.zeros((1,1), dtype=[(fldname, object)]) + assert_raises(ValueError, savemat, BytesIO(), + {'longstruct': st1}, format='5',long_field_names=True) + + +def test_long_field_names_in_struct(): + # Regression test - long_field_names was erased if you passed a struct + # within a struct + lim = 63 + fldname = 'a' * lim + cell = np.ndarray((1,2),dtype=object) + st1 = np.zeros((1,1), dtype=[(fldname, object)]) + cell[0,0] = st1 + cell[0,1] = st1 + savemat(BytesIO(), {'longstruct': cell}, format='5',long_field_names=True) + # + # Check to make sure it fails with long field names off + # + assert_raises(ValueError, savemat, BytesIO(), + {'longstruct': cell}, format='5', long_field_names=False) + + +def test_cell_with_one_thing_in_it(): + # Regression test - make a cell array that's 1 x 2 and put two + # strings in it. It works. Make a cell array that's 1 x 1 and put + # a string in it. It should work but, in the old days, it didn't. + cells = np.ndarray((1,2),dtype=object) + cells[0,0] = 'Hello' + cells[0,1] = 'World' + savemat(BytesIO(), {'x': cells}, format='5') + + cells = np.ndarray((1,1),dtype=object) + cells[0,0] = 'Hello, world' + savemat(BytesIO(), {'x': cells}, format='5') + + +def test_writer_properties(): + # Tests getting, setting of properties of matrix writer + mfw = MatFile5Writer(BytesIO()) + assert_equal(mfw.global_vars, []) + mfw.global_vars = ['avar'] + assert_equal(mfw.global_vars, ['avar']) + assert_equal(mfw.unicode_strings, False) + mfw.unicode_strings = True + assert_equal(mfw.unicode_strings, True) + assert_equal(mfw.long_field_names, False) + mfw.long_field_names = True + assert_equal(mfw.long_field_names, True) + + +def test_use_small_element(): + # Test whether we're using small data element or not + sio = BytesIO() + wtr = MatFile5Writer(sio) + # First check size for no sde for name + arr = np.zeros(10) + wtr.put_variables({'aaaaa': arr}) + w_sz = len(sio.getvalue()) + # Check small name results in largish difference in size + sio.truncate(0) + sio.seek(0) + wtr.put_variables({'aaaa': arr}) + assert_(w_sz - len(sio.getvalue()) > 4) + # Whereas increasing name size makes less difference + sio.truncate(0) + sio.seek(0) + wtr.put_variables({'aaaaaa': arr}) + assert_(len(sio.getvalue()) - w_sz < 4) + + +def test_save_dict(): + # Test that both dict and OrderedDict can be saved (as recarray), + # loaded as matstruct, and preserve order + ab_exp = np.array([[(1, 2)]], dtype=[('a', object), ('b', object)]) + for dict_type in (dict, OrderedDict): + # Initialize with tuples to keep order + d = dict_type([('a', 1), ('b', 2)]) + stream = BytesIO() + savemat(stream, {'dict': d}) + stream.seek(0) + vals = loadmat(stream)['dict'] + assert_equal(vals.dtype.names, ('a', 'b')) + assert_array_equal(vals, ab_exp) + + +def test_1d_shape(): + # New 5 behavior is 1D -> row vector + arr = np.arange(5) + for format in ('4', '5'): + # Column is the default + stream = BytesIO() + savemat(stream, {'oned': arr}, format=format) + vals = loadmat(stream) + assert_equal(vals['oned'].shape, (1, 5)) + # can be explicitly 'column' for oned_as + stream = BytesIO() + savemat(stream, {'oned':arr}, + format=format, + oned_as='column') + vals = loadmat(stream) + assert_equal(vals['oned'].shape, (5,1)) + # but different from 'row' + stream = BytesIO() + savemat(stream, {'oned':arr}, + format=format, + oned_as='row') + vals = loadmat(stream) + assert_equal(vals['oned'].shape, (1,5)) + + +def test_compression(): + arr = np.zeros(100).reshape((5,20)) + arr[2,10] = 1 + stream = BytesIO() + savemat(stream, {'arr':arr}) + raw_len = len(stream.getvalue()) + vals = loadmat(stream) + assert_array_equal(vals['arr'], arr) + stream = BytesIO() + savemat(stream, {'arr':arr}, do_compression=True) + compressed_len = len(stream.getvalue()) + vals = loadmat(stream) + assert_array_equal(vals['arr'], arr) + assert_(raw_len > compressed_len) + # Concatenate, test later + arr2 = arr.copy() + arr2[0,0] = 1 + stream = BytesIO() + savemat(stream, {'arr':arr, 'arr2':arr2}, do_compression=False) + vals = loadmat(stream) + assert_array_equal(vals['arr2'], arr2) + stream = BytesIO() + savemat(stream, {'arr':arr, 'arr2':arr2}, do_compression=True) + vals = loadmat(stream) + assert_array_equal(vals['arr2'], arr2) + + +def test_single_object(): + stream = BytesIO() + savemat(stream, {'A':np.array(1, dtype=object)}) + + +def test_skip_variable(): + # Test skipping over the first of two variables in a MAT file + # using mat_reader_factory and put_variables to read them in. + # + # This is a regression test of a problem that's caused by + # using the compressed file reader seek instead of the raw file + # I/O seek when skipping over a compressed chunk. + # + # The problem arises when the chunk is large: this file has + # a 256x256 array of random (uncompressible) doubles. + # + filename = pjoin(test_data_path,'test_skip_variable.mat') + # + # Prove that it loads with loadmat + # + d = loadmat(filename, struct_as_record=True) + assert_('first' in d) + assert_('second' in d) + # + # Make the factory + # + factory, file_opened = mat_reader_factory(filename, struct_as_record=True) + # + # This is where the factory breaks with an error in MatMatrixGetter.to_next + # + d = factory.get_variables('second') + assert_('second' in d) + factory.mat_stream.close() + + +def test_empty_struct(): + # ticket 885 + filename = pjoin(test_data_path,'test_empty_struct.mat') + # before ticket fix, this would crash with ValueError, empty data + # type + d = loadmat(filename, struct_as_record=True) + a = d['a'] + assert_equal(a.shape, (1,1)) + assert_equal(a.dtype, np.dtype(object)) + assert_(a[0,0] is None) + stream = BytesIO() + arr = np.array((), dtype='U') + # before ticket fix, this used to give data type not understood + savemat(stream, {'arr':arr}) + d = loadmat(stream) + a2 = d['arr'] + assert_array_equal(a2, arr) + + +def test_save_empty_dict(): + # saving empty dict also gives empty struct + stream = BytesIO() + savemat(stream, {'arr': {}}) + d = loadmat(stream) + a = d['arr'] + assert_equal(a.shape, (1,1)) + assert_equal(a.dtype, np.dtype(object)) + assert_(a[0,0] is None) + + +def assert_any_equal(output, alternatives): + """ Assert `output` is equal to at least one element in `alternatives` + """ + one_equal = False + for expected in alternatives: + if np.all(output == expected): + one_equal = True + break + assert_(one_equal) + + +def test_to_writeable(): + # Test to_writeable function + res = to_writeable(np.array([1])) # pass through ndarrays + assert_equal(res.shape, (1,)) + assert_array_equal(res, 1) + # Dict fields can be written in any order + expected1 = np.array([(1, 2)], dtype=[('a', '|O8'), ('b', '|O8')]) + expected2 = np.array([(2, 1)], dtype=[('b', '|O8'), ('a', '|O8')]) + alternatives = (expected1, expected2) + assert_any_equal(to_writeable({'a':1,'b':2}), alternatives) + # Fields with underscores discarded with a warning message. + with pytest.warns(MatWriteWarning, match='Starting field name with'): + assert_any_equal(to_writeable({'a':1, 'b':2, '_c':3}), alternatives) + # Not-string fields discarded + assert_any_equal(to_writeable({'a':1,'b':2, 100:3}), alternatives) + # String fields that are valid Python identifiers discarded + with pytest.warns(MatWriteWarning, match='Starting field name with'): + assert_any_equal(to_writeable({'a':1, 'b':2, '99':3}), alternatives) + # Object with field names is equivalent + + class klass: + pass + + c = klass + c.a = 1 + c.b = 2 + assert_any_equal(to_writeable(c), alternatives) + # empty list and tuple go to empty array + res = to_writeable([]) + assert_equal(res.shape, (0,)) + assert_equal(res.dtype.type, np.float64) + res = to_writeable(()) + assert_equal(res.shape, (0,)) + assert_equal(res.dtype.type, np.float64) + # None -> None + assert_(to_writeable(None) is None) + # String to strings + assert_equal(to_writeable('a string').dtype.type, np.str_) + # Scalars to numpy to NumPy scalars + res = to_writeable(1) + assert_equal(res.shape, ()) + assert_equal(res.dtype.type, np.array(1).dtype.type) + assert_array_equal(res, 1) + # Empty dict returns EmptyStructMarker + assert_(to_writeable({}) is EmptyStructMarker) + # Object does not have (even empty) __dict__ + assert_(to_writeable(object()) is None) + # Custom object does have empty __dict__, returns EmptyStructMarker + + class C: + pass + + assert_(to_writeable(c()) is EmptyStructMarker) + # dict keys with legal characters are convertible + res = to_writeable({'a': 1})['a'] + assert_equal(res.shape, (1,)) + assert_equal(res.dtype.type, np.object_) + # Only fields with illegal characters, falls back to EmptyStruct + with pytest.warns(MatWriteWarning, match='Starting field name with'): + assert_(to_writeable({'1':1}) is EmptyStructMarker) + + with pytest.warns(MatWriteWarning, match='Starting field name with'): + assert_(to_writeable({'_a':1}) is EmptyStructMarker) + # Unless there are valid fields, in which case structured array + with pytest.warns(MatWriteWarning, match='Starting field name with'): + assert_equal(to_writeable({'1':1, 'f': 2}), + np.array([(2,)], dtype=[('f', '|O8')])) + + +def test_recarray(): + # check roundtrip of structured array + dt = [('f1', 'f8'), + ('f2', 'S10')] + arr = np.zeros((2,), dtype=dt) + arr[0]['f1'] = 0.5 + arr[0]['f2'] = 'python' + arr[1]['f1'] = 99 + arr[1]['f2'] = 'not perl' + stream = BytesIO() + savemat(stream, {'arr': arr}) + d = loadmat(stream, struct_as_record=False) + a20 = d['arr'][0,0] + assert_equal(a20.f1, 0.5) + assert_equal(a20.f2, 'python') + d = loadmat(stream, struct_as_record=True) + a20 = d['arr'][0,0] + assert_equal(a20['f1'], 0.5) + assert_equal(a20['f2'], 'python') + # structs always come back as object types + assert_equal(a20.dtype, np.dtype([('f1', 'O'), + ('f2', 'O')])) + a21 = d['arr'].flat[1] + assert_equal(a21['f1'], 99) + assert_equal(a21['f2'], 'not perl') + + +def test_save_object(): + class C: + pass + c = C() + c.field1 = 1 + c.field2 = 'a string' + stream = BytesIO() + savemat(stream, {'c': c}) + d = loadmat(stream, struct_as_record=False) + c2 = d['c'][0,0] + assert_equal(c2.field1, 1) + assert_equal(c2.field2, 'a string') + d = loadmat(stream, struct_as_record=True) + c2 = d['c'][0,0] + assert_equal(c2['field1'], 1) + assert_equal(c2['field2'], 'a string') + + +def test_read_opts(): + # tests if read is seeing option sets, at initialization and after + # initialization + arr = np.arange(6).reshape(1,6) + stream = BytesIO() + savemat(stream, {'a': arr}) + rdr = MatFile5Reader(stream) + back_dict = rdr.get_variables() + rarr = back_dict['a'] + assert_array_equal(rarr, arr) + rdr = MatFile5Reader(stream, squeeze_me=True) + assert_array_equal(rdr.get_variables()['a'], arr.reshape((6,))) + rdr.squeeze_me = False + assert_array_equal(rarr, arr) + rdr = MatFile5Reader(stream, byte_order=boc.native_code) + assert_array_equal(rdr.get_variables()['a'], arr) + # inverted byte code leads to error on read because of swapped + # header etc. + rdr = MatFile5Reader(stream, byte_order=boc.swapped_code) + assert_raises(Exception, rdr.get_variables) + rdr.byte_order = boc.native_code + assert_array_equal(rdr.get_variables()['a'], arr) + arr = np.array(['a string']) + stream.truncate(0) + stream.seek(0) + savemat(stream, {'a': arr}) + rdr = MatFile5Reader(stream) + assert_array_equal(rdr.get_variables()['a'], arr) + rdr = MatFile5Reader(stream, chars_as_strings=False) + carr = np.atleast_2d(np.array(list(arr.item()), dtype='U1')) + assert_array_equal(rdr.get_variables()['a'], carr) + rdr.chars_as_strings = True + assert_array_equal(rdr.get_variables()['a'], arr) + + +def test_empty_string(): + # make sure reading empty string does not raise error + estring_fname = pjoin(test_data_path, 'single_empty_string.mat') + fp = open(estring_fname, 'rb') + rdr = MatFile5Reader(fp) + d = rdr.get_variables() + fp.close() + assert_array_equal(d['a'], np.array([], dtype='U1')) + # Empty string round trip. Matlab cannot distinguish + # between a string array that is empty, and a string array + # containing a single empty string, because it stores strings as + # arrays of char. There is no way of having an array of char that + # is not empty, but contains an empty string. + stream = BytesIO() + savemat(stream, {'a': np.array([''])}) + rdr = MatFile5Reader(stream) + d = rdr.get_variables() + assert_array_equal(d['a'], np.array([], dtype='U1')) + stream.truncate(0) + stream.seek(0) + savemat(stream, {'a': np.array([], dtype='U1')}) + rdr = MatFile5Reader(stream) + d = rdr.get_variables() + assert_array_equal(d['a'], np.array([], dtype='U1')) + stream.close() + + +def test_corrupted_data(): + import zlib + for exc, fname in [(ValueError, 'corrupted_zlib_data.mat'), + (zlib.error, 'corrupted_zlib_checksum.mat')]: + with open(pjoin(test_data_path, fname), 'rb') as fp: + rdr = MatFile5Reader(fp) + assert_raises(exc, rdr.get_variables) + + +def test_corrupted_data_check_can_be_disabled(): + with open(pjoin(test_data_path, 'corrupted_zlib_data.mat'), 'rb') as fp: + rdr = MatFile5Reader(fp, verify_compressed_data_integrity=False) + rdr.get_variables() + + +def test_read_both_endian(): + # make sure big- and little- endian data is read correctly + for fname in ('big_endian.mat', 'little_endian.mat'): + fp = open(pjoin(test_data_path, fname), 'rb') + rdr = MatFile5Reader(fp) + d = rdr.get_variables() + fp.close() + assert_array_equal(d['strings'], + np.array([['hello'], + ['world']], dtype=object)) + assert_array_equal(d['floats'], + np.array([[2., 3.], + [3., 4.]], dtype=np.float32)) + + +def test_write_opposite_endian(): + # We don't support writing opposite endian .mat files, but we need to behave + # correctly if the user supplies an other-endian NumPy array to write out. + float_arr = np.array([[2., 3.], + [3., 4.]]) + int_arr = np.arange(6).reshape((2, 3)) + uni_arr = np.array(['hello', 'world'], dtype='U') + stream = BytesIO() + savemat(stream, { + 'floats': float_arr.byteswap().view(float_arr.dtype.newbyteorder()), + 'ints': int_arr.byteswap().view(int_arr.dtype.newbyteorder()), + 'uni_arr': uni_arr.byteswap().view(uni_arr.dtype.newbyteorder()), + }) + rdr = MatFile5Reader(stream) + d = rdr.get_variables() + assert_array_equal(d['floats'], float_arr) + assert_array_equal(d['ints'], int_arr) + assert_array_equal(d['uni_arr'], uni_arr) + stream.close() + + +def test_logical_array(): + # The roundtrip test doesn't verify that we load the data up with the + # correct (bool) dtype + with open(pjoin(test_data_path, 'testbool_8_WIN64.mat'), 'rb') as fobj: + rdr = MatFile5Reader(fobj, mat_dtype=True) + d = rdr.get_variables() + x = np.array([[True], [False]], dtype=np.bool_) + assert_array_equal(d['testbools'], x) + assert_equal(d['testbools'].dtype, x.dtype) + + +def test_logical_out_type(): + # Confirm that bool type written as uint8, uint8 class + # See gh-4022 + stream = BytesIO() + barr = np.array([False, True, False]) + savemat(stream, {'barray': barr}) + stream.seek(0) + reader = MatFile5Reader(stream) + reader.initialize_read() + reader.read_file_header() + hdr, _ = reader.read_var_header() + assert_equal(hdr.mclass, mio5p.mxUINT8_CLASS) + assert_equal(hdr.is_logical, True) + var = reader.read_var_array(hdr, False) + assert_equal(var.dtype.type, np.uint8) + + +def test_roundtrip_zero_dimensions(): + stream = BytesIO() + savemat(stream, {'d':np.empty((10, 0))}) + d = loadmat(stream) + assert d['d'].shape == (10, 0) + + +def test_mat4_3d(): + # test behavior when writing 3-D arrays to matlab 4 files + stream = BytesIO() + arr = np.arange(24).reshape((2,3,4)) + assert_raises(ValueError, savemat, stream, {'a': arr}, True, '4') + + +def test_func_read(): + func_eg = pjoin(test_data_path, 'testfunc_7.4_GLNX86.mat') + fp = open(func_eg, 'rb') + rdr = MatFile5Reader(fp) + d = rdr.get_variables() + fp.close() + assert isinstance(d['testfunc'], MatlabFunction) + stream = BytesIO() + wtr = MatFile5Writer(stream) + # This test mat file has `__header__` field. + with pytest.warns(MatWriteWarning, match='Starting field name with'): + assert_raises(MatWriteError, wtr.put_variables, d) + + +def test_mat_dtype(): + double_eg = pjoin(test_data_path, 'testmatrix_6.1_SOL2.mat') + fp = open(double_eg, 'rb') + rdr = MatFile5Reader(fp, mat_dtype=False) + d = rdr.get_variables() + fp.close() + assert_equal(d['testmatrix'].dtype.kind, 'u') + + fp = open(double_eg, 'rb') + rdr = MatFile5Reader(fp, mat_dtype=True) + d = rdr.get_variables() + fp.close() + assert_equal(d['testmatrix'].dtype.kind, 'f') + + +def test_sparse_in_struct(): + # reproduces bug found by DC where Cython code was insisting on + # ndarray return type, but getting sparse matrix + st = {'sparsefield': eye_array(4)} + stream = BytesIO() + savemat(stream, {'a':st}) + d = loadmat(stream, struct_as_record=True) + assert_array_equal(d['a'][0, 0]['sparsefield'].toarray(), np.eye(4)) + + +def test_mat_struct_squeeze(): + stream = BytesIO() + in_d = {'st':{'one':1, 'two':2}} + savemat(stream, in_d) + # no error without squeeze + loadmat(stream, struct_as_record=False) + # previous error was with squeeze, with mat_struct + loadmat(stream, struct_as_record=False, squeeze_me=True) + + +def test_scalar_squeeze(): + stream = BytesIO() + in_d = {'scalar': [[0.1]], 'string': 'my name', 'st':{'one':1, 'two':2}} + savemat(stream, in_d) + out_d = loadmat(stream, squeeze_me=True) + assert_(isinstance(out_d['scalar'], float)) + assert_(isinstance(out_d['string'], str)) + assert_(isinstance(out_d['st'], np.ndarray)) + + +def test_str_round(): + # from report by Angus McMorland on mailing list 3 May 2010 + stream = BytesIO() + in_arr = np.array(['Hello', 'Foob']) + out_arr = np.array(['Hello', 'Foob ']) + savemat(stream, dict(a=in_arr)) + res = loadmat(stream) + # resulted in ['HloolFoa', 'elWrdobr'] + assert_array_equal(res['a'], out_arr) + stream.truncate(0) + stream.seek(0) + # Make Fortran ordered version of string + in_str = in_arr.tobytes(order='F') + in_from_str = np.ndarray(shape=a.shape, + dtype=in_arr.dtype, + order='F', + buffer=in_str) + savemat(stream, dict(a=in_from_str)) + assert_array_equal(res['a'], out_arr) + # unicode save did lead to buffer too small error + stream.truncate(0) + stream.seek(0) + in_arr_u = in_arr.astype('U') + out_arr_u = out_arr.astype('U') + savemat(stream, {'a': in_arr_u}) + res = loadmat(stream) + assert_array_equal(res['a'], out_arr_u) + + +def test_fieldnames(): + # Check that field names are as expected + stream = BytesIO() + savemat(stream, {'a': {'a':1, 'b':2}}) + res = loadmat(stream) + field_names = res['a'].dtype.names + assert_equal(set(field_names), {'a', 'b'}) + + +def test_loadmat_varnames(): + # Test that we can get just one variable from a mat file using loadmat + mat5_sys_names = ['__globals__', + '__header__', + '__version__'] + for eg_file, sys_v_names in ( + (pjoin(test_data_path, 'testmulti_4.2c_SOL2.mat'), []), (pjoin( + test_data_path, 'testmulti_7.4_GLNX86.mat'), mat5_sys_names)): + vars = loadmat(eg_file) + assert_equal(set(vars.keys()), set(['a', 'theta'] + sys_v_names)) + vars = loadmat(eg_file, variable_names='a') + assert_equal(set(vars.keys()), set(['a'] + sys_v_names)) + vars = loadmat(eg_file, variable_names=['a']) + assert_equal(set(vars.keys()), set(['a'] + sys_v_names)) + vars = loadmat(eg_file, variable_names=['theta']) + assert_equal(set(vars.keys()), set(['theta'] + sys_v_names)) + vars = loadmat(eg_file, variable_names=('theta',)) + assert_equal(set(vars.keys()), set(['theta'] + sys_v_names)) + vars = loadmat(eg_file, variable_names=[]) + assert_equal(set(vars.keys()), set(sys_v_names)) + vnames = ['theta'] + vars = loadmat(eg_file, variable_names=vnames) + assert_equal(vnames, ['theta']) + + +def test_round_types(): + # Check that saving, loading preserves dtype in most cases + arr = np.arange(10) + stream = BytesIO() + for dts in ('f8','f4','i8','i4','i2','i1', + 'u8','u4','u2','u1','c16','c8'): + stream.truncate(0) + stream.seek(0) # needed for BytesIO in Python 3 + savemat(stream, {'arr': arr.astype(dts)}) + vars = loadmat(stream) + assert_equal(np.dtype(dts), vars['arr'].dtype) + + +def test_varmats_from_mat(): + # Make a mat file with several variables, write it, read it back + names_vars = (('arr', mlarr(np.arange(10))), + ('mystr', mlarr('a string')), + ('mynum', mlarr(10))) + + # Dict like thing to give variables in defined order + class C: + def items(self): + return names_vars + stream = BytesIO() + savemat(stream, C()) + varmats = varmats_from_mat(stream) + assert_equal(len(varmats), 3) + for i in range(3): + name, var_stream = varmats[i] + exp_name, exp_res = names_vars[i] + assert_equal(name, exp_name) + res = loadmat(var_stream) + assert_array_equal(res[name], exp_res) + + +def test_one_by_zero(): + # Test 1x0 chars get read correctly + func_eg = pjoin(test_data_path, 'one_by_zero_char.mat') + fp = open(func_eg, 'rb') + rdr = MatFile5Reader(fp) + d = rdr.get_variables() + fp.close() + assert_equal(d['var'].shape, (0,)) + + +def test_load_mat4_le(): + # We were getting byte order wrong when reading little-endian floa64 dense + # matrices on big-endian platforms + mat4_fname = pjoin(test_data_path, 'test_mat4_le_floats.mat') + vars = loadmat(mat4_fname) + assert_array_equal(vars['a'], [[0.1, 1.2]]) + + +def test_unicode_mat4(): + # Mat4 should save unicode as latin1 + bio = BytesIO() + var = {'second_cat': 'Schrödinger'} + savemat(bio, var, format='4') + var_back = loadmat(bio) + assert_equal(var_back['second_cat'], var['second_cat']) + + +def test_logical_sparse(): + # Test we can read logical sparse stored in mat file as bytes. + # See https://github.com/scipy/scipy/issues/3539. + # In some files saved by MATLAB, the sparse data elements (Real Part + # Subelement in MATLAB speak) are stored with apparent type double + # (miDOUBLE) but are in fact single bytes. + filename = pjoin(test_data_path,'logical_sparse.mat') + # Before fix, this would crash with: + # ValueError: indices and data should have the same size + d = loadmat(filename, struct_as_record=True, spmatrix=False) + log_sp = d['sp_log_5_4'] + assert_(issparse(log_sp) and log_sp.format == "csc") + assert_equal(log_sp.dtype.type, np.bool_) + assert_array_equal(log_sp.toarray(), + [[True, True, True, False], + [False, False, True, False], + [False, False, True, False], + [False, False, False, False], + [False, False, False, False]]) + + +def test_empty_sparse(): + # Can we read empty sparse matrices? + sio = BytesIO() + import scipy.sparse + empty_sparse = scipy.sparse.csr_array([[0,0],[0,0]]) + savemat(sio, dict(x=empty_sparse)) + sio.seek(0) + + res = loadmat(sio, spmatrix=False) + assert not scipy.sparse.isspmatrix(res['x']) + res = loadmat(sio, spmatrix=True) + assert scipy.sparse.isspmatrix(res['x']) + res = loadmat(sio) # chk default + assert scipy.sparse.isspmatrix(res['x']) + + assert_array_equal(res['x'].shape, empty_sparse.shape) + assert_array_equal(res['x'].toarray(), 0) + # Do empty sparse matrices get written with max nnz 1? + # See https://github.com/scipy/scipy/issues/4208 + sio.seek(0) + reader = MatFile5Reader(sio) + reader.initialize_read() + reader.read_file_header() + hdr, _ = reader.read_var_header() + assert_equal(hdr.nzmax, 1) + + +def test_empty_mat_error(): + # Test we get a specific warning for an empty mat file + sio = BytesIO() + assert_raises(MatReadError, loadmat, sio) + + +def test_miuint32_compromise(): + # Reader should accept miUINT32 for miINT32, but check signs + # mat file with miUINT32 for miINT32, but OK values + filename = pjoin(test_data_path, 'miuint32_for_miint32.mat') + res = loadmat(filename) + assert_equal(res['an_array'], np.arange(10)[None, :]) + # mat file with miUINT32 for miINT32, with negative value + filename = pjoin(test_data_path, 'bad_miuint32.mat') + with assert_raises(ValueError): + loadmat(filename) + + +def test_miutf8_for_miint8_compromise(): + # Check reader accepts ascii as miUTF8 for array names + filename = pjoin(test_data_path, 'miutf8_array_name.mat') + res = loadmat(filename) + assert_equal(res['array_name'], [[1]]) + # mat file with non-ascii utf8 name raises error + filename = pjoin(test_data_path, 'bad_miutf8_array_name.mat') + with assert_raises(ValueError): + loadmat(filename) + + +def test_bad_utf8(): + # Check that reader reads bad UTF with 'replace' option + filename = pjoin(test_data_path,'broken_utf8.mat') + res = loadmat(filename) + assert_equal(res['bad_string'], + b'\x80 am broken'.decode('utf8', 'replace')) + + +def test_save_unicode_field(tmpdir): + filename = os.path.join(str(tmpdir), 'test.mat') + test_dict = {'a':{'b':1,'c':'test_str'}} + savemat(filename, test_dict) + + +def test_save_custom_array_type(tmpdir): + class CustomArray: + def __array__(self, dtype=None, copy=None): + return np.arange(6.0).reshape(2, 3) + a = CustomArray() + filename = os.path.join(str(tmpdir), 'test.mat') + savemat(filename, {'a': a}) + out = loadmat(filename) + assert_array_equal(out['a'], np.array(a)) + + +def test_filenotfound(): + # Check the correct error is thrown + assert_raises(OSError, loadmat, "NotExistentFile00.mat") + assert_raises(OSError, loadmat, "NotExistentFile00") + + +def test_simplify_cells(): + # Test output when simplify_cells=True + filename = pjoin(test_data_path, 'testsimplecell.mat') + res1 = loadmat(filename, simplify_cells=True) + res2 = loadmat(filename, simplify_cells=False) + assert_(isinstance(res1["s"], dict)) + assert_(isinstance(res2["s"], np.ndarray)) + assert_array_equal(res1["s"]["mycell"], np.array(["a", "b", "c"])) + + +@pytest.mark.parametrize('version, filt, regex', [ + (0, '_4*_*', None), + (1, '_5*_*', None), + (1, '_6*_*', None), + (1, '_7*_*', '^((?!hdf5).)*$'), # not containing hdf5 + (2, '_7*_*', '.*hdf5.*'), + (1, '8*_*', None), +]) +def test_matfile_version(version, filt, regex): + use_filt = pjoin(test_data_path, f'test*{filt}.mat') + files = glob(use_filt) + if regex is not None: + files = [file for file in files if re.match(regex, file) is not None] + assert len(files) > 0, \ + f"No files for version {version} using filter {filt}" + for file in files: + got_version = matfile_version(file) + assert got_version[0] == version + + +def test_opaque(): + """Test that we can read a MatlabOpaque object.""" + data = loadmat(pjoin(test_data_path, 'parabola.mat')) + assert isinstance(data['parabola'], MatlabFunction) + assert isinstance(data['parabola'].item()[3].item()[3], MatlabOpaque) + + +def test_opaque_simplify(): + """Test that we can read a MatlabOpaque object when simplify_cells=True.""" + data = loadmat(pjoin(test_data_path, 'parabola.mat'), simplify_cells=True) + assert isinstance(data['parabola'], MatlabFunction) + + +def test_deprecation(): + """Test that access to previous attributes still works.""" + # This should be accessible immediately from scipy.io import + with assert_warns(DeprecationWarning): + scipy.io.matlab.mio5_params.MatlabOpaque + + # These should be importable but warn as well + with assert_warns(DeprecationWarning): + from scipy.io.matlab.miobase import MatReadError # noqa: F401 + + +def test_gh_17992(tmp_path): + rng = np.random.default_rng(12345) + outfile = tmp_path / "lists.mat" + array_one = rng.random((5,3)) + array_two = rng.random((6,3)) + list_of_arrays = [array_one, array_two] + savemat(outfile, + {'data': list_of_arrays}, + long_field_names=True, + do_compression=True) + # round trip check + new_dict = {} + loadmat(outfile, + new_dict) + assert_allclose(new_dict["data"][0][0], array_one) + assert_allclose(new_dict["data"][0][1], array_two) + + +def test_gh_19659(tmp_path): + d = { + "char_array": np.array([list("char"), list("char")], dtype="U1"), + "string_array": np.array(["string", "string"]), + } + outfile = tmp_path / "tmp.mat" + # should not error: + savemat(outfile, d, format="4") + + +def test_large_m4(): + # Test we can read a Matlab 4 file with array > 2GB. + # (In fact, test we get the correct error from reading a truncated + # version). + # See https://github.com/scipy/scipy/issues/21256 + # Data file is first 1024 bytes of: + # >>> a = np.zeros((134217728, 3)) + # >>> siom.savemat('big_m4.mat', {'a': a}, format='4') + truncated_mat = pjoin(test_data_path, 'debigged_m4.mat') + match = ("Not enough bytes to read matrix 'a';" + if np.intp == np.int64 else + "Variable 'a' has byte length longer than largest possible") + with pytest.raises(ValueError, match=match): + loadmat(truncated_mat) + + +def test_gh_19223(): + from scipy.io.matlab import varmats_from_mat # noqa: F401 + + +def test_invalid_field_name_warning(): + names_vars = ( + ('_1', mlarr(np.arange(10))), + ('mystr', mlarr('a string'))) + check_mat_write_warning(names_vars) + + names_vars = (('mymap', {"a": 1, "_b": 2}),) + check_mat_write_warning(names_vars) + + names_vars = (('mymap', {"a": 1, "1a": 2}),) + check_mat_write_warning(names_vars) + + +def check_mat_write_warning(names_vars): + class C: + def items(self): + return names_vars + + stream = BytesIO() + with pytest.warns(MatWriteWarning, match='Starting field name with'): + savemat(stream, C()) + + +def test_corrupt_files(): + # Test we can detect truncated or corrupt (all zero) files. + for n in (2, 4, 10, 19): + with pytest.raises(MatReadError, + match="Mat file appears to be truncated"): + loadmat(BytesIO(b'\x00' * n)) + with pytest.raises(MatReadError, + match="Mat file appears to be corrupt"): + loadmat(BytesIO(b'\x00' * 20)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio5_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio5_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..082c046dea5f02702c8158141796649fae7e1f9d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio5_utils.py @@ -0,0 +1,179 @@ +""" Testing mio5_utils Cython module + +""" +import sys + +from io import BytesIO + +import numpy as np + +from numpy.testing import assert_array_equal, assert_equal, assert_ +from pytest import raises as assert_raises + +import scipy.io.matlab._byteordercodes as boc +import scipy.io.matlab._streams as streams +import scipy.io.matlab._mio5_params as mio5p +import scipy.io.matlab._mio5_utils as m5u + + +def test_byteswap(): + for val in ( + 1, + 0x100, + 0x10000): + a = np.array(val, dtype=np.uint32) + b = a.byteswap() + c = m5u.byteswap_u4(a) + assert_equal(b.item(), c) + d = m5u.byteswap_u4(c) + assert_equal(a.item(), d) + + +def _make_tag(base_dt, val, mdtype, sde=False): + ''' Makes a simple matlab tag, full or sde ''' + base_dt = np.dtype(base_dt) + bo = boc.to_numpy_code(base_dt.byteorder) + byte_count = base_dt.itemsize + if not sde: + udt = bo + 'u4' + padding = 8 - (byte_count % 8) + all_dt = [('mdtype', udt), + ('byte_count', udt), + ('val', base_dt)] + if padding: + all_dt.append(('padding', 'u1', padding)) + else: # is sde + udt = bo + 'u2' + padding = 4-byte_count + if bo == '<': # little endian + all_dt = [('mdtype', udt), + ('byte_count', udt), + ('val', base_dt)] + else: # big endian + all_dt = [('byte_count', udt), + ('mdtype', udt), + ('val', base_dt)] + if padding: + all_dt.append(('padding', 'u1', padding)) + tag = np.zeros((1,), dtype=all_dt) + tag['mdtype'] = mdtype + tag['byte_count'] = byte_count + tag['val'] = val + return tag + + +def _write_stream(stream, *strings): + stream.truncate(0) + stream.seek(0) + for s in strings: + stream.write(s) + stream.seek(0) + + +def _make_readerlike(stream, byte_order=boc.native_code): + class R: + pass + r = R() + r.mat_stream = stream + r.byte_order = byte_order + r.struct_as_record = True + r.uint16_codec = sys.getdefaultencoding() + r.chars_as_strings = False + r.mat_dtype = False + r.squeeze_me = False + return r + + +def test_read_tag(): + # mainly to test errors + # make reader-like thing + str_io = BytesIO() + r = _make_readerlike(str_io) + c_reader = m5u.VarReader5(r) + # This works for StringIO but _not_ BytesIO + assert_raises(OSError, c_reader.read_tag) + # bad SDE + tag = _make_tag('i4', 1, mio5p.miINT32, sde=True) + tag['byte_count'] = 5 + _write_stream(str_io, tag.tobytes()) + assert_raises(ValueError, c_reader.read_tag) + + +def test_read_stream(): + tag = _make_tag('i4', 1, mio5p.miINT32, sde=True) + tag_str = tag.tobytes() + str_io = BytesIO(tag_str) + st = streams.make_stream(str_io) + s = streams._read_into(st, tag.itemsize) + assert_equal(s, tag.tobytes()) + + +def test_read_numeric(): + # make reader-like thing + str_io = BytesIO() + r = _make_readerlike(str_io) + # check simplest of tags + for base_dt, val, mdtype in (('u2', 30, mio5p.miUINT16), + ('i4', 1, mio5p.miINT32), + ('i2', -1, mio5p.miINT16)): + for byte_code in ('<', '>'): + r.byte_order = byte_code + c_reader = m5u.VarReader5(r) + assert_equal(c_reader.little_endian, byte_code == '<') + assert_equal(c_reader.is_swapped, byte_code != boc.native_code) + for sde_f in (False, True): + dt = np.dtype(base_dt).newbyteorder(byte_code) + a = _make_tag(dt, val, mdtype, sde_f) + a_str = a.tobytes() + _write_stream(str_io, a_str) + el = c_reader.read_numeric() + assert_equal(el, val) + # two sequential reads + _write_stream(str_io, a_str, a_str) + el = c_reader.read_numeric() + assert_equal(el, val) + el = c_reader.read_numeric() + assert_equal(el, val) + + +def test_read_numeric_writeable(): + # make reader-like thing + str_io = BytesIO() + r = _make_readerlike(str_io, '<') + c_reader = m5u.VarReader5(r) + dt = np.dtype('' + rdr.mat_stream.read(4) # presumably byte padding + mdict = read_minimat_vars(rdr) + fp.close() + return mdict + + +def test_jottings(): + # example + fname = os.path.join(test_data_path, 'parabola.mat') + read_workspace_vars(fname) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6ccb52fa6d8d5692fbb1443b5fc492cfa12b4fcc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_mio_utils.py @@ -0,0 +1,45 @@ +""" Testing + +""" + +import numpy as np + +from numpy.testing import assert_array_equal, assert_ + +from scipy.io.matlab._mio_utils import squeeze_element, chars_to_strings + + +def test_squeeze_element(): + a = np.zeros((1,3)) + assert_array_equal(np.squeeze(a), squeeze_element(a)) + # 0-D output from squeeze gives scalar + sq_int = squeeze_element(np.zeros((1,1), dtype=float)) + assert_(isinstance(sq_int, float)) + # Unless it's a structured array + sq_sa = squeeze_element(np.zeros((1,1),dtype=[('f1', 'f')])) + assert_(isinstance(sq_sa, np.ndarray)) + # Squeezing empty arrays maintain their dtypes. + sq_empty = squeeze_element(np.empty(0, np.uint8)) + assert sq_empty.dtype == np.uint8 + + +def test_chars_strings(): + # chars as strings + strings = ['learn ', 'python', 'fast ', 'here '] + str_arr = np.array(strings, dtype='U6') # shape (4,) + chars = [list(s) for s in strings] + char_arr = np.array(chars, dtype='U1') # shape (4,6) + assert_array_equal(chars_to_strings(char_arr), str_arr) + ca2d = char_arr.reshape((2,2,6)) + sa2d = str_arr.reshape((2,2)) + assert_array_equal(chars_to_strings(ca2d), sa2d) + ca3d = char_arr.reshape((1,2,2,6)) + sa3d = str_arr.reshape((1,2,2)) + assert_array_equal(chars_to_strings(ca3d), sa3d) + # Fortran ordered arrays + char_arrf = np.array(chars, dtype='U1', order='F') # shape (4,6) + assert_array_equal(chars_to_strings(char_arrf), str_arr) + # empty array + arr = np.array([['']], dtype='U1') + out_arr = np.array([''], dtype='U1') + assert_array_equal(chars_to_strings(arr), out_arr) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_miobase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_miobase.py new file mode 100644 index 0000000000000000000000000000000000000000..a325c7ac386043f9cd974f8d20de4492255cf9e6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_miobase.py @@ -0,0 +1,32 @@ +""" Testing miobase module +""" + +import numpy as np + +from numpy.testing import assert_equal +from pytest import raises as assert_raises + +from scipy.io.matlab._miobase import matdims + + +def test_matdims(): + # Test matdims dimension finder + assert_equal(matdims(np.array(1)), (1, 1)) # NumPy scalar + assert_equal(matdims(np.array([1])), (1, 1)) # 1-D array, 1 element + assert_equal(matdims(np.array([1,2])), (2, 1)) # 1-D array, 2 elements + assert_equal(matdims(np.array([[2],[3]])), (2, 1)) # 2-D array, column vector + assert_equal(matdims(np.array([[2,3]])), (1, 2)) # 2-D array, row vector + # 3d array, rowish vector + assert_equal(matdims(np.array([[[2,3]]])), (1, 1, 2)) + assert_equal(matdims(np.array([])), (0, 0)) # empty 1-D array + assert_equal(matdims(np.array([[]])), (1, 0)) # empty 2-D array + assert_equal(matdims(np.array([[[]]])), (1, 1, 0)) # empty 3-D array + assert_equal(matdims(np.empty((1, 0, 1))), (1, 0, 1)) # empty 3-D array + # Optional argument flips 1-D shape behavior. + assert_equal(matdims(np.array([1,2]), 'row'), (1, 2)) # 1-D array, 2 elements + # The argument has to make sense though + assert_raises(ValueError, matdims, np.array([1,2]), 'bizarre') + # Check empty sparse matrices get their own shape + from scipy.sparse import csr_array, csc_array + assert_equal(matdims(csr_array(np.zeros((3, 3)))), (3, 3)) + assert_equal(matdims(csc_array(np.zeros((2, 2)))), (2, 2)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_pathological.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_pathological.py new file mode 100644 index 0000000000000000000000000000000000000000..87d8a88a4daca2537177575ad680637d482294cf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_pathological.py @@ -0,0 +1,33 @@ +""" Test reading of files not conforming to matlab specification + +We try and read any file that matlab reads, these files included +""" +from os.path import dirname, join as pjoin + +from numpy.testing import assert_ +from pytest import raises as assert_raises + +from scipy.io.matlab._mio import loadmat + +TEST_DATA_PATH = pjoin(dirname(__file__), 'data') + + +def test_multiple_fieldnames(): + # Example provided by Dharhas Pothina + # Extracted using mio5.varmats_from_mat + multi_fname = pjoin(TEST_DATA_PATH, 'nasty_duplicate_fieldnames.mat') + vars = loadmat(multi_fname) + funny_names = vars['Summary'].dtype.names + assert_({'_1_Station_Q', '_2_Station_Q', + '_3_Station_Q'}.issubset(funny_names)) + + +def test_malformed1(): + # Example from gh-6072 + # Contains malformed header data, which previously resulted into a + # buffer overflow. + # + # Should raise an exception, not segfault + fname = pjoin(TEST_DATA_PATH, 'malformed1.mat') + with open(fname, 'rb') as f: + assert_raises(ValueError, loadmat, f) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_streams.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..d7e90f58555058f12f9c078d5289d3c24ab9d0d5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/matlab/tests/test_streams.py @@ -0,0 +1,241 @@ +""" Testing + +""" + +import platform +import os +import random +import sys +import zlib + +from io import BytesIO + + +from tempfile import mkstemp +from contextlib import contextmanager + +import numpy as np + +from numpy.testing import assert_, assert_equal +from pytest import raises as assert_raises +import pytest + +from scipy.io.matlab._streams import (make_stream, + GenericStream, ZlibInputStream, + _read_into, _read_string, BLOCK_SIZE) + + +@contextmanager +def setup_test_file(): + val = b'a\x00string' + fd, fname = mkstemp() + + with os.fdopen(fd, 'wb') as fs: + fs.write(val) + with open(fname, 'rb') as fs: + gs = BytesIO(val) + cs = BytesIO(val) + yield fs, gs, cs + os.unlink(fname) + + +def test_make_stream(): + with setup_test_file() as (fs, gs, cs): + # test stream initialization + assert_(isinstance(make_stream(gs), GenericStream)) + + +def test_tell_seek(): + with setup_test_file() as (fs, gs, cs): + for s in (fs, gs, cs): + st = make_stream(s) + res = st.seek(0) + assert_equal(res, 0) + assert_equal(st.tell(), 0) + res = st.seek(5) + assert_equal(res, 0) + assert_equal(st.tell(), 5) + res = st.seek(2, 1) + assert_equal(res, 0) + assert_equal(st.tell(), 7) + res = st.seek(-2, 2) + assert_equal(res, 0) + assert_equal(st.tell(), 6) + + +def test_read(): + with setup_test_file() as (fs, gs, cs): + for s in (fs, gs, cs): + st = make_stream(s) + st.seek(0) + res = st.read(-1) + assert_equal(res, b'a\x00string') + st.seek(0) + res = st.read(4) + assert_equal(res, b'a\x00st') + # read into + st.seek(0) + res = _read_into(st, 4) + assert_equal(res, b'a\x00st') + res = _read_into(st, 4) + assert_equal(res, b'ring') + assert_raises(OSError, _read_into, st, 2) + # read alloc + st.seek(0) + res = _read_string(st, 4) + assert_equal(res, b'a\x00st') + res = _read_string(st, 4) + assert_equal(res, b'ring') + assert_raises(OSError, _read_string, st, 2) + + +class TestZlibInputStream: + def _get_data(self, size): + data = random.randbytes(size) + compressed_data = zlib.compress(data) + stream = BytesIO(compressed_data) + return stream, len(compressed_data), data + + def test_read(self): + SIZES = [0, 1, 10, BLOCK_SIZE//2, BLOCK_SIZE-1, + BLOCK_SIZE, BLOCK_SIZE+1, 2*BLOCK_SIZE-1] + + READ_SIZES = [BLOCK_SIZE//2, BLOCK_SIZE-1, + BLOCK_SIZE, BLOCK_SIZE+1] + + def check(size, read_size): + compressed_stream, compressed_data_len, data = self._get_data(size) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + data2 = b'' + so_far = 0 + while True: + block = stream.read(min(read_size, + size - so_far)) + if not block: + break + so_far += len(block) + data2 += block + assert_equal(data, data2) + + for size in SIZES: + for read_size in READ_SIZES: + check(size, read_size) + + def test_read_max_length(self): + data = random.randbytes(1234) + compressed_data = zlib.compress(data) + compressed_stream = BytesIO(compressed_data + b"abbacaca") + stream = ZlibInputStream(compressed_stream, len(compressed_data)) + + stream.read(len(data)) + assert_equal(compressed_stream.tell(), len(compressed_data)) + + assert_raises(OSError, stream.read, 1) + + def test_read_bad_checksum(self): + data = random.randbytes(10) + compressed_data = zlib.compress(data) + + # break checksum + compressed_data = (compressed_data[:-1] + + bytes([(compressed_data[-1] + 1) & 255])) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, len(compressed_data)) + + assert_raises(zlib.error, stream.read, len(data)) + + def test_seek(self): + compressed_stream, compressed_data_len, data = self._get_data(1024) + + stream = ZlibInputStream(compressed_stream, compressed_data_len) + + stream.seek(123) + p = 123 + assert_equal(stream.tell(), p) + d1 = stream.read(11) + assert_equal(d1, data[p:p+11]) + + stream.seek(321, 1) + p = 123+11+321 + assert_equal(stream.tell(), p) + d2 = stream.read(21) + assert_equal(d2, data[p:p+21]) + + stream.seek(641, 0) + p = 641 + assert_equal(stream.tell(), p) + d3 = stream.read(11) + assert_equal(d3, data[p:p+11]) + + assert_raises(OSError, stream.seek, 10, 2) + assert_raises(OSError, stream.seek, -1, 1) + assert_raises(ValueError, stream.seek, 1, 123) + + stream.seek(10000, 1) + assert_raises(OSError, stream.read, 12) + + def test_seek_bad_checksum(self): + data = random.randbytes(10) + compressed_data = zlib.compress(data) + + # break checksum + compressed_data = (compressed_data[:-1] + + bytes([(compressed_data[-1] + 1) & 255])) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, len(compressed_data)) + + assert_raises(zlib.error, stream.seek, len(data)) + + def test_all_data_read(self): + compressed_stream, compressed_data_len, data = self._get_data(1024) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + assert_(not stream.all_data_read()) + stream.seek(512) + assert_(not stream.all_data_read()) + stream.seek(1024) + assert_(stream.all_data_read()) + + @pytest.mark.skipif( + (platform.system() == 'Windows' and sys.version_info >= (3, 14)), + reason='gh-23185') + def test_all_data_read_overlap(self): + COMPRESSION_LEVEL = 6 + + data = np.arange(33707000, dtype=np.uint8) + compressed_data = zlib.compress(data, COMPRESSION_LEVEL) + compressed_data_len = len(compressed_data) + + # check that part of the checksum overlaps + assert_(compressed_data_len == BLOCK_SIZE + 2) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + assert_(not stream.all_data_read()) + stream.seek(len(data)) + assert_(stream.all_data_read()) + + @pytest.mark.skipif( + (platform.system() == 'Windows' and sys.version_info >= (3, 14)), + reason='gh-23185') + def test_all_data_read_bad_checksum(self): + COMPRESSION_LEVEL = 6 + + data = np.arange(33707000, dtype=np.uint8) + compressed_data = zlib.compress(data, COMPRESSION_LEVEL) + compressed_data_len = len(compressed_data) + + # check that part of the checksum overlaps + assert_(compressed_data_len == BLOCK_SIZE + 2) + + # break checksum + compressed_data = (compressed_data[:-1] + + bytes([(compressed_data[-1] + 1) & 255])) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + assert_(not stream.all_data_read()) + stream.seek(len(data)) + + assert_raises(zlib.error, stream.all_data_read) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54b7cd00267dd424f467b52272545eaa53d7029d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f518f86da0ba19d9c7eb7cb67a7fd6dd9fe419f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9f6eb5ddfe963ad2e88472123abe6999bbdba72 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_mmio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_mmio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..852157e00efbb712349067a56d961e2cddadd612 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_mmio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_netcdf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_netcdf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d60f9a044b495461002451c9bb5bdbe64052c7c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_netcdf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e0b2e64c1bda7cc7d31ff74c43f926562080c27 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_wavfile.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_wavfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13c9b81d46e91f9ea4a41a43a504741e6a434bec Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/__pycache__/test_wavfile.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/Transparent Busy.ani b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/Transparent Busy.ani new file mode 100644 index 0000000000000000000000000000000000000000..3be500032786398c3efdbd9f873f705b6c1636bd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/Transparent Busy.ani differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_1d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_1d.sav new file mode 100644 index 0000000000000000000000000000000000000000..619a1259670a361ac76ffa86c481a813dbaec07a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_1d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_2d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_2d.sav new file mode 100644 index 0000000000000000000000000000000000000000..804d8b1a8a90636c880e974b6f85bd385033306b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_2d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_3d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..3fa56c450eaa916d9c91b492ba17e7e843df2d53 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_3d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_4d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_4d.sav new file mode 100644 index 0000000000000000000000000000000000000000..4bb951e274a399f091ff70b639d6e3b55ee1e122 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_4d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_5d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_5d.sav new file mode 100644 index 0000000000000000000000000000000000000000..2854dbc8b1e53f298ac3b135eac1f06e73940152 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_5d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_6d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_6d.sav new file mode 100644 index 0000000000000000000000000000000000000000..91588d348d5f89af354209840062202d5b28c1df Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_6d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_7d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_7d.sav new file mode 100644 index 0000000000000000000000000000000000000000..3e978fad540a8979435d4561de151573696affd8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_7d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_8d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_8d.sav new file mode 100644 index 0000000000000000000000000000000000000000..f699fe2427dfe876283de0fcade2c2325a262061 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_8d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav new file mode 100644 index 0000000000000000000000000000000000000000..8e3a402c60a515149811e2ca21628e97180c4956 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav new file mode 100644 index 0000000000000000000000000000000000000000..dd3504f0ecfaed178ace02e1a8a84650111c3936 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..285da7f78ffbbf2155fd2e4e648f19a1d3a42ac3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav new file mode 100644 index 0000000000000000000000000000000000000000..d99fa48f0a43ec06c3101560f9cade829c8b1940 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav new file mode 100644 index 0000000000000000000000000000000000000000..de5e984e49f507ae550b1ae2fd54b799e742a195 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav new file mode 100644 index 0000000000000000000000000000000000000000..bb76671a65be41fd2a426146c6c366f1e7fb07c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav new file mode 100644 index 0000000000000000000000000000000000000000..995d23c6ed05b095442b6247b09191126f797f23 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav new file mode 100644 index 0000000000000000000000000000000000000000..4249ec62119e264d55a81d3faf9c87dcaed1c7c8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_1.nc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_1.nc new file mode 100644 index 0000000000000000000000000000000000000000..5775622d0ef85828b436dffcd21366f7538fc55c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_1.nc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_2.nc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_2.nc new file mode 100644 index 0000000000000000000000000000000000000000..07db1cd986a4c3b9929c01c1f22bcc3f562b1c16 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_2.nc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_3_maskedvals.nc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_3_maskedvals.nc new file mode 100644 index 0000000000000000000000000000000000000000..57f8bf9da3bca295c15508963c77a870222af0bc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/example_3_maskedvals.nc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat new file mode 100644 index 0000000000000000000000000000000000000000..87731eb9d4b1f2ac827a212436fe6de175431e11 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-mixed.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-mixed.dat new file mode 100644 index 0000000000000000000000000000000000000000..a165a7a30424b20af9a3a0636c5e655239ea6fa5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-mixed.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat new file mode 100644 index 0000000000000000000000000000000000000000..c3bb9dcbe50ef784ce3282b28e53f4c40beb48ce Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat new file mode 100644 index 0000000000000000000000000000000000000000..351801fd47a2e3e48d9b63034fbae28f8318c9f9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat new file mode 100644 index 0000000000000000000000000000000000000000..64bf92f74a457d2f4bc42798493db15cc3ab1008 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..3d3f27f88eef4e02451d18204cdcfd51f96f6d15 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat new file mode 100644 index 0000000000000000000000000000000000000000..0bd683096f18eadceb7168f811c75bf072baecfe Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..25269ff9ea4f6dd3f8a9ca0c8ad27d399e4248f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat new file mode 100644 index 0000000000000000000000000000000000000000..9850de37cf86af622b759625c15e6b1a9477ce47 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat new file mode 100644 index 0000000000000000000000000000000000000000..98c09c2dff6e1ef605e25ed1d00afe94597abddc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat new file mode 100644 index 0000000000000000000000000000000000000000..959098d2a9cdd6140758843e059d4ca529b14279 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..49c0ec1d18d9f08111fe2d2a269ed407da71b158 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat new file mode 100644 index 0000000000000000000000000000000000000000..bb936b8789920ce18281fa754a5c048b31e59ba8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..cb3e9e4876249f42924a43232b74f05b91123815 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/invalid_pointer.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/invalid_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..d53893c6c734e6c7771e08042c16874623dc6f0e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/invalid_pointer.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/null_pointer.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/null_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..8cee5ebecc3bef248ed37c438e0731160b31a310 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/null_pointer.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_byte.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_byte.sav new file mode 100644 index 0000000000000000000000000000000000000000..e4027b3cf302b8610b87d9ef8b0aac39d5a40ef9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_byte.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_byte_descr.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_byte_descr.sav new file mode 100644 index 0000000000000000000000000000000000000000..182e29bc57dc05154388553a71876820025bca8d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_byte_descr.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_complex32.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_complex32.sav new file mode 100644 index 0000000000000000000000000000000000000000..593e8c6208ab0bf3aa869de89e213b8aa9f8c071 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_complex32.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_complex64.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_complex64.sav new file mode 100644 index 0000000000000000000000000000000000000000..edb19d388afbaff44e5f0883978e6a74e9755613 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_complex64.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_float32.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_float32.sav new file mode 100644 index 0000000000000000000000000000000000000000..be9e3877ea845da76d9466c14d70c4cce882368c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_float32.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_float64.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_float64.sav new file mode 100644 index 0000000000000000000000000000000000000000..9680b2878c6008a27c8fc9ae6966903ff936cc4a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_float64.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..d02b1756ac043a4ba6119acb28ef34c40359a4dd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int16.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int16.sav new file mode 100644 index 0000000000000000000000000000000000000000..603525694cc307d47412717c4c2f85ddc960897b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int16.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int32.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int32.sav new file mode 100644 index 0000000000000000000000000000000000000000..40210b889402c0f27562296ab39ce1a714f0d0ef Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int32.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int64.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int64.sav new file mode 100644 index 0000000000000000000000000000000000000000..c91cd0a561e011a2f18c86119e45392fbc0be825 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_int64.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_string.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_string.sav new file mode 100644 index 0000000000000000000000000000000000000000..ee6e69fe8461edfa580f682761118c8afe2add3a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_string.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint16.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint16.sav new file mode 100644 index 0000000000000000000000000000000000000000..759c2e64fa034c6ddbdbe6181efae1e699a0c314 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint16.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint32.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint32.sav new file mode 100644 index 0000000000000000000000000000000000000000..74dec7b8933418d30d17c83d617443a73ceef0c6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint32.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint64.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint64.sav new file mode 100644 index 0000000000000000000000000000000000000000..fc9da5796eab6ce9fb59488b836ba2f567de7b25 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/scalar_uint64.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays.sav new file mode 100644 index 0000000000000000000000000000000000000000..40c9cd330e0c731968d71dbbfeae9bd8c4a745a2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav new file mode 100644 index 0000000000000000000000000000000000000000..f1aa416f8e661893be282a490005536953d4b7af Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..6f01fbfd109e76c94b6e6e9bfd9eb388f39d99ee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..bac9b207488eb9712ec27fb3567155f0dd773f34 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_inherit.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_inherit.sav new file mode 100644 index 0000000000000000000000000000000000000000..8babd56306f09fa612f731ce593ae13c75f84f4c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_inherit.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav new file mode 100644 index 0000000000000000000000000000000000000000..a3c678162911426702a9a6e932761385a01f247e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..38b812261125e6aabef8618955b234f6c7b04955 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..db1c256c85a707f0a0d78c28241b78d1eddcab1e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers.sav new file mode 100644 index 0000000000000000000000000000000000000000..acbb058a307090f6c9e2d8402c7badf6bb48144c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..d16f4655cc20318db2b0d629cd5ed6d7be01b518 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..732dd2cbfa9c7fd029bb59b4cfcb630cc1077f54 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars.sav new file mode 100644 index 0000000000000000000000000000000000000000..69d7eaf4ecf8747c21d07e14edcf65b4e394974c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..2222391ae5b93ba34c1fdb982c02eb97d9658b58 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..a35f1acfb4cb93ecb637310bbfa7fc1a2151d483 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/various_compressed.sav b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/various_compressed.sav new file mode 100644 index 0000000000000000000000000000000000000000..dcdb0b0d433939d6a240c86e5060214cd8875732 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/data/various_compressed.sav differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_fortran.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_fortran.py new file mode 100644 index 0000000000000000000000000000000000000000..a1094a3c24af9080eaa23cf5f00625b3c5f81b59 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_fortran.py @@ -0,0 +1,344 @@ +''' Tests for fortran sequential files ''' + +import tempfile +import shutil +import os +from os import path +from glob import iglob +import threading +import re + +from numpy.testing import assert_equal, assert_allclose +import numpy as np +import pytest + +from scipy.io import (FortranFile, + FortranEOFError, + FortranFormattingError) + + +DATA_PATH = path.join(path.dirname(__file__), 'data') + + +@pytest.fixture +def io_lock(): + return threading.Lock() + + +def test_fortranfiles_read(io_lock): + for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")): + m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I) + if not m: + raise RuntimeError(f"Couldn't match {filename} filename to regex") + + dims = (int(m.group(2)), int(m.group(3)), int(m.group(4))) + + dtype = m.group(1).replace('s', '<') + + with io_lock: + f = FortranFile(filename, 'r', ' 0] = 1 + info = (2, 2, 3, 'coordinate', 'pattern', 'general') + mmwrite(self.fn, a, field='pattern') + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn, spmatrix=False) + assert_array_almost_equal(p, b.toarray()) + assert not scipy.sparse.isspmatrix(b) + + b = mmread(self.fn, spmatrix=True) + assert scipy.sparse.isspmatrix(b) + b = mmread(self.fn) # chk default + assert scipy.sparse.isspmatrix(b) + + def test_gh13634_non_skew_symmetric_int(self): + a = scipy.sparse.csr_array([[1, 2], [-2, 99]], dtype=np.int32) + self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general')) + + def test_gh13634_non_skew_symmetric_float(self): + a = scipy.sparse.csr_array([[1, 2], [-2, 99.]], dtype=np.float32) + self.check(a, (2, 2, 4, 'coordinate', 'real', 'general')) + + +_32bit_integer_dense_example = '''\ +%%MatrixMarket matrix array integer general +2 2 +2147483647 +2147483646 +2147483647 +2147483646 +''' + +_32bit_integer_sparse_example = '''\ +%%MatrixMarket matrix coordinate integer symmetric +2 2 2 +1 1 2147483647 +2 2 2147483646 +''' + +_64bit_integer_dense_example = '''\ +%%MatrixMarket matrix array integer general +2 2 + 2147483648 +-9223372036854775806 + -2147483648 + 9223372036854775807 +''' + +_64bit_integer_sparse_general_example = '''\ +%%MatrixMarket matrix coordinate integer general +2 2 3 +1 1 2147483648 +1 2 9223372036854775807 +2 2 9223372036854775807 +''' + +_64bit_integer_sparse_symmetric_example = '''\ +%%MatrixMarket matrix coordinate integer symmetric +2 2 3 +1 1 2147483648 +1 2 -9223372036854775807 +2 2 9223372036854775807 +''' + +_64bit_integer_sparse_skew_example = '''\ +%%MatrixMarket matrix coordinate integer skew-symmetric +2 2 3 +1 1 2147483648 +1 2 -9223372036854775807 +2 2 9223372036854775807 +''' + +_over64bit_integer_dense_example = '''\ +%%MatrixMarket matrix array integer general +2 2 + 2147483648 +9223372036854775807 + 2147483648 +9223372036854775808 +''' + +_over64bit_integer_sparse_example = '''\ +%%MatrixMarket matrix coordinate integer symmetric +2 2 2 +1 1 2147483648 +2 2 19223372036854775808 +''' + + +class TestMMIOReadLargeIntegers: + def setup_method(self): + self.tmpdir = mkdtemp(suffix=str(threading.get_native_id())) + self.fn = os.path.join(self.tmpdir, 'testfile.mtx') + + def teardown_method(self): + shutil.rmtree(self.tmpdir) + + def check_read(self, example, a, info, dense, over32, over64): + with open(self.fn, 'w') as f: + f.write(example) + assert_equal(mminfo(self.fn), info) + if ((over32 and (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite) + or over64): + assert_raises(OverflowError, mmread, self.fn) + else: + b = mmread(self.fn, spmatrix=False) + if not dense: + b = b.toarray() + assert_equal(a, b) + + def test_read_32bit_integer_dense(self): + a = array([[2**31-1, 2**31-1], + [2**31-2, 2**31-2]], dtype=np.int64) + self.check_read(_32bit_integer_dense_example, + a, + (2, 2, 4, 'array', 'integer', 'general'), + dense=True, + over32=False, + over64=False) + + def test_read_32bit_integer_sparse(self): + a = array([[2**31-1, 0], + [0, 2**31-2]], dtype=np.int64) + self.check_read(_32bit_integer_sparse_example, + a, + (2, 2, 2, 'coordinate', 'integer', 'symmetric'), + dense=False, + over32=False, + over64=False) + + def test_read_64bit_integer_dense(self): + a = array([[2**31, -2**31], + [-2**63+2, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_dense_example, + a, + (2, 2, 4, 'array', 'integer', 'general'), + dense=True, + over32=True, + over64=False) + + def test_read_64bit_integer_sparse_general(self): + a = array([[2**31, 2**63-1], + [0, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_sparse_general_example, + a, + (2, 2, 3, 'coordinate', 'integer', 'general'), + dense=False, + over32=True, + over64=False) + + def test_read_64bit_integer_sparse_symmetric(self): + a = array([[2**31, -2**63+1], + [-2**63+1, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_sparse_symmetric_example, + a, + (2, 2, 3, 'coordinate', 'integer', 'symmetric'), + dense=False, + over32=True, + over64=False) + + def test_read_64bit_integer_sparse_skew(self): + a = array([[2**31, -2**63+1], + [2**63-1, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_sparse_skew_example, + a, + (2, 2, 3, 'coordinate', 'integer', 'skew-symmetric'), + dense=False, + over32=True, + over64=False) + + def test_read_over64bit_integer_dense(self): + self.check_read(_over64bit_integer_dense_example, + None, + (2, 2, 4, 'array', 'integer', 'general'), + dense=True, + over32=True, + over64=True) + + def test_read_over64bit_integer_sparse(self): + self.check_read(_over64bit_integer_sparse_example, + None, + (2, 2, 2, 'coordinate', 'integer', 'symmetric'), + dense=False, + over32=True, + over64=True) + + +_general_example = '''\ +%%MatrixMarket matrix coordinate real general +%================================================================================= +% +% This ASCII file represents a sparse MxN matrix with L +% nonzeros in the following Matrix Market format: +% +% +----------------------------------------------+ +% |%%MatrixMarket matrix coordinate real general | <--- header line +% |% | <--+ +% |% comments | |-- 0 or more comment lines +% |% | <--+ +% | M N L | <--- rows, columns, entries +% | I1 J1 A(I1, J1) | <--+ +% | I2 J2 A(I2, J2) | | +% | I3 J3 A(I3, J3) | |-- L lines +% | . . . | | +% | IL JL A(IL, JL) | <--+ +% +----------------------------------------------+ +% +% Indices are 1-based, i.e. A(1,1) is the first element. +% +%================================================================================= + 5 5 8 + 1 1 1.000e+00 + 2 2 1.050e+01 + 3 3 1.500e-02 + 1 4 6.000e+00 + 4 2 2.505e+02 + 4 4 -2.800e+02 + 4 5 3.332e+01 + 5 5 1.200e+01 +''' + +_hermitian_example = '''\ +%%MatrixMarket matrix coordinate complex hermitian + 5 5 7 + 1 1 1.0 0 + 2 2 10.5 0 + 4 2 250.5 22.22 + 3 3 1.5e-2 0 + 4 4 -2.8e2 0 + 5 5 12. 0 + 5 4 0 33.32 +''' + +_skew_example = '''\ +%%MatrixMarket matrix coordinate real skew-symmetric + 5 5 7 + 1 1 1.0 + 2 2 10.5 + 4 2 250.5 + 3 3 1.5e-2 + 4 4 -2.8e2 + 5 5 12. + 5 4 0 +''' + +_symmetric_example = '''\ +%%MatrixMarket matrix coordinate real symmetric + 5 5 7 + 1 1 1.0 + 2 2 10.5 + 4 2 250.5 + 3 3 1.5e-2 + 4 4 -2.8e2 + 5 5 12. + 5 4 8 +''' + +_symmetric_pattern_example = '''\ +%%MatrixMarket matrix coordinate pattern symmetric + 5 5 7 + 1 1 + 2 2 + 4 2 + 3 3 + 4 4 + 5 5 + 5 4 +''' + +# example (without comment lines) from Figure 1 in +# https://math.nist.gov/MatrixMarket/reports/MMformat.ps +_empty_lines_example = '''\ +%%MatrixMarket MATRIX Coordinate Real General + + 5 5 8 + +1 1 1.0 +2 2 10.5 +3 3 1.5e-2 +4 4 -2.8E2 +5 5 12. + 1 4 6 + 4 2 250.5 + 4 5 33.32 + +''' + + +class TestMMIOCoordinate: + def setup_method(self): + self.tmpdir = mkdtemp(suffix=str(threading.get_native_id())) + self.fn = os.path.join(self.tmpdir, 'testfile.mtx') + + def teardown_method(self): + shutil.rmtree(self.tmpdir) + + def check_read(self, example, a, info): + f = open(self.fn, 'w') + f.write(example) + f.close() + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn, spmatrix=False).toarray() + assert_array_almost_equal(a, b) + + def test_read_general(self): + a = [[1, 0, 0, 6, 0], + [0, 10.5, 0, 0, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 33.32], + [0, 0, 0, 0, 12]] + self.check_read(_general_example, a, + (5, 5, 8, 'coordinate', 'real', 'general')) + + def test_read_hermitian(self): + a = [[1, 0, 0, 0, 0], + [0, 10.5, 0, 250.5 - 22.22j, 0], + [0, 0, .015, 0, 0], + [0, 250.5 + 22.22j, 0, -280, -33.32j], + [0, 0, 0, 33.32j, 12]] + self.check_read(_hermitian_example, a, + (5, 5, 7, 'coordinate', 'complex', 'hermitian')) + + def test_read_skew(self): + a = [[1, 0, 0, 0, 0], + [0, 10.5, 0, -250.5, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 0], + [0, 0, 0, 0, 12]] + self.check_read(_skew_example, a, + (5, 5, 7, 'coordinate', 'real', 'skew-symmetric')) + + def test_read_symmetric(self): + a = [[1, 0, 0, 0, 0], + [0, 10.5, 0, 250.5, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 8], + [0, 0, 0, 8, 12]] + self.check_read(_symmetric_example, a, + (5, 5, 7, 'coordinate', 'real', 'symmetric')) + + def test_read_symmetric_pattern(self): + a = [[1, 0, 0, 0, 0], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 0], + [0, 1, 0, 1, 1], + [0, 0, 0, 1, 1]] + self.check_read(_symmetric_pattern_example, a, + (5, 5, 7, 'coordinate', 'pattern', 'symmetric')) + + def test_read_empty_lines(self): + a = [[1, 0, 0, 6, 0], + [0, 10.5, 0, 0, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 33.32], + [0, 0, 0, 0, 12]] + self.check_read(_empty_lines_example, a, + (5, 5, 8, 'coordinate', 'real', 'general')) + + def test_empty_write_read(self): + # https://github.com/scipy/scipy/issues/1410 (Trac #883) + + b = scipy.sparse.coo_array((10, 10)) + mmwrite(self.fn, b) + + assert_equal(mminfo(self.fn), + (10, 10, 0, 'coordinate', 'real', 'symmetric')) + a = b.toarray() + b = mmread(self.fn, spmatrix=False).toarray() + assert_array_almost_equal(a, b) + + def test_bzip2_py3(self): + # test if fix for #2152 works + try: + # bz2 module isn't always built when building Python. + import bz2 + except ImportError: + return + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + + b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + fn_bzip2 = f"{self.fn}.bz2" + with open(self.fn, 'rb') as f_in: + f_out = bz2.BZ2File(fn_bzip2, 'wb') + f_out.write(f_in.read()) + f_out.close() + + a = mmread(fn_bzip2, spmatrix=False).toarray() + assert_array_almost_equal(a, b.toarray()) + + def test_gzip_py3(self): + # test if fix for #2152 works + try: + # gzip module can be missing from Python installation + import gzip + except ImportError: + return + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + + b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + fn_gzip = f"{self.fn}.gz" + with open(self.fn, 'rb') as f_in: + f_out = gzip.open(fn_gzip, 'wb') + f_out.write(f_in.read()) + f_out.close() + + a = mmread(fn_gzip, spmatrix=False).toarray() + assert_array_almost_equal(a, b.toarray()) + + def test_real_write_read(self): + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + + b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + assert_equal(mminfo(self.fn), + (5, 5, 8, 'coordinate', 'real', 'general')) + a = b.toarray() + b = mmread(self.fn, spmatrix=False).toarray() + assert_array_almost_equal(a, b) + + def test_complex_write_read(self): + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j, + 250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j]) + + b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + assert_equal(mminfo(self.fn), + (5, 5, 8, 'coordinate', 'complex', 'general')) + a = b.toarray() + b = mmread(self.fn, spmatrix=False).toarray() + assert_array_almost_equal(a, b) + + def test_sparse_formats(self, tmp_path): + # Note: `tmp_path` is a pytest fixture, it handles cleanup + tmpdir = tmp_path / 'sparse_formats' + tmpdir.mkdir() + + mats = [] + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + mats.append(scipy.sparse.coo_array((V, (I, J)), shape=(5, 5))) + + V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j, + 250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j]) + mats.append(scipy.sparse.coo_array((V, (I, J)), shape=(5, 5))) + + for mat in mats: + expected = mat.toarray() + for fmt in ['csr', 'csc', 'coo']: + fname = tmpdir / (fmt + '.mtx') + mmwrite(fname, mat.asformat(fmt)) + result = mmread(fname, spmatrix=False).toarray() + assert_array_almost_equal(result, expected) + + def test_precision(self): + test_values = [pi] + [10**(i) for i in range(0, -10, -1)] + test_precisions = range(1, 10) + for value in test_values: + for precision in test_precisions: + # construct sparse matrix with test value at last main diagonal + n = 10**precision + 1 + A = scipy.sparse.dok_array((n, n)) + A[n-1, n-1] = value + # write matrix with test precision and read again + mmwrite(self.fn, A, precision=precision) + A = scipy.io.mmread(self.fn, spmatrix=False) + # check for right entries in matrix + assert_array_equal(A.row, [n-1]) + assert_array_equal(A.col, [n-1]) + assert_allclose(A.data, [float(f'{value:.{precision}g}')]) + + def test_bad_number_of_coordinate_header_fields(self): + s = """\ + %%MatrixMarket matrix coordinate real general + 5 5 8 999 + 1 1 1.000e+00 + 2 2 1.050e+01 + 3 3 1.500e-02 + 1 4 6.000e+00 + 4 2 2.505e+02 + 4 4 -2.800e+02 + 4 5 3.332e+01 + 5 5 1.200e+01 + """ + text = textwrap.dedent(s).encode('ascii') + with pytest.raises(ValueError, match='not of length 3'): + scipy.io.mmread(io.BytesIO(text)) + + +def test_gh11389(): + mmread(io.StringIO("%%MatrixMarket matrix coordinate complex symmetric\n" + " 1 1 1\n" + "1 1 -2.1846000000000e+02 0.0000000000000e+00"), + spmatrix=False) + + +def test_gh18123(tmp_path): + lines = [" %%MatrixMarket matrix coordinate real general\n", + "5 5 3\n", + "2 3 1.0\n", + "3 4 2.0\n", + "3 5 3.0\n"] + test_file = tmp_path / "test.mtx" + with open(test_file, "w") as f: + f.writelines(lines) + mmread(test_file, spmatrix=False) + +def test_mtx_append(tmp_path): + a = mmread(io.StringIO("%%MatrixMarket matrix coordinate complex symmetric\n" + " 1 1 1\n" + "1 1 -2.1846000000000e+02 0.0000000000000e+00"), + spmatrix=False) + test_writefile = tmp_path / "test_mtx" + test_readfile = tmp_path / "test_mtx.mtx" + mmwrite(test_writefile, a) + mmread(test_readfile, spmatrix=False) + + +def test_threadpoolctl(): + try: + import threadpoolctl + if not hasattr(threadpoolctl, "register"): + pytest.skip("threadpoolctl too old") + return + except ImportError: + pytest.skip("no threadpoolctl") + return + + with threadpoolctl.threadpool_limits(limits=4): + assert_equal(fmm.PARALLELISM, 4) + + with threadpoolctl.threadpool_limits(limits=2, user_api='scipy'): + assert_equal(fmm.PARALLELISM, 2) + + +def test_gh21999_file_not_exist(): + tmpdir = mkdtemp(suffix=str(threading.get_native_id())) + wrong_fn = os.path.join(tmpdir, 'not_exist_test_file.mtx') + assert_raises(FileNotFoundError, mmread, wrong_fn) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_netcdf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_netcdf.py new file mode 100644 index 0000000000000000000000000000000000000000..f049b921b4f431a344422d334c1582c58bf6f43d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_netcdf.py @@ -0,0 +1,553 @@ +''' Tests for netcdf ''' +import os +from os.path import join as pjoin, dirname +import shutil +import tempfile +import warnings +from io import BytesIO +from glob import glob +from contextlib import contextmanager + +import numpy as np +from numpy.testing import (assert_, assert_allclose, assert_equal, + break_cycles, IS_PYPY) +import pytest +from pytest import raises as assert_raises + +from scipy.io import netcdf_file +from scipy._lib._tmpdirs import in_tempdir + +TEST_DATA_PATH = pjoin(dirname(__file__), 'data') + +N_EG_ELS = 11 # number of elements for example variable +VARTYPE_EG = 'b' # var type for example variable + + +pytestmark = pytest.mark.thread_unsafe + + +@contextmanager +def make_simple(*args, **kwargs): + f = netcdf_file(*args, **kwargs) + f.history = 'Created for a test' + f.createDimension('time', N_EG_ELS) + time = f.createVariable('time', VARTYPE_EG, ('time',)) + time[:] = np.arange(N_EG_ELS) + time.units = 'days since 2008-01-01' + f.flush() + yield f + f.close() + + +def check_simple(ncfileobj): + '''Example fileobj tests ''' + assert_equal(ncfileobj.history, b'Created for a test') + time = ncfileobj.variables['time'] + assert_equal(time.units, b'days since 2008-01-01') + assert_equal(time.shape, (N_EG_ELS,)) + assert_equal(time[-1], N_EG_ELS-1) + +def assert_mask_matches(arr, expected_mask): + ''' + Asserts that the mask of arr is effectively the same as expected_mask. + + In contrast to numpy.ma.testutils.assert_mask_equal, this function allows + testing the 'mask' of a standard numpy array (the mask in this case is treated + as all False). + + Parameters + ---------- + arr : ndarray or MaskedArray + Array to test. + expected_mask : array_like of booleans + A list giving the expected mask. + ''' + + mask = np.ma.getmaskarray(arr) + assert_equal(mask, expected_mask) + + +def test_read_write_files(): + # test round trip for example file + cwd = os.getcwd() + try: + tmpdir = tempfile.mkdtemp() + os.chdir(tmpdir) + with make_simple('simple.nc', 'w') as f: + pass + # read the file we just created in 'a' mode + with netcdf_file('simple.nc', 'a') as f: + check_simple(f) + # add something + f._attributes['appendRan'] = 1 + + # To read the NetCDF file we just created:: + with netcdf_file('simple.nc') as f: + # Using mmap is the default (but not on pypy) + assert_equal(f.use_mmap, not IS_PYPY) + check_simple(f) + assert_equal(f._attributes['appendRan'], 1) + + # Read it in append (and check mmap is off) + with netcdf_file('simple.nc', 'a') as f: + assert_(not f.use_mmap) + check_simple(f) + assert_equal(f._attributes['appendRan'], 1) + + # Now without mmap + with netcdf_file('simple.nc', mmap=False) as f: + # Using mmap is the default + assert_(not f.use_mmap) + check_simple(f) + + # To read the NetCDF file we just created, as file object, no + # mmap. When n * n_bytes(var_type) is not divisible by 4, this + # raised an error in pupynere 1.0.12 and scipy rev 5893, because + # calculated vsize was rounding up in units of 4 - see + # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html + with open('simple.nc', 'rb') as fobj: + with netcdf_file(fobj) as f: + # by default, don't use mmap for file-like + assert_(not f.use_mmap) + check_simple(f) + + # Read file from fileobj, with mmap + with warnings.catch_warnings(): + if IS_PYPY: + warnings.filterwarnings( + "ignore", + "Cannot close a netcdf_file opened with mmap=True.*", + RuntimeWarning + ) + with open('simple.nc', 'rb') as fobj: + with netcdf_file(fobj, mmap=True) as f: + assert_(f.use_mmap) + check_simple(f) + + # Again read it in append mode (adding another att) + with open('simple.nc', 'r+b') as fobj: + with netcdf_file(fobj, 'a') as f: + assert_(not f.use_mmap) + check_simple(f) + f.createDimension('app_dim', 1) + var = f.createVariable('app_var', 'i', ('app_dim',)) + var[:] = 42 + + # And... check that app_var made it in... + with netcdf_file('simple.nc') as f: + check_simple(f) + assert_equal(f.variables['app_var'][:], 42) + + finally: + if IS_PYPY: + # windows cannot remove a dead file held by a mmap + # that has not been collected in PyPy + break_cycles() + break_cycles() + os.chdir(cwd) + shutil.rmtree(tmpdir) + + +def test_read_write_sio(): + eg_sio1 = BytesIO() + with make_simple(eg_sio1, 'w'): + str_val = eg_sio1.getvalue() + + eg_sio2 = BytesIO(str_val) + with netcdf_file(eg_sio2) as f2: + check_simple(f2) + + # Test that error is raised if attempting mmap for sio + eg_sio3 = BytesIO(str_val) + assert_raises(ValueError, netcdf_file, eg_sio3, 'r', True) + # Test 64-bit offset write / read + eg_sio_64 = BytesIO() + with make_simple(eg_sio_64, 'w', version=2) as f_64: + str_val = eg_sio_64.getvalue() + + eg_sio_64 = BytesIO(str_val) + with netcdf_file(eg_sio_64) as f_64: + check_simple(f_64) + assert_equal(f_64.version_byte, 2) + # also when version 2 explicitly specified + eg_sio_64 = BytesIO(str_val) + with netcdf_file(eg_sio_64, version=2) as f_64: + check_simple(f_64) + assert_equal(f_64.version_byte, 2) + + +def test_bytes(): + raw_file = BytesIO() + f = netcdf_file(raw_file, mode='w') + # Dataset only has a single variable, dimension and attribute to avoid + # any ambiguity related to order. + f.a = 'b' + f.createDimension('dim', 1) + var = f.createVariable('var', np.int16, ('dim',)) + var[0] = -9999 + var.c = 'd' + f.sync() + + actual = raw_file.getvalue() + + expected = (b'CDF\x01' + b'\x00\x00\x00\x00' + b'\x00\x00\x00\x0a' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x03' + b'dim\x00' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x0c' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x01' + b'a\x00\x00\x00' + b'\x00\x00\x00\x02' + b'\x00\x00\x00\x01' + b'b\x00\x00\x00' + b'\x00\x00\x00\x0b' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x03' + b'var\x00' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x00' + b'\x00\x00\x00\x0c' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x01' + b'c\x00\x00\x00' + b'\x00\x00\x00\x02' + b'\x00\x00\x00\x01' + b'd\x00\x00\x00' + b'\x00\x00\x00\x03' + b'\x00\x00\x00\x04' + b'\x00\x00\x00\x78' + b'\xd8\xf1\x80\x01') + + assert_equal(actual, expected) + + +def test_encoded_fill_value(): + with netcdf_file(BytesIO(), mode='w') as f: + f.createDimension('x', 1) + var = f.createVariable('var', 'S1', ('x',)) + assert_equal(var._get_encoded_fill_value(), b'\x00') + var._FillValue = b'\x01' + assert_equal(var._get_encoded_fill_value(), b'\x01') + var._FillValue = b'\x00\x00' # invalid, wrong size + assert_equal(var._get_encoded_fill_value(), b'\x00') + + +def test_read_example_data(): + # read any example data files + for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')): + with netcdf_file(fname, 'r'): + pass + with netcdf_file(fname, 'r', mmap=False): + pass + + +def test_itemset_no_segfault_on_readonly(): + # Regression test for ticket #1202. + # Open the test file in read-only mode. + + filename = pjoin(TEST_DATA_PATH, 'example_1.nc') + with warnings.catch_warnings(): + message = ("Cannot close a netcdf_file opened with mmap=True, when " + "netcdf_variables or arrays referring to its data still exist") + warnings.filterwarnings("ignore", message, RuntimeWarning) + with netcdf_file(filename, 'r', mmap=True) as f: + time_var = f.variables['time'] + + # time_var.assignValue(42) should raise a RuntimeError--not seg. fault! + assert_raises(RuntimeError, time_var.assignValue, 42) + + +def test_appending_issue_gh_8625(): + stream = BytesIO() + + with make_simple(stream, mode='w') as f: + f.createDimension('x', 2) + f.createVariable('x', float, ('x',)) + f.variables['x'][...] = 1 + f.flush() + contents = stream.getvalue() + + stream = BytesIO(contents) + with netcdf_file(stream, mode='a') as f: + f.variables['x'][...] = 2 + + +def test_write_invalid_dtype(): + dtypes = ['int64', 'uint64'] + if np.dtype('int').itemsize == 8: # 64-bit machines + dtypes.append('int') + if np.dtype('uint').itemsize == 8: # 64-bit machines + dtypes.append('uint') + + with netcdf_file(BytesIO(), 'w') as f: + f.createDimension('time', N_EG_ELS) + for dt in dtypes: + assert_raises(ValueError, f.createVariable, 'time', dt, ('time',)) + + +def test_flush_rewind(): + stream = BytesIO() + with make_simple(stream, mode='w') as f: + f.createDimension('x',4) # x is used in createVariable + v = f.createVariable('v', 'i2', ['x']) + v[:] = 1 + f.flush() + len_single = len(stream.getvalue()) + f.flush() + len_double = len(stream.getvalue()) + + assert_(len_single == len_double) + + +def test_dtype_specifiers(): + # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work. + # Specifying np.int16 or similar only works from the same commit as this + # comment was made. + with make_simple(BytesIO(), mode='w') as f: + f.createDimension('x',4) + f.createVariable('v1', 'i2', ['x']) + f.createVariable('v2', np.int16, ['x']) + f.createVariable('v3', np.dtype(np.int16), ['x']) + + +def test_ticket_1720(): + io = BytesIO() + + items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] + + with netcdf_file(io, 'w') as f: + f.history = 'Created for a test' + f.createDimension('float_var', 10) + float_var = f.createVariable('float_var', 'f', ('float_var',)) + float_var[:] = items + float_var.units = 'metres' + f.flush() + contents = io.getvalue() + + io = BytesIO(contents) + with netcdf_file(io, 'r') as f: + assert_equal(f.history, b'Created for a test') + float_var = f.variables['float_var'] + assert_equal(float_var.units, b'metres') + assert_equal(float_var.shape, (10,)) + assert_allclose(float_var[:], items) + + +def test_mmaps_segfault(): + filename = pjoin(TEST_DATA_PATH, 'example_1.nc') + + if not IS_PYPY: + with warnings.catch_warnings(): + warnings.simplefilter("error") + with netcdf_file(filename, mmap=True) as f: + x = f.variables['lat'][:] + # should not raise warnings + del x + + def doit(): + with netcdf_file(filename, mmap=True) as f: + return f.variables['lat'][:] + + # should not crash + with warnings.catch_warnings(): + message = ("Cannot close a netcdf_file opened with mmap=True, when " + "netcdf_variables or arrays referring to its data still exist") + warnings.filterwarnings("ignore", message, RuntimeWarning) + x = doit() + x.sum() + + +def test_zero_dimensional_var(): + io = BytesIO() + with make_simple(io, 'w') as f: + v = f.createVariable('zerodim', 'i2', []) + # This is checking that .isrec returns a boolean - don't simplify it + # to 'assert not ...' + assert v.isrec is False, v.isrec + f.flush() + + +def test_byte_gatts(): + # Check that global "string" atts work like they did before py3k + # unicode and general bytes confusion + with in_tempdir(): + filename = 'g_byte_atts.nc' + f = netcdf_file(filename, 'w') + f._attributes['holy'] = b'grail' + f._attributes['witch'] = 'floats' + f.close() + f = netcdf_file(filename, 'r') + assert_equal(f._attributes['holy'], b'grail') + assert_equal(f._attributes['witch'], b'floats') + f.close() + + +def test_open_append(): + # open 'w' put one attr + with in_tempdir(): + filename = 'append_dat.nc' + f = netcdf_file(filename, 'w') + f._attributes['Kilroy'] = 'was here' + f.close() + + # open again in 'a', read the att and a new one + f = netcdf_file(filename, 'a') + assert_equal(f._attributes['Kilroy'], b'was here') + f._attributes['naughty'] = b'Zoot' + f.close() + + # open yet again in 'r' and check both atts + f = netcdf_file(filename, 'r') + assert_equal(f._attributes['Kilroy'], b'was here') + assert_equal(f._attributes['naughty'], b'Zoot') + f.close() + + +def test_append_recordDimension(): + dataSize = 100 + + with in_tempdir(): + # Create file with record time dimension + with netcdf_file('withRecordDimension.nc', 'w') as f: + f.createDimension('time', None) + f.createVariable('time', 'd', ('time',)) + f.createDimension('x', dataSize) + x = f.createVariable('x', 'd', ('x',)) + x[:] = np.array(range(dataSize)) + f.createDimension('y', dataSize) + y = f.createVariable('y', 'd', ('y',)) + y[:] = np.array(range(dataSize)) + f.createVariable('testData', 'i', ('time', 'x', 'y')) + f.flush() + f.close() + + for i in range(2): + # Open the file in append mode and add data + with netcdf_file('withRecordDimension.nc', 'a') as f: + f.variables['time'].data = np.append(f.variables["time"].data, i) + f.variables['testData'][i, :, :] = np.full((dataSize, dataSize), i) + f.flush() + + # Read the file and check that append worked + with netcdf_file('withRecordDimension.nc') as f: + assert_equal(f.variables['time'][-1], i) + assert_equal(f.variables['testData'][-1, :, :].copy(), + np.full((dataSize, dataSize), i)) + assert_equal(f.variables['time'].data.shape[0], i+1) + assert_equal(f.variables['testData'].data.shape[0], i+1) + + # Read the file and check that 'data' was not saved as user defined + # attribute of testData variable during append operation + with netcdf_file('withRecordDimension.nc') as f: + with assert_raises(KeyError) as ar: + f.variables['testData']._attributes['data'] + ex = ar.value + assert_equal(ex.args[0], 'data') + +def test_maskandscale(): + t = np.linspace(20, 30, 15) + t[3] = 100 + tm = np.ma.masked_greater(t, 99) + fname = pjoin(TEST_DATA_PATH, 'example_2.nc') + with netcdf_file(fname, maskandscale=True) as f: + Temp = f.variables['Temperature'] + assert_equal(Temp.missing_value, 9999) + assert_equal(Temp.add_offset, 20) + assert_equal(Temp.scale_factor, np.float32(0.01)) + found = Temp[:].compressed() + del Temp # Remove ref to mmap, so file can be closed. + expected = np.round(tm.compressed(), 2) + assert_allclose(found, expected) + + with in_tempdir(): + newfname = 'ms.nc' + f = netcdf_file(newfname, 'w', maskandscale=True) + f.createDimension('Temperature', len(tm)) + temp = f.createVariable('Temperature', 'i', ('Temperature',)) + temp.missing_value = 9999 + temp.scale_factor = 0.01 + temp.add_offset = 20 + temp[:] = tm + f.close() + + with netcdf_file(newfname, maskandscale=True) as f: + Temp = f.variables['Temperature'] + assert_equal(Temp.missing_value, 9999) + assert_equal(Temp.add_offset, 20) + assert_equal(Temp.scale_factor, np.float32(0.01)) + expected = np.round(tm.compressed(), 2) + found = Temp[:].compressed() + del Temp + assert_allclose(found, expected) + + +# ------------------------------------------------------------------------ +# Test reading with masked values (_FillValue / missing_value) +# ------------------------------------------------------------------------ + +def test_read_withValuesNearFillValue(): + # Regression test for ticket #5626 + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var1_fillval0'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_withNoFillValue(): + # For a variable with no fill value, reading data with maskandscale=True + # should return unmasked data + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var2_noFillval'][:] + assert_mask_matches(vardata, [False, False, False]) + assert_equal(vardata, [1,2,3]) + +def test_read_withFillValueAndMissingValue(): + # For a variable with both _FillValue and missing_value, the _FillValue + # should be used + IRRELEVANT_VALUE = 9999 + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var3_fillvalAndMissingValue'][:] + assert_mask_matches(vardata, [True, False, False]) + assert_equal(vardata, [IRRELEVANT_VALUE, 2, 3]) + +def test_read_withMissingValue(): + # For a variable with missing_value but not _FillValue, the missing_value + # should be used + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var4_missingValue'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_withFillValNaN(): + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var5_fillvalNaN'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_withChar(): + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var6_char'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_with2dVar(): + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var7_2d'][:] + assert_mask_matches(vardata, [[True, False], [False, False], [False, True]]) + +def test_read_withMaskAndScaleFalse(): + # If a variable has a _FillValue (or missing_value) attribute, but is read + # with maskandscale set to False, the result should be unmasked + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + # Open file with mmap=False to avoid problems with closing a mmap'ed file + # when arrays referring to its data still exist: + with netcdf_file(fname, maskandscale=False, mmap=False) as f: + vardata = f.variables['var3_fillvalAndMissingValue'][:] + assert_mask_matches(vardata, [False, False, False]) + assert_equal(vardata, [1, 2, 3]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_paths.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..7f4bb25c59950f3fa06477406e2fa4f44629ace4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_paths.py @@ -0,0 +1,93 @@ +""" +Ensure that we can use pathlib.Path objects in all relevant IO functions. +""" +from pathlib import Path + +import numpy as np + +import scipy.io +import scipy.io.wavfile +from scipy._lib._tmpdirs import tempdir +import scipy.sparse + + +class TestPaths: + data = np.arange(5).astype(np.int64) + + def test_savemat(self): + with tempdir() as temp_dir: + path = Path(temp_dir) / 'data.mat' + scipy.io.savemat(path, {'data': self.data}) + assert path.is_file() + + def test_loadmat(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + path = Path(temp_dir) / 'data.mat' + scipy.io.savemat(str(path), {'data': self.data}) + + mat_contents = scipy.io.loadmat(path) + assert (mat_contents['data'] == self.data).all() + + def test_whosmat(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + path = Path(temp_dir) / 'data.mat' + scipy.io.savemat(str(path), {'data': self.data}) + + contents = scipy.io.whosmat(path) + assert contents[0] == ('data', (1, 5), 'int64') + + def test_readsav(self): + path = Path(__file__).parent / 'data/scalar_string.sav' + scipy.io.readsav(path) + + def test_hb_read(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + data = scipy.sparse.eye_array(3, format='csr') + path = Path(temp_dir) / 'data.hb' + scipy.io.hb_write(str(path), data) + + data_new = scipy.io.hb_read(path, spmatrix=False) + assert (data_new != data).nnz == 0 + + def test_hb_write(self): + with tempdir() as temp_dir: + data = scipy.sparse.eye_array(3, format='csr') + path = Path(temp_dir) / 'data.hb' + scipy.io.hb_write(path, data) + assert path.is_file() + + def test_mmio_read(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + data = scipy.sparse.eye_array(3, format='csr') + path = Path(temp_dir) / 'data.mtx' + scipy.io.mmwrite(str(path), data) + + data_new = scipy.io.mmread(path, spmatrix=False) + assert (data_new != data).nnz == 0 + + def test_mmio_write(self): + with tempdir() as temp_dir: + data = scipy.sparse.eye_array(3, format='csr') + path = Path(temp_dir) / 'data.mtx' + scipy.io.mmwrite(path, data) + + def test_netcdf_file(self): + path = Path(__file__).parent / 'data/example_1.nc' + scipy.io.netcdf_file(path) + + def test_wavfile_read(self): + path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav' + scipy.io.wavfile.read(path) + + def test_wavfile_write(self): + # Read from str path, write to Path + input_path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav' + rate, data = scipy.io.wavfile.read(str(input_path)) + + with tempdir() as temp_dir: + output_path = Path(temp_dir) / input_path.name + scipy.io.wavfile.write(output_path, rate, data) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_wavfile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_wavfile.py new file mode 100644 index 0000000000000000000000000000000000000000..fd3d9fabd899f850d575666dd87d80bcbd6d3996 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/io/tests/test_wavfile.py @@ -0,0 +1,520 @@ +import os +import sys +from io import (BytesIO, UnsupportedOperation) +import threading +import warnings + +import numpy as np +from numpy.testing import (assert_equal, assert_, assert_array_equal, + break_cycles, IS_PYPY) +import pytest +from pytest import raises, warns + +from scipy.io import wavfile + + +def datafile(fn): + return os.path.join(os.path.dirname(__file__), 'data', fn) + + +def test_read_1(): + # 32-bit PCM (which uses extensible format) + for mmap in [False, True]: + filename = 'test-44100Hz-le-1ch-4bytes.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 44100) + assert_(np.issubdtype(data.dtype, np.int32)) + assert_equal(data.shape, (4410,)) + + del data + + +def test_read_2(): + # 8-bit unsigned PCM + for mmap in [False, True]: + filename = 'test-8000Hz-le-2ch-1byteu.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.uint8)) + assert_equal(data.shape, (800, 2)) + + del data + + +def test_read_3(): + # Little-endian float + for mmap in [False, True]: + filename = 'test-44100Hz-2ch-32bit-float-le.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 44100) + assert_(np.issubdtype(data.dtype, np.float32)) + assert_equal(data.shape, (441, 2)) + + del data + + +def test_read_4(): + # Contains unsupported 'PEAK' chunk + for mmap in [False, True]: + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + "Chunk .non-data. not understood, skipping it", + wavfile.WavFileWarning + ) + filename = 'test-48000Hz-2ch-64bit-float-le-wavex.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 48000) + assert_(np.issubdtype(data.dtype, np.float64)) + assert_equal(data.shape, (480, 2)) + + del data + + +def test_read_5(): + # Big-endian float + for mmap in [False, True]: + filename = 'test-44100Hz-2ch-32bit-float-be.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 44100) + assert_(np.issubdtype(data.dtype, np.float32)) + assert_(data.dtype.byteorder == '>' or (sys.byteorder == 'big' and + data.dtype.byteorder == '=')) + assert_equal(data.shape, (441, 2)) + + del data + + +def test_5_bit_odd_size_no_pad(): + # 5-bit, 1 B container, 5 channels, 9 samples, 45 B data chunk + # Generated by LTspice, which incorrectly omits pad byte, but should be + # readable anyway + for mmap in [False, True]: + filename = 'test-8000Hz-le-5ch-9S-5bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.uint8)) + assert_equal(data.shape, (9, 5)) + + # 8-5 = 3 LSBits should be 0 + assert_equal(data & 0b00000111, 0) + + # Unsigned + assert_equal(data.max(), 0b11111000) # Highest possible + assert_equal(data[0, 0], 128) # Midpoint is 128 for <= 8-bit + assert_equal(data.min(), 0) # Lowest possible + + del data + + +def test_12_bit_even_size(): + # 12-bit, 2 B container, 4 channels, 9 samples, 72 B data chunk + # Generated by LTspice from 1 Vpk sine waves + for mmap in [False, True]: + filename = 'test-8000Hz-le-4ch-9S-12bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int16)) + assert_equal(data.shape, (9, 4)) + + # 16-12 = 4 LSBits should be 0 + assert_equal(data & 0b00000000_00001111, 0) + + # Signed + assert_equal(data.max(), 0b01111111_11110000) # Highest possible + assert_equal(data[0, 0], 0) # Midpoint is 0 for >= 9-bit + assert_equal(data.min(), -0b10000000_00000000) # Lowest possible + + del data + + +def test_24_bit_odd_size_with_pad(): + # 24-bit, 3 B container, 3 channels, 5 samples, 45 B data chunk + # Should not raise any warnings about the data chunk pad byte + filename = 'test-8000Hz-le-3ch-5S-24bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int32)) + assert_equal(data.shape, (5, 3)) + + # All LSBytes should be 0 + assert_equal(data & 0xff, 0) + + # Hand-made max/min samples under different conventions: + # 2**(N-1) 2**(N-1)-1 LSB + assert_equal(data, [[-0x8000_0000, -0x7fff_ff00, -0x200], + [-0x4000_0000, -0x3fff_ff00, -0x100], + [+0x0000_0000, +0x0000_0000, +0x000], + [+0x4000_0000, +0x3fff_ff00, +0x100], + [+0x7fff_ff00, +0x7fff_ff00, +0x200]]) + # ^ clipped + + +def test_20_bit_extra_data(): + # 20-bit, 3 B container, 1 channel, 10 samples, 30 B data chunk + # with extra data filling container beyond the bit depth + filename = 'test-1234Hz-le-1ch-10S-20bit-extra.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 1234) + assert_(np.issubdtype(data.dtype, np.int32)) + assert_equal(data.shape, (10,)) + + # All LSBytes should still be 0, because 3 B container in 4 B dtype + assert_equal(data & 0xff, 0) + + # But it should load the data beyond 20 bits + assert_((data & 0xf00).any()) + + # Full-scale positive/negative samples, then being halved each time + assert_equal(data, [+0x7ffff000, # +full-scale 20-bit + -0x7ffff000, # -full-scale 20-bit + +0x7ffff000 >> 1, # +1/2 + -0x7ffff000 >> 1, # -1/2 + +0x7ffff000 >> 2, # +1/4 + -0x7ffff000 >> 2, # -1/4 + +0x7ffff000 >> 3, # +1/8 + -0x7ffff000 >> 3, # -1/8 + +0x7ffff000 >> 4, # +1/16 + -0x7ffff000 >> 4, # -1/16 + ]) + + +def test_36_bit_odd_size(): + # 36-bit, 5 B container, 3 channels, 5 samples, 75 B data chunk + pad + filename = 'test-8000Hz-le-3ch-5S-36bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # 28 LSBits should be 0 + assert_equal(data & 0xfffffff, 0) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_f000_0000, -0x2000_0000], + [-0x4000_0000_0000_0000, -0x3fff_ffff_f000_0000, -0x1000_0000], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000_0000], + [+0x4000_0000_0000_0000, +0x3fff_ffff_f000_0000, +0x1000_0000], + [+0x7fff_ffff_f000_0000, +0x7fff_ffff_f000_0000, +0x2000_0000]] + # ^ clipped + + assert_equal(data, correct) + + +def test_45_bit_even_size(): + # 45-bit, 6 B container, 3 channels, 5 samples, 90 B data chunk + filename = 'test-8000Hz-le-3ch-5S-45bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # 19 LSBits should be 0 + assert_equal(data & 0x7ffff, 0) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_fff8_0000, -0x10_0000], + [-0x4000_0000_0000_0000, -0x3fff_ffff_fff8_0000, -0x08_0000], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x00_0000], + [+0x4000_0000_0000_0000, +0x3fff_ffff_fff8_0000, +0x08_0000], + [+0x7fff_ffff_fff8_0000, +0x7fff_ffff_fff8_0000, +0x10_0000]] + # ^ clipped + + assert_equal(data, correct) + + +def test_53_bit_odd_size(): + # 53-bit, 7 B container, 3 channels, 5 samples, 105 B data chunk + pad + filename = 'test-8000Hz-le-3ch-5S-53bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # 11 LSBits should be 0 + assert_equal(data & 0x7ff, 0) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_f800, -0x1000], + [-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_f800, -0x0800], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000], + [+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_f800, +0x0800], + [+0x7fff_ffff_ffff_f800, +0x7fff_ffff_ffff_f800, +0x1000]] + # ^ clipped + + assert_equal(data, correct) + + +def test_64_bit_even_size(): + # 64-bit, 8 B container, 3 channels, 5 samples, 120 B data chunk + for mmap in [False, True]: + filename = 'test-8000Hz-le-3ch-5S-64bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_ffff, -0x2], + [-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_ffff, -0x1], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0], + [+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_ffff, +0x1], + [+0x7fff_ffff_ffff_ffff, +0x7fff_ffff_ffff_ffff, +0x2]] + # ^ clipped + + assert_equal(data, correct) + + del data + + +def test_unsupported_mmap(): + # Test containers that cannot be mapped to numpy types + for filename in {'test-8000Hz-le-3ch-5S-24bit.wav', + 'test-8000Hz-le-3ch-5S-36bit.wav', + 'test-8000Hz-le-3ch-5S-45bit.wav', + 'test-8000Hz-le-3ch-5S-53bit.wav', + 'test-1234Hz-le-1ch-10S-20bit-extra.wav'}: + with raises(ValueError, match="mmap.*not compatible"): + rate, data = wavfile.read(datafile(filename), mmap=True) + + +def test_rifx(): + # Compare equivalent RIFX and RIFF files + for rifx, riff in {('test-44100Hz-be-1ch-4bytes.wav', + 'test-44100Hz-le-1ch-4bytes.wav'), + ('test-8000Hz-be-3ch-5S-24bit.wav', + 'test-8000Hz-le-3ch-5S-24bit.wav')}: + rate1, data1 = wavfile.read(datafile(rifx), mmap=False) + rate2, data2 = wavfile.read(datafile(riff), mmap=False) + assert_equal(rate1, rate2) + assert_equal(data1, data2) + + +def test_rf64(): + # Compare equivalent RF64 and RIFF files + for rf64, riff in {('test-44100Hz-le-1ch-4bytes-rf64.wav', + 'test-44100Hz-le-1ch-4bytes.wav'), + ('test-8000Hz-le-3ch-5S-24bit-rf64.wav', + 'test-8000Hz-le-3ch-5S-24bit.wav')}: + rate1, data1 = wavfile.read(datafile(rf64), mmap=False) + rate2, data2 = wavfile.read(datafile(riff), mmap=False) + assert_array_equal(rate1, rate2) + assert_array_equal(data1, data2) + + +@pytest.mark.xslow +def test_write_roundtrip_rf64(tmpdir): + dtype = np.dtype(" 0 + assert rate == 44100 + # also test writing (gh-12176) + data[0] = 0 + + +def test_read_early_eof(): + # File ends after 'fact' chunk at boundary, no data read + for mmap in [False, True]: + filename = 'test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match="Unexpected end of file."): + wavfile.read(fp, mmap=mmap) + + +def test_read_incomplete_chunk(): + # File ends inside 'fmt ' chunk ID, no data read + for mmap in [False, True]: + filename = 'test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match="Incomplete chunk ID.*b'f'"): + wavfile.read(fp, mmap=mmap) + + +def test_read_inconsistent_header(): + # File header's size fields contradict each other + for mmap in [False, True]: + filename = 'test-8000Hz-le-3ch-5S-24bit-inconsistent.wav' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match="header is invalid"): + wavfile.read(fp, mmap=mmap) + + +# signed 8-bit integer PCM is not allowed +# unsigned > 8-bit integer PCM is not allowed +# 8- or 16-bit float PCM is not expected +# g and q are platform-dependent, so not included +@pytest.mark.parametrize("dt_str", ["i2", ">i4", ">i8", ">f4", ">f8", '|u1']) +@pytest.mark.parametrize("channels", [1, 2, 5]) +@pytest.mark.parametrize("rate", [8000, 32000]) +@pytest.mark.parametrize("mmap", [False, True]) +@pytest.mark.parametrize("realfile", [False, True]) +def test_write_roundtrip(realfile, mmap, rate, channels, dt_str, tmpdir): + dtype = np.dtype(dt_str) + if realfile: + tmpfile = str(tmpdir.join(str(threading.get_native_id()), 'temp.wav')) + os.makedirs(os.path.dirname(tmpfile), exist_ok=True) + else: + tmpfile = BytesIO() + data = np.random.rand(100, channels) + if channels == 1: + data = data[:, 0] + if dtype.kind == 'f': + # The range of the float type should be in [-1, 1] + data = data.astype(dtype) + else: + data = (data*128).astype(dtype) + + wavfile.write(tmpfile, rate, data) + + rate2, data2 = wavfile.read(tmpfile, mmap=mmap) + + assert_equal(rate, rate2) + assert_(data2.dtype.byteorder in ('<', '=', '|'), msg=data2.dtype) + assert_array_equal(data, data2) + # also test writing (gh-12176) + if realfile: + data2[0] = 0 + else: + with pytest.raises(ValueError, match='read-only'): + data2[0] = 0 + + if realfile and mmap and IS_PYPY and sys.platform == 'win32': + # windows cannot remove a dead file held by a mmap but not collected + # in PyPy; since the filename gets reused in this test, clean this up + break_cycles() + break_cycles() + + +@pytest.mark.parametrize("dtype", [np.float16]) +def test_wavfile_dtype_unsupported(tmpdir, dtype): + tmpfile = str(tmpdir.join('temp.wav')) + rng = np.random.default_rng(1234) + data = rng.random((100, 5)).astype(dtype) + rate = 8000 + with pytest.raises(ValueError, match="Unsupported"): + wavfile.write(tmpfile, rate, data) + +def test_seek_emulating_reader_invalid_seek(): + # Dummy data for the reader + reader = wavfile.SeekEmulatingReader(BytesIO(b'\x00\x00')) + + # Test SEEK_END with an invalid whence value + with pytest.raises(UnsupportedOperation): + reader.seek(0, 5) # Invalid whence value + + # Test with negative seek value + with pytest.raises(UnsupportedOperation): + reader.seek(-1, 0) # Negative position with SEEK_SET + + # Test SEEK_END with valid parameters (should not raise) + pos = reader.seek(0, os.SEEK_END) # Valid usage + assert pos == 2, f"Failed to seek to end, got position {pos}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..772f45f1450ded87937e356a3aeb22c996a198c6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bf2808e3b56434063b9612cb34ee97f655c1760 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9fe6ce989fb0fe86d8d51c07c275d3298463e85 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e022abc3f5659caf5fea2e5947cbc663688694a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de78b6623a701f7c219b67684d9ae839a8ac1bc2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c5de3dd30d59be3c0c4db80ff5264c77262bfca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0737001c79dbffb16f6f9242e2653b2af3de53e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d352e5a3a300bbb8cf2abde2cc788a7381fbcf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecdb415225aca4d870789b1e2e410b454fc03c9d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48f131732abab94705f7a6d70dd5fae1e3f1f689 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75de5054a9023db8ab0db4aadf429c965a537980 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3a56501822167ef690fa39b8fa8ff945fdb0e94 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d3602f3a1ff7b63ea706860af4438e1e62cb9f0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82f4aba6dbd53a03878766018dd4d7a05f6c643b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81b2fd825be2b8f75e3123e968c85c820d6dbcc6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cc69c51d4261ecf20e78b6acb2b98c68add0a1d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_misc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_misc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d91ee6289d046e27db95f178ae57d7c22a8d0868 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_misc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35d8b1594c23d4bf19622449e61cc0b2b8edc791 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_sketches.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_sketches.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcd875546b172e4d369875a460ad2801cf926add Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_sketches.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_solvers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_solvers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40388450ca93ccb8839d359eb9c61112e5d5d2d6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_solvers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98a62f69f73ef632df2f560c6c35beea33bed9d1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_testutils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_testutils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57d1fa0114bcc4d68468326f928a134e327f94fd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/_testutils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/basic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27b529be0830e8e3b894b46b20cdec9c104b0bdb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/basic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/blas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/blas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1997a899bcb86a5deeccec0de64c19050e743c73 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/blas.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d11578323ad57501f7d1b5628ab34a79958fce97 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d238cbd3787bc5585a0236631799337bc2f0e83e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3c01ee6b9dcc1385695d8de715a18e87f11d999 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e8e700f84f09b581d853dd09fb8829a1d3f6a69 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..676041d2a455bd8267c93ed3ff0c2a42c8dba254 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d824ca6f9031cffd1bf8f3b6f3ac05f9db6b9cb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/interpolative.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/interpolative.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c69ce1ae2b44d4d007f778642ad374c2c6333513 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/interpolative.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/lapack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/lapack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee0152f6bd456ba0fbb5420a05c44d42098ba017 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/lapack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5292e6bae16374b23f4d07ebb9ffe722e419528a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/misc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/misc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49eecf09bf6a38571a9326a2bb21b63edf5cf11e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/misc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..279ab655fae63f5ef72d8b65456ce913ab5748b9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2913059b264c7b6eacf1aecd4114faeed4b56720 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_batch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_batch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..338c5056dd398a23db37489577a4461f18c4afd6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_batch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c46850e1df3f7b47e7a5874e600cb6b9270aa00 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7816e4755fb25622f4a1682a1ab11743636460a1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0b69857a3bbc416a901c50ad2110576c995de9e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..703b9cf12b714b592ea7392450611fab3ba8e307 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9afaccb2ee573d67b5e65a7d70f691612168f65d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1849a38c6a63a097db26340e98b24c66d80c7485 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9dcb77973c9c73728c01474558b88101e2ad691 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce74803fe373d2766b580b7e406fe376e893d041 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39c693ba70a4dcecba3500fc8a7d99262a16040a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_extending.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_extending.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b068ac9b35d56a6385d966b74445e69c3a57d90 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_extending.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20b6302e8f85c374b2a7f0d0b4e575a76ed94c51 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b36f6b1611f0a998043d94d30fe1fbccdc91ff6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c761f437a9037e5540e507ecd8b0dee80d2e0b97 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8acb866d19085c50ef4c5f2669cdd820ae087a76 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe0bc50187fe878b872b7b9f142ceb0ee765f0c4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17fe798e9301c4de2f9965441d3f0b34a5a98d36 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06b048f42a9c4c3d12c91b3911caacc0846daab4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ca19c3c75119c475469b1aa2e38c6547edc5800 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d8a6d1de29d6499592c23b48269de65a36bd141 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx new file mode 100644 index 0000000000000000000000000000000000000000..1ea585301bcd5fe448344c01b5769cee69980cde --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +#cython: language_level=3 +#cython: boundscheck=False +#cython: wraparound=False + +cimport scipy.linalg +from scipy.linalg.cython_blas cimport cdotu +from scipy.linalg.cython_lapack cimport dgtsv + +cpdef tridiag(double[:] a, double[:] b, double[:] c, double[:] x): + """ Solve the system A y = x for y where A is the tridiagonal matrix with + subdiagonal 'a', diagonal 'b', and superdiagonal 'c'. """ + cdef int n=b.shape[0], nrhs=1, info + # Solution is written over the values in x. + dgtsv(&n, &nrhs, &a[0], &b[0], &c[0], &x[0], &n, &info) + +cpdef float complex complex_dot(float complex[:] cx, float complex[:] cy): + """ Take dot product of two complex vectors """ + cdef: + int n = cx.shape[0] + int incx = cx.strides[0] // sizeof(cx[0]) + int incy = cy.strides[0] // sizeof(cy[0]) + return cdotu(&n, &cx[0], &incx, &cy[0], &incy) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/_cython_examples/meson.build b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/_cython_examples/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..c27ae9e79bbf42479e1202def2d3edd576a05eb3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/_cython_examples/meson.build @@ -0,0 +1,34 @@ +project('random-build-examples', 'c', 'cpp', 'cython') + +fs = import('fs') + +py3 = import('python').find_installation(pure: false) + +cy = meson.get_compiler('cython') + +if not cy.version().version_compare('>=3.0.8') + error('tests requires Cython >= 3.0.8') +endif + +cython_args = [] +if cy.version().version_compare('>=3.1.0') + cython_args += ['-Xfreethreading_compatible=True'] +endif + +py3.extension_module( + 'extending', + 'extending.pyx', + install: false, + cython_args: cython_args, + c_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this +) + +extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx') +py3.extension_module( + 'extending_cpp', + extending_cpp, + install: false, + override_options : ['cython_language=cpp'], + cython_args: cython_args, + cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_basic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..4e124d26d8784f04058d9a3476c3e5096675c9ee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_basic.py @@ -0,0 +1,2767 @@ +import os +import platform +import itertools +import warnings + +import numpy as np +from numpy import (arange, array, dot, zeros, identity, conjugate, transpose, + float32) + +from numpy.testing import (assert_equal, assert_almost_equal, assert_, + assert_array_almost_equal, assert_allclose, + assert_array_equal) +import pytest +from pytest import raises as assert_raises + +from scipy.linalg import (solve, inv, det, lstsq, pinv, pinvh, norm, + solve_banded, solveh_banded, solve_triangular, + solve_circulant, circulant, LinAlgError, block_diag, + matrix_balance, qr, LinAlgWarning) + +from scipy.linalg._testutils import assert_no_overwrite +from scipy._lib._testutils import check_free_memory, IS_MUSL +from scipy.linalg.blas import HAS_ILP64 +from scipy.conftest import skip_xp_invalid_arg + +REAL_DTYPES = (np.float32, np.float64, np.longdouble) +COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble) +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +parametrize_overwrite_arg = pytest.mark.parametrize( + "overwrite_kw", [{"overwrite_a": True}, {"overwrite_a": False}, {}], + ids=["True", "False", "None"] +) + + +parametrize_overwrite_b_arg = pytest.mark.parametrize( + "overwrite_b_kw", [{"overwrite_b": True}, {"overwrite_b": False}, {}], + ids=["True", "False", "None"] +) + + +def _eps_cast(dtyp): + """Get the epsilon for dtype, possibly downcast to BLAS types.""" + dt = dtyp + if dt == np.longdouble: + dt = np.float64 + elif dt == np.clongdouble: + dt = np.complex128 + return np.finfo(dt).eps + + +class TestSolveBanded: + + def test_real(self): + a = array([[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2, 1, 20, 2], + [0, -1, 7, 14]]) + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]]) + l, u = 2, 1 + b4 = array([10.0, 0.0, 2.0, 14.0]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((l, u), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_complex(self): + a = array([[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2j, 1, 20, 2j], + [0, -1, 7, 14]]) + ab = array([[0.0, 20, 6, 2j], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2j, -1, 0, 0]]) + l, u = 2, 1 + b4 = array([10.0, 0.0, 2.0, 14.0j]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1j], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((l, u), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_tridiag_real(self): + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0]]) + a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag( + ab[2, :-1], -1) + b4 = array([10.0, 0.0, 2.0, 14.0]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((1, 1), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_tridiag_complex(self): + ab = array([[0.0, 20, 6, 2j], + [1, 4, 20, 14], + [-30, 1, 7, 0]]) + a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag( + ab[2, :-1], -1) + b4 = array([10.0, 0.0, 2.0, 14.0j]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((1, 1), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_check_finite(self): + a = array([[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2, 1, 20, 2], + [0, -1, 7, 14]]) + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]]) + l, u = 2, 1 + b4 = array([10.0, 0.0, 2.0, 14.0]) + x = solve_banded((l, u), ab, b4, check_finite=False) + assert_array_almost_equal(dot(a, x), b4) + + def test_bad_shape(self): + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]]) + l, u = 2, 1 + bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1, 4) + assert_raises(ValueError, solve_banded, (l, u), ab, bad) + assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0]) + + # Values of (l,u) are not compatible with ab. + assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0]) + + def test_1x1(self): + # gh-8906 noted that the case of A@x = b with 1x1 A was handled + # incorrectly; check that this is resolved. Typical case: + # nupper == nlower == 0 + # A = [[2]] + b = array([[1., 2., 3.]]) + ref = array([[0.5, 1.0, 1.5]]) + x = solve_banded((0, 0), [[2]], b) + assert_allclose(x, ref, rtol=1e-15) + + # However, the user *can* represent the same system with garbage rows + # in `ab`. Test the case with `nupper == 1, nlower == 1`. + x = solve_banded((1, 1), [[0], [2], [0]], b) + assert_allclose(x, ref, rtol=1e-15) + assert_equal(x.dtype, np.dtype('f8')) + assert_array_equal(b, [[1.0, 2.0, 3.0]]) + + def test_native_list_arguments(self): + a = [[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2, 1, 20, 2], + [0, -1, 7, 14]] + ab = [[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]] + l, u = 2, 1 + b = [10.0, 0.0, 2.0, 14.0] + x = solve_banded((l, u), ab, b) + assert_array_almost_equal(dot(a, x), b) + + @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_ab, dt_b): + # ab contains one empty row corresponding to the diagonal + ab = np.array([[]], dtype=dt_ab) + b = np.array([], dtype=dt_b) + x = solve_banded((0, 0), ab, b) + + assert x.shape == (0,) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x = solve_banded((0, 0), ab, b) + + assert x.shape == (0, 0) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + +class TestSolveHBanded: + + def test_01_upper(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # with the RHS as a 1D array. + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0, 2.0]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + def test_02_upper(self): + # Solve + # [ 4 1 2 0] [1 6] + # [ 1 4 1 2] X = [4 2] + # [ 2 1 4 1] [1 6] + # [ 0 2 1 4] [2 1] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]]) + b = array([[1.0, 6.0], + [4.0, 2.0], + [1.0, 6.0], + [2.0, 1.0]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_03_upper(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # with the RHS as a 2D array with shape (3,1). + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1, 1) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, array([0., 1., 0., 0.]).reshape(-1, 1)) + + def test_01_lower(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 1.0, 1.0, -99], + [2.0, 2.0, 0.0, 0.0]]) + b = array([1.0, 4.0, 1.0, 2.0]) + x = solveh_banded(ab, b, lower=True) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + def test_02_lower(self): + # Solve + # [ 4 1 2 0] [1 6] + # [ 1 4 1 2] X = [4 2] + # [ 2 1 4 1] [1 6] + # [ 0 2 1 4] [2 1] + # + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 1.0, 1.0, -99], + [2.0, 2.0, 0.0, 0.0]]) + b = array([[1.0, 6.0], + [4.0, 2.0], + [1.0, 6.0], + [2.0, 1.0]]) + x = solveh_banded(ab, b, lower=True) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_01_float32(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]], dtype=float32) + b = array([1.0, 4.0, 1.0, 2.0], dtype=float32) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + def test_02_float32(self): + # Solve + # [ 4 1 2 0] [1 6] + # [ 1 4 1 2] X = [4 2] + # [ 2 1 4 1] [1 6] + # [ 0 2 1 4] [2 1] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]], dtype=float32) + b = array([[1.0, 6.0], + [4.0, 2.0], + [1.0, 6.0], + [2.0, 1.0]], dtype=float32) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_01_complex(self): + # Solve + # [ 4 -j 2 0] [2-j] + # [ j 4 -j 2] X = [4-j] + # [ 2 j 4 -j] [4+j] + # [ 0 2 j 4] [2+j] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, -1.0j, -1.0j, -1.0j], + [4.0, 4.0, 4.0, 4.0]]) + b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0]) + + def test_02_complex(self): + # Solve + # [ 4 -j 2 0] [2-j 2+4j] + # [ j 4 -j 2] X = [4-j -1-j] + # [ 2 j 4 -j] [4+j 4+2j] + # [ 0 2 j 4] [2+j j] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, -1.0j, -1.0j, -1.0j], + [4.0, 4.0, 4.0, 4.0]]) + b = array([[2-1j, 2+4j], + [4.0-1j, -1-1j], + [4.0+1j, 4+2j], + [2+1j, 1j]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0j], + [1.0, 0.0], + [1.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_01_upper(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # with the RHS as a 1D array. + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_tridiag_02_upper(self): + # Solve + # [ 4 1 0] [1 4] + # [ 1 4 1] X = [4 2] + # [ 0 1 4] [1 4] + # + ab = array([[-99, 1.0, 1.0], + [4.0, 4.0, 4.0]]) + b = array([[1.0, 4.0], + [4.0, 2.0], + [1.0, 4.0]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_03_upper(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # with the RHS as a 2D array with shape (3,1). + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0]).reshape(-1, 1) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1)) + + def test_tridiag_01_lower(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # + ab = array([[4.0, 4.0, 4.0], + [1.0, 1.0, -99]]) + b = array([1.0, 4.0, 1.0]) + x = solveh_banded(ab, b, lower=True) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_tridiag_02_lower(self): + # Solve + # [ 4 1 0] [1 4] + # [ 1 4 1] X = [4 2] + # [ 0 1 4] [1 4] + # + ab = array([[4.0, 4.0, 4.0], + [1.0, 1.0, -99]]) + b = array([[1.0, 4.0], + [4.0, 2.0], + [1.0, 4.0]]) + x = solveh_banded(ab, b, lower=True) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_01_float32(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32) + b = array([1.0, 4.0, 1.0], dtype=float32) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_tridiag_02_float32(self): + # Solve + # [ 4 1 0] [1 4] + # [ 1 4 1] X = [4 2] + # [ 0 1 4] [1 4] + # + ab = array([[-99, 1.0, 1.0], + [4.0, 4.0, 4.0]], dtype=float32) + b = array([[1.0, 4.0], + [4.0, 2.0], + [1.0, 4.0]], dtype=float32) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_01_complex(self): + # Solve + # [ 4 -j 0] [ -j] + # [ j 4 -j] X = [4-j] + # [ 0 j 4] [4+j] + # + ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]]) + b = array([-1.0j, 4.0-1j, 4+1j]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 1.0]) + + def test_tridiag_02_complex(self): + # Solve + # [ 4 -j 0] [ -j 4j] + # [ j 4 -j] X = [4-j -1-j] + # [ 0 j 4] [4+j 4 ] + # + ab = array([[-99, -1.0j, -1.0j], + [4.0, 4.0, 4.0]]) + b = array([[-1j, 4.0j], + [4.0-1j, -1.0-1j], + [4.0+1j, 4.0]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0j], + [1.0, 0.0], + [1.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_check_finite(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # with the RHS as a 1D array. + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0]) + x = solveh_banded(ab, b, check_finite=False) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_bad_shapes(self): + ab = array([[-99, 1.0, 1.0], + [4.0, 4.0, 4.0]]) + b = array([[1.0, 4.0], + [4.0, 2.0]]) + assert_raises(ValueError, solveh_banded, ab, b) + assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0]) + assert_raises(ValueError, solveh_banded, ab, [1.0]) + + def test_1x1(self): + x = solveh_banded([[1]], [[1, 2, 3]]) + assert_array_equal(x, [[1.0, 2.0, 3.0]]) + assert_equal(x.dtype, np.dtype('f8')) + + def test_native_list_arguments(self): + # Same as test_01_upper, using python's native list. + ab = [[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]] + b = [1.0, 4.0, 1.0, 2.0] + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_ab, dt_b): + # ab contains one empty row corresponding to the diagonal + ab = np.array([[]], dtype=dt_ab) + b = np.array([], dtype=dt_b) + x = solveh_banded(ab, b) + + assert x.shape == (0,) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x = solveh_banded(ab, b) + + assert x.shape == (0, 0) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + +class TestSolve: + def test_20Feb04_bug(self): + a = [[1, 1], [1.0, 0]] # ok + x0 = solve(a, [1, 0j]) + assert_array_almost_equal(dot(a, x0), [1, 0]) + + # gives failure with clapack.zgesv(..,rowmajor=0) + a = [[1, 1], [1.2, 0]] + b = [1, 0j] + x0 = solve(a, b) + assert_array_almost_equal(dot(a, x0), [1, 0]) + + def test_simple(self): + a = [[1, 20], [-30, 4]] + for b in ([[1, 0], [0, 1]], + [1, 0], + [[2, 1], [-30, 4]] + ): + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_complex(self): + a = array([[5, 2], [2j, 4]], 'D') + for b in ([1j, 0], + [[1j, 1j], [0, 2]], + [1, 0j], + array([1, 0], 'D'), + ): + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_pos(self): + a = [[2, 3], [3, 5]] + for lower in [0, 1]: + for b in ([[1, 0], [0, 1]], + [1, 0] + ): + x = solve(a, b, assume_a='pos', lower=lower) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_pos_complexb(self): + a = [[5, 2], [2, 4]] + for b in ([1j, 0], + [[1j, 1j], [0, 2]], + ): + x = solve(a, b, assume_a='pos') + assert_array_almost_equal(dot(a, x), b) + + def test_simple_sym(self): + a = [[2, 3], [3, -5]] + for lower in [0, 1]: + for b in ([[1, 0], [0, 1]], + [1, 0] + ): + x = solve(a, b, assume_a='sym', lower=lower) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_sym_complexb(self): + a = [[5, 2], [2, -4]] + for b in ([1j, 0], + [[1j, 1j], [0, 2]] + ): + x = solve(a, b, assume_a='sym') + assert_array_almost_equal(dot(a, x), b) + + def test_simple_sym_complex(self): + a = [[5, 2+1j], [2+1j, -4]] + for b in ([1j, 0], + [1, 0], + [[1j, 1j], [0, 2]] + ): + x = solve(a, b, assume_a='sym') + assert_array_almost_equal(dot(a, x), b) + + def test_simple_her_actuallysym(self): + a = [[2, 3], [3, -5]] + for lower in [0, 1]: + for b in ([[1, 0], [0, 1]], + [1, 0], + [1j, 0], + ): + x = solve(a, b, assume_a='her', lower=lower) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_her(self): + a = [[5, 2+1j], [2-1j, -4]] + for b in ([1j, 0], + [1, 0], + [[1j, 1j], [0, 2]] + ): + x = solve(a, b, assume_a='her') + assert_array_almost_equal(dot(a, x), b) + + def test_nils_20Feb04(self): + rng = np.random.default_rng(1234) + n = 2 + A = rng.random([n, n])+rng.random([n, n])*1j + X = zeros((n, n), 'D') + Ainv = inv(A) + R = identity(n)+identity(n)*0j + for i in arange(0, n): + r = R[:, i] + X[:, i] = solve(A, r) + assert_array_almost_equal(X, Ainv) + + def test_random(self): + rng = np.random.default_rng(1234) + n = 20 + a = rng.random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + for i in range(4): + b = rng.random([n, 3]) + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_random_complex(self): + rng = np.random.default_rng(1234) + n = 20 + a = rng.random([n, n]) + 1j * rng.random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + for i in range(2): + b = rng.random([n, 3]) + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_random_sym(self): + rng = np.random.default_rng(1234) + n = 20 + a = rng.random([n, n]) + for i in range(n): + a[i, i] = abs(20*(.1+a[i, i])) + for j in range(i): + a[i, j] = a[j, i] + for i in range(4): + b = rng.random([n]) + x = solve(a, b, assume_a="pos") + assert_array_almost_equal(dot(a, x), b) + + def test_random_sym_complex(self): + rng = np.random.default_rng(1234) + n = 20 + a = rng.random([n, n]) + a = a + 1j*rng.random([n, n]) + for i in range(n): + a[i, i] = abs(20*(.1+a[i, i])) + for j in range(i): + a[i, j] = conjugate(a[j, i]) + b = rng.random([n])+2j*rng.random([n]) + for i in range(2): + x = solve(a, b, assume_a="pos") + assert_array_almost_equal(dot(a, x), b) + + def test_check_finite(self): + a = [[1, 20], [-30, 4]] + for b in ([[1, 0], [0, 1]], [1, 0], + [[2, 1], [-30, 4]]): + x = solve(a, b, check_finite=False) + assert_array_almost_equal(dot(a, x), b) + + def test_scalar_a_and_1D_b(self): + a = 1 + b = [1, 2, 3] + x = solve(a, b) + assert_array_almost_equal(x.ravel(), b) + assert_(x.shape == (3,), 'Scalar_a_1D_b test returned wrong shape') + + def test_simple2(self): + a = np.array([[1.80, 2.88, 2.05, -0.89], + [525.00, -295.00, -95.00, -380.00], + [1.58, -2.69, -2.90, -1.04], + [-1.11, -0.66, -0.59, 0.80]]) + + b = np.array([[9.52, 18.47], + [2435.00, 225.00], + [0.77, -13.28], + [-6.22, -6.21]]) + + x = solve(a, b) + assert_array_almost_equal(x, np.array([[1., -1, 3, -5], + [3, 2, 4, 1]]).T) + + def test_simple_complex2(self): + a = np.array([[-1.34+2.55j, 0.28+3.17j, -6.39-2.20j, 0.72-0.92j], + [-1.70-14.10j, 33.10-1.50j, -1.50+13.40j, 12.90+13.80j], + [-3.29-2.39j, -1.91+4.42j, -0.14-1.35j, 1.72+1.35j], + [2.41+0.39j, -0.56+1.47j, -0.83-0.69j, -1.96+0.67j]]) + + b = np.array([[26.26+51.78j, 31.32-6.70j], + [64.30-86.80j, 158.60-14.20j], + [-5.75+25.31j, -2.15+30.19j], + [1.16+2.57j, -2.56+7.55j]]) + + x = solve(a, b) + assert_array_almost_equal(x, np. array([[1+1.j, -1-2.j], + [2-3.j, 5+1.j], + [-4-5.j, -3+4.j], + [6.j, 2-3.j]])) + + @pytest.mark.parametrize("assume_a", ['her', 'sym']) + def test_symmetric_hermitian(self, assume_a): + # An upper triangular matrix will be used for symmetric/hermitian matrix a + a = np.array([[-1.84, 0.11-0.11j, -1.78-1.18j, 3.91-1.50j], + [0, -4.63, -1.84+0.03j, 2.21+0.21j], + [0, 0, -8.87, 1.58-0.90j], + [0, 0, 0, -1.36]]) + b = np.array([[2.98-10.18j, 28.68-39.89j], + [-9.58+3.88j, -24.79-8.40j], + [-0.77-16.05j, 4.23-70.02j], + [7.79+5.48j, -35.39+18.01j]]) + + a2 = a.T if assume_a == 'sym' else a.conj().T # for testing `lower` + a3 = a + a2 # for reference solution + a3[np.arange(4), np.arange(4)] = np.diag(a) + ref = solve(a3, b, assume_a='general') + + x = solve(a, b, assume_a=assume_a) + assert_array_almost_equal(x, ref) + # Also transpose(/conjugate) `a` and test for lower triangular data + # This also tests gh-22265 resolution; otherwise, a warning would be emitted + x = solve(a2, b, assume_a=assume_a, lower=True) + assert_array_almost_equal(x, ref) + + def test_pos_and_sym(self): + A = np.arange(1, 10).reshape(3, 3) + x = solve(np.tril(A)/9, np.ones(3), assume_a='pos') + assert_array_almost_equal(x, [9., 1.8, 1.]) + x = solve(np.tril(A)/9, np.ones(3), assume_a='sym') + assert_array_almost_equal(x, [9., 1.8, 1.]) + + def test_singularity(self): + a = np.array([[1, 0, 0, 0, 0, 0, 1, 0, 1], + [1, 1, 1, 0, 0, 0, 1, 0, 1], + [0, 1, 1, 0, 0, 0, 1, 0, 1], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1]]) + b = np.arange(9)[:, None] + assert_raises(LinAlgError, solve, a, b) + + @pytest.mark.parametrize('structure', + ('diagonal', 'tridiagonal', 'lower triangular', + 'upper triangular', 'symmetric', 'hermitian', + 'positive definite', 'general', 'banded', None)) + def test_ill_condition_warning(self, structure): + rng = np.random.default_rng(234859349452) + n = 10 + d = np.logspace(0, 50, n) + A = np.diag(d) + b = rng.random(size=n) + message = "(Ill-conditioned matrix|An ill-conditioned matrix)" + with pytest.warns(LinAlgWarning, match=message): + solve(A, b, assume_a=structure) + + @pytest.mark.parametrize('structure', + ('diagonal', 'tridiagonal', 'lower triangular', + 'upper triangular', 'symmetric', 'hermitian', + 'positive definite', 'general', None)) + def test_exactly_singular_gh22263(self, structure): + n = 10 + A = np.zeros((n, n)) + b = np.ones(n) + with (pytest.raises(LinAlgError, match="singular"), np.errstate(all='ignore')): + solve(A, b, assume_a=structure) + + @pytest.mark.parametrize('b', [0, 1, [0, 1]]) + def test_singular_scalar(self, b): + # regression test for gh-24355: scalar a=0 is singular + # thus should raise the same error + + with pytest.raises(LinAlgError): + a = np.zeros((1, 1)) + solve(a, b) + + with pytest.raises(LinAlgError): + solve(0, b) + + with pytest.raises(LinAlgError): + solve([[0]], b) + + def test_multiple_rhs(self): + a = np.eye(2) + rng = np.random.default_rng(1234) + b = rng.random((2, 12)) + x = solve(a, b) + assert_array_almost_equal(x, b) + + def test_transposed_keyword(self): + A = np.arange(9).reshape(3, 3) + 1 + x = solve(np.tril(A)/9, np.ones(3), transposed=True) + assert_array_almost_equal(x, [1.2, 0.2, 1]) + x = solve(np.tril(A)/9, np.ones(3), transposed=False) + assert_array_almost_equal(x, [9, -5.4, -1.2]) + + @pytest.mark.skip(reason="1. why? 2. deprecate the kwarg altogether?") + def test_transposed_notimplemented(self): + a = np.eye(3).astype(complex) + with assert_raises(NotImplementedError): + solve(a, a, transposed=True) + + def test_nonsquare_a(self): + assert_raises(ValueError, solve, [1, 2], 1) + + def test_size_mismatch_with_1D_b(self): + assert_array_almost_equal(solve(np.eye(3), np.ones(3)), np.ones(3)) + assert_raises(ValueError, solve, np.eye(3), np.ones(4)) + + def test_assume_a_keyword(self): + assert_raises(ValueError, solve, 1, 1, assume_a='zxcv') + + @pytest.mark.parametrize("size", [10, 100]) + @pytest.mark.parametrize("assume_a", ['gen', 'sym', 'pos', 'her', 'tridiagonal']) + @pytest.mark.parametrize( + "dtype", [np.float32, np.float64, np.complex64, np.complex128] + ) + def test_all_type_size_routine_combinations(self, size, dtype, assume_a): + rng = np.random.default_rng(1234) + is_complex = dtype in (np.complex64, np.complex128) + + a = rng.standard_normal((size, size)).astype(dtype) + b = rng.standard_normal(size).astype(dtype) + if is_complex: + a += (1j*rng.standard_normal((size, size))).astype(dtype) + + if assume_a == 'sym': # Can still be complex but only symmetric + a = a + a.T + elif assume_a == 'her': # Handle hermitian matrices here instead + a = a + a.T.conj() + elif assume_a == 'pos': + a = a.T.conj() @ a + 0.1*np.eye(size) + elif assume_a == 'tridiagonal': + a = (np.diag(np.diag(a)) + + np.diag(np.diag(a, 1), 1) + + np.diag(np.diag(a, -1), -1) + ) + + tol = 1e-12 if dtype in (np.float64, np.complex128) else 1e-6 + + if assume_a in ['gen', 'sym', 'her']: + # We revert the tolerance from before + # 4b4a6e7c34fa4060533db38f9a819b98fa81476c + if dtype in (np.float32, np.complex64): + tol *= 10 + + x = solve(a, b, assume_a=assume_a) + assert_allclose(a @ x, b, atol=tol * size, rtol=tol * size) + + if assume_a == 'sym' and not is_complex: + x = solve(a, b, assume_a=assume_a, transposed=True) + assert_allclose(a @ x, b, atol=tol * size, rtol=tol * size) + + @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_a, dt_b): + a = np.empty((0, 0), dtype=dt_a) + b = np.empty(0, dtype=dt_b) + x = solve(a, b) + + assert x.size == 0 + dt_nonempty = solve(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)).dtype + assert x.dtype == dt_nonempty + assert x.shape == np.linalg.solve(a, b).shape + + a = np.ones((3, 0, 2, 2), dtype=dt_a) + b = np.ones((2, 4), dtype=dt_b) + x = solve(a, b) + assert x.shape == (3, 0, 2, 4) + assert x.dtype == dt_nonempty + + def test_empty_rhs(self): + a = np.eye(2) + b = [[], []] + x = solve(a, b) + assert_(x.size == 0, 'Returned array is not empty') + assert_(x.shape == (2, 0), 'Returned empty array shape is wrong') + + @pytest.mark.parametrize('dtype', [np.float64, np.complex128]) + @pytest.mark.parametrize('assume_a', ['diagonal', 'tridiagonal', 'banded', + 'lower triangular', 'upper triangular', + 'pos', 'positive definite', + 'symmetric', 'hermitian', 'banded', + 'general', 'sym', 'her', 'gen']) + @pytest.mark.parametrize('nrhs', [(), (5,)]) + @pytest.mark.parametrize('transposed', [True, False]) + @pytest.mark.parametrize('overwrite', [True, False]) + @pytest.mark.parametrize('fortran', [True, False]) + def test_structure_detection(self, dtype, assume_a, nrhs, transposed, + overwrite, fortran): + rng = np.random.default_rng(982345982439826) + n = 5 if not assume_a == 'banded' else 20 + b = rng.random(size=(n,) + nrhs) + A = rng.random(size=(n, n)) + + if np.issubdtype(dtype, np.complexfloating): + b = b + rng.random(size=(n,) + nrhs) * 1j + A = A + rng.random(size=(n, n)) * 1j + + if assume_a == 'diagonal': + A = np.diag(np.diag(A)) + elif assume_a == 'lower triangular': + A = np.tril(A) + elif assume_a == 'upper triangular': + A = np.triu(A) + elif assume_a == 'tridiagonal': + A = (np.diag(np.diag(A)) + + np.diag(np.diag(A, -1), -1) + + np.diag(np.diag(A, 1), 1)) + elif assume_a == 'banded': + A = np.triu(np.tril(A, 2), -1) + elif assume_a in {'symmetric', 'sym'}: + A = A + A.T + elif assume_a in {'hermitian', 'her'}: + A = A + A.conj().T + elif assume_a in {'positive definite', 'pos'}: + A = A @ A.T.conj() + + if fortran: + A = np.asfortranarray(A) + + A_copy = A.copy(order='A') + b_copy = b.copy() + + if np.issubdtype(dtype, np.complexfloating) and transposed: + message = "scipy.linalg.solve can currently..." + with pytest.raises(NotImplementedError, match=message): + solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite, + transposed=transposed) + return + + res = solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite, + transposed=transposed, assume_a=assume_a) + + # Check that solution this solution is *correct* + ref = np.linalg.solve(A_copy.T if transposed else A_copy, b_copy) + assert_allclose(res, ref) + + # Check that `solve` correctly identifies the structure and returns + # *exactly* the same solution whether `assume_a` is specified or not + if assume_a != 'banded': # structure detection removed for banded + assert_allclose( + solve(A_copy, b_copy, transposed=transposed), res, atol=1e-15 + ) + + # Check that overwrite was respected + if not overwrite: + assert_equal(A, A_copy) + assert_equal(b, b_copy) + + @pytest.mark.skipif( + np.__version__ < '2', reason="solve chokes on b.ndim == 1 in numpy < 2" + ) + @pytest.mark.parametrize( + "assume_a", + [ + None, "diagonal", "general", "upper triangular", "lower triangular", "pos", + ] + ) + def test_vs_np_solve(self, assume_a): + e = np.eye(2) + a = np.arange(1, 4*3*2 + 1).reshape((4, 3, 2, 1, 1)) * e + + b = np.ones(2) + assert_allclose(solve(a, b, assume_a=assume_a), np.linalg.solve(a, b)) + + b = np.ones((2, 1)) + assert_allclose(solve(a, b, assume_a=assume_a), np.linalg.solve(a, b)) + + b = np.ones((2, 2)) * [1, 2] + assert_allclose(solve(a, b, assume_a=assume_a), np.linalg.solve(a, b)) + + def test_pos_lower(self): + # regression test for + # https://github.com/scipy/scipy/pull/23071#issuecomment-3085826112 + rng = np.random.default_rng(0) + a = rng.normal(size=(4, 4)) + a = np.tril(np.matmul(a, np.conj(a.T))) # lower triangle of hermitian array + b = rng.normal(size=(4, 2)) + out = solve(a, b, assume_a='pos', lower=True) + + aa = a + a.T - np.diag(np.diag(a)) # the full hermitian array + result_np = np.linalg.solve(aa, b) + assert_allclose(out, result_np, atol=1e-15) + + # repeat with uplo='U' + out = solve(a.T, b, assume_a='pos', lower=False) + assert_allclose(out, result_np, atol=1e-15) + + def test_pos_fails_sym_complex(self): + # regression test for the `solve` analog of gh-24359 + # the matrix is 1) symmetric not hermitian, and 2) not positive definite: + a = np.asarray([[ 182.56985285-64.28859483j, -177.24879835+11.0780499j ], + [-177.24879835+11.0780499j , 177.24879835-11.0780499j ]]) + b = np.eye(2) + + ainv = solve(a, b) + assert_allclose(ainv @ a, np.eye(2), atol=1e-14) + + ainv_sym = solve(a, b, assume_a="sym") + assert_allclose(ainv_sym, ainv, atol=1e-14) + + # Specifying assume_a="pos" disables the structure detection, and directly + # calls LAPACK routines zportf and zpotri. + # Since zportf(a) does not error out, neither does solve. + ainv_chol = solve(a, b, assume_a="pos") + assert not np.allclose(ainv, ainv_chol, atol=1e-14) + + # Setting assume_a="pos" with a non-pos def matrix returned nonsense. + # This is at least consistent with inv. + ainv_inv = inv(a, assume_a="pos") + assert_allclose(ainv_chol, ainv_inv, atol=1e-14) + + def test_readonly(self): + a = np.eye(3) + a.flags.writeable = False + b = np.ones(3) + x = solve(a, b) + assert_allclose(x, b, atol=1e-14) + + @parametrize_overwrite_arg + def test_batch_negative_stride(self, overwrite_kw): + a = np.arange(3*8).reshape(2, 3, 2, 2) + a = a[:, ::-1, :, :] + b = np.ones(2) + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + assert_allclose(a @ x[..., None] - b, 0, atol=1e-14) + + # use b with a negative stride now + b = np.ones((2, 4))[:, ::-1] + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + (b.shape[-1],) + assert_allclose(a @ x - b, 0, atol=1e-14) + + @parametrize_overwrite_arg + def test_core_negative_stride(self, overwrite_kw): + a = np.arange(3*8).reshape(2, 3, 2, 2) + a = a[:, :, ::-1, :] + b = np.ones(2) + x = solve(a, b, **overwrite_kw) + + assert x.shape == a.shape[:-1] + assert_allclose(a @ x[..., None] - b, 0, atol=1e-14) + + # use b with a negative stride now + b = np.ones((2, 4))[::-1, :] + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + (b.shape[-1],) + assert_allclose(a @ x - b, 0, atol=1e-14) + + @parametrize_overwrite_arg + def test_core_non_contiguous(self, overwrite_kw): + a = np.arange(3*8*2).reshape(2, 3, 2, 4) + a = a[..., ::2] + b = np.ones(2) + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + assert_allclose(a @ x[..., None] - b, 0, atol=1e-14) + + # use strided b now + b = np.ones(4)[::2] + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + assert_allclose(a @ x[..., None] - b, 0, atol=1e-14) + + @parametrize_overwrite_arg + def test_batch_non_contiguous(self, overwrite_kw): + a = np.arange(3*8*2).reshape(2, 6, 2, 2) + a = a[:, ::2, ...] + b = np.ones(2) + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + assert_allclose(a @ x[..., None] - b, 0, atol=1e-14) + + # use strided b now + b = np.ones((2, 6))[:, ::2] + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + (b.shape[-1],) + assert_allclose(a @ x - b, 0, atol=1e-14) + + @parametrize_overwrite_arg + def test_batch_weird_strides(self, overwrite_kw): + a = np.arange(3*8*2).reshape(2, 3, 2, 2, 2) + a = a.transpose(1, 3, 4, 0, 2) + + b = np.ones(2) + x = solve(a, b, **overwrite_kw) + assert x.shape == a.shape[:-1] + assert_allclose(a @ x[..., None] - b, 0, atol=1e-14) + + @parametrize_overwrite_arg + @parametrize_overwrite_b_arg + @pytest.mark.parametrize('a_dtype', [int, float]) + @pytest.mark.parametrize('a_order', ['C', 'F']) + @pytest.mark.parametrize('b_dtype', [int, float]) + @pytest.mark.parametrize('b_order', ['C', 'F']) + @pytest.mark.parametrize('b_ndim', [1, 2]) # XXX ndim > 2 + @pytest.mark.parametrize('transposed', [True, False]) + def test_overwrite_args( + self, overwrite_kw, overwrite_b_kw, a_dtype, a_order, + b_dtype, b_order, b_ndim, transposed + ): + n = 3 + a = np.arange(1, n**2 + 1).reshape(n, n) + np.eye(n) + a = a.astype(a_dtype, order=a_order) + + b = np.arange(n) + if b_ndim > 1: + b = np.stack([b*j for j in range(b_ndim)]).T + b = b.astype(b_dtype, order=b_order) + + a_ref = a.copy() + b_ref = b.copy() + + # solve and check that the solution is correct for all parameters + x = solve(a, b, **overwrite_kw, **overwrite_b_kw, transposed=transposed) + a_or_aT = a_ref.T if transposed else a_ref + assert_allclose(a_or_aT @ x, b_ref, atol=1e-14) + + # now check that it worked in-place where expected + overwrite_a = overwrite_kw.get('overwrite_a', False) + a_inplace = overwrite_a and (a.dtype != int) and a.flags['F_CONTIGUOUS'] + + overwrite_b = overwrite_b_kw.get('overwrite_b', False) + b_inplace = overwrite_b and (b.dtype != int) and b.flags['F_CONTIGUOUS'] + + assert np.shares_memory(x, b) == b_inplace + + assert (b == b_ref).all() != b_inplace + assert (a == a_ref).all() != a_inplace + + def test_posdef_not_posdef(self): + # the `b` matrix is invertible but not positive definite + a = np.arange(9).reshape(3, 3) + A = a + a.T + np.eye(3) + b = np.ones(3) + + # cholesky solver fails, and the routine falls back to the general inverse + x0 = solve(A, b) + assert_allclose(A @ x0, b, atol=1e-14) + + # but it does not fall back if `assume_a` is given + with assert_raises(LinAlgError): + solve(A, b, assume_a='pos') + + def test_diagonal(self): + a = np.stack([np.triu(np.ones((3, 3))), np.diag(np.arange(1, 4))]) + b = np.ones(3) + x = solve(a, b) + + # basic diagonal solve + assert_allclose(x[1, ...], 1 / np.arange(1, 4), atol=1e-14) + + # ill-conditioned inputs warn + a = np.asarray([[1e30, 0], [0, 1]]) + b = np.ones(2) + with pytest.warns(LinAlgWarning): + solve(a, b, assume_a="diagonal") + + # singular input raises + a = np.asarray([[0, 0], [0, 1]]) + b = np.ones(2) + with pytest.raises(LinAlgError): + solve(a, b, assume_a="diagonal") + + def test_tridiagonal(self): + n = 4 + a = -2*np.diag(np.ones(n)) + np.diag(np.ones(3), 1) + np.diag(np.ones(3), -1) + a = np.stack([np.triu(np.ones((n, n))), a]) + b = np.ones(4) + x = solve(a, b) + + # basic tridiag solve + assert_allclose(x[1, ...], np.asarray([-2., -3., -3., -2.]), atol=1e-15) + + # ill-conditioned inputs warn + a[1, 0, 0] = 1e20 + with pytest.warns(LinAlgWarning): + solve(a, b, assume_a="tridiagonal") + + # singular inputss raise + a[1, 0, 0] = a[1, 0, 1] = 0 + with pytest.raises(LinAlgError): + solve(a, b, assume_a="tridiagonal") + + +class TestSolveTriangular: + + def test_simple(self): + """ + solve_triangular on a simple 2x2 matrix. + """ + A = array([[1, 0], [1, 2]]) + b = [1, 1] + sol = solve_triangular(A, b, lower=True) + assert_array_almost_equal(sol, [1, 0]) + + # check that it works also for non-contiguous matrices + sol = solve_triangular(A.T, b, lower=False) + assert_array_almost_equal(sol, [.5, .5]) + + # and that it gives the same result as trans=1 + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [.5, .5]) + + b = identity(2) + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]]) + + def test_simple_complex(self): + """ + solve_triangular on a simple 2x2 complex matrix + """ + A = array([[1+1j, 0], [1j, 2]]) + b = identity(2) + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]]) + + # check other option combinations with complex rhs + b = np.diag([1+1j, 1+2j]) + sol = solve_triangular(A, b, lower=True, trans=0) + assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]]) + + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]]) + + sol = solve_triangular(A, b, lower=True, trans=2) + assert_array_almost_equal(sol, [[1j, -0.75-0.25j], [0, 0.5+1j]]) + + sol = solve_triangular(A.T, b, lower=False, trans=0) + assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]]) + + sol = solve_triangular(A.T, b, lower=False, trans=1) + assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]]) + + sol = solve_triangular(A.T, b, lower=False, trans=2) + assert_array_almost_equal(sol, [[1j, 0], [-0.5, 0.5+1j]]) + + def test_check_finite(self): + """ + solve_triangular on a simple 2x2 matrix. + """ + A = array([[1, 0], [1, 2]]) + b = [1, 1] + sol = solve_triangular(A, b, lower=True, check_finite=False) + assert_array_almost_equal(sol, [1, 0]) + + @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_a, dt_b): + a = np.empty((0, 0), dtype=dt_a) + b = np.empty(0, dtype=dt_b) + x = solve_triangular(a, b) + + assert x.size == 0 + dt_nonempty = solve_triangular( + np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b) + ).dtype + assert x.dtype == dt_nonempty + + def test_empty_rhs(self): + a = np.eye(2) + b = [[], []] + x = solve_triangular(a, b) + assert_(x.size == 0, 'Returned array is not empty') + assert_(x.shape == (2, 0), 'Returned empty array shape is wrong') + + +class TestInv: + def test_simple(self): + a = [[1, 2], [3, 4]] + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), np.eye(2)) + a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]] + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), np.eye(3)) + + def test_random(self): + rng = np.random.default_rng(1234) + n = 20 + for i in range(4): + a = rng.random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), + identity(n)) + + def test_simple_complex(self): + a = [[1, 2], [3, 4j]] + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]]) + + def test_random_complex(self): + rng = np.random.default_rng(1234) + n = 20 + for i in range(4): + a = rng.random([n, n])+2j*rng.random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), + identity(n)) + + def test_check_finite(self): + a = [[1, 2], [3, 4]] + a_inv = inv(a, check_finite=False) + assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]]) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a_inv = inv(a) + assert a_inv.size == 0 + assert a_inv.dtype == inv(np.eye(2, dtype=dt)).dtype + + a = np.ones((3, 0, 2, 2), dtype=dt) + a_inv = inv(a) + assert a_inv.shape == (3, 0, 2, 2) + + a = np.ones((3, 1, 0, 0), dtype=dt) + a_inv = inv(a) + assert a_inv.shape == (3, 1, 0, 0) + + @parametrize_overwrite_arg + def test_overwrite_a(self, overwrite_kw): + n = 3 + a0 = np.arange(1, n**2 + 1).reshape(n, n) + np.eye(n) + + # int arrays are copied internally + a = a0.copy() + a_inv = inv(a, **overwrite_kw) + assert_allclose(a_inv @ a, np.eye(n), atol=1e-14) + assert_equal(a, a0) + assert not np.shares_memory(a, a_inv) + + # float C ordered arrays are copied, too + a = a0.copy().astype(float) + a_inv = inv(a, **overwrite_kw) + assert_allclose(a_inv @ a0, np.eye(n), atol=1e-14) + assert_equal(a, a0) + assert not np.shares_memory(a, a_inv) + + # 2D F-ordered arrays of LAPACK-compatible dtypes: inv works inplace. + # IOW, the output is always the inverse, and the original input may be + # destroyed, depending on the `overwrite_a` kwarg value + a = a0.astype(float).copy(order='F') + a_inv = inv(a, **overwrite_kw) + assert_allclose(a_inv @ a0, np.eye(n), atol=1e-14) + + overwrite_a = overwrite_kw.get("overwrite_a", False) + assert (a == a0).all() != overwrite_a + assert np.shares_memory(a, a_inv) == overwrite_a + + @pytest.mark.parametrize( + "dtyp", [np.float16, np.float32, np.longdouble, np.clongdouble] + ) + def test_dtypes(self, dtyp): + # backwards compat: inv(float16)->float32 ; inv(clongdouble)->complex128 etc + a = np.arange(4).reshape(2, 2).astype(dtyp) + + a_inv = inv(a) + assert_allclose(a @ a_inv, np.eye(a.shape[0]), atol=100*np.finfo(a.dtype).eps) + + dt_map = { + 'e': 'f', # float16 -> float32 + 'f': 'f', + 'g': 'd', # longdouble -> float64 + 'G': 'D' # clongdouble -> complex128 + } + assert a_inv.dtype.char == dt_map[a.dtype.char] + + def test_readonly(self): + a = np.eye(3) + a.flags.writeable = False + + a_inv = inv(a) + assert_allclose(a_inv, a, atol=1e-14) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_batch_core_1x1(self, dt): + a = np.arange(3*2, dtype=dt).reshape(3, 2, 1, 1) + 1 + a_inv = inv(a) + assert a_inv.shape == a.shape + assert_allclose(a @ a_inv, 1.) + + @parametrize_overwrite_arg + def test_batch_zero_stride(self, overwrite_kw): + a = np.arange(3*2*2, dtype=float).reshape(3, 2, 2) + aa = a[None, ...] + a_inv = inv(aa, **overwrite_kw) + assert a_inv.shape == aa.shape + assert_allclose(aa @ a_inv, np.broadcast_to(np.eye(2), aa.shape), atol=2e-14) + + aa = a[:, None, ...] + a_inv = inv(aa, **overwrite_kw) + assert a_inv.shape == aa.shape + assert_allclose(aa @ a_inv, np.broadcast_to(np.eye(2), aa.shape), atol=2e-14) + + @parametrize_overwrite_arg + def test_batch_negative_stride(self, overwrite_kw): + a = np.arange(3*8).reshape(2, 3, 2, 2) + a = a[:, ::-1, :, :] + a_inv = inv(a, **overwrite_kw) + assert a_inv.shape == a.shape + assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=5e-14) + + @parametrize_overwrite_arg + def test_core_negative_stride(self, overwrite_kw): + a = np.arange(3*8).reshape(2, 3, 2, 2) + a = a[:, :, ::-1, :] + a_inv = inv(a, **overwrite_kw) + assert a_inv.shape == a.shape + assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=5e-14) + + @parametrize_overwrite_arg + def test_core_non_contiguous(self, overwrite_kw): + a = np.arange(3*8*2).reshape(2, 3, 2, 4) + a = a[..., ::2] + a_inv = inv(a, **overwrite_kw) + assert a_inv.shape == (2, 3, 2, 2) + assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=5e-14) + + @parametrize_overwrite_arg + def test_batch_non_contiguous(self, overwrite_kw): + a = np.arange(3*8*2).reshape(2, 6, 2, 2) + a = a[:, ::2, ...] + a_inv = inv(a, **overwrite_kw) + assert a_inv.shape == (2, 3, 2, 2) + assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=2e-13) + + @parametrize_overwrite_arg + def test_singular(self, overwrite_kw): + # 2D case: A singular matrix: raise + + with assert_raises(LinAlgError): + inv(np.ones((2, 2))) + + # batched case: If all slices are singlar, raise + with assert_raises(LinAlgError): + inv(np.ones((3, 2, 2))) + + # XXX: shall we make this behavior configurable somehow? + # A "keep-going" option would be this: + # if some of the slices are singular and some are not, + # - singular slices are filled with nans + # - non-singular slices are inverted + # - there is no error + a = np.stack((np.ones((2, 2), dtype=complex), np.arange(4).reshape(2, 2))) + with assert_raises(LinAlgError): + inv(a) + + # this would be true for a "keep-going" option + # assert np.isnan(a_inv[0, ...]).all() + # assert_allclose(a_inv[1, ...] @ a[1, ...], np.eye(2), atol=1e-14) + + def test_ill_cond(self): + a = np.diag([1., 1e-20]) + with pytest.warns(LinAlgWarning): + inv(a) + + a2 = np.stack([np.diag([1., 1e-20]), np.diag([1, 1]), np.diag([1, 1e-20])]) + with pytest.warns(LinAlgWarning): + inv(a2) + + def test_wrong_assume_a(self): + with assert_raises(KeyError): + inv(np.eye(2), assume_a="kaboom") + + def test_posdef(self): + x = np.arange(25, dtype=float).reshape(5, 5) + y = x + x.T + y += 21*np.eye(5) + + y_inv0 = inv(y) + y_inv1 = inv(y, assume_a="pos") + + assert_allclose(y_inv1, y_inv0, atol=1e-15) + + # check that the lower triangle is not referenced for `lower=False` + mask = np.where(1 - np.tri(*y.shape, -1) == 0, np.nan, 1) + y_inv2 = inv(y*mask, check_finite=False, assume_a="pos", lower=False) + assert_allclose(y_inv2, y_inv0, atol=1e-15) + + # repeat with the upper triangle + y_inv3 = inv(y*mask.T, check_finite=False, assume_a="pos", lower=True) + assert_allclose(y_inv3, y_inv0, atol=1e-15) + + @pytest.mark.parametrize('complex_', [False, True]) + def test_posdef_not_posdef(self, complex_): + # the `b` matrix is invertible but not pos definite: test the "sym" fallback + a = np.arange(9).reshape(3, 3) + b = a + a.T + np.eye(3) + if complex_: + b = b + 1j*b + + # cholesky solver fails, and the routine falls back to the symmetric inverse + b_inv0 = inv(b) + assert_allclose(b_inv0 @ b, np.eye(3), atol=3e-15) + + # but it does not fall back if `assume_a` is given + with assert_raises(LinAlgError): + inv(b, assume_a='pos') + + # test posdef fallback to the hermitian solver, too + if complex_: + a = np.arange(9).reshape(3, 3) + a = a + 1j*a + b = a + a.T.conj() + np.eye(3) + assert_allclose(inv(b) @ b, np.eye(3), atol=3e-15) + + def test_pos_fails_sym_complex(self): + # regression test for gh-24359 + # the matrix is 1) symmetric not hermitian, and 2) not positive definite: + a = np.asarray([[ 182.56985285-64.28859483j, -177.24879835+11.0780499j ], + [-177.24879835+11.0780499j , 177.24879835-11.0780499j ]]) + + ainv = inv(a) + assert_allclose(ainv @ a, np.eye(2), atol=1e-14) + + ainv_sym = inv(a, assume_a="sym") + assert_allclose(ainv_sym, ainv, atol=1e-14) + + # Specifying assume_a="pos" disables the structure detection, and directly + # calls LAPACK routines zportf and zpotri. + # Since zportf(a) does not error out, neither does inv + ainv_chol = inv(a, assume_a="pos") + assert not np.allclose(ainv, ainv_chol, atol=1e-14) + + # Setting assume_a="pos" with a non-pos def matrix returned nonsense. + # This is at least consistent with solve. + ainv_slv = solve(a, np.eye(2), assume_a="pos") + assert_allclose(ainv_chol, ainv_slv, atol=1e-14) + + # Repeat it for bunch of simple cases to cover more branches + # Real symmetric, positive definite + a = np.eye(4) + np.ones(4) + res = inv(a) + assert_allclose(res @ a, np.eye(4), atol=1e-14) + + # Real symmetric, NOT positive definite + a = -np.eye(4) + np.ones(4) + res = inv(a) + assert_allclose(res @ a, np.eye(4), atol=1e-14) + + # Real, not symmetric + a = -np.eye(4) + np.ones(4) + a[0, -1] = 2. + res = inv(a) + assert_allclose(res @ a, np.eye(4), atol=1e-14) + + # | Test | is_symm | is_herm | pos def | + # |---------------------------------------|---------|---------|---------| + # | Complex, both sym+herm, pos def | 1 | 1 | yes | + # | Complex, symmetric only | 1 | 0 | - | + # | Complex, both sym+herm, NOT pos def | 1 | 1 | no | + # | Complex, neither | 0 | 0 | - | + # | Complex, hermitian only, pos def | 0 | 1 | yes | + # | Complex, hermitian only, NOT pos def | 0 | 1 | no | + + # Complex, both symmetric and hermitian, positive definite + a = (np.eye(4) + np.ones(4)).astype(np.complex128) + res = inv(a) + assert_allclose(res @ a, np.eye(4), atol=1e-14) + + # Complex, symmetric only (not hermitian) + a = (np.eye(4)*1.0j + np.ones(4)).astype(np.complex128) + res = inv(a) + assert_allclose(res @ a, np.eye(4), atol=1e-14) + + # Complex, both symmetric and hermitian, NOT positive definite + a = (-np.eye(4) + np.ones(4)).astype(np.complex128) + res = inv(a) + assert_allclose(res @ a, np.eye(4), atol=1e-14) + + # Complex, neither symmetric nor hermitian + a = (-np.eye(4) + np.ones(4)).astype(np.complex128) + a[0, -1] = 2. + res = inv(a) + assert_allclose(res @ a, np.eye(4), atol=1e-14) + + # Complex, hermitian only, positive definite + a = np.array([[2, 1+1j], [1-1j, 2]], dtype=np.complex128) + res = inv(a) + assert_allclose(res @ a, np.eye(2), atol=1e-14) + + # Complex, hermitian only, NOT positive definite + a = np.array([[-1, 1+1j], [1-1j, -1]], dtype=np.complex128) + res = inv(a) + assert_allclose(res @ a, np.eye(2), atol=1e-14) + + @pytest.mark.parametrize('complex_', [False, True]) + @pytest.mark.parametrize('sym_herm', ['sym', 'her']) + def test_sym_her(self, complex_, sym_herm): + # test "sym" and "her" modes + a = np.arange(9).reshape(3, 3) + if complex_: + a = a + 1j*a + + if sym_herm == "sym": + b = a + a.T + else: # sym_herm == "herm": + b = a + a.T.conj() + + b = b + np.eye(3) + + b_inv0 = np.linalg.inv(b) + assert_allclose(b_inv0 @ b, np.eye(3), atol=1e-14) + + b_inv1 = inv(b, assume_a=sym_herm) + assert_allclose(b_inv0, b_inv1, atol=1e-15) + + # check that the "other" triangle is not referenced + mask = np.where(1 - np.tri(*a.shape, -1) == 0, np.nan, 1) + b_inv2 = inv(b*mask, check_finite=False, assume_a=sym_herm, lower=False) + assert_allclose(b_inv2, b_inv0, atol=1e-15) + + # repeat with the upper triangle + b_inv3 = inv(b*mask.T, check_finite=False, assume_a=sym_herm, lower=True) + assert_allclose(b_inv3, b_inv0, atol=1e-15) + + def test_triangular_1(self): + x = np.arange(25, dtype=float).reshape(5, 5) + y = x + x.T + y += 21*np.eye(5) + y_inv0 = inv(y, assume_a='upper triangular') + + # check that upper triangular differs from posdef + y_inv_posdef = inv(y, assume_a='pos') + assert not np.allclose(y_inv0, y_inv_posdef) + + def test_triangular_2(self): + y = np.ones(25, dtype=float).reshape(5, 5) + + y_inv_0_u = inv(np.triu(y)) + assert_allclose(y_inv_0_u @ np.triu(y), np.eye(5), atol=1e-15) + + y_inv_1_u = inv(y, assume_a='upper triangular') + assert_allclose(y_inv_1_u @ np.triu(y), np.eye(5), atol=1e-15) + + # check that the lower triangle is not referenced for "upper triangular" + mask = np.where(1 - np.tri(*y.shape, -1) == 0, np.nan, 1) + y_inv_2_u = inv(y*mask, check_finite=False, assume_a='upper triangular') + assert_allclose(y_inv_2_u @ np.triu(y), np.eye(5), atol=1e-15) + + # repeat for the lower traingular matrix + y_inv_0_l = inv(np.tril(y)) + assert_allclose(y_inv_0_l @ np.tril(y), np.eye(5), atol=1e-15) + + y_inv_1_l = inv(y, assume_a='lower triangular') + assert_allclose(y_inv_1_l @ np.tril(y), np.eye(5), atol=1e-15) + + # check that the lower triangle is not referenced for "lower triangular" + mask = np.where(1 - np.tri(*y.shape, -1) == 0, np.nan, 1) + y_inv_2_l = inv(y*mask.T, check_finite=False, assume_a='lower triangular') + assert_allclose(y_inv_2_l @ np.tril(y), np.eye(5), atol=1e-15) + + def test_diagonal(self): + a = np.stack([np.triu(np.ones((3, 3))), np.diag(np.arange(1, 4))]) + inv_a = inv(a) + + # basic diagonal invert + assert_allclose(inv_a[1], np.diag(1 / np.arange(1, 4)), atol=1e-14) + + # ill-conditioned inputs warn + a = np.asarray([[1e30, 0], [0, 1]]) + with pytest.warns(LinAlgWarning): + inv(a, assume_a="diagonal") + + # singular input raises + a = np.asarray([[0, 0], [0, 1]]) + with pytest.raises(LinAlgError): + inv(a, assume_a="diagonal") + + +class TestDet: + def test_1x1_all_singleton_dims(self): + a = np.array([[1]]) + deta = det(a) + assert deta.dtype.char == 'd' + assert np.isscalar(deta) + assert deta == 1. + a = np.array([[[[1]]]], dtype='f') + deta = det(a) + assert deta.dtype.char == 'd' + assert deta.shape == (1, 1) + assert_equal(deta, [[1.0]]) + a = np.array([[[1 + 3.j]]], dtype=np.complex64) + deta = det(a) + assert deta.dtype.char == 'D' + assert deta.shape == (1,) + assert_equal(deta, [1.+3.j]) + + def test_1by1_stacked_input_output(self): + rng = np.random.default_rng(1680305949878959) + a = rng.random([4, 5, 1, 1], dtype=np.float32) + deta = det(a) + assert deta.dtype.char == 'd' + assert deta.shape == (4, 5) + assert_allclose(deta, np.squeeze(a)) + + a = rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j) + deta = det(a) + assert deta.dtype.char == 'D' + assert deta.shape == (4, 5) + assert_allclose(deta, np.squeeze(a)) + + @pytest.mark.parametrize('shape', [[2, 2], [20, 20], [3, 2, 20, 20]]) + def test_simple_det_shapes_real_complex(self, shape): + rng = np.random.default_rng(1680305949878959) + a = rng.uniform(-1., 1., size=shape) + d1, d2 = det(a), np.linalg.det(a) + assert_allclose(d1, d2) + + b = rng.uniform(-1., 1., size=shape)*1j + b += rng.uniform(-0.5, 0.5, size=shape) + d3, d4 = det(b), np.linalg.det(b) + assert_allclose(d3, d4) + + def test_for_known_det_values(self): + # Hadamard8 + a = np.array([[1, 1, 1, 1, 1, 1, 1, 1], + [1, -1, 1, -1, 1, -1, 1, -1], + [1, 1, -1, -1, 1, 1, -1, -1], + [1, -1, -1, 1, 1, -1, -1, 1], + [1, 1, 1, 1, -1, -1, -1, -1], + [1, -1, 1, -1, -1, 1, -1, 1], + [1, 1, -1, -1, -1, -1, 1, 1], + [1, -1, -1, 1, -1, 1, 1, -1]]) + assert_allclose(det(a), 4096.) + + # consecutive number array always singular + assert_allclose(det(np.arange(25).reshape(5, 5)), 0.) + + # simple anti-diagonal block array + # Upper right has det (-2+1j) and lower right has (-2-1j) + # det(a) = - (-2+1j) (-2-1j) = 5. + a = np.array([[0.+0.j, 0.+0.j, 0.-1.j, 1.-1.j], + [0.+0.j, 0.+0.j, 1.+0.j, 0.-1.j], + [0.+1.j, 1.+1.j, 0.+0.j, 0.+0.j], + [1.+0.j, 0.+1.j, 0.+0.j, 0.+0.j]], dtype=np.complex64) + assert_allclose(det(a), 5.+0.j) + + # Fiedler companion complexified + # >>> a = scipy.linalg.fiedler_companion(np.arange(1, 10)) + a = np.array([[-2., -3., 1., 0., 0., 0., 0., 0.], + [1., 0., 0., 0., 0., 0., 0., 0.], + [0., -4., 0., -5., 1., 0., 0., 0.], + [0., 1., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., -6., 0., -7., 1., 0.], + [0., 0., 0., 1., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., -8., 0., -9.], + [0., 0., 0., 0., 0., 1., 0., 0.]])*1.j + assert_allclose(det(a), 9.) + + # g and G dtypes are handled differently in windows and other platforms + @pytest.mark.parametrize('typ', [x for x in np.typecodes['All'][:20] + if x not in 'gG']) + def test_sample_compatible_dtype_input(self, typ): + rng = np.random.default_rng(1680305949878959) + n = 4 + a = rng.random([n, n]).astype(typ) # value is not important + assert isinstance(det(a), (np.float64 | np.complex128)) + + def test_incompatible_dtype_input(self): + # Double backslashes needed for escaping pytest regex. + msg = 'cannot be cast to float\\(32, 64\\)' + + for c, t in zip('SUO', ['bytes8', 'str32', 'object']): + with assert_raises(TypeError, match=msg): + det(np.array([['a', 'b']]*2, dtype=c)) + with assert_raises(TypeError, match=msg): + det(np.array([[b'a', b'b']]*2, dtype='V')) + with assert_raises(TypeError, match=msg): + det(np.array([[100, 200]]*2, dtype='datetime64[s]')) + with assert_raises(TypeError, match=msg): + det(np.array([[100, 200]]*2, dtype='timedelta64[s]')) + + def test_empty_edge_cases(self): + assert_allclose(det(np.empty([0, 0])), 1.) + assert_allclose(det(np.empty([0, 0, 0])), np.array([])) + assert_allclose(det(np.empty([3, 0, 0])), np.array([1., 1., 1.])) + with assert_raises(ValueError, match='Last 2 dimensions'): + det(np.empty([0, 0, 3])) + with assert_raises(ValueError, match='at least two-dimensional'): + det(np.array([])) + with assert_raises(ValueError, match='Last 2 dimensions'): + det(np.array([[]])) + with assert_raises(ValueError, match='Last 2 dimensions'): + det(np.array([[[]]])) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty_dtype(self, dt): + a = np.empty((0, 0), dtype=dt) + d = det(a) + assert d.shape == () + assert d.dtype == det(np.eye(2, dtype=dt)).dtype + + a = np.empty((3, 0, 0), dtype=dt) + d = det(a) + assert d.shape == (3,) + assert d.dtype == det(np.zeros((3, 1, 1), dtype=dt)).dtype + + def test_overwrite_a(self): + # If all conditions are met then input should be overwritten; + # - dtype is one of 'fdFD' + # - C-contiguous + # - writeable + a = np.arange(9).reshape(3, 3).astype(np.float32) + ac = a.copy() + deta = det(ac, overwrite_a=True) + assert_allclose(deta, 0.) + assert not (a == ac).all() + + def test_readonly_array(self): + a = np.array([[2., 0., 1.], [5., 3., -1.], [1., 1., 1.]]) + a.setflags(write=False) + # overwrite_a will be overridden + assert_allclose(det(a, overwrite_a=True), 10.) + + def test_simple_check_finite(self): + a = [[1, 2], [3, np.inf]] + with assert_raises(ValueError, match='array must not contain'): + det(a) + + +def direct_lstsq(a, b, cmplx=0): + at = transpose(a) + if cmplx: + at = conjugate(at) + a1 = dot(at, a) + b1 = dot(at, b) + return solve(a1, b1) + + +class TestLstsq: + lapack_drivers = ('gelsd', 'gelss', 'gelsy', None) + + def test_simple_exact(self): + for dtype in REAL_DTYPES: + a = np.array([[1, 20], [-30, 4]], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + for bt in (((1, 0), (0, 1)), (1, 0), + ((2, 1), (-30, 4))): + # Store values in case they are overwritten + # later + a1 = a.copy() + b = np.array(bt, dtype=dtype) + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == 2, + f'expected efficient rank 2, got {r}') + assert_allclose(dot(a, x), b, + atol=25 * _eps_cast(a1.dtype), + rtol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_simple_overdet(self): + for dtype in REAL_DTYPES: + a = np.array([[1, 2], [4, 5], [3, 4]], dtype=dtype) + b = np.array([1, 2, 3], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + if lapack_driver == 'gelsy': + residuals = np.sum((b - a.dot(x))**2) + else: + residuals = out[1] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0), + residuals, + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + assert_allclose(x, (-0.428571428571429, 0.85714285714285), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_simple_overdet_complex(self): + for dtype in COMPLEX_DTYPES: + a = np.array([[1+2j, 2], [4, 5], [3, 4]], dtype=dtype) + b = np.array([1, 2+4j, 3], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + + x = out[0] + if lapack_driver == 'gelsy': + res = b - a.dot(x) + residuals = np.sum(res * res.conj()) + else: + residuals = out[1] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0), + residuals, + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + assert_allclose( + x, (-0.4831460674157303 + 0.258426966292135j, + 0.921348314606741 + 0.292134831460674j), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_simple_underdet(self): + for dtype in REAL_DTYPES: + a = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype) + b = np.array([1, 2], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + + x = out[0] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(x, (-0.055555555555555, 0.111111111111111, + 0.277777777777777), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + @pytest.mark.parametrize("dtype", REAL_DTYPES) + @pytest.mark.parametrize("n", (20, 200)) + @pytest.mark.parametrize("lapack_driver", lapack_drivers) + @pytest.mark.parametrize("overwrite", (True, False)) + def test_random_exact(self, dtype, n, lapack_driver, overwrite): + rng = np.random.RandomState(1234) + + a = np.asarray(rng.random([n, n]), dtype=dtype) + for i in range(n): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(4): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == n, f'expected efficient rank {n}, ' + f'got {r}') + if dtype is np.float32: + assert_allclose( + dot(a, x), b, + rtol=500 * _eps_cast(a1.dtype), + atol=500 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + else: + assert_allclose( + dot(a, x), b, + rtol=1000 * _eps_cast(a1.dtype), + atol=1000 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + @pytest.mark.skipif(IS_MUSL, reason="may segfault on Alpine, see gh-17630") + @pytest.mark.parametrize("dtype", COMPLEX_DTYPES) + @pytest.mark.parametrize("n", (20, 200)) + @pytest.mark.parametrize("lapack_driver", lapack_drivers) + @pytest.mark.parametrize("overwrite", (True, False)) + def test_random_complex_exact(self, dtype, n, lapack_driver, overwrite): + rng = np.random.RandomState(1234) + + a = np.asarray(rng.random([n, n]) + 1j*rng.random([n, n]), + dtype=dtype) + for i in range(n): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(2): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == n, f'expected efficient rank {n}, ' + f'got {r}') + if dtype is np.complex64: + assert_allclose( + dot(a, x), b, + rtol=400 * _eps_cast(a1.dtype), + atol=400 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + else: + assert_allclose( + dot(a, x), b, + rtol=1000 * _eps_cast(a1.dtype), + atol=1000 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_random_overdet(self): + rng = np.random.RandomState(1234) + for dtype in REAL_DTYPES: + for (n, m) in ((20, 15), (200, 2)): + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + a = np.asarray(rng.random([n, m]), dtype=dtype) + for i in range(m): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(4): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == m, f'expected efficient rank {m}, ' + f'got {r}') + assert_allclose( + x, direct_lstsq(a, b, cmplx=0), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_random_complex_overdet(self): + rng = np.random.RandomState(1234) + for dtype in COMPLEX_DTYPES: + for (n, m) in ((20, 15), (200, 2)): + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + a = np.asarray(rng.random([n, m]) + 1j*rng.random([n, m]), + dtype=dtype) + for i in range(m): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(2): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten + # later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == m, f'expected efficient rank {m}, ' + f'got {r}') + assert_allclose( + x, direct_lstsq(a, b, cmplx=1), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_check_finite(self): + with warnings.catch_warnings(): + # On (some) OSX this tests triggers a warning (gh-7538) + warnings.filterwarnings("ignore", + "internal gelsd driver lwork query error,.*" + "Falling back to 'gelss' driver.", RuntimeWarning) + + at = np.array(((1, 20), (-30, 4))) + for dtype, bt, lapack_driver, overwrite, check_finite in \ + itertools.product(REAL_DTYPES, + (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))), + TestLstsq.lapack_drivers, + (True, False), + (True, False)): + + a = at.astype(dtype) + b = np.array(bt, dtype=dtype) + # Store values in case they are overwritten + # later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + check_finite=check_finite, overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(dot(a, x), b, + rtol=25 * _eps_cast(a.dtype), + atol=25 * _eps_cast(a.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_empty(self): + for a_shape, b_shape in (((0, 2), (0,)), + ((0, 4), (0, 2)), + ((4, 0), (4,)), + ((4, 0), (4, 2))): + b = np.ones(b_shape) + x, residues, rank, s = lstsq(np.zeros(a_shape), b) + assert_equal(x, np.zeros((a_shape[1],) + b_shape[1:])) + residues_should_be = (np.empty((0,)) if a_shape[1] + else np.linalg.norm(b, axis=0)**2) + assert_equal(residues, residues_should_be) + assert_(rank == 0, 'expected rank 0') + assert_equal(s, np.empty((0,))) + + @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty_dtype(self, dt_a, dt_b): + a = np.empty((0, 0), dtype=dt_a) + b = np.empty(0, dtype=dt_b) + x, residues, rank, s = lstsq(a, b) + + assert x.size == 0 + dt_nonempty = lstsq(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b))[0].dtype + assert x.dtype == dt_nonempty + + +class TestPinv: + def test_simple_real(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + a_pinv = pinv(a) + assert_array_almost_equal(dot(a, a_pinv), np.eye(3)) + + def test_simple_complex(self): + a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], + dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], + dtype=float)) + a_pinv = pinv(a) + assert_array_almost_equal(dot(a, a_pinv), np.eye(3)) + + def test_simple_singular(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) + a_pinv = pinv(a) + expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01], + [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02], + [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]]) + assert_array_almost_equal(a_pinv, expected) + + def test_simple_cols(self): + a = array([[1, 2, 3], [4, 5, 6]], dtype=float) + a_pinv = pinv(a) + expected = array([[-0.94444444, 0.44444444], + [-0.11111111, 0.11111111], + [0.72222222, -0.22222222]]) + assert_array_almost_equal(a_pinv, expected) + + def test_simple_rows(self): + a = array([[1, 2], [3, 4], [5, 6]], dtype=float) + a_pinv = pinv(a) + expected = array([[-1.33333333, -0.33333333, 0.66666667], + [1.08333333, 0.33333333, -0.41666667]]) + assert_array_almost_equal(a_pinv, expected) + + def test_check_finite(self): + a = array([[1, 2, 3], [4, 5, 6.], [7, 8, 10]]) + a_pinv = pinv(a, check_finite=False) + assert_array_almost_equal(dot(a, a_pinv), np.eye(3)) + + def test_native_list_argument(self): + a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + a_pinv = pinv(a) + expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01], + [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02], + [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]]) + assert_array_almost_equal(a_pinv, expected) + + def test_atol_rtol(self): + rng = np.random.default_rng(1234) + n = 12 + # get a random ortho matrix for shuffling + q, _ = qr(rng.random((n, n))) + a_m = np.arange(35.0).reshape(7, 5) + a = a_m.copy() + a[0, 0] = 0.001 + atol = 1e-5 + rtol = 0.05 + # svds of a_m is ~ [116.906, 4.234, tiny, tiny, tiny] + # svds of a is ~ [116.906, 4.234, 4.62959e-04, tiny, tiny] + # Just abs cutoff such that we arrive at a_modified + a_p = pinv(a_m, atol=atol, rtol=0.) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + # Now adiff1 should be around atol value while adiff2 should be + # relatively tiny + assert_allclose(np.linalg.norm(adiff1), 5e-4, atol=5.e-4) + assert_allclose(np.linalg.norm(adiff2), 5e-14, atol=5.e-14) + + # Now do the same but remove another sv ~4.234 via rtol + a_p = pinv(a_m, atol=atol, rtol=rtol) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + assert_allclose(np.linalg.norm(adiff1), 4.233, rtol=0.01) + assert_allclose(np.linalg.norm(adiff2), 4.233, rtol=0.01) + + @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a_pinv = pinv(a) + assert a_pinv.size == 0 + assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype + + +class TestPinvSymmetric: + def test_simple_real(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + a = np.dot(a, a.T) + a_pinv = pinvh(a) + assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3)) + + def test_nonpositive(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) + a = np.dot(a, a.T) + u, s, vt = np.linalg.svd(a) + s[0] *= -1 + a = np.dot(u * s, vt) # a is now symmetric non-positive and singular + a_pinv = pinv(a) + a_pinvh = pinvh(a) + assert_array_almost_equal(a_pinv, a_pinvh) + + def test_simple_complex(self): + a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], + dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], + dtype=float)) + a = np.dot(a, a.conj().T) + a_pinv = pinvh(a) + assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3)) + + def test_native_list_argument(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + a = np.dot(a, a.T) + a_pinv = pinvh(a.tolist()) + assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3)) + + def test_zero_eigenvalue(self): + # https://github.com/scipy/scipy/issues/12515 + # the SYEVR eigh driver may give the zero eigenvalue > eps + a = np.array([[1, -1, 0], [-1, 2, -1], [0, -1, 1]]) + p = pinvh(a) + assert_allclose(p @ a @ p, p, atol=1e-15) + assert_allclose(a @ p @ a, a, atol=1e-15) + + def test_atol_rtol(self): + rng = np.random.default_rng(1234) + n = 12 + # get a random ortho matrix for shuffling + q, _ = qr(rng.random((n, n))) + a = np.diag([4, 3, 2, 1, 0.99e-4, 0.99e-5] + [0.99e-6]*(n-6)) + a = q.T @ a @ q + a_m = np.diag([4, 3, 2, 1, 0.99e-4, 0.] + [0.]*(n-6)) + a_m = q.T @ a_m @ q + atol = 1e-5 + rtol = (4.01e-4 - 4e-5)/4 + # Just abs cutoff such that we arrive at a_modified + a_p = pinvh(a, atol=atol, rtol=0.) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + # Now adiff1 should dance around atol value since truncation + # while adiff2 should be relatively tiny + assert_allclose(norm(adiff1), atol, rtol=0.1) + assert_allclose(norm(adiff2), 1e-12, atol=1e-11) + + # Now do the same but through rtol cancelling atol value + a_p = pinvh(a, atol=atol, rtol=rtol) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + # adiff1 and adiff2 should be elevated to ~1e-4 due to mismatch + assert_allclose(norm(adiff1), 1e-4, rtol=0.1) + assert_allclose(norm(adiff2), 1e-4, rtol=0.1) + + @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a_pinv = pinvh(a) + assert a_pinv.size == 0 + assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype + + +@pytest.mark.parametrize('scale', (1e-20, 1., 1e20)) +@pytest.mark.parametrize('pinv_', (pinv, pinvh)) +def test_auto_rcond(scale, pinv_): + x = np.array([[1, 0], [0, 1e-10]]) * scale + expected = np.diag(1. / np.diag(x)) + x_inv = pinv_(x) + assert_allclose(x_inv, expected) + + +class TestVectorNorms: + + def test_types(self): + for dtype in np.typecodes['AllFloat']: + x = np.array([1, 2, 3], dtype=dtype) + tol = max(1e-15, np.finfo(dtype).eps.real * 20) + assert_allclose(norm(x), np.sqrt(14), rtol=tol) + assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol) + + for dtype in np.typecodes['Complex']: + x = np.array([1j, 2j, 3j], dtype=dtype) + tol = max(1e-15, np.finfo(dtype).eps.real * 20) + assert_allclose(norm(x), np.sqrt(14), rtol=tol) + assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol) + + def test_overflow(self): + # unlike numpy's norm, this one is + # safer on overflow + a = array([1e20], dtype=float32) + assert_almost_equal(norm(a), a) + + def test_stable(self): + # more stable than numpy's norm + a = array([1e4] + [1]*10000, dtype=float32) + try: + # snrm in double precision; we obtain the same as for float64 + # -- large atol needed due to varying blas implementations + assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2) + except AssertionError: + # snrm implemented in single precision, == np.linalg.norm result + msg = ": Result should equal either 0.0 or 0.5 (depending on " \ + "implementation of snrm2)." + assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg) + + def test_zero_norm(self): + assert_equal(norm([1, 0, 3], 0), 2) + assert_equal(norm([1, 2, 3], 0), 3) + + def test_axis_kwd(self): + a = np.array([[[2, 1], [3, 4]]] * 2, 'd') + assert_allclose(norm(a, axis=1), [[3.60555128, 4.12310563]] * 2) + assert_allclose(norm(a, 1, axis=1), [[5.] * 2] * 2) + + def test_keepdims_kwd(self): + a = np.array([[[2, 1], [3, 4]]] * 2, 'd') + b = norm(a, axis=1, keepdims=True) + assert_allclose(b, [[[3.60555128, 4.12310563]]] * 2) + assert_(b.shape == (2, 1, 2)) + assert_allclose(norm(a, 1, axis=2, keepdims=True), [[[3.], [7.]]] * 2) + + @pytest.mark.skipif(not HAS_ILP64, reason="64-bit BLAS required") + def test_large_vector(self): + check_free_memory(free_mb=17000) + x = np.zeros([2**31], dtype=np.float64) + x[-1] = 1 + res = norm(x) + del x + assert_allclose(res, 1.0) + + +class TestMatrixNorms: + + def test_matrix_norms(self): + # Not all of these are matrix norms in the most technical sense. + rng = np.random.default_rng(1234) + for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4): + for t in np.float32, np.float64, np.complex64, np.complex128, np.int64: + A = 10 * rng.standard_normal((n, m)).astype(t) + if np.issubdtype(A.dtype, np.complexfloating): + A += 10j * rng.standard_normal((n, m)) + t_high = np.complex128 + else: + t_high = np.float64 + for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf): + actual = norm(A, ord=order) + desired = np.linalg.norm(A, ord=order) + # SciPy may return higher precision matrix norms. + # This is a consequence of using LAPACK. + if not np.allclose(actual, desired): + desired = np.linalg.norm(A.astype(t_high), ord=order) + assert_allclose(actual, desired) + + def test_axis_kwd(self): + a = np.array([[[2, 1], [3, 4]]] * 2, 'd') + b = norm(a, ord=np.inf, axis=(1, 0)) + c = norm(np.swapaxes(a, 0, 1), ord=np.inf, axis=(0, 1)) + d = norm(a, ord=1, axis=(0, 1)) + assert_allclose(b, c) + assert_allclose(c, d) + assert_allclose(b, d) + assert_(b.shape == c.shape == d.shape) + b = norm(a, ord=1, axis=(1, 0)) + c = norm(np.swapaxes(a, 0, 1), ord=1, axis=(0, 1)) + d = norm(a, ord=np.inf, axis=(0, 1)) + assert_allclose(b, c) + assert_allclose(c, d) + assert_allclose(b, d) + assert_(b.shape == c.shape == d.shape) + + def test_keepdims_kwd(self): + a = np.arange(120, dtype='d').reshape(2, 3, 4, 5) + b = norm(a, ord=np.inf, axis=(1, 0), keepdims=True) + c = norm(a, ord=1, axis=(0, 1), keepdims=True) + assert_allclose(b, c) + assert_(b.shape == c.shape) + + def test_empty(self): + a = np.empty((0, 0)) + assert_allclose(norm(a), 0.) + assert_allclose(norm(a, axis=0), np.zeros((0,))) + assert_allclose(norm(a, keepdims=True), np.zeros((1, 1))) + + a = np.empty((0, 3)) + assert_allclose(norm(a), 0.) + assert_allclose(norm(a, axis=0), np.zeros((3,))) + assert_allclose(norm(a, keepdims=True), np.zeros((1, 1))) + + +class TestOverwrite: + def test_solve(self): + assert_no_overwrite(solve, [(3, 3), (3,)]) + + def test_solve_triangular(self): + assert_no_overwrite(solve_triangular, [(3, 3), (3,)]) + + def test_solve_banded(self): + assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b), + [(4, 6), (6,)]) + + def test_solveh_banded(self): + assert_no_overwrite(solveh_banded, [(2, 6), (6,)]) + + def test_inv(self): + assert_no_overwrite(inv, [(3, 3)]) + + def test_det(self): + assert_no_overwrite(det, [(3, 3)]) + + def test_lstsq(self): + assert_no_overwrite(lstsq, [(3, 2), (3,)]) + + def test_pinv(self): + assert_no_overwrite(pinv, [(3, 3)]) + + def test_pinvh(self): + assert_no_overwrite(pinvh, [(3, 3)]) + + +class TestSolveCirculant: + + def test_basic1(self): + c = np.array([1, 2, 3, 5]) + b = np.array([1, -1, 1, 0]) + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_basic2(self): + # b is a 2-d matrix. + c = np.array([1, 2, -3, -5]) + b = np.arange(12).reshape(4, 3) + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_basic3(self): + # b is a 3-d matrix. + c = np.array([1, 2, -3, -5]) + b = np.arange(24).reshape(4, 3, 2) + x = solve_circulant(c, b) + y = solve(circulant(c), b.reshape(4, -1)).reshape(b.shape) + assert_allclose(x, y) + + def test_complex(self): + # Complex b and c + c = np.array([1+2j, -3, 4j, 5]) + b = np.arange(8).reshape(4, 2) + 0.5j + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_random_b_and_c(self): + # Random b and c + rng = np.random.RandomState(54321) + c = rng.standard_normal(50) + b = rng.standard_normal(50) + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_singular(self): + # c gives a singular circulant matrix. + c = np.array([1, 1, 0, 0]) + b = np.array([1, 2, 3, 4]) + x = solve_circulant(c, b, singular='lstsq') + y, res, rnk, s = lstsq(circulant(c), b) + assert_allclose(x, y) + assert_raises(LinAlgError, solve_circulant, x, y) + + def test_axis_args(self): + # Test use of caxis, baxis and outaxis. + + # c has shape (2, 1, 4) + c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]]) + + # b has shape (3, 4) + b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]]) + + x = solve_circulant(c, b, baxis=1) + assert_equal(x.shape, (4, 2, 3)) + expected = np.empty_like(x) + expected[:, 0, :] = solve(circulant(c[0].ravel()), b.T) + expected[:, 1, :] = solve(circulant(c[1].ravel()), b.T) + assert_allclose(x, expected) + + x = solve_circulant(c, b, baxis=1, outaxis=-1) + assert_equal(x.shape, (2, 3, 4)) + assert_allclose(np.moveaxis(x, -1, 0), expected) + + # np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3). + x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1) + assert_equal(x.shape, (4, 2, 3)) + assert_allclose(x, expected) + + def test_native_list_arguments(self): + # Same as test_basic1 using python's native list. + c = [1, 2, 3, 5] + b = [1, -1, 1, 0] + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + @pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_c, dt_b): + c = np.array([], dtype=dt_c) + b = np.array([], dtype=dt_b) + x = solve_circulant(c, b) + assert x.shape == (0,) + assert x.dtype == solve_circulant(np.arange(3, dtype=dt_c), + np.ones(3, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x1 = solve_circulant(c, b) + assert x1.shape == (0, 0) + assert x1.dtype == x.dtype + + +class TestMatrix_Balance: + @skip_xp_invalid_arg + def test_string_arg(self): + assert_raises(ValueError, matrix_balance, 'Some string for fail') + + def test_infnan_arg(self): + assert_raises(ValueError, matrix_balance, + np.array([[1, 2], [3, np.inf]])) + assert_raises(ValueError, matrix_balance, + np.array([[1, 2], [3, np.nan]])) + + def test_scaling(self): + _, y = matrix_balance(np.array([[1000, 1], [1000, 0]])) + # Pre/post LAPACK 3.5.0 gives the same result up to an offset + # since in each case col norm is x1000 greater and + # 1000 / 32 ~= 1 * 32 hence balanced with 2 ** 5. + assert_allclose(np.diff(np.log2(np.diag(y))), [5]) + + def test_scaling_order(self): + A = np.array([[1, 0, 1e-4], [1, 1, 1e-2], [1e4, 1e2, 1]]) + x, y = matrix_balance(A) + assert_allclose(solve(y, A).dot(y), x) + + def test_separate(self): + _, (y, z) = matrix_balance(np.array([[1000, 1], [1000, 0]]), + separate=1) + assert_equal(np.diff(np.log2(y)), [5]) + assert_allclose(z, np.arange(2)) + + def test_permutation(self): + A = block_diag(np.ones((2, 2)), np.tril(np.ones((2, 2))), + np.ones((3, 3))) + x, (y, z) = matrix_balance(A, separate=1) + assert_allclose(y, np.ones_like(y)) + assert_allclose(z, np.array([0, 1, 6, 5, 4, 3, 2])) + + def test_perm_and_scaling(self): + # Matrix with its diagonal removed + cases = ( # Case 0 + np.array([[0., 0., 0., 0., 0.000002], + [0., 0., 0., 0., 0.], + [2., 2., 0., 0., 0.], + [2., 2., 0., 0., 0.], + [0., 0., 0.000002, 0., 0.]]), + # Case 1 user reported GH-7258 + np.array([[-0.5, 0., 0., 0.], + [0., -1., 0., 0.], + [1., 0., -0.5, 0.], + [0., 1., 0., -1.]]), + # Case 2 user reported GH-7258 + np.array([[-3., 0., 1., 0.], + [-1., -1., -0., 1.], + [-3., -0., -0., 0.], + [-1., -0., 1., -1.]]) + ) + + for A in cases: + x, y = matrix_balance(A) + x, (s, p) = matrix_balance(A, separate=1) + ip = np.empty_like(p) + ip[p] = np.arange(A.shape[0]) + assert_allclose(y, np.diag(s)[ip, :]) + assert_allclose(solve(y, A).dot(y), x) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + b, t = matrix_balance(a) + + assert b.size == 0 + assert t.size == 0 + + b_n, t_n = matrix_balance(np.eye(2, dtype=dt)) + assert b.dtype == b_n.dtype + assert t.dtype == t_n.dtype + + b, (scale, perm) = matrix_balance(a, separate=True) + assert b.size == 0 + assert scale.size == 0 + assert perm.size == 0 + + b_n, (scale_n, perm_n) = matrix_balance(a, separate=True) + assert b.dtype == b_n.dtype + assert scale.dtype == scale_n.dtype + assert perm.dtype == perm_n.dtype + + +class TestDTypes: + """Check backwards compatibility for dtypes vs scipy 1.16.""" + + def get_arr2D(self, tcode): + # return a valid 2D array for the typecode + if tcode == 'M': + return np.eye(2, dtype='datetime64[ms]') + elif tcode == 'V': + return np.asarray([[b'a', b'b'], [b'c', b'd']], dtype='V') + else: + return np.eye(2, dtype=tcode) + + def get_arr1D(self, tcode): + # return a valid 1D array for the typecode + if tcode == 'M': + return np.ones(2, dtype='datetime64[ms]') + elif tcode == 'V': + return np.asarray([b'a', b'b'], dtype='V') + else: + return np.ones(2, dtype=tcode) + + @pytest.mark.parametrize("tcode", np.typecodes['All']) + def test_inv(self, tcode): + # check backwards compat vs scipy 1.16 + a = self.get_arr2D(tcode) + if tcode in 'SUVO': + # raises + with pytest.raises(ValueError): + inv(a) + else: + # passes + inv(a) + + @pytest.mark.parametrize("tcode", np.typecodes['All']) + def test_det(self, tcode): + a = self.get_arr2D(tcode) + + is_arm = platform.machine() == 'arm64' + is_windows = os.name == 'nt' + + failing_tcodes = 'SUVOmM' + if not (is_arm or is_windows): + failing_tcodes += 'gG' + + if tcode in failing_tcodes: + # raises + with pytest.raises(TypeError): + det(a) + else: + # passes + det(a) + + @pytest.mark.filterwarnings("ignore:Casting complex values") + @pytest.mark.parametrize("tcode_a", np.typecodes['All']) + @pytest.mark.parametrize("tcode_b", np.typecodes['All']) + def test_solve(self, tcode_a, tcode_b): + a = self.get_arr2D(tcode_a) + b = self.get_arr1D(tcode_b) + + can_combine = True + try: + np.result_type(tcode_a, tcode_b) + except TypeError: + can_combine = False + + if not can_combine: + # np.exceptions.DTypePromotionError subclasses TypeError + with pytest.raises(TypeError): + solve(a, b) + elif tcode_a in 'SUVO' or tcode_b in 'VO': + with pytest.raises(ValueError): + solve(a, b) + else: + solve(a, b) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_batch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..29977258a1933429f0849726c73d8da6d4f7e4cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_batch.py @@ -0,0 +1,620 @@ +import inspect +import pytest +import numpy as np +from numpy.testing import assert_allclose +from scipy import linalg, sparse + + +real_floating = [np.float32, np.float64] +complex_floating = [np.complex64, np.complex128] +floating = real_floating + complex_floating + + +def get_random(shape, *, dtype, rng): + A = rng.random(shape) + if np.issubdtype(dtype, np.complexfloating): + A = A + rng.random(shape) * 1j + return A.astype(dtype) + +def get_nearly_hermitian(shape, dtype, atol, rng): + # Generate a batch of nearly Hermitian matrices with specified + # `shape` and `dtype`. `atol` controls the level of noise in + # Hermitian-ness to by generated by `rng`. + A = rng.random(shape).astype(dtype) + At = np.conj(A.swapaxes(-1, -2)) + noise = rng.standard_normal(size=A.shape).astype(dtype) * atol + return A + At + noise + + +class TestBatch: + # Test batch support for most linalg functions + + def batch_test(self, fun, arrays, *, core_dim=2, n_out=1, kwargs=None, dtype=None, + broadcast=True, check_kwargs=True): + # Check that all outputs of batched call `fun(A, **kwargs)` are the same + # as if we loop over the separate vectors/matrices in `A`. Also check + # that `fun` accepts `A` by position or keyword and that results are + # identical. This is important because the name of the array argument + # is manually specified to the decorator, and it's easy to mess up. + # However, this makes it hard to test positional arguments passed + # after the array, so we test that separately for a few functions to + # make sure the decorator is working as it should. + + kwargs = {} if kwargs is None else kwargs + parameters = list(inspect.signature(fun).parameters.keys()) + arrays = (arrays,) if not isinstance(arrays, tuple) else arrays + + # Identical results when passing argument by keyword or position + res2 = fun(*arrays, **kwargs) + if check_kwargs: + res1 = fun(**dict(zip(parameters, arrays)), **kwargs) + for out1, out2 in zip(res1, res2): # even a single array is iterable... + np.testing.assert_equal(out1, out2) + + # Check results vs looping over + res = (res2,) if n_out == 1 else res2 + # This is not the general behavior (only batch dimensions get + # broadcasted by the decorator) but it's easier for testing. + if broadcast: + arrays = np.broadcast_arrays(*arrays) + batch_shape = arrays[0].shape[:-core_dim] + for i in range(batch_shape[0]): + for j in range(batch_shape[1]): + arrays_ij = (array[i, j] for array in arrays) + ref = fun(*arrays_ij, **kwargs) + ref = ((np.asarray(ref),) if n_out == 1 else + tuple(np.asarray(refk) for refk in ref)) + for k in range(n_out): + assert_allclose(res[k][i, j], ref[k]) + assert np.shape(res[k][i, j]) == ref[k].shape + + for k in range(len(ref)): + out_dtype = ref[k].dtype if dtype is None else dtype + assert res[k].dtype == out_dtype + + return res2 # return original, non-tuplized result + + @pytest.mark.parametrize('dtype', floating) + def test_expm_cond(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = rng.random((5, 3, 4, 4)).astype(dtype) + self.batch_test(linalg.expm_cond, A) + + @pytest.mark.parametrize('dtype', floating) + def test_issymmetric(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_nearly_hermitian((5, 3, 4, 4), dtype, 3e-4, rng) + res = self.batch_test(linalg.issymmetric, A, kwargs=dict(atol=1e-3)) + assert not np.all(res) # ensure test is not trivial: not all True or False; + assert np.any(res) # also confirms that `atol` is passed to issymmetric + + @pytest.mark.parametrize('dtype', floating) + def test_ishermitian(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_nearly_hermitian((5, 3, 4, 4), dtype, 3e-4, rng) + res = self.batch_test(linalg.ishermitian, A, kwargs=dict(atol=1e-3)) + assert not np.all(res) # ensure test is not trivial: not all True or False; + assert np.any(res) # also confirms that `atol` is passed to ishermitian + + @pytest.mark.parametrize('dtype', floating) + def test_diagsvd(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = rng.random((5, 3, 4)).astype(dtype) + res1 = self.batch_test(linalg.diagsvd, A, kwargs=dict(M=6, N=4), core_dim=1) + # test that `M, N` can be passed by position + res2 = linalg.diagsvd(A, 6, 4) + np.testing.assert_equal(res1, res2) + + @pytest.mark.parametrize('fun', [linalg.inv, linalg.sqrtm, linalg.signm, + linalg.sinm, linalg.cosm, linalg.tanhm, + linalg.sinhm, linalg.coshm, linalg.tanhm, + linalg.pinv, linalg.pinvh, linalg.orth]) + @pytest.mark.parametrize('dtype', floating) + def test_matmat(self, fun, dtype): # matrix in, matrix out + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + + # sqrtm can return complex output for real input resulting in i/o type + # mismatch. Nudge the eigenvalues to positive side to avoid this. + if fun == linalg.sqrtm: + A = A + 3*np.eye(4, dtype=dtype) + + self.batch_test(fun, A) + + @pytest.mark.parametrize('dtype', floating) + def test_null_space(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 6), dtype=dtype, rng=rng) + self.batch_test(linalg.null_space, A) + + @pytest.mark.parametrize('dtype', floating) + def test_funm(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 4, 3, 3), dtype=dtype, rng=rng) + self.batch_test(linalg.funm, A, kwargs=dict(func=np.sin)) + + @pytest.mark.parametrize('dtype', floating) + def test_fractional_matrix_power(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 4, 3, 3), dtype=dtype, rng=rng) + res1 = self.batch_test(linalg.fractional_matrix_power, A, kwargs={'t':1.5}) + # test that `t` can be passed by position + res2 = linalg.fractional_matrix_power(A, 1.5) + np.testing.assert_equal(res1, res2) + + @pytest.mark.parametrize('dtype', floating) + def test_logm(self, dtype): + # One test failed absolute tolerance with default random seed + rng = np.random.default_rng(89940026998903887141749720079406074936) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + A = A + 3*np.eye(4) # avoid complex output for real input + res1 = self.batch_test(linalg.logm, A) + # test that `disp` can be passed by position + res2 = linalg.logm(A) + for res1i, res2i in zip(res1, res2): + np.testing.assert_equal(res1i, res2i) + + @pytest.mark.parametrize('dtype', floating) + def test_pinv(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + self.batch_test(linalg.pinv, A, n_out=2, kwargs=dict(return_rank=True)) + + @pytest.mark.parametrize('dtype', floating) + def test_matrix_balance(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + self.batch_test(linalg.matrix_balance, A, n_out=2) + self.batch_test(linalg.matrix_balance, A, n_out=2, kwargs={'separate':True}) + + @pytest.mark.parametrize('dtype', floating) + def test_bandwidth(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((4, 4), dtype=dtype, rng=rng) + A = np.asarray([np.triu(A, k) for k in range(-3, 3)]).reshape((2, 3, 4, 4)) + self.batch_test(linalg.bandwidth, A, n_out=2) + + @pytest.mark.parametrize('fun_n_out', [(linalg.cholesky, 1), (linalg.ldl, 3), + (linalg.cho_factor, 2)]) + @pytest.mark.parametrize('dtype', floating) + def test_ldl_cholesky(self, fun_n_out, dtype): + rng = np.random.default_rng(8342310302941288912051) + fun, n_out = fun_n_out + A = get_nearly_hermitian((5, 3, 4, 4), dtype, 0, rng) # exactly Hermitian + A = A + 4*np.eye(4, dtype=dtype) # ensure positive definite for Cholesky + self.batch_test(fun, A, n_out=n_out) + + @pytest.mark.parametrize('compute_uv', [False, True]) + @pytest.mark.parametrize('dtype', floating) + def test_svd(self, compute_uv, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 2, 4), dtype=dtype, rng=rng) + n_out = 3 if compute_uv else 1 + self.batch_test(linalg.svd, A, n_out=n_out, kwargs=dict(compute_uv=compute_uv)) + + @pytest.mark.parametrize('fun', [linalg.polar, linalg.qr, linalg.rq]) + @pytest.mark.parametrize('dtype', floating) + def test_polar_qr_rq(self, fun, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 2, 4), dtype=dtype, rng=rng) + self.batch_test(fun, A, n_out=2) + + @pytest.mark.parametrize('cdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_qr_multiply(self, cdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + c = get_random(cdim, dtype=dtype, rng=rng) + res = linalg.qr_multiply(A, c, mode='left') + q, r = linalg.qr(A) + ref = q @ c + atol = 1e-6 if dtype in {np.float32, np.complex64} else 1e-12 + assert_allclose(res[0], ref, atol=atol) + assert_allclose(res[1], r, atol=atol) + + @pytest.mark.parametrize('uvdim', [[(5,), (3,)], [(4, 5, 2), (4, 3, 2)]]) + @pytest.mark.parametrize('dtype', floating) + def test_qr_update(self, uvdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + udim, vdim = uvdim + A = get_random((4, 5, 3), dtype=dtype, rng=rng) + u = get_random(udim, dtype=dtype, rng=rng) + v = get_random(vdim, dtype=dtype, rng=rng) + q, r = linalg.qr(A) + res = linalg.qr_update(q, r, u, v) + for i in range(4): + qi, ri = q[i], r[i] + ui, vi = (u, v) if u.ndim == 1 else (u[i], v[i]) + ref_i = linalg.qr_update(qi, ri, ui, vi) + assert_allclose(res[0][i], ref_i[0]) + assert_allclose(res[1][i], ref_i[1]) + + @pytest.mark.parametrize('udim', [(5,), (4, 3, 5)]) + @pytest.mark.parametrize('kdim', [(), (4,)]) + @pytest.mark.parametrize('dtype', floating) + def test_qr_insert(self, udim, kdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((4, 5, 5), dtype=dtype, rng=rng) + u = get_random(udim, dtype=dtype, rng=rng) + k = rng.integers(0, 5, size=kdim) + q, r = linalg.qr(A) + res = linalg.qr_insert(q, r, u, k) + for i in range(4): + qi, ri = q[i], r[i] + ki = k if k.ndim == 0 else k[i] + ui = u if u.ndim == 1 else u[i] + ref_i = linalg.qr_insert(qi, ri, ui, ki) + assert_allclose(res[0][i], ref_i[0]) + assert_allclose(res[1][i], ref_i[1]) + + @pytest.mark.parametrize('kdim', [(), (4,)]) + @pytest.mark.parametrize('dtype', floating) + def test_qr_delete(self, kdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((4, 5, 5), dtype=dtype, rng=rng) + k = rng.integers(0, 4, size=kdim) + q, r = linalg.qr(A) + res = linalg.qr_delete(q, r, k) + for i in range(4): + qi, ri = q[i], r[i] + ki = k if k.ndim == 0 else k[i] + ref_i = linalg.qr_delete(qi, ri, ki) + assert_allclose(res[0][i], ref_i[0]) + assert_allclose(res[1][i], ref_i[1]) + + @pytest.mark.parametrize('fun', [linalg.schur, linalg.lu_factor]) + @pytest.mark.parametrize('dtype', floating) + def test_schur_lu(self, fun, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + self.batch_test(fun, A, n_out=2) + + @pytest.mark.parametrize('calc_q', [False, True]) + @pytest.mark.parametrize('dtype', floating) + def test_hessenberg(self, calc_q, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + n_out = 2 if calc_q else 1 + self.batch_test(linalg.hessenberg, A, n_out=n_out, kwargs=dict(calc_q=calc_q)) + + @pytest.mark.parametrize('eigvals_only', [False, True]) + @pytest.mark.parametrize('dtype', floating) + def test_eig_banded(self, eigvals_only, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + n_out = 1 if eigvals_only else 2 + self.batch_test(linalg.eig_banded, A, n_out=n_out, + kwargs=dict(eigvals_only=eigvals_only)) + + @pytest.mark.parametrize('dtype', floating) + def test_eigvals_banded(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng) + self.batch_test(linalg.eigvals_banded, A) + + @pytest.mark.parametrize('two_in', [False, True]) + @pytest.mark.parametrize('fun_n_nout', [(linalg.eigh, 1), (linalg.eigh, 2), + (linalg.eigvalsh, 1), (linalg.eigvals, 1)]) + @pytest.mark.parametrize('dtype', floating) + def test_eigh(self, two_in, fun_n_nout, dtype): + rng = np.random.default_rng(8342310302941288912051) + fun, n_out = fun_n_nout + A = get_nearly_hermitian((1, 3, 4, 4), dtype, 0, rng) # exactly Hermitian + B = get_nearly_hermitian((2, 1, 4, 4), dtype, 0, rng) # exactly Hermitian + B = B + 4*np.eye(4).astype(dtype) # needs to be positive definite + args = (A, B) if two_in else (A,) + kwargs = dict(eigvals_only=True) if (n_out == 1 and fun==linalg.eigh) else {} + self.batch_test(fun, args, n_out=n_out, kwargs=kwargs) + + @pytest.mark.parametrize('compute_expm', [False, True]) + @pytest.mark.parametrize('dtype', floating) + def test_expm_frechet(self, compute_expm, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((1, 3, 4, 4), dtype=dtype, rng=rng) + E = get_random((2, 1, 4, 4), dtype=dtype, rng=rng) + n_out = 2 if compute_expm else 1 + self.batch_test(linalg.expm_frechet, (A, E), n_out=n_out, + kwargs=dict(compute_expm=compute_expm)) + + @pytest.mark.parametrize('dtype', floating) + def test_subspace_angles(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((1, 3, 4, 3), dtype=dtype, rng=rng) + B = get_random((2, 1, 4, 3), dtype=dtype, rng=rng) + self.batch_test(linalg.subspace_angles, (A, B)) + # just to show that A and B don't need to be broadcastable + M, N, K = 4, 5, 3 + A = get_random((1, 3, M, N), dtype=dtype, rng=rng) + B = get_random((2, 1, M, K), dtype=dtype, rng=rng) + assert linalg.subspace_angles(A, B).shape == (2, 3, min(N, K)) + + @pytest.mark.parametrize('fun', [linalg.svdvals]) + @pytest.mark.parametrize('dtype', floating) + def test_svdvals(self, fun, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 4, 5), dtype=dtype, rng=rng) + self.batch_test(fun, A) + + @pytest.mark.parametrize('fun_n_out', [(linalg.orthogonal_procrustes, 2), + (linalg.khatri_rao, 1), + (linalg.solve_continuous_lyapunov, 1), + (linalg.solve_discrete_lyapunov, 1), + (linalg.qz, 4), + (linalg.ordqz, 6)]) + @pytest.mark.parametrize('dtype', floating) + def test_two_generic_matrix_inputs(self, fun_n_out, dtype): + rng = np.random.default_rng(8342310302941288912051) + fun, n_out = fun_n_out + A = get_random((2, 3, 4, 4), dtype=dtype, rng=rng) + B = get_random((2, 3, 4, 4), dtype=dtype, rng=rng) + self.batch_test(fun, (A, B), n_out=n_out) + + @pytest.mark.parametrize('dtype', floating) + def test_cossin(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + p, q = 3, 4 + X = get_random((2, 3, 10, 10), dtype=dtype, rng=rng) + x11, x12, x21, x22 = (X[..., :p, :q], X[..., :p, q:], + X[..., p:, :q], X[..., p:, q:]) + res = linalg.cossin(X, p, q) + ref = linalg.cossin((x11, x12, x21, x22)) + for res_i, ref_i in zip(res, ref): + np.testing.assert_equal(res_i, ref_i) + + for j in range(2): + for k in range(3): + ref_jk = linalg.cossin(X[j, k], p, q) + for res_i, ref_ijk in zip(res, ref_jk): + np.testing.assert_equal(res_i[j, k], ref_ijk) + + @pytest.mark.parametrize('dtype', floating) + def test_sylvester(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + B = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + C = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + self.batch_test(linalg.solve_sylvester, (A, B, C)) + + @pytest.mark.parametrize('fun', [linalg.solve_continuous_are, + linalg.solve_discrete_are]) + @pytest.mark.parametrize('dtype', floating) + def test_are(self, fun, dtype): + rng = np.random.default_rng(8342310302941288912051) + a = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + b = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + q = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng) + r = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng) + a = a + 5*np.eye(5) # making these positive definite seems to help + b = b + 5*np.eye(5) + q = q + 5*np.eye(5) + r = r + 5*np.eye(5) + e = np.eye(5) + s = np.zeros((5, 5)) + self.batch_test(fun, (a, b, q, r)) + self.batch_test(fun, (a, b, q, r, e)) + self.batch_test(fun, (a, b, q, r, e, s)) + + res = fun(a, b, q, r) + ref = fun(a, b, q, r, s=s) + np.testing.assert_allclose(res, ref) + + @pytest.mark.parametrize('dtype', floating) + def test_rsf2cs(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 4, 4), dtype=dtype, rng=rng) + T, Z = linalg.schur(A) + self.batch_test(linalg.rsf2csf, (T, Z), n_out=2) + + @pytest.mark.parametrize('dtype', floating) + def test_cholesky_banded(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + ab = get_random((5, 4, 3, 6), dtype=dtype, rng=rng) + ab[..., -1, :] = 10 # make diagonal dominant + self.batch_test(linalg.cholesky_banded, ab) + + @pytest.mark.parametrize('dtype', floating) + def test_block_diag(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + a = get_random((1, 3, 1, 3), dtype=dtype, rng=rng) + b = get_random((2, 1, 3, 6), dtype=dtype, rng=rng) + c = get_random((1, 1, 3, 2), dtype=dtype, rng=rng) + + # batch_test doesn't have the logic to broadcast just the batch shapes, + # so do it manually. + a2 = np.broadcast_to(a, (2, 3, 1, 3)) + b2 = np.broadcast_to(b, (2, 3, 3, 6)) + c2 = np.broadcast_to(c, (2, 3, 3, 2)) + ref = self.batch_test(linalg.block_diag, (a2, b2, c2), + check_kwargs=False, broadcast=False) + + # Check that `block_diag` broadcasts the batch shapes as expected. + res = linalg.block_diag(a, b, c) + assert_allclose(res, ref) + + @pytest.mark.parametrize('fun_n_out', [(linalg.eigh_tridiagonal, 2), + (linalg.eigvalsh_tridiagonal, 1)]) + @pytest.mark.parametrize('dtype', real_floating) + # "Only real arrays currently supported" + def test_eigh_tridiagonal(self, fun_n_out, dtype): + rng = np.random.default_rng(8342310302941288912051) + fun, n_out = fun_n_out + d = get_random((3, 4, 5), dtype=dtype, rng=rng) + e = get_random((3, 4, 4), dtype=dtype, rng=rng) + self.batch_test(fun, (d, e), core_dim=1, n_out=n_out, broadcast=False) + + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_solve(self, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + b = get_random(bdim, dtype=dtype, rng=rng) + x = linalg.solve(A, b) + if len(bdim) == 1: + x = x[..., np.newaxis] + b = b[..., np.newaxis] + assert_allclose(A @ x - b, 0, atol=2e-6) + assert_allclose(x, np.linalg.solve(A, b), atol=3e-6) + + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_lu_solve(self, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + b = get_random(bdim, dtype=dtype, rng=rng) + lu_and_piv = linalg.lu_factor(A) + x = linalg.lu_solve(lu_and_piv, b) + if len(bdim) == 1: + x = x[..., np.newaxis] + b = b[..., np.newaxis] + assert_allclose(A @ x - b, 0, atol=2e-6) + assert_allclose(x, np.linalg.solve(A, b), atol=3e-6) + + @pytest.mark.parametrize('l_and_u', [(1, 1), ([2, 1, 0], [0, 1 , 2])]) + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_solve_banded(self, l_and_u, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + l, u = l_and_u + ab = get_random((2, 3, 3, 5), dtype=dtype, rng=rng) + b = get_random(bdim, dtype=dtype, rng=rng) + x = linalg.solve_banded((l, u), ab, b) + for i in range(2): + for j in range(3): + bij = b if len(bdim) <= 2 else b[i, j] + lj = l if np.ndim(l) == 0 else l[j] + uj = u if np.ndim(u) == 0 else u[j] + xij = linalg.solve_banded((lj, uj), ab[i, j], bij) + assert_allclose(x[i, j], xij) + + @pytest.mark.parametrize('separate_r', [False, True]) + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_solve_toeplitz(self, separate_r, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + c = get_random((2, 3, 5), dtype=dtype, rng=rng) + r = get_random((2, 3, 5), dtype=dtype, rng=rng) + c_or_cr = (c, r) if separate_r else c + b = get_random(bdim, dtype=dtype, rng=rng) + x = linalg.solve_toeplitz(c_or_cr, b) + for i in range(2): + for j in range(3): + bij = b if len(bdim) <= 2 else b[i, j] + c_or_cr_ij = (c[i, j], r[i, j]) if separate_r else c[i, j] + xij = linalg.solve_toeplitz(c_or_cr_ij, bij) + assert_allclose(x[i, j], xij) + + @pytest.mark.parametrize('separate_r', [False, True]) + @pytest.mark.parametrize('xdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_matmul_toeplitz(self, separate_r, xdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + c = get_random((2, 3, 5), dtype=dtype, rng=rng) + r = get_random((2, 3, 5), dtype=dtype, rng=rng) + c_or_cr = (c, r) if separate_r else c + x = get_random(xdim, dtype=dtype, rng=rng) + res = linalg.matmul_toeplitz(c_or_cr, x) + if separate_r: + ref = linalg.toeplitz(c, r) @ x + else: + ref = linalg.toeplitz(c) @ x + atol = 1e-6 if dtype in {np.float32, np.complex64} else 1e-12 + assert_allclose(res, ref, atol=atol) + + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_cho_solve(self, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng) + A = A + 5*np.eye(5) + c_and_lower = linalg.cho_factor(A) + b = get_random(bdim, dtype=dtype, rng=rng) + x = linalg.cho_solve(c_and_lower, b) + if len(bdim) == 1: + x = x[..., np.newaxis] + b = b[..., np.newaxis] + assert_allclose(A @ x - b, 0, atol=1e-6) + assert_allclose(x, np.linalg.solve(A, b), atol=2e-6) + + @pytest.mark.parametrize('lower', [False, True]) + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_cho_solve_banded(self, lower, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 3, 5), dtype=dtype, rng=rng) + row_diag = 0 if lower else -1 + A[:, :, row_diag] = 10 + cb = linalg.cholesky_banded(A, lower=lower) + b = get_random(bdim, dtype=dtype, rng=rng) + x = linalg.cho_solve_banded((cb, lower), b) + for i in range(2): + for j in range(3): + bij = b if len(bdim) <= 2 else b[i, j] + xij = linalg.cho_solve_banded((cb[i, j], lower), bij) + assert_allclose(x[i, j], xij) + + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_solveh_banded(self, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 3, 5), dtype=dtype, rng=rng) + A[:, :, -1] = 10 + b = get_random(bdim, dtype=dtype, rng=rng) + x = linalg.solveh_banded(A, b) + for i in range(2): + for j in range(3): + bij = b if len(bdim) <= 2 else b[i, j] + xij = linalg.solveh_banded(A[i, j], bij) + assert_allclose(x[i, j], xij) + + @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)]) + @pytest.mark.parametrize('dtype', floating) + def test_solve_triangular(self, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng) + A = np.tril(A) + b = get_random(bdim, dtype=dtype, rng=rng) + x = linalg.solve_triangular(A, b, lower=True) + if len(bdim) == 1: + x = x[..., np.newaxis] + b = b[..., np.newaxis] + atol = 1e-10 if dtype in (np.complex128, np.float64) else 2e-4 + assert_allclose(A @ x - b, 0, atol=atol) + assert_allclose(x, np.linalg.solve(A, b), atol=5*atol) + + @pytest.mark.parametrize('bdim', [(4,), (4, 3), (2, 3, 4, 3)]) + @pytest.mark.parametrize('dtype', floating) + def test_lstsq(self, bdim, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((2, 3, 4, 5), dtype=dtype, rng=rng) + b = get_random(bdim, dtype=dtype, rng=rng) + res = linalg.lstsq(A, b) + x = res[0] + if len(bdim) == 1: + x = x[..., np.newaxis] + b = b[..., np.newaxis] + assert_allclose(A @ x - b, 0, atol=2e-6) + assert len(res) == 4 + + @pytest.mark.parametrize('dtype', floating) + def test_clarkson_woodruff_transform(self, dtype): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 6), dtype=dtype, rng=rng) + self.batch_test(linalg.clarkson_woodruff_transform, A, + kwargs=dict(sketch_size=3, rng=311224)) + + def test_clarkson_woodruff_transform_sparse(self): + rng = np.random.default_rng(8342310302941288912051) + A = get_random((5, 3, 4, 6), dtype=np.float64, rng=rng) + A = sparse.coo_array(A) + message = "Batch support for sparse arrays is not available." + with pytest.raises(NotImplementedError, match=message): + linalg.clarkson_woodruff_transform(A, sketch_size=3, rng=rng) + + @pytest.mark.parametrize('f, args', [ + (linalg.toeplitz, (np.ones((0, 4)),)), + (linalg.eig, (np.ones((3, 0, 5, 5)),)), + ]) + def test_zero_size_batch(self, f, args): + message = "does not support zero-size batches." + with pytest.raises(ValueError, match=message): + f(*args) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_blas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_blas.py new file mode 100644 index 0000000000000000000000000000000000000000..6eefea9c53c30d2ca5c26da4a97ea0968f289576 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_blas.py @@ -0,0 +1,1037 @@ +# +# Created by: Pearu Peterson, April 2002 +# + +import math +import pytest +import numpy as np +from numpy.testing import (assert_equal, assert_almost_equal, + assert_array_almost_equal, assert_allclose) +from pytest import raises as assert_raises + +from numpy import (arange, triu, tril, zeros, tril_indices, ones, + diag, append, eye, nonzero) + +import scipy +from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve + +try: + from scipy.linalg import _cblas as cblas +except ImportError: + cblas = None + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +def test_get_blas_funcs(): + # check that it returns Fortran code for arrays that are + # fortran-ordered + f1, f2, f3 = get_blas_funcs( + ('axpy', 'axpy', 'axpy'), + (np.empty((2, 2), dtype=np.complex64, order='F'), + np.empty((2, 2), dtype=np.complex128, order='C')) + ) + + # get_blas_funcs will choose libraries depending on most generic + # array + assert_equal(f1.typecode, 'z') + assert_equal(f2.typecode, 'z') + if cblas is not None: + assert_equal(f1.module_name, 'cblas') + assert_equal(f2.module_name, 'cblas') + + # check defaults. + f1 = get_blas_funcs('rotg') + assert_equal(f1.typecode, 'd') + + # check also dtype interface + f1 = get_blas_funcs('gemm', dtype=np.complex64) + assert_equal(f1.typecode, 'c') + f1 = get_blas_funcs('gemm', dtype='F') + assert_equal(f1.typecode, 'c') + + # extended precision complex + f1 = get_blas_funcs('gemm', dtype=np.clongdouble) + assert_equal(f1.typecode, 'z') + + # check safe complex upcasting + f1 = get_blas_funcs('axpy', + (np.empty((2, 2), dtype=np.float64), + np.empty((2, 2), dtype=np.complex64)) + ) + assert_equal(f1.typecode, 'z') + + +def test_get_blas_funcs_alias(): + # check alias for get_blas_funcs + f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64) + assert f.typecode == 'c' + assert g.typecode == 'c' + + f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64) + assert f is g + assert f is h + + +def parametrize_blas(mod, func_name, prefixes): + if mod is None: + return pytest.mark.skip(reason="cblas not available") + params = [] + for prefix in prefixes: + if 'z' in prefix: + dtype = np.complex128 + elif 'c' in prefix: + dtype = np.complex64 + elif 'd' in prefix: + dtype = np.float64 + else: + assert 's' in prefix + dtype = np.float32 + + f = getattr(mod, prefix + func_name) + params.append(pytest.param(f, dtype, id=prefix + func_name)) + + return pytest.mark.parametrize("f,dtype", params) + + +class TestCBLAS1Simple: + @parametrize_blas(cblas, "axpy", "sdcz") + def test_axpy(self, f, dtype): + assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), + [7, 9, 18]) + if dtype in COMPLEX_DTYPES: + assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), + [7, 10j-1, 18]) + + +class TestFBLAS1Simple: + + @parametrize_blas(fblas, "axpy", "sdcz") + def test_axpy(self, f, dtype): + assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), + [7, 9, 18]) + if dtype in COMPLEX_DTYPES: + assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), + [7, 10j-1, 18]) + + @parametrize_blas(fblas, "copy", "sdcz") + def test_copy(self, f, dtype): + assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5]) + if dtype in COMPLEX_DTYPES: + assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j]) + + @parametrize_blas(fblas, "asum", ["s", "d", "sc", "dz"]) + def test_asum(self, f, dtype): + assert_almost_equal(f([3, -4, 5]), 12) + if dtype in COMPLEX_DTYPES: + assert_almost_equal(f([3j, -4, 3-4j]), 14) + + @parametrize_blas(fblas, "dot", "sd") + def test_dot(self, f, dtype): + assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9) + + @parametrize_blas(fblas, "dotu", "cz") + def test_dotu(self, f, dtype): + assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j) + + @parametrize_blas(fblas, "dotc", "cz") + def test_dotc(self, f, dtype): + assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j) + + @parametrize_blas(fblas, "nrm2", ["s", "d", "sc", "dz"]) + def test_nrm2(self, f, dtype): + assert_almost_equal(f([3, -4, 5]), math.sqrt(50)) + if dtype in COMPLEX_DTYPES: + assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50)) + + @parametrize_blas(fblas, "scal", ["s", "d", "cs", "zd"]) + def test_scal(self, f, dtype): + assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10]) + if dtype in COMPLEX_DTYPES: + assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j]) + + @parametrize_blas(fblas, "swap", "sdcz") + def test_swap(self, f, dtype): + x, y = [2, 3, 1], [-2, 3, 7] + x1, y1 = f(x, y) + assert_array_almost_equal(x1, y) + assert_array_almost_equal(y1, x) + + if dtype in COMPLEX_DTYPES: + x, y = [2, 3j, 1], [-2, 3, 7-3j] + x1, y1 = f(x, y) + assert_array_almost_equal(x1, y) + assert_array_almost_equal(y1, x) + + @parametrize_blas(fblas, "amax", ["is", "id", "ic", "iz"]) + def test_amax(self, f, dtype): + assert_equal(f([-2, 4, 3]), 1) + if dtype in COMPLEX_DTYPES: + assert_equal(f([-5, 4+3j, 6]), 1) + + # XXX: need tests for rot,rotm,rotg,rotmg + + +class TestFBLAS2Simple: + @parametrize_blas(fblas, "gemv", "sdcz") + def test_gemv(self, f, dtype): + assert_array_almost_equal(f(3, [[3]], [-4]), [-36]) + assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21]) + if dtype in COMPLEX_DTYPES: + assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j]) + assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]), + [-48-21j]) + + @parametrize_blas(fblas, "ger", "sd") + def test_ger(self, f, dtype): + assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]]) + assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]), + [[6, 8], [12, 16], [18, 24]]) + assert_array_almost_equal(f(1, [1, 2], [3, 4], + a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]]) + if dtype in COMPLEX_DTYPES: + assert_array_almost_equal(f(1, [1j, 2], [3, 4]), + [[3j, 4j], [6, 8]]) + assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]), + [[6, 8], [12, 16], [18, 24]]) + + @parametrize_blas(fblas, "geru", "cz") + def test_geru(self, f, dtype): + assert_array_almost_equal(f(1, [1j, 2], [3, 4]), + [[3j, 4j], [6, 8]]) + assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]), + [[6, 8], [12, 16], [18, 24]]) + + @parametrize_blas(fblas, "gerc", "cz") + def test_gerc(self, f, dtype): + assert_array_almost_equal(f(1, [1j, 2], [3, 4]), + [[3j, 4j], [6, 8]]) + assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]), + [[6, 8], [12, 16], [18, 24]]) + + @parametrize_blas(fblas, "syr", "sdcz") + def test_syr(self, f, dtype): + x = np.arange(1, 5, dtype='d') + resx = np.triu(x[:, np.newaxis] * x) + resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1]) + y = np.linspace(0, 8.5, 17, endpoint=False) + z = np.arange(1, 9, dtype='d').view('D') + resz = np.triu(z[:, np.newaxis] * z) + resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1]) + w = np.c_[np.zeros(4), z, np.zeros(4)].ravel() + + rtol = np.finfo(dtype).eps + + assert_allclose(f(1.0, x), resx, rtol=rtol) + assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol) + assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, y, incx=-2, offx=2, n=4), + resx_reverse, rtol=rtol) + + if dtype in COMPLEX_DTYPES: + assert_allclose(f(1.0, z), resz, rtol=rtol) + assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol) + assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), + resz_reverse, rtol=rtol) + + a = np.zeros((4, 4), dtype, 'F') + b = f(1.0, z, a=a, overwrite_a=True) + assert_allclose(a, resz, rtol=rtol) + b = f(2.0, z, a=a) + assert a is not b + assert_allclose(b, 3*resz, rtol=rtol) + + else: + a = np.zeros((4, 4), dtype, 'F') + b = f(1.0, x, a=a, overwrite_a=True) + assert_allclose(a, resx, rtol=rtol) + b = f(2.0, x, a=a) + assert a is not b + assert_allclose(b, 3*resx, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, incx=0) + assert_raises(Exception, f, 1.0, x, offx=5) + assert_raises(Exception, f, 1.0, x, offx=-2) + assert_raises(Exception, f, 1.0, x, n=-2) + assert_raises(Exception, f, 1.0, x, n=5) + assert_raises(Exception, f, 1.0, x, lower=2) + assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) + + @parametrize_blas(fblas, "her", "cz") + def test_her(self, f, dtype): + x = np.arange(1, 5, dtype='d') + z = np.arange(1, 9, dtype='d').view('D') + rehz = np.triu(z[:, np.newaxis] * z.conj()) + rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj()) + w = np.c_[np.zeros(4), z, np.zeros(4)].ravel() + + rtol = np.finfo(dtype).eps + + assert_allclose(f(1.0, z), rehz, rtol=rtol) + assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol) + assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), + rehz_reverse, rtol=rtol) + + a = np.zeros((4, 4), dtype, 'F') + b = f(1.0, z, a=a, overwrite_a=True) + assert_allclose(a, rehz, rtol=rtol) + + b = f(2.0, z, a=a) + assert a is not b + assert_allclose(b, 3*rehz, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, incx=0) + assert_raises(Exception, f, 1.0, x, offx=5) + assert_raises(Exception, f, 1.0, x, offx=-2) + assert_raises(Exception, f, 1.0, x, n=-2) + assert_raises(Exception, f, 1.0, x, n=5) + assert_raises(Exception, f, 1.0, x, lower=2) + assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) + + @parametrize_blas(fblas, "syr2", "sd") + def test_syr2(self, f, dtype): + x = np.arange(1, 5, dtype='d') + y = np.arange(5, 9, dtype='d') + resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x) + resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1] + + y[::-1, np.newaxis] * x[::-1]) + + q = np.linspace(0, 8.5, 17, endpoint=False) + rtol = np.finfo(dtype).eps + + assert_allclose(f(1.0, x, y), resxy, rtol=rtol) + assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) + assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol) + + assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10), + resxy, rtol=rtol) + assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3), + resxy[:3, :3], rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10), + resxy_reverse, rtol=rtol) + + a = np.zeros((4, 4), dtype, 'F') + b = f(1.0, x, y, a=a, overwrite_a=True) + assert_allclose(a, resxy, rtol=rtol) + + b = f(2.0, x, y, a=a) + assert a is not b + assert_allclose(b, 3*resxy, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, y, incx=0) + assert_raises(Exception, f, 1.0, x, y, offx=5) + assert_raises(Exception, f, 1.0, x, y, offx=-2) + assert_raises(Exception, f, 1.0, x, y, incy=0) + assert_raises(Exception, f, 1.0, x, y, offy=5) + assert_raises(Exception, f, 1.0, x, y, offy=-2) + assert_raises(Exception, f, 1.0, x, y, n=-2) + assert_raises(Exception, f, 1.0, x, y, n=5) + assert_raises(Exception, f, 1.0, x, y, lower=2) + assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2, 2), 'd', 'F')) + + @parametrize_blas(fblas, "her2", "cz") + def test_her2(self, f, dtype): + x = np.arange(1, 9, dtype='d').view('D') + y = np.arange(9, 17, dtype='d').view('D') + resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj() + resxy = np.triu(resxy) + + resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj() + resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj() + resxy_reverse = np.triu(resxy_reverse) + + u = np.c_[np.zeros(4), x, np.zeros(4)].ravel() + v = np.c_[np.zeros(4), y, np.zeros(4)].ravel() + + rtol = np.finfo(dtype).eps + + assert_allclose(f(1.0, x, y), resxy, rtol=rtol) + assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) + assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(), + rtol=rtol) + + assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1), + resxy, rtol=rtol) + assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3), + resxy[:3, :3], rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1), + resxy_reverse, rtol=rtol) + + a = np.zeros((4, 4), dtype, 'F') + b = f(1.0, x, y, a=a, overwrite_a=True) + assert_allclose(a, resxy, rtol=rtol) + + b = f(2.0, x, y, a=a) + assert a is not b + assert_allclose(b, 3*resxy, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, y, incx=0) + assert_raises(Exception, f, 1.0, x, y, offx=5) + assert_raises(Exception, f, 1.0, x, y, offx=-2) + assert_raises(Exception, f, 1.0, x, y, incy=0) + assert_raises(Exception, f, 1.0, x, y, offy=5) + assert_raises(Exception, f, 1.0, x, y, offy=-2) + assert_raises(Exception, f, 1.0, x, y, n=-2) + assert_raises(Exception, f, 1.0, x, y, n=5) + assert_raises(Exception, f, 1.0, x, y, lower=2) + assert_raises(Exception, f, 1.0, x, y, + a=np.zeros((2, 2), 'd', 'F')) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_gbmv(self, dtype): + rng = np.random.default_rng(1234) + n = 7 + m = 5 + kl = 1 + ku = 2 + # fake a banded matrix via toeplitz + A = toeplitz(append(rng.random(kl+1), zeros(m-kl-1)), + append(rng.random(ku+1), zeros(n-ku-1))) + A = A.astype(dtype) + Ab = zeros((kl+ku+1, n), dtype=dtype) + + # Form the banded storage + Ab[2, :5] = A[0, 0] # diag + Ab[1, 1:6] = A[0, 1] # sup1 + Ab[0, 2:7] = A[0, 2] # sup2 + Ab[3, :4] = A[1, 0] # sub1 + + x = rng.random(n).astype(dtype) + y = rng.random(m).astype(dtype) + alpha, beta = dtype(3), dtype(-5) + + func, = get_blas_funcs(('gbmv',), dtype=dtype) + y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab, + x=x, y=y, beta=beta) + y2 = alpha * A.dot(x) + beta * y + assert_array_almost_equal(y1, y2) + + y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab, + x=y, y=x, beta=beta, trans=1) + y2 = alpha * A.T.dot(y) + beta * x + assert_array_almost_equal(y1, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_sbmv_hbmv(self, dtype): + rng = np.random.default_rng(1234) + n = 6 + k = 2 + A = zeros((n, n), dtype=dtype) + Ab = zeros((k+1, n), dtype=dtype) + + # Form the array and its packed banded storage + A[arange(n), arange(n)] = rng.random(n) + for ind2 in range(1, k+1): + temp = rng.random(n-ind2) + A[arange(n-ind2), arange(ind2, n)] = temp + Ab[-1-ind2, ind2:] = temp + A = A.astype(dtype) + if dtype in COMPLEX_DTYPES: + A += A.conj().T + func, = get_blas_funcs(('hbmv',), dtype=dtype) + else: + A += A.T + func, = get_blas_funcs(('sbmv',), dtype=dtype) + + Ab[-1, :] = diag(A) + x = rng.random(n).astype(dtype) + y = rng.random(n).astype(dtype) + alpha, beta = dtype(1.25), dtype(3) + + y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta) + y2 = alpha * A.dot(x) + beta * y + assert_array_almost_equal(y1, y2) + + @pytest.mark.parametrize("fname,dtype", [ + *[('spmv', dtype) for dtype in REAL_DTYPES + COMPLEX_DTYPES], + *[('hpmv', dtype) for dtype in COMPLEX_DTYPES], + ]) + def test_spmv_hpmv(self, fname, dtype): + rng = np.random.default_rng(1234) + n = 3 + A = rng.random((n, n)).astype(dtype) + if dtype in COMPLEX_DTYPES: + A += rng.random((n, n))*1j + A += A.T if fname == 'spmv' else A.conj().T + c, r = tril_indices(n) + Ap = A[r, c] + x = rng.random(n).astype(dtype) + y = rng.random(n).astype(dtype) + xlong = arange(2*n).astype(dtype) + ylong = ones(2*n).astype(dtype) + alpha, beta = dtype(1.25), dtype(2) + + func, = get_blas_funcs((fname,), dtype=dtype) + y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta) + y2 = alpha * A.dot(x) + beta * y + assert_array_almost_equal(y1, y2) + + # Test inc and offsets + y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap, + incx=2, incy=2, offx=n, offy=n) + y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2] + assert_array_almost_equal(y1[3::2], y2) + assert_almost_equal(y1[4], ylong[4]) + + @pytest.mark.parametrize("fname,dtype", [ + *[('spr', dtype) for dtype in REAL_DTYPES + COMPLEX_DTYPES], + *[('hpr', dtype) for dtype in COMPLEX_DTYPES], + ]) + def test_spr_hpr(self, fname, dtype): + rng = np.random.default_rng(1234) + n = 3 + A = rng.random((n, n)).astype(dtype) + if dtype in COMPLEX_DTYPES: + A += rng.random((n, n))*1j + A += A.T if fname == 'spr' else A.conj().T + c, r = tril_indices(n) + Ap = A[r, c] + x = rng.random(n).astype(dtype) + + alpha = np.finfo(dtype).dtype.type(2.5) + if fname == 'hpr': + func, = get_blas_funcs(('hpr',), dtype=dtype) + y2 = alpha * x[:, None].dot(x[None, :].conj()) + A + else: + func, = get_blas_funcs(('spr',), dtype=dtype) + y2 = alpha * x[:, None].dot(x[None, :]) + A + + y1 = func(n=n, alpha=alpha, ap=Ap, x=x) + y1f = zeros((3, 3), dtype=dtype) + y1f[r, c] = y1 + y1f[c, r] = y1.conj() if fname == 'hpr' else y1 + assert_array_almost_equal(y1f, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_spr2_hpr2(self, dtype): + rng = np.random.default_rng(1234) + n = 3 + A = rng.random((n, n)).astype(dtype) + if dtype in COMPLEX_DTYPES: + A += rng.random((n, n))*1j + A += A.conj().T + func, = get_blas_funcs(('hpr2',), dtype=dtype) + else: + A += A.T + func, = get_blas_funcs(('spr2',), dtype=dtype) + + c, r = tril_indices(n) + Ap = A[r, c] + x = rng.random(n).astype(dtype) + y = rng.random(n).astype(dtype) + alpha = dtype(2) + + u = alpha.conj() * x[:, None].dot(y[None, :].conj()) + y2 = A + u + u.conj().T + y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap) + y1f = zeros((3, 3), dtype=dtype) + y1f[r, c] = y1 + y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj() + assert_array_almost_equal(y1f, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_tbmv(self, dtype): + rng = np.random.default_rng(1234) + n = 10 + k = 3 + x = rng.random(n).astype(dtype) + A = zeros((n, n), dtype=dtype) + # Banded upper triangular array + for sup in range(k+1): + A[arange(n-sup), arange(sup, n)] = rng.random(n-sup) + + # Add complex parts for c,z + if dtype in COMPLEX_DTYPES: + A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype) + + # Form the banded storage + Ab = zeros((k+1, n), dtype=dtype) + for row in range(k+1): + Ab[-row-1, row:] = diag(A, k=row) + func, = get_blas_funcs(('tbmv',), dtype=dtype) + + y1 = func(k=k, a=Ab, x=x) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) + y2 = A.T.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) + y2 = A.conj().T.dot(x) + assert_array_almost_equal(y1, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_tbsv(self, dtype): + rng = np.random.default_rng(12345) + n = 6 + k = 3 + x = rng.random(n).astype(dtype) + A = zeros((n, n), dtype=dtype) + # Banded upper triangular array + for sup in range(k+1): + A[arange(n-sup), arange(sup, n)] = rng.random(n-sup) + + # Add complex parts for c,z + if dtype in COMPLEX_DTYPES: + A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype) + + # Form the banded storage + Ab = zeros((k+1, n), dtype=dtype) + for row in range(k+1): + Ab[-row-1, row:] = diag(A, k=row) + func, = get_blas_funcs(('tbsv',), dtype=dtype) + + y1 = func(k=k, a=Ab, x=x) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) + y2 = solve(A.T, x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) + y2 = solve(A.conj().T, x) + assert_array_almost_equal(y1, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_tpmv(self, dtype): + rng = np.random.default_rng(1234) + n = 10 + x = rng.random(n).astype(dtype) + # Upper triangular array + if dtype in COMPLEX_DTYPES: + A = triu(rng.random((n, n)) + rng.random((n, n))*1j) + else: + A = triu(rng.random((n, n))) + + # Form the packed storage + c, r = tril_indices(n) + Ap = A[r, c] + func, = get_blas_funcs(('tpmv',), dtype=dtype) + + y1 = func(n=n, ap=Ap, x=x) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) + y2 = A.T.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) + y2 = A.conj().T.dot(x) + assert_array_almost_equal(y1, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_tpsv(self, dtype): + rng = np.random.default_rng(1234) + n = 10 + x = rng.random(n).astype(dtype) + # Upper triangular array + if dtype in COMPLEX_DTYPES: + A = triu(rng.random((n, n)) + rng.random((n, n))*1j) + else: + A = triu(rng.random((n, n))) + A += eye(n) + # Form the packed storage + c, r = tril_indices(n) + Ap = A[r, c] + func, = get_blas_funcs(('tpsv',), dtype=dtype) + + y1 = func(n=n, ap=Ap, x=x) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) + y2 = solve(A.T, x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) + y2 = solve(A.conj().T, x) + assert_array_almost_equal(y1, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_trmv(self, dtype): + rng = np.random.default_rng(1234) + n = 3 + A = (rng.random((n, n))+eye(n)).astype(dtype) + x = rng.random(3).astype(dtype) + func, = get_blas_funcs(('trmv',), dtype=dtype) + + y1 = func(a=A, x=x) + y2 = triu(A).dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = triu(A).dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=1) + y2 = triu(A).T.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=2) + y2 = triu(A).conj().T.dot(x) + assert_array_almost_equal(y1, y2) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_trsv(self, dtype): + rng = np.random.default_rng(1234) + n = 15 + A = (rng.random((n, n))+eye(n)).astype(dtype) + x = rng.random(n).astype(dtype) + func, = get_blas_funcs(('trsv',), dtype=dtype) + + y1 = func(a=A, x=x) + y2 = solve(triu(A), x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, lower=1) + y2 = solve(tril(A), x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = solve(triu(A), x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=1) + y2 = solve(triu(A).T, x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=2) + y2 = solve(triu(A).conj().T, x) + assert_array_almost_equal(y1, y2) + + +class TestFBLAS3Simple: + @parametrize_blas(fblas, "gemm", "sdcz") + def test_gemm(self, f, dtype): + assert_array_almost_equal(f(3, [3], [-4]), [[-36]]) + assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21]) + if dtype in COMPLEX_DTYPES: + assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]]) + assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j]) + + +class TestBLAS3Symm: + + def setup_method(self): + self.a = np.array([[1., 2.], + [0., 1.]]) + self.b = np.array([[1., 0., 3.], + [0., -1., 2.]]) + self.c = np.ones((2, 3)) + self.t = np.array([[2., -1., 8.], + [3., 0., 9.]]) + + @parametrize_blas(fblas, "symm", "sdcz") + def test_symm(self, f, dtype): + res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) + assert_array_almost_equal(res, self.t) + + res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) + assert_array_almost_equal(res, self.t) + + res = f(a=self.a, b=self.b.T, side=1, c=self.c.T, + alpha=1., beta=1.) + assert_array_almost_equal(res, self.t.T) + + @parametrize_blas(fblas, "symm", "sdcz") + def test_symm_wrong_side(self, f, dtype): + """`side=1` means C <- B*A, hence shapes of A and B are to be + compatible. Otherwise, f2py exception is raised. + """ + # FIXME narrow down to _fblas.error + with pytest.raises(Exception): + f(a=self.a, b=self.b, alpha=1, side=1) + + @parametrize_blas(fblas, "symm", "sdcz") + def test_symm_wrong_uplo(self, f, dtype): + """SYMM only considers the upper/lower part of A. Hence setting + wrong value for `lower` (default is lower=0, meaning upper triangle) + gives a wrong result. + """ + res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) + assert np.allclose(res, self.t) + res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) + assert not np.allclose(res, self.t) + + +class TestBLAS3Syrk: + def setup_method(self): + self.a = np.array([[1., 0.], + [0., -2.], + [2., 3.]]) + self.t = np.array([[1., 0., 2.], + [0., 4., -6.], + [2., -6., 13.]]) + self.tt = np.array([[5., 6.], + [6., 13.]]) + + @parametrize_blas(fblas, "syrk", "sdcz") + def test_syrk(self, f, dtype): + c = f(a=self.a, alpha=1.) + assert_array_almost_equal(np.triu(c), np.triu(self.t)) + + c = f(a=self.a, alpha=1., lower=1) + assert_array_almost_equal(np.tril(c), np.tril(self.t)) + + c0 = np.ones(self.t.shape) + c = f(a=self.a, alpha=1., beta=1., c=c0) + assert_array_almost_equal(np.triu(c), np.triu(self.t+c0)) + + c = f(a=self.a, alpha=1., trans=1) + assert_array_almost_equal(np.triu(c), np.triu(self.tt)) + + # prints '0-th dimension must be fixed to 3 but got 5', + # FIXME: suppress? + @parametrize_blas(fblas, "syrk", "sdcz") + def test_syrk_wrong_c(self, f, dtype): + # FIXME narrow down to _fblas.error + with pytest.raises(Exception): + f(a=self.a, alpha=1., c=np.ones((5, 8))) + # if C is supplied, it must have compatible dimensions + + +class TestBLAS3Syr2k: + def setup_method(self): + self.a = np.array([[1., 0.], + [0., -2.], + [2., 3.]]) + self.b = np.array([[0., 1.], + [1., 0.], + [0, 1.]]) + self.t = np.array([[0., -1., 3.], + [-1., 0., 0.], + [3., 0., 6.]]) + self.tt = np.array([[0., 1.], + [1., 6]]) + + @parametrize_blas(fblas, "syr2k", "sdcz") + def test_syr2k(self, f, dtype): + c = f(a=self.a, b=self.b, alpha=1.) + assert_array_almost_equal(np.triu(c), np.triu(self.t)) + + c = f(a=self.a, b=self.b, alpha=1., lower=1) + assert_array_almost_equal(np.tril(c), np.tril(self.t)) + + c0 = np.ones(self.t.shape) + c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0) + assert_array_almost_equal(np.triu(c), np.triu(self.t+c0)) + + c = f(a=self.a, b=self.b, alpha=1., trans=1) + assert_array_almost_equal(np.triu(c), np.triu(self.tt)) + + # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress? + @parametrize_blas(fblas, "syr2k", "sdcz") + def test_syr2k_wrong_c(self, f, dtype): + with pytest.raises(Exception): + f(a=self.a, b=self.b, alpha=1., c=np.zeros((15, 8))) + # if C is supplied, it must have compatible dimensions + + +class TestSyHe: + """Quick and simple tests for (zc)-symm, syrk, syr2k.""" + + def setup_method(self): + self.sigma_y = np.array([[0., -1.j], + [1.j, 0.]]) + + @parametrize_blas(fblas, "symm", "zc") + def test_symm(self, f, dtype): + # NB: a is symmetric w/upper diag of ONLY + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([1, -1])) + + @parametrize_blas(fblas, "hemm", "zc") + def test_hemm(self, f, dtype): + # NB: a is hermitian w/upper diag of ONLY + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([1, 1])) + + @parametrize_blas(fblas, "syrk", "zc") + def test_syrk(self, f, dtype): + res = f(a=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([-1, -1])) + + @parametrize_blas(fblas, "herk", "zc") + def test_herk(self, f, dtype): + res = f(a=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([1, 1])) + + @parametrize_blas(fblas, "syr2k", "zc") + def test_syr2k_zr(self, f, dtype): + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1])) + + @parametrize_blas(fblas, "her2k", "zc") + def test_her2k_zr(self, f, dtype): + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1])) + + +class TestTRMM: + """Quick and simple tests for *trmm.""" + + def setup_method(self): + self.a = np.array([[1., 2., ], + [-2., 1.]]) + self.b = np.array([[3., 4., -1.], + [5., 6., -2.]]) + + self.a2 = np.array([[1, 1, 2, 3], + [0, 1, 4, 5], + [0, 0, 1, 6], + [0, 0, 0, 1]], order="f") + self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]], + order="f") + + @pytest.mark.parametrize("dtype", DTYPES) + def test_side(self, dtype): + trmm = get_blas_funcs("trmm", dtype=dtype) + # Provide large A array that works for side=1 but not 0 (see gh-10841) + assert_raises(Exception, trmm, 1.0, self.a2, self.b2) + res = trmm(1.0, self.a2.astype(dtype), self.b2.astype(dtype), + side=1) + k = self.b2.shape[1] + assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0., + atol=100*np.finfo(dtype).eps) + + @parametrize_blas(fblas, "trmm", "sdcz") + def test_ab(self, f, dtype): + result = f(1., self.a, self.b) + # default a is upper triangular + expected = np.array([[13., 16., -5.], + [ 5., 6., -2.]]) + assert_array_almost_equal(result, expected) + + @parametrize_blas(fblas, "trmm", "sdcz") + def test_ab_lower(self, f, dtype): + result = f(1., self.a, self.b, lower=True) + expected = np.array([[ 3., 4., -1.], + [-1., -2., 0.]]) # now a is lower triangular + assert_array_almost_equal(result, expected) + + @parametrize_blas(fblas, "trmm", "sdcz") + def test_b_overwrites(self, f, dtype): + # BLAS *trmm modifies B argument in-place. + # Here the default is to copy, but this can be overridden + b = self.b.astype(dtype) + for overwr in [True, False]: + bcopy = b.copy() + result = f(1., self.a, bcopy, overwrite_b=overwr) + # C-contiguous arrays are copied + assert not bcopy.flags.f_contiguous + assert not np.may_share_memory(bcopy, result) + assert_equal(bcopy, b) + + bcopy = np.asfortranarray(b.copy()) # or just transpose it + result = f(1., self.a, bcopy, overwrite_b=True) + assert bcopy.flags.f_contiguous + assert np.may_share_memory(bcopy, result) + assert_array_almost_equal(bcopy, result) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_trsm(dtype): + rng = np.random.default_rng(1234) + tol = np.finfo(dtype).eps*1000 + func, = get_blas_funcs(('trsm',), dtype=dtype) + + # Test protection against size mismatches + A = rng.random((4, 5)).astype(dtype) + B = rng.random((4, 4)).astype(dtype) + alpha = dtype(1) + assert_raises(Exception, func, alpha, A, B) + assert_raises(Exception, func, alpha, A.T, B) + + n = 8 + m = 7 + alpha = dtype(-2.5) + if dtype in COMPLEX_DTYPES: + A = (rng.random((m, m)) + rng.random((m, m))*1j) + eye(m) + else: + A = rng.random((m, m)) + eye(m) + A = A.astype(dtype) + Au = triu(A) + Al = tril(A) + B1 = rng.random((m, n)).astype(dtype) + B2 = rng.random((n, m)).astype(dtype) + + x1 = func(alpha=alpha, a=A, b=B1) + assert_equal(B1.shape, x1.shape) + x2 = solve(Au, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B1, trans_a=1) + x2 = solve(Au.T, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B1, trans_a=2) + x2 = solve(Au.conj().T, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B1, diag=1) + Au[arange(m), arange(m)] = dtype(1) + x2 = solve(Au, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1) + x2 = solve(Au.conj().T, alpha*B2.conj().T) + assert_allclose(x1, x2.conj().T, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1) + Al[arange(m), arange(m)] = dtype(1) + x2 = solve(Al.conj().T, alpha*B2.conj().T) + assert_allclose(x1, x2.conj().T, atol=tol) + + +@pytest.mark.xfail(run=False, + reason="gh-16930") +def test_gh_169309(): + x = np.repeat(10, 9) + actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1) + expected = math.sqrt(500) + assert_allclose(actual, expected) + + +def test_dnrm2_neg_incx(): + # check that dnrm2(..., incx < 0) raises + # XXX: remove the test after the lowest supported BLAS implements + # negative incx (new in LAPACK 3.10) + x = np.repeat(10, 9) + incx = -1 + with assert_raises(fblas.__fblas_error): + scipy.linalg.blas.dnrm2(x, 5, 3, incx) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cython_blas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cython_blas.py new file mode 100644 index 0000000000000000000000000000000000000000..9926191963b6fc59e636b2ce3ba790ff6b030afb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cython_blas.py @@ -0,0 +1,118 @@ +import numpy as np +from numpy.testing import (assert_allclose, + assert_equal) +import scipy.linalg.cython_blas as blas + +class TestDGEMM: + + def test_transposes(self): + + a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2] + b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2] + c = np.empty((2, 4))[:2,:2] + + blas._test_dgemm(1., a, b, 0., c) + assert_allclose(c, a.dot(b)) + + blas._test_dgemm(1., a.T, b, 0., c) + assert_allclose(c, a.T.dot(b)) + + blas._test_dgemm(1., a, b.T, 0., c) + assert_allclose(c, a.dot(b.T)) + + blas._test_dgemm(1., a.T, b.T, 0., c) + assert_allclose(c, a.T.dot(b.T)) + + blas._test_dgemm(1., a, b, 0., c.T) + assert_allclose(c, a.dot(b).T) + + blas._test_dgemm(1., a.T, b, 0., c.T) + assert_allclose(c, a.T.dot(b).T) + + blas._test_dgemm(1., a, b.T, 0., c.T) + assert_allclose(c, a.dot(b.T).T) + + blas._test_dgemm(1., a.T, b.T, 0., c.T) + assert_allclose(c, a.T.dot(b.T).T) + + def test_shapes(self): + a = np.arange(6, dtype='d').reshape((3, 2)) + b = np.arange(-6, 2, dtype='d').reshape((2, 4)) + c = np.empty((3, 4)) + + blas._test_dgemm(1., a, b, 0., c) + assert_allclose(c, a.dot(b)) + + blas._test_dgemm(1., b.T, a.T, 0., c.T) + assert_allclose(c, b.T.dot(a.T).T) + +class TestWfuncPointers: + """ Test the function pointers that are expected to fail on + Mac OS X without the additional entry statement in their definitions + in fblas_l1.pyf.src. """ + + def test_complex_args(self): + + cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64) + cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64) + + assert_allclose(blas._test_cdotc(cx, cy), + -17.6468753815+21.3718757629j) + assert_allclose(blas._test_cdotu(cx, cy), + -6.11562538147+30.3156242371j) + + assert_equal(blas._test_icamax(cx), 3) + + assert_allclose(blas._test_scasum(cx), 18.625) + assert_allclose(blas._test_scnrm2(cx), 13.1796483994) + + assert_allclose(blas._test_cdotc(cx[::2], cy[::2]), + -18.1000003815+21.2000007629j) + assert_allclose(blas._test_cdotu(cx[::2], cy[::2]), + -6.10000038147+30.7999992371j) + assert_allclose(blas._test_scasum(cx[::2]), 18.) + assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499) + + def test_double_args(self): + + x = np.array([5., -3, -.5], np.float64) + y = np.array([2, 1, .5], np.float64) + + assert_allclose(blas._test_dasum(x), 8.5) + assert_allclose(blas._test_ddot(x, y), 6.75) + assert_allclose(blas._test_dnrm2(x), 5.85234975815) + + assert_allclose(blas._test_dasum(x[::2]), 5.5) + assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75) + assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297) + + assert_equal(blas._test_idamax(x), 1) + + def test_float_args(self): + + x = np.array([5., -3, -.5], np.float32) + y = np.array([2, 1, .5], np.float32) + + assert_equal(blas._test_isamax(x), 1) + + assert_allclose(blas._test_sasum(x), 8.5) + assert_allclose(blas._test_sdot(x, y), 6.75) + assert_allclose(blas._test_snrm2(x), 5.85234975815) + + assert_allclose(blas._test_sasum(x[::2]), 5.5) + assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75) + assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297) + + def test_double_complex_args(self): + + cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128) + cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128) + + assert_equal(blas._test_izamax(cx), 3) + + assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j) + assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j) + + assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j) + assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cython_lapack.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cython_lapack.py new file mode 100644 index 0000000000000000000000000000000000000000..763cd8a01e232cf842cf8aa03836aabafe56b193 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cython_lapack.py @@ -0,0 +1,22 @@ +from numpy.testing import assert_allclose +from scipy.linalg import cython_lapack as cython_lapack +from scipy.linalg import lapack + + +class TestLamch: + + def test_slamch(self): + for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']: + assert_allclose(cython_lapack._test_slamch(c), + lapack.slamch(c)) + + def test_dlamch(self): + for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']: + assert_allclose(cython_lapack._test_dlamch(c), + lapack.dlamch(c)) + + def test_complex_ladiv(self): + cx = .5 + 1.j + cy = .875 + 2.j + assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j) + assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f82ee5b88b840053810e7f555c56136e6d469384 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py @@ -0,0 +1,134 @@ +import numpy as np +from scipy.linalg import bandwidth, issymmetric, ishermitian +from scipy.conftest import skip_xp_invalid_arg +import pytest +from pytest import raises + + +@skip_xp_invalid_arg +def test_bandwidth_dtypes(): + n = 5 + for t in np.typecodes['All']: + A = np.zeros([n, n], dtype=t) + if t in 'eUVOMm': + raises(TypeError, bandwidth, A) + elif t == 'G': # No-op test. On win these pass on others fail. + pass + else: + _ = bandwidth(A) + + +def test_bandwidth_non2d_input(): + A = np.array([1, 2, 3]) + raises(ValueError, bandwidth, A) + + +@pytest.mark.parametrize('T', [x for x in np.typecodes['All'] + if x not in 'eGUVOMmS']) +def test_bandwidth_square_inputs(T): + n = 20 + k = 4 + R = np.zeros([n, n], dtype=T, order='F') + # form a banded matrix inplace + R[[x for x in range(n)], [x for x in range(n)]] = 1 + R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1 + R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1 + R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1 + assert bandwidth(R) == (k, k) + A = np.array([ + [1, 1, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + ]) + assert bandwidth(A) == (2, 2) + + +@skip_xp_invalid_arg +@pytest.mark.parametrize('T', [x for x in np.typecodes['All'] + if x not in 'eGUVOMm']) +def test_bandwidth_rect_inputs(T): + n, m = 10, 20 + k = 5 + R = np.zeros([n, m], dtype=T, order='F') + # form a banded matrix inplace + R[[x for x in range(n)], [x for x in range(n)]] = 1 + R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1 + R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1 + R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1 + assert bandwidth(R) == (k, k) + + +@skip_xp_invalid_arg +def test_issymetric_ishermitian_dtypes(): + n = 5 + for t in np.typecodes['All']: + A = np.zeros([n, n], dtype=t) + if t in 'eUVOMm': + raises(TypeError, issymmetric, A) + raises(TypeError, ishermitian, A) + elif t == 'G': # No-op test. On win these pass on others fail. + pass + else: + assert issymmetric(A) + assert ishermitian(A) + + +def test_issymmetric_ishermitian_invalid_input(): + A = np.array([1, 2, 3]) + raises(ValueError, issymmetric, A) + raises(ValueError, ishermitian, A) + A = np.array([[[1, 2, 3], [4, 5, 6]]]) + raises(ValueError, issymmetric, A) + raises(ValueError, ishermitian, A) + A = np.array([[1, 2, 3], [4, 5, 6]]) + raises(ValueError, issymmetric, A) + raises(ValueError, ishermitian, A) + + +def test_issymetric_complex_decimals(): + A = np.arange(1, 10).astype(complex).reshape(3, 3) + A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j + # make entries decimal + A /= np.pi + A = A + A.T + assert issymmetric(A) + + +def test_ishermitian_complex_decimals(): + A = np.arange(1, 10).astype(complex).reshape(3, 3) + A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j + # make entries decimal + A /= np.pi + A = A + A.T.conj() + assert ishermitian(A) + + +def test_issymmetric_approximate_results(): + n = 20 + rng = np.random.RandomState(123456789) + x = rng.uniform(high=5., size=[n, n]) + y = x @ x.T # symmetric + p = rng.standard_normal([n, n]) + z = p @ y @ p.T + assert issymmetric(z, atol=1e-10) + assert issymmetric(z, atol=1e-10, rtol=0.) + assert issymmetric(z, atol=0., rtol=1e-12) + assert issymmetric(z, atol=1e-13, rtol=1e-12) + + +def test_ishermitian_approximate_results(): + n = 20 + rng = np.random.RandomState(987654321) + x = rng.uniform(high=5., size=[n, n]) + y = x @ x.T # symmetric + p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j + z = p @ y @ p.conj().T + assert ishermitian(z, atol=1e-10) + assert ishermitian(z, atol=1e-10, rtol=0.) + assert ishermitian(z, atol=0., rtol=1e-12) + assert ishermitian(z, atol=1e-13, rtol=1e-12) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp.py new file mode 100644 index 0000000000000000000000000000000000000000..87b35695bd25516a0e85b2f6bd8aa978d46df0ed --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp.py @@ -0,0 +1,3189 @@ +import itertools +import platform +import sys +import warnings + +import numpy as np +from numpy.testing import (assert_equal, assert_almost_equal, + assert_array_almost_equal, assert_array_equal, + assert_, assert_allclose) + +import pytest +from pytest import raises as assert_raises + +from scipy.linalg import (eig, eigvals, lu, svd, svdvals, cholesky, qr, + schur, rsf2csf, lu_solve, lu_factor, solve, diagsvd, + hessenberg, rq, eig_banded, eigvals_banded, eigh, + eigvalsh, qr_multiply, qz, orth, ordqz, + subspace_angles, hadamard, eigvalsh_tridiagonal, + eigh_tridiagonal, null_space, cdf2rdf, LinAlgError) + +from scipy.linalg.lapack import (dgbtrf, dgbtrs, zgbtrf, zgbtrs, dsbev, + dsbevd, dsbevx, zhbevd, zhbevx) + +from scipy.linalg._misc import norm +from scipy.linalg._decomp_qz import _select_function +from scipy.stats import ortho_group + +from numpy import (array, diag, full, linalg, argsort, zeros, arange, + float32, complex64, ravel, sqrt, iscomplex, shape, sort, + sign, asarray, isfinite, ndarray, eye,) + +from scipy.linalg._testutils import assert_no_overwrite +from scipy.sparse._sputils import matrix + +from scipy._lib._testutils import check_free_memory +from scipy.linalg.blas import HAS_ILP64 +from scipy.conftest import skip_xp_invalid_arg +from scipy.__config__ import CONFIG + +IS_WASM = (sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"]) + + +def _random_hermitian_matrix(n, posdef=False, dtype=float): + "Generate random sym/hermitian array of the given size n" + # FIXME non-deterministic rng + if dtype in COMPLEX_DTYPES: + A = np.random.rand(n, n) + np.random.rand(n, n)*1.0j + A = (A + A.conj().T)/2 + else: + A = np.random.rand(n, n) + A = (A + A.T)/2 + + if posdef: + A += sqrt(2*n)*np.eye(n) + + return A.astype(dtype) + + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +# XXX: This function should not be defined here, but somewhere in +# scipy.linalg namespace +def symrand(dim_or_eigv, rng): + """Return a random symmetric (Hermitian) matrix. + + If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues + uniformly distributed on (-1,1). + + If 'dim_or_eigv' is 1-D real array 'a', return a matrix whose + eigenvalues are 'a'. + """ + if isinstance(dim_or_eigv, int): + dim = dim_or_eigv + d = rng.random(dim)*2 - 1 + elif (isinstance(dim_or_eigv, ndarray) and + len(dim_or_eigv.shape) == 1): + dim = dim_or_eigv.shape[0] + d = dim_or_eigv + else: + raise TypeError("input type not supported.") + + v = ortho_group.rvs(dim) + h = v.T.conj() @ diag(d) @ v + # to avoid roundoff errors, symmetrize the matrix (again) + h = 0.5*(h.T+h) + return h + + +class TestEigVals: + + def test_simple(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + w = eigvals(a) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + assert_array_almost_equal(w, exact_w) + + def test_simple_tr(self): + a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]], 'd').T + a = a.copy() + a = a.T + w = eigvals(a) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + assert_array_almost_equal(w, exact_w) + + def test_simple_complex(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]] + w = eigvals(a) + exact_w = [(9+1j+sqrt(92+6j))/2, + 0, + (9+1j-sqrt(92+6j))/2] + assert_array_almost_equal(w, exact_w) + + def test_finite(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + w = eigvals(a, check_finite=False) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + assert_array_almost_equal(w, exact_w) + + @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + w = eigvals(a) + assert w.shape == (0,) + assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype + + w = eigvals(a, homogeneous_eigvals=True) + assert w.shape == (2, 0) + assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype + + +class TestEig: + + def test_simple(self): + a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + w, v = eig(a) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + v0 = array([1, 1, (1+sqrt(93)/3)/2]) + v1 = array([3., 0, -1]) + v2 = array([1, 1, (1-sqrt(93)/3)/2]) + v0 = v0 / norm(v0) + v1 = v1 / norm(v1) + v2 = v2 / norm(v2) + assert_array_almost_equal(w, exact_w) + assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0])) + assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1])) + assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2])) + for i in range(3): + assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i]) + w, v = eig(a, left=1, right=0) + for i in range(3): + assert_array_almost_equal(a.T @ v[:, i], w[i]*v[:, i]) + + def test_simple_complex_eig(self): + a = array([[1, 2], [-2, 1]]) + w, vl, vr = eig(a, left=1, right=1) + assert_array_almost_equal(w, array([1+2j, 1-2j])) + for i in range(2): + assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i]) + for i in range(2): + assert_array_almost_equal(a.conj().T @ vl[:, i], + w[i].conj()*vl[:, i]) + + def test_simple_complex(self): + a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]]) + w, vl, vr = eig(a, left=1, right=1) + for i in range(3): + assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i]) + for i in range(3): + assert_array_almost_equal(a.conj().T @ vl[:, i], + w[i].conj()*vl[:, i]) + + def test_gh_3054(self): + a = [[1]] + b = [[0]] + w, vr = eig(a, b, homogeneous_eigvals=True) + assert_allclose(w[1, 0], 0) + assert_(w[0, 0] != 0) + assert_allclose(vr, 1) + + w, vr = eig(a, b) + assert_equal(w, np.inf) + assert_allclose(vr, 1) + + def _check_gen_eig(self, A, B, atol_homog=1e-13, rtol_homog=1e-13, + atol=1e-13, rtol=1e-13): + if B is not None: + A, B = asarray(A), asarray(B) + B0 = B + else: + A = asarray(A) + B0 = B + B = np.eye(*A.shape) + msg = f"\n{A!r}\n{B!r}" + + # Eigenvalues in homogeneous coordinates + w, vr = eig(A, B0, homogeneous_eigvals=True) + wt = eigvals(A, B0, homogeneous_eigvals=True) + val1 = A @ vr * w[1, :] + val2 = B @ vr * w[0, :] + for i in range(val1.shape[1]): + assert_allclose(val1[:, i], val2[:, i], + rtol=rtol_homog, atol=atol_homog, err_msg=msg) + + if B0 is None: + assert_allclose(w[1, :], 1) + assert_allclose(wt[1, :], 1) + + perm = np.lexsort(w) + permt = np.lexsort(wt) + assert_allclose(w[:, perm], wt[:, permt], atol=1e-7, rtol=1e-7, + err_msg=msg) + + length = np.empty(len(vr)) + + for i in range(len(vr)): + length[i] = norm(vr[:, i]) + + assert_allclose(length, np.ones(length.size), err_msg=msg, + atol=1e-7, rtol=1e-7) + + # Convert homogeneous coordinates + beta_nonzero = (w[1, :] != 0) + wh = w[0, beta_nonzero] / w[1, beta_nonzero] + + # Eigenvalues in standard coordinates + w, vr = eig(A, B0) + wt = eigvals(A, B0) + val1 = A @ vr + val2 = B @ vr * w + res = val1 - val2 + for i in range(res.shape[1]): + if np.all(isfinite(res[:, i])): + assert_allclose(res[:, i], 0, + rtol=rtol, atol=atol, err_msg=msg) + + # try to consistently order eigenvalues, including complex conjugate pairs + w_fin = w[isfinite(w)] + wt_fin = wt[isfinite(wt)] + + # prune noise in the real parts + w_fin = -1j * np.real_if_close(1j*w_fin, tol=1e-10) + wt_fin = -1j * np.real_if_close(1j*wt_fin, tol=1e-10) + + perm = argsort(abs(w_fin) + w_fin.imag) + permt = argsort(abs(wt_fin) + wt_fin.imag) + + assert_allclose(w_fin[perm], wt_fin[permt], + atol=1e-7, rtol=1e-7, err_msg=msg) + + length = np.empty(len(vr)) + for i in range(len(vr)): + length[i] = norm(vr[:, i]) + assert_allclose(length, np.ones(length.size), err_msg=msg) + + # Compare homogeneous and nonhomogeneous versions + assert_allclose(sort(wh), sort(w[np.isfinite(w)])) + + def test_singular(self): + # Example taken from + # https://web.archive.org/web/20040903121217/http://www.cs.umu.se/research/nla/singular_pairs/guptri/matlab.html + A = array([[22, 34, 31, 31, 17], + [45, 45, 42, 19, 29], + [39, 47, 49, 26, 34], + [27, 31, 26, 21, 15], + [38, 44, 44, 24, 30]]) + B = array([[13, 26, 25, 17, 24], + [31, 46, 40, 26, 37], + [26, 40, 19, 25, 25], + [16, 25, 27, 14, 23], + [24, 35, 18, 21, 22]]) + + with np.errstate(all='ignore'): + self._check_gen_eig(A, B, atol_homog=5e-13, atol=5e-13) + + def test_falker(self): + # Test matrices giving some Nan generalized eigenvalues. + M = diag(array([1, 0, 3])) + K = array(([2, -1, -1], [-1, 2, -1], [-1, -1, 2])) + D = array(([1, -1, 0], [-1, 1, 0], [0, 0, 0])) + Z = zeros((3, 3)) + I3 = eye(3) + A = np.block([[I3, Z], [Z, -K]]) + B = np.block([[Z, I3], [M, D]]) + + with np.errstate(all='ignore'): + self._check_gen_eig(A, B) + + def test_bad_geneig(self): + # Ticket #709 (strange return values from DGGEV) + + def matrices(omega): + c1 = -9 + omega**2 + c2 = 2*omega + A = [[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, c1, 0], + [0, 0, 0, c1]] + B = [[0, 0, 1, 0], + [0, 0, 0, 1], + [1, 0, 0, -c2], + [0, 1, c2, 0]] + return A, B + + # With a buggy LAPACK, this can fail for different omega on different + # machines -- so we need to test several values + with np.errstate(all='ignore'): + for k in range(100): + A, B = matrices(omega=k*5./100) + self._check_gen_eig(A, B) + + def test_make_eigvals(self): + # Step through all paths in _make_eigvals + # Real eigenvalues + rng = np.random.RandomState(1234) + A = symrand(3, rng) + self._check_gen_eig(A, None) + B = symrand(3, rng) + self._check_gen_eig(A, B) + # Complex eigenvalues + A = rng.random((3, 3)) + 1j*rng.random((3, 3)) + self._check_gen_eig(A, None) + B = rng.random((3, 3)) + 1j*rng.random((3, 3)) + self._check_gen_eig(A, B) + + def test_check_finite(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + w, v = eig(a, check_finite=False) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + v0 = array([1, 1, (1+sqrt(93)/3)/2]) + v1 = array([3., 0, -1]) + v2 = array([1, 1, (1-sqrt(93)/3)/2]) + v0 = v0 / norm(v0) + v1 = v1 / norm(v1) + v2 = v2 / norm(v2) + assert_array_almost_equal(w, exact_w) + assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0])) + assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1])) + assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2])) + for i in range(3): + assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i]) + + def test_not_square_error(self): + """Check that passing a non-square array raises a ValueError.""" + A = np.arange(6).reshape(3, 2) + assert_raises(ValueError, eig, A) + + def test_shape_mismatch(self): + """Check that passing arrays of with different shapes + raises a ValueError.""" + A = eye(2) + B = np.arange(9.0).reshape(3, 3) + assert_raises(ValueError, eig, A, B) + assert_raises(ValueError, eig, B, A) + + def test_gh_11577(self): + # https://github.com/scipy/scipy/issues/11577 + # `A - lambda B` should have 4 and 8 among the eigenvalues, and this + # was apparently broken on some platforms + A = np.array([[12.0, 28.0, 76.0, 220.0], + [16.0, 32.0, 80.0, 224.0], + [24.0, 40.0, 88.0, 232.0], + [40.0, 56.0, 104.0, 248.0]], dtype='float64') + B = np.array([[2.0, 4.0, 10.0, 28.0], + [3.0, 5.0, 11.0, 29.0], + [5.0, 7.0, 13.0, 31.0], + [9.0, 11.0, 17.0, 35.0]], dtype='float64') + + D, V = eig(A, B) + + # The problem is ill-conditioned, and two other eigenvalues + # depend on ATLAS/OpenBLAS version, compiler version etc + # see gh-11577 for discussion + # + # NB: it is tempting to use `assert_allclose(D[:2], [4, 8])` instead but + # the ordering of eigenvalues also comes out different on different + # systems depending on who knows what. + with warnings.catch_warnings(): + # isclose chokes on inf/nan values + warnings.filterwarnings( + "ignore", "invalid value encountered in multiply", RuntimeWarning) + assert np.isclose(D, 4.0, atol=1e-14).any() + assert np.isclose(D, 8.0, atol=1e-14).any() + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + w, vr = eig(a) + + w_n, vr_n = eig(np.eye(2, dtype=dt)) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype #eigvals(np.eye(2, dtype=dt)).dtype + + assert_allclose(vr, np.empty((0, 0))) + assert vr.shape == (0, 0) + assert vr.dtype == vr_n.dtype + + w, vr = eig(a, homogeneous_eigvals=True) + assert w.shape == (2, 0) + assert w.dtype == w_n.dtype + + assert vr.shape == (0, 0) + assert vr.dtype == vr_n.dtype + + @pytest.mark.parametrize("include_B", [False, True]) + @pytest.mark.parametrize("left", [False, True]) + @pytest.mark.parametrize("right", [False, True]) + @pytest.mark.parametrize("homogeneous_eigvals", [False, True]) + @pytest.mark.parametrize("dtype", [np.float32, np.complex128]) + def test_nd_input(self, include_B, left, right, homogeneous_eigvals, dtype): + batch_shape = (3, 2) + core_shape = (4, 4) + rng = np.random.default_rng(3249823598235) + A = rng.random(batch_shape + core_shape).astype(dtype) + B = rng.random(batch_shape + core_shape).astype(dtype) + kwargs = dict(right=right, homogeneous_eigvals=homogeneous_eigvals) + + if include_B: + res = eig(A, b=B, left=left, **kwargs) + else: + res = eig(A, left=left, **kwargs) + + for i in range(batch_shape[0]): + for j in range(batch_shape[1]): + if include_B: + ref = eig(A[i, j], b=B[i, j], left=left, **kwargs) + else: + ref = eig(A[i, j], left=left, **kwargs) + + if left or right: + for k in range(len(ref)): + assert_allclose(res[k][i, j], ref[k]) + else: + assert_allclose(res[i, j], ref) + + +class TestEigBanded: + def setup_method(self): + self.create_bandmat() + + def create_bandmat(self): + """Create the full matrix `self.fullmat` and + the corresponding band matrix `self.bandmat`.""" + N = 10 + self.KL = 2 # number of subdiagonals (below the diagonal) + self.KU = 2 # number of superdiagonals (above the diagonal) + + # symmetric band matrix + self.sym_mat = (diag(full(N, 1.0)) + + diag(full(N-1, -1.0), -1) + diag(full(N-1, -1.0), 1) + + diag(full(N-2, -2.0), -2) + diag(full(N-2, -2.0), 2)) + + # hermitian band matrix + self.herm_mat = (diag(full(N, -1.0)) + + 1j*diag(full(N-1, 1.0), -1) + - 1j*diag(full(N-1, 1.0), 1) + + diag(full(N-2, -2.0), -2) + + diag(full(N-2, -2.0), 2)) + + # general real band matrix + self.real_mat = (diag(full(N, 1.0)) + + diag(full(N-1, -1.0), -1) + diag(full(N-1, -3.0), 1) + + diag(full(N-2, 2.0), -2) + diag(full(N-2, -2.0), 2)) + + # general complex band matrix + self.comp_mat = (1j*diag(full(N, 1.0)) + + diag(full(N-1, -1.0), -1) + + 1j*diag(full(N-1, -3.0), 1) + + diag(full(N-2, 2.0), -2) + + diag(full(N-2, -2.0), 2)) + + # Eigenvalues and -vectors from linalg.eig + ew, ev = linalg.eig(self.sym_mat) + ew = ew.real + args = argsort(ew) + self.w_sym_lin = ew[args] + self.evec_sym_lin = ev[:, args] + + ew, ev = linalg.eig(self.herm_mat) + ew = ew.real + args = argsort(ew) + self.w_herm_lin = ew[args] + self.evec_herm_lin = ev[:, args] + + # Extract upper bands from symmetric and hermitian band matrices + # (for use in dsbevd, dsbevx, zhbevd, zhbevx + # and their single precision versions) + LDAB = self.KU + 1 + self.bandmat_sym = zeros((LDAB, N), dtype=float) + self.bandmat_herm = zeros((LDAB, N), dtype=complex) + for i in range(LDAB): + self.bandmat_sym[LDAB-i-1, i:N] = diag(self.sym_mat, i) + self.bandmat_herm[LDAB-i-1, i:N] = diag(self.herm_mat, i) + + # Extract bands from general real and complex band matrix + # (for use in dgbtrf, dgbtrs and their single precision versions) + LDAB = 2*self.KL + self.KU + 1 + self.bandmat_real = zeros((LDAB, N), dtype=float) + self.bandmat_real[2*self.KL, :] = diag(self.real_mat) # diagonal + for i in range(self.KL): + # superdiagonals + self.bandmat_real[2*self.KL-1-i, i+1:N] = diag(self.real_mat, i+1) + # subdiagonals + self.bandmat_real[2*self.KL+1+i, 0:N-1-i] = diag(self.real_mat, + -i-1) + + self.bandmat_comp = zeros((LDAB, N), dtype=complex) + self.bandmat_comp[2*self.KL, :] = diag(self.comp_mat) # diagonal + for i in range(self.KL): + # superdiagonals + self.bandmat_comp[2*self.KL-1-i, i+1:N] = diag(self.comp_mat, i+1) + # subdiagonals + self.bandmat_comp[2*self.KL+1+i, 0:N-1-i] = diag(self.comp_mat, + -i-1) + + # absolute value for linear equation system A*x = b + self.b = 1.0*arange(N) + self.bc = self.b * (1 + 1j) + + ##################################################################### + + def test_dsbev(self): + """Compare dsbev eigenvalues and eigenvectors with + the result of linalg.eig.""" + w, evec, info = dsbev(self.bandmat_sym, compute_v=1) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_sym_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) + + def test_dsbevd(self): + """Compare dsbevd eigenvalues and eigenvectors with + the result of linalg.eig.""" + w, evec, info = dsbevd(self.bandmat_sym, compute_v=1) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_sym_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) + + def test_dsbevx(self): + """Compare dsbevx eigenvalues and eigenvectors + with the result of linalg.eig.""" + N, N = shape(self.sym_mat) + # Achtung: Argumente 0.0,0.0,range? + w, evec, num, ifail, info = dsbevx(self.bandmat_sym, 0.0, 0.0, 1, N, + compute_v=1, range=2) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_sym_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) + + def test_zhbevd(self): + """Compare zhbevd eigenvalues and eigenvectors + with the result of linalg.eig.""" + w, evec, info = zhbevd(self.bandmat_herm, compute_v=1) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_herm_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin)) + + def test_zhbevx(self): + """Compare zhbevx eigenvalues and eigenvectors + with the result of linalg.eig.""" + N, N = shape(self.herm_mat) + # Achtung: Argumente 0.0,0.0,range? + w, evec, num, ifail, info = zhbevx(self.bandmat_herm, 0.0, 0.0, 1, N, + compute_v=1, range=2) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_herm_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin)) + + def test_eigvals_banded(self): + """Compare eigenvalues of eigvals_banded with those of linalg.eig.""" + w_sym = eigvals_banded(self.bandmat_sym) + w_sym = w_sym.real + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + + w_herm = eigvals_banded(self.bandmat_herm) + w_herm = w_herm.real + assert_array_almost_equal(sort(w_herm), self.w_herm_lin) + + # extracting eigenvalues with respect to an index range + ind1 = 2 + ind2 = np.longlong(6) + w_sym_ind = eigvals_banded(self.bandmat_sym, + select='i', select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_sym_ind), + self.w_sym_lin[ind1:ind2+1]) + w_herm_ind = eigvals_banded(self.bandmat_herm, + select='i', select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_herm_ind), + self.w_herm_lin[ind1:ind2+1]) + + # extracting eigenvalues with respect to a value range + v_lower = self.w_sym_lin[ind1] - 1.0e-5 + v_upper = self.w_sym_lin[ind2] + 1.0e-5 + w_sym_val = eigvals_banded(self.bandmat_sym, + select='v', select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_sym_val), + self.w_sym_lin[ind1:ind2+1]) + + v_lower = self.w_herm_lin[ind1] - 1.0e-5 + v_upper = self.w_herm_lin[ind2] + 1.0e-5 + w_herm_val = eigvals_banded(self.bandmat_herm, + select='v', + select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_herm_val), + self.w_herm_lin[ind1:ind2+1]) + + w_sym = eigvals_banded(self.bandmat_sym, check_finite=False) + w_sym = w_sym.real + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + + def test_eig_banded(self): + """Compare eigenvalues and eigenvectors of eig_banded + with those of linalg.eig. """ + w_sym, evec_sym = eig_banded(self.bandmat_sym) + evec_sym_ = evec_sym[:, argsort(w_sym.real)] + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin)) + + w_herm, evec_herm = eig_banded(self.bandmat_herm) + evec_herm_ = evec_herm[:, argsort(w_herm.real)] + assert_array_almost_equal(sort(w_herm), self.w_herm_lin) + assert_array_almost_equal(abs(evec_herm_), abs(self.evec_herm_lin)) + + # extracting eigenvalues with respect to an index range + ind1 = 2 + ind2 = 6 + w_sym_ind, evec_sym_ind = eig_banded(self.bandmat_sym, + select='i', + select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_sym_ind), + self.w_sym_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_sym_ind), + abs(self.evec_sym_lin[:, ind1:ind2+1])) + + w_herm_ind, evec_herm_ind = eig_banded(self.bandmat_herm, + select='i', + select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_herm_ind), + self.w_herm_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_herm_ind), + abs(self.evec_herm_lin[:, ind1:ind2+1])) + + # extracting eigenvalues with respect to a value range + v_lower = self.w_sym_lin[ind1] - 1.0e-5 + v_upper = self.w_sym_lin[ind2] + 1.0e-5 + w_sym_val, evec_sym_val = eig_banded(self.bandmat_sym, + select='v', + select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_sym_val), + self.w_sym_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_sym_val), + abs(self.evec_sym_lin[:, ind1:ind2+1])) + + v_lower = self.w_herm_lin[ind1] - 1.0e-5 + v_upper = self.w_herm_lin[ind2] + 1.0e-5 + w_herm_val, evec_herm_val = eig_banded(self.bandmat_herm, + select='v', + select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_herm_val), + self.w_herm_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_herm_val), + abs(self.evec_herm_lin[:, ind1:ind2+1])) + + w_sym, evec_sym = eig_banded(self.bandmat_sym, check_finite=False) + evec_sym_ = evec_sym[:, argsort(w_sym.real)] + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin)) + + def test_dgbtrf(self): + """Compare dgbtrf LU factorisation with the LU factorisation result + of linalg.lu.""" + M, N = shape(self.real_mat) + lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU) + + # extract matrix u from lu_symm_band + u = diag(lu_symm_band[2*self.KL, :]) + for i in range(self.KL + self.KU): + u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1) + + p_lin, l_lin, u_lin = lu(self.real_mat, permute_l=0) + assert_array_almost_equal(u, u_lin) + + def test_zgbtrf(self): + """Compare zgbtrf LU factorisation with the LU factorisation result + of linalg.lu.""" + M, N = shape(self.comp_mat) + lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU) + + # extract matrix u from lu_symm_band + u = diag(lu_symm_band[2*self.KL, :]) + for i in range(self.KL + self.KU): + u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1) + + p_lin, l_lin, u_lin = lu(self.comp_mat, permute_l=0) + assert_array_almost_equal(u, u_lin) + + def test_dgbtrs(self): + """Compare dgbtrs solutions for linear equation system A*x = b + with solutions of linalg.solve.""" + + lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU) + y, info = dgbtrs(lu_symm_band, self.KL, self.KU, self.b, ipiv) + + y_lin = linalg.solve(self.real_mat, self.b) + assert_array_almost_equal(y, y_lin) + + def test_zgbtrs(self): + """Compare zgbtrs solutions for linear equation system A*x = b + with solutions of linalg.solve.""" + + lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU) + y, info = zgbtrs(lu_symm_band, self.KL, self.KU, self.bc, ipiv) + + y_lin = linalg.solve(self.comp_mat, self.bc) + assert_array_almost_equal(y, y_lin) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a_band = np.empty((0, 0), dtype=dt) + w, v = eig_banded(a_band) + + w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=dt)) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype + + assert v.shape == (0, 0) + assert v.dtype == v_n.dtype + + w = eig_banded(a_band, eigvals_only=True) + assert w.shape == (0,) + assert w.dtype == w_n.dtype + +class TestEigTridiagonal: + def setup_method(self): + self.create_trimat() + + def create_trimat(self): + """Create the full matrix `self.fullmat`, `self.d`, and `self.e`.""" + N = 10 + + # symmetric band matrix + self.d = full(N, 1.0) + self.e = full(N-1, -1.0) + self.full_mat = (diag(self.d) + diag(self.e, -1) + diag(self.e, 1)) + + ew, ev = linalg.eig(self.full_mat) + ew = ew.real + args = argsort(ew) + self.w = ew[args] + self.evec = ev[:, args] + + def test_degenerate(self): + """Test error conditions.""" + # Wrong sizes + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e[:-1]) + # Must be real + assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e * 1j) + # Bad driver + assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e, + lapack_driver=1.) + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e, + lapack_driver='foo') + # Bad bounds + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e, + select='i', select_range=(0, -1)) + + def test_eigvalsh_tridiagonal(self): + """Compare eigenvalues of eigvalsh_tridiagonal with those of eig.""" + # can't use ?STERF with subselection + for driver in ('sterf', 'stev', 'stevd', 'stebz', 'stemr', 'auto'): + w = eigvalsh_tridiagonal(self.d, self.e, lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w) + + for driver in ('sterf', 'stev', 'stevd'): + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e, + lapack_driver=driver, select='i', + select_range=(0, 1)) + for driver in ('stebz', 'stemr', 'auto'): + # extracting eigenvalues with respect to the full index range + w_ind = eigvalsh_tridiagonal( + self.d, self.e, select='i', select_range=(0, len(self.d)-1), + lapack_driver=driver) + assert_array_almost_equal(sort(w_ind), self.w) + + # extracting eigenvalues with respect to an index range + ind1 = 2 + ind2 = 6 + w_ind = eigvalsh_tridiagonal( + self.d, self.e, select='i', select_range=(ind1, ind2), + lapack_driver=driver) + assert_array_almost_equal(sort(w_ind), self.w[ind1:ind2+1]) + + # extracting eigenvalues with respect to a value range + v_lower = self.w[ind1] - 1.0e-5 + v_upper = self.w[ind2] + 1.0e-5 + w_val = eigvalsh_tridiagonal( + self.d, self.e, select='v', select_range=(v_lower, v_upper), + lapack_driver=driver) + assert_array_almost_equal(sort(w_val), self.w[ind1:ind2+1]) + + def test_eigh_tridiagonal(self): + """Compare eigenvalues and eigenvectors of eigh_tridiagonal + with those of eig. """ + # can't use ?STERF when eigenvectors are requested + assert_raises(ValueError, eigh_tridiagonal, self.d, self.e, + lapack_driver='sterf') + for driver in ('stebz', 'stev', 'stevd', 'stemr', 'auto'): + w, evec = eigh_tridiagonal(self.d, self.e, lapack_driver=driver) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w) + assert_array_almost_equal(abs(evec_), abs(self.evec)) + + assert_raises(ValueError, eigh_tridiagonal, self.d, self.e, + lapack_driver='stev', select='i', select_range=(0, 1)) + for driver in ('stebz', 'stemr', 'auto'): + # extracting eigenvalues with respect to an index range + ind1 = 0 + ind2 = len(self.d)-1 + w, evec = eigh_tridiagonal( + self.d, self.e, select='i', select_range=(ind1, ind2), + lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w) + assert_array_almost_equal(abs(evec), abs(self.evec)) + ind1 = 2 + ind2 = 6 + w, evec = eigh_tridiagonal( + self.d, self.e, select='i', select_range=(ind1, ind2), + lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w[ind1:ind2+1]) + assert_array_almost_equal(abs(evec), + abs(self.evec[:, ind1:ind2+1])) + + # extracting eigenvalues with respect to a value range + v_lower = self.w[ind1] - 1.0e-5 + v_upper = self.w[ind2] + 1.0e-5 + w, evec = eigh_tridiagonal( + self.d, self.e, select='v', select_range=(v_lower, v_upper), + lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w[ind1:ind2+1]) + assert_array_almost_equal(abs(evec), + abs(self.evec[:, ind1:ind2+1])) + + def test_eigh_tridiagonal_1x1(self): + """See gh-20075""" + a = np.array([-2.0]) + b = np.array([]) + x = eigh_tridiagonal(a, b, eigvals_only=True) + assert x.ndim == 1 + assert_allclose(x, a) + x, V = eigh_tridiagonal(a, b, select="i", select_range=(0, 0)) + assert x.ndim == 1 + assert V.ndim == 2 + assert_allclose(x, a) + assert_allclose(V, array([[1.]])) + + x, V = eigh_tridiagonal(a, b, select="v", select_range=(-2, 0)) + assert x.size == 0 + assert x.shape == (0,) + assert V.shape == (1, 0) + + +class TestEigh: + def test_wrong_inputs(self): + # Nonsquare a + assert_raises(ValueError, eigh, np.ones([1, 2])) + # Nonsquare b + assert_raises(ValueError, eigh, np.ones([2, 2]), np.ones([2, 1])) + # Incompatible a, b sizes + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([2, 2])) + # Wrong type parameter for generalized problem + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + type=4) + # Both value and index subsets requested + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_value=[1, 2], subset_by_index=[2, 4]) + # Invalid upper index spec + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_index=[0, 4]) + # Invalid lower index + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_index=[-2, 2]) + # Invalid index spec #2 + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_index=[2, 0]) + # Invalid value spec + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_value=[2, 0]) + # Invalid driver name + assert_raises(ValueError, eigh, np.ones([2, 2]), driver='wrong') + # Generalized driver selection without b + assert_raises(ValueError, eigh, np.ones([3, 3]), None, driver='gvx') + # Standard driver with b + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + driver='evr') + # Subset request from invalid driver + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + driver='gvd', subset_by_index=[1, 2]) + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + driver='gvd', subset_by_index=[1, 2]) + + def test_nonpositive_b(self): + assert_raises(LinAlgError, eigh, np.ones([3, 3]), np.ones([3, 3])) + + # index based subsets are done in the legacy test_eigh() + def test_value_subsets(self): + for ind, dt in enumerate(DTYPES): + + a = _random_hermitian_matrix(20, dtype=dt) + w, v = eigh(a, subset_by_value=[-2, 2]) + assert_equal(v.shape[1], len(w)) + assert all((w > -2) & (w < 2)) + + b = _random_hermitian_matrix(20, posdef=True, dtype=dt) + w, v = eigh(a, b, subset_by_value=[-2, 2]) + assert_equal(v.shape[1], len(w)) + assert all((w > -2) & (w < 2)) + + def test_eigh_integer(self): + a = array([[1, 2], [2, 7]]) + b = array([[3, 1], [1, 5]]) + w, z = eigh(a) + w, z = eigh(a, b) + + @skip_xp_invalid_arg + def test_eigh_of_sparse(self): + # This tests the rejection of inputs that eigh cannot currently handle. + import scipy.sparse + a = scipy.sparse.identity(2).tocsc() + b = np.atleast_2d(a) + assert_raises(ValueError, eigh, a) + assert_raises(ValueError, eigh, b) + + @pytest.mark.parametrize('dtype_', DTYPES) + @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx")) + def test_various_drivers_standard(self, driver, dtype_): + a = _random_hermitian_matrix(n=20, dtype=dtype_) + w, v = eigh(a, driver=driver) + assert_allclose(a @ v - (v * w), 0., + atol=1000*np.finfo(dtype_).eps, + rtol=0.) + + @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx")) + def test_1x1_lwork(self, driver): + w, v = eigh([[1]], driver=driver) + assert_allclose(w, array([1.]), atol=1e-15) + assert_allclose(v, array([[1.]]), atol=1e-15) + + # complex case now + w, v = eigh([[1j]], driver=driver) + assert_allclose(w, array([0]), atol=1e-15) + assert_allclose(v, array([[1.]]), atol=1e-15) + + @pytest.mark.parametrize('type', (1, 2, 3)) + @pytest.mark.parametrize('driver', ("gv", "gvd", "gvx")) + def test_various_drivers_generalized(self, driver, type): + atol = np.spacing(5000.) + a = _random_hermitian_matrix(20) + b = _random_hermitian_matrix(20, posdef=True) + w, v = eigh(a=a, b=b, driver=driver, type=type) + if type == 1: + assert_allclose(a @ v - w*(b @ v), 0., atol=atol, rtol=0.) + elif type == 2: + assert_allclose(a @ b @ v - v * w, 0., atol=atol, rtol=0.) + else: + assert_allclose(b @ a @ v - v * w, 0., atol=atol, rtol=0.) + + def test_eigvalsh_new_args(self): + a = _random_hermitian_matrix(5) + w = eigvalsh(a, subset_by_index=[1, 2]) + assert_equal(len(w), 2) + + w2 = eigvalsh(a, subset_by_index=[1, 2]) + assert_equal(len(w2), 2) + assert_allclose(w, w2) + + b = np.diag([1, 1.2, 1.3, 1.5, 2]) + w3 = eigvalsh(b, subset_by_value=[1, 1.4]) + assert_equal(len(w3), 2) + assert_allclose(w3, np.array([1.2, 1.3])) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + w, v = eigh(a) + + w_n, v_n = eigh(np.eye(2, dtype=dt)) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype + + assert v.shape == (0, 0) + assert v.dtype == v_n.dtype + + w = eigh(a, eigvals_only=True) + assert_allclose(w, np.empty((0,))) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype + +class TestSVD_GESDD: + lapack_driver = 'gesdd' + + def test_degenerate(self): + assert_raises(TypeError, svd, [[1.]], lapack_driver=1.) + assert_raises(ValueError, svd, [[1.]], lapack_driver='foo') + + def test_simple(self): + a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(3)) + assert_array_almost_equal(vh.T @ vh, eye(3)) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_singular(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(3)) + assert_array_almost_equal(vh.T @ vh, eye(3)) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_underdet(self): + a = [[1, 2, 3], [4, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(u.shape[0])) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_overdet(self): + a = [[1, 2], [4, 5], [3, 4]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(u.shape[1])) + assert_array_almost_equal(vh.T @ vh, eye(2)) + sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + m = 15 + for i in range(3): + for a in [rng.random([n, m]), rng.random([m, n])]: + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(u.shape[1])) + assert_array_almost_equal(vh @ vh.T, eye(vh.shape[0])) + sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_complex(self): + a = [[1, 2, 3], [1, 2j, 3], [2, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.conj().T @ u, eye(u.shape[1])) + assert_array_almost_equal(vh.conj().T @ vh, eye(vh.shape[0])) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + m = 15 + for i in range(3): + for full_matrices in (True, False): + for a in [rng.random([n, m]), rng.random([m, n])]: + a = a + 1j*rng.random(list(a.shape)) + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.conj().T @ u, + eye(u.shape[1])) + # This fails when [m,n] + # assert_array_almost_equal(vh.conj().T @ vh, + # eye(len(vh),dtype=vh.dtype.char)) + sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_crash_1580(self): + rng = np.random.RandomState(1234) + sizes = [(13, 23), (30, 50), (60, 100)] + for sz in sizes: + for dt in [np.float32, np.float64, np.complex64, np.complex128]: + a = rng.rand(*sz).astype(dt) + # should not crash + svd(a, lapack_driver=self.lapack_driver) + + def test_check_finite(self): + a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]] + u, s, vh = svd(a, check_finite=False, lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(3)) + assert_array_almost_equal(vh.T @ vh, eye(3)) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_gh_5039(self): + # This is a smoke test for https://github.com/scipy/scipy/issues/5039 + # + # The following is reported to raise "ValueError: On entry to DGESDD + # parameter number 12 had an illegal value". + # `interp1d([1,2,3,4], [1,2,3,4], kind='cubic')` + # This is reported to only show up on LAPACK 3.0.3. + # + # The matrix below is taken from the call to + # `B = _fitpack._bsplmat(order, xk)` in interpolate._find_smoothest + b = np.array( + [[0.16666667, 0.66666667, 0.16666667, 0., 0., 0.], + [0., 0.16666667, 0.66666667, 0.16666667, 0., 0.], + [0., 0., 0.16666667, 0.66666667, 0.16666667, 0.], + [0., 0., 0., 0.16666667, 0.66666667, 0.16666667]]) + svd(b, lapack_driver=self.lapack_driver) + + @pytest.mark.skipif(not HAS_ILP64, reason="64-bit LAPACK required") + @pytest.mark.slow + def test_large_matrix(self): + check_free_memory(free_mb=17000) + A = np.zeros([1, 2**31], dtype=np.float32) + A[0, -1] = 1 + u, s, vh = svd(A, full_matrices=False) + assert_allclose(s[0], 1.0) + assert_allclose(u[0, 0] * vh[0, -1], 1.0) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, dtype): + a = np.zeros((m, n), dtype=dtype) + k = min(m, n) + dchar = a.dtype.char + real_dchar = dchar.lower() if dchar in 'FD' else dchar + + u, s, v = svd(a) + assert_equal(u.shape, (m, m)) + assert_equal(u.dtype, dtype) + assert_equal(s.shape, (k,)) + assert_equal(s.dtype, np.dtype(real_dchar)) + assert_equal(v.shape, (n, n)) + assert_equal(v.dtype, dtype) + + u, s, v = svd(a, full_matrices=False) + assert_equal(u.shape, (m, k)) + assert_equal(u.dtype, dtype) + assert_equal(s.shape, (k,)) + assert_equal(s.dtype, np.dtype(real_dchar)) + assert_equal(v.shape, (k, n)) + assert_equal(v.dtype, dtype) + + s = svd(a, compute_uv=False) + assert_equal(s.shape, (k,)) + assert_equal(s.dtype, np.dtype(real_dchar)) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, dt, m, n): + a0 = np.eye(3, dtype=dt) + u0, s0, v0 = svd(a0) + + a = np.empty((m, n), dtype=dt) + u, s, v = svd(a) + assert_allclose(u, np.identity(m)) + assert_allclose(s, np.empty((0,))) + assert_allclose(v, np.identity(n)) + + assert u.dtype == u0.dtype + assert v.dtype == v0.dtype + assert s.dtype == s0.dtype + + u, s, v = svd(a, full_matrices=False) + assert_allclose(u, np.empty((m, 0))) + assert_allclose(s, np.empty((0,))) + assert_allclose(v, np.empty((0, n))) + + assert u.dtype == u0.dtype + assert v.dtype == v0.dtype + assert s.dtype == s0.dtype + + s = svd(a, compute_uv=False) + assert_allclose(s, np.empty((0,))) + + assert s.dtype == s0.dtype + +class TestSVD_GESVD(TestSVD_GESDD): + lapack_driver = 'gesvd' + + +# Allocating an array of such a size leads to _ArrayMemoryError(s) +# since the maximum memory that can be in 32-bit (WASM) is 4GB +@pytest.mark.skipif(IS_WASM, reason="out of memory in WASM") +@pytest.mark.xfail_on_32bit("out of memory in 32-bit CI workflow") +@pytest.mark.parallel_threads_limit(2) # 1.9 GiB per thread RAM usage +@pytest.mark.fail_slow(10) +def test_svd_gesdd_nofegfault(): + # svd(a) with {U,VT}.size > INT_MAX does not segfault + # cf https://github.com/scipy/scipy/issues/14001 + df=np.ones((4799, 53130), dtype=np.float64) + with assert_raises(ValueError): + svd(df) + + +def test_gesdd_nan_error_message(): + A = np.eye(2) + A[0, 0] = np.nan + with pytest.raises(ValueError, match="NaN"): + svd(A, check_finite=False) + + +class TestSVDVals: + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + for a in [[]], np.empty((2, 0)), np.ones((0, 3)): + a = np.array(a, dtype=dt) + s = svdvals(a) + assert_equal(s, np.empty(0)) + + s0 = svdvals(np.eye(2, dtype=dt)) + assert s.dtype == s0.dtype + + def test_simple(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + s = svdvals(a) + assert_(len(s) == 3) + assert_(s[0] >= s[1] >= s[2]) + + def test_simple_underdet(self): + a = [[1, 2, 3], [4, 5, 6]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_simple_overdet(self): + a = [[1, 2], [4, 5], [3, 4]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_simple_complex(self): + a = [[1, 2, 3], [1, 20, 3j], [2, 5, 6]] + s = svdvals(a) + assert_(len(s) == 3) + assert_(s[0] >= s[1] >= s[2]) + + def test_simple_underdet_complex(self): + a = [[1, 2, 3], [4, 5j, 6]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_simple_overdet_complex(self): + a = [[1, 2], [4, 5], [3j, 4]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_check_finite(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + s = svdvals(a, check_finite=False) + assert_(len(s) == 3) + assert_(s[0] >= s[1] >= s[2]) + + @pytest.mark.slow + def test_crash_2609(self): + rng = np.random.default_rng(1234) + a = rng.random((1500, 2800)) + # Shouldn't crash: + svdvals(a) + + +class TestDiagSVD: + + def test_simple(self): + assert_array_almost_equal(diagsvd([1, 0, 0], 3, 3), + [[1, 0, 0], [0, 0, 0], [0, 0, 0]]) + + +class TestQR: + def test_simple(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_simple_left(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a) + c = [1, 2, 3] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + qc, r2 = qr_multiply(a, eye(3), "left") + assert_array_almost_equal(q, qc) + + def test_simple_right(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a) + c = [1, 2, 3] + qc, r2 = qr_multiply(a, c) + assert_array_almost_equal(c @ q, qc) + assert_array_almost_equal(r, r2) + qc, r = qr_multiply(a, eye(3)) + assert_array_almost_equal(q, qc) + + def test_simple_pivoting(self): + a = np.asarray([[8, 2, 3], [2, 9, 3], [5, 3, 6]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_left_pivoting(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3] + qc, r, jpvt = qr_multiply(a, c, "left", True) + assert_array_almost_equal(q @ c, qc) + + def test_simple_right_pivoting(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3] + qc, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, qc) + + def test_simple_trap(self): + a = [[8, 2, 3], [2, 9, 3]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + + def test_simple_trap_pivoting(self): + a = np.asarray([[8, 2, 3], [2, 9, 3]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_tall(self): + # full version + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_simple_tall_pivoting(self): + # full version pivoting + a = np.asarray([[8, 2], [2, 9], [5, 3]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_tall_e(self): + # economy version + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a, mode='economic') + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (3, 2)) + assert_equal(r.shape, (2, 2)) + + def test_simple_tall_e_pivoting(self): + # economy version pivoting + a = np.asarray([[8, 2], [2, 9], [5, 3]]) + q, r, p = qr(a, pivoting=True, mode='economic') + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p], mode='economic') + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_tall_left(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a, mode="economic") + c = [1, 2] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + c = array([1, 2, 0]) + qc, r2 = qr_multiply(a, c, "left", overwrite_c=True) + assert_array_almost_equal(q @ c[:2], qc) + qc, r = qr_multiply(a, eye(2), "left") + assert_array_almost_equal(qc, q) + + def test_simple_tall_left_pivoting(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r, jpvt = qr(a, mode="economic", pivoting=True) + c = [1, 2] + qc, r, kpvt = qr_multiply(a, c, "left", True) + assert_array_equal(jpvt, kpvt) + assert_array_almost_equal(q @ c, qc) + qc, r, jpvt = qr_multiply(a, eye(2), "left", True) + assert_array_almost_equal(qc, q) + + def test_simple_tall_right(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a, mode="economic") + c = [1, 2, 3] + cq, r2 = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + assert_array_almost_equal(r, r2) + cq, r = qr_multiply(a, eye(3)) + assert_array_almost_equal(cq, q) + + def test_simple_tall_right_pivoting(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r, jpvt = qr(a, pivoting=True, mode="economic") + c = [1, 2, 3] + cq, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, cq) + cq, r, jpvt = qr_multiply(a, eye(3), pivoting=True) + assert_array_almost_equal(cq, q) + + def test_simple_fat(self): + # full version + a = [[8, 2, 5], [2, 9, 3]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + + def test_simple_fat_pivoting(self): + # full version pivoting + a = np.asarray([[8, 2, 5], [2, 9, 3]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_fat_e(self): + # economy version + a = [[8, 2, 3], [2, 9, 5]] + q, r = qr(a, mode='economic') + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + + def test_simple_fat_e_pivoting(self): + # economy version pivoting + a = np.asarray([[8, 2, 3], [2, 9, 5]]) + q, r, p = qr(a, pivoting=True, mode='economic') + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + q2, r2 = qr(a[:, p], mode='economic') + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_fat_left(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r = qr(a, mode="economic") + c = [1, 2] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + qc, r = qr_multiply(a, eye(2), "left") + assert_array_almost_equal(qc, q) + + def test_simple_fat_left_pivoting(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r, jpvt = qr(a, mode="economic", pivoting=True) + c = [1, 2] + qc, r, jpvt = qr_multiply(a, c, "left", True) + assert_array_almost_equal(q @ c, qc) + qc, r, jpvt = qr_multiply(a, eye(2), "left", True) + assert_array_almost_equal(qc, q) + + def test_simple_fat_right(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r = qr(a, mode="economic") + c = [1, 2] + cq, r2 = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + assert_array_almost_equal(r, r2) + cq, r = qr_multiply(a, eye(2)) + assert_array_almost_equal(cq, q) + + def test_simple_fat_right_pivoting(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r, jpvt = qr(a, pivoting=True, mode="economic") + c = [1, 2] + cq, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, cq) + cq, r, jpvt = qr_multiply(a, eye(2), pivoting=True) + assert_array_almost_equal(cq, q) + + def test_simple_complex(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + assert_array_almost_equal(q.conj().T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_simple_complex_left(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = [1, 2, 3+4j] + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(3), "left") + assert_array_almost_equal(q, qc) + + def test_simple_complex_right(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = [1, 2, 3+4j] + qc, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, qc) + qc, r = qr_multiply(a, eye(3)) + assert_array_almost_equal(q, qc) + + def test_simple_tall_complex_left(self): + a = [[8, 2+3j], [2, 9], [5+7j, 3]] + q, r = qr(a, mode="economic") + c = [1, 2+2j] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + c = array([1, 2, 0]) + qc, r2 = qr_multiply(a, c, "left", overwrite_c=True) + assert_array_almost_equal(q @ c[:2], qc) + qc, r = qr_multiply(a, eye(2), "left") + assert_array_almost_equal(qc, q) + + def test_simple_complex_left_conjugate(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = [1, 2, 3+4j] + qc, r = qr_multiply(a, c, "left", conjugate=True) + assert_array_almost_equal(q.conj() @ c, qc) + + def test_simple_complex_tall_left_conjugate(self): + a = [[3, 3+4j], [5, 2+2j], [3, 2]] + q, r = qr(a, mode='economic') + c = [1, 3+4j] + qc, r = qr_multiply(a, c, "left", conjugate=True) + assert_array_almost_equal(q.conj() @ c, qc) + + def test_simple_complex_right_conjugate(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = np.array([1, 2, 3+4j]) + qc, r = qr_multiply(a, c, conjugate=True) + assert_array_almost_equal(c @ q.conj(), qc) + + def test_simple_complex_pivoting(self): + a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.conj().T @ q, eye(3)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_complex_left_pivoting(self): + a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]) + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3+4j] + qc, r, jpvt = qr_multiply(a, c, "left", True) + assert_array_almost_equal(q @ c, qc) + + def test_simple_complex_right_pivoting(self): + a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]) + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3+4j] + qc, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, qc) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a) + + def test_random_left(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(n), "left") + assert_array_almost_equal(q, qc) + + def test_random_right(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + cq, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + cq, r = qr_multiply(a, eye(n)) + assert_array_almost_equal(q, cq) + + def test_random_pivoting(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_tall(self): + rng = np.random.RandomState(1234) + # full version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a) + + def test_random_tall_left(self): + rng = np.random.RandomState(1234) + # full version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a, mode="economic") + c = rng.random([n]) + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(n), "left") + assert_array_almost_equal(qc, q) + + def test_random_tall_right(self): + rng = np.random.RandomState(1234) + # full version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a, mode="economic") + c = rng.random([m]) + cq, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + cq, r = qr_multiply(a, eye(m)) + assert_array_almost_equal(cq, q) + + def test_random_tall_pivoting(self): + rng = np.random.RandomState(1234) + # full version pivoting + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_tall_e(self): + rng = np.random.RandomState(1234) + # economy version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a, mode='economic') + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (n, n)) + + def test_random_tall_e_pivoting(self): + rng = np.random.RandomState(1234) + # economy version pivoting + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r, p = qr(a, pivoting=True, mode='economic') + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a[:, p]) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (n, n)) + q2, r2 = qr(a[:, p], mode='economic') + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_trap(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a) + + def test_random_trap_pivoting(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r = qr(a) + assert_array_almost_equal(q.conj().T @ q, eye(n)) + assert_array_almost_equal(q @ r, a) + + def test_random_complex_left(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + 1j*rng.random([n]) + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(n), "left") + assert_array_almost_equal(q, qc) + + def test_random_complex_right(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + 1j*rng.random([n]) + cq, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + cq, r = qr_multiply(a, eye(n)) + assert_array_almost_equal(q, cq) + + def test_random_complex_pivoting(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.conj().T @ q, eye(n)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_check_finite(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a, check_finite=False) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_lwork(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + # Get comparison values + q, r = qr(a, lwork=None) + + # Test against minimum valid lwork + q2, r2 = qr(a, lwork=3) + assert_array_almost_equal(q2, q) + assert_array_almost_equal(r2, r) + + # Test against larger lwork + q3, r3 = qr(a, lwork=10) + assert_array_almost_equal(q3, q) + assert_array_almost_equal(r3, r) + + # Test against explicit lwork=-1 + q4, r4 = qr(a, lwork=-1) + assert_array_almost_equal(q4, q) + assert_array_almost_equal(r4, r) + + # Test against invalid lwork + assert_raises(Exception, qr, (a,), {'lwork': 0}) + assert_raises(Exception, qr, (a,), {'lwork': 2}) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize("pivoting", [False, True]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, pivoting, dtype): + k = min(m, n) + + a = np.zeros((m, n), dtype=dtype) + q, r, *other = qr(a, pivoting=pivoting) + assert_equal(q.shape, (m, m)) + assert_equal(q.dtype, dtype) + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + r, *other = qr(a, mode='r', pivoting=pivoting) + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + q, r, *other = qr(a, mode='economic', pivoting=pivoting) + assert_equal(q.shape, (m, k)) + assert_equal(q.dtype, dtype) + assert_equal(r.shape, (k, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + (raw, tau), r, *other = qr(a, mode='raw', pivoting=pivoting) + assert_equal(raw.shape, (m, n)) + assert_equal(raw.dtype, dtype) + assert_equal(tau.shape, (k,)) + assert_equal(tau.dtype, dtype) + assert_equal(r.shape, (k, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, m, n): + k = min(m, n) + + a = np.empty((m, n)) + q, r = qr(a) + assert_allclose(q, np.identity(m)) + assert_allclose(r, np.empty((m, n))) + + q, r, p = qr(a, pivoting=True) + assert_allclose(q, np.identity(m)) + assert_allclose(r, np.empty((m, n))) + assert_allclose(p, np.arange(n)) + + r, = qr(a, mode='r') + assert_allclose(r, np.empty((m, n))) + + q, r = qr(a, mode='economic') + assert_allclose(q, np.empty((m, k))) + assert_allclose(r, np.empty((k, n))) + + (raw, tau), r = qr(a, mode='raw') + assert_allclose(raw, np.empty((m, n))) + assert_allclose(tau, np.empty((k,))) + assert_allclose(r, np.empty((k, n))) + + def test_multiply_empty(self): + a = np.empty((0, 0)) + c = np.empty((0, 0)) + cq, r = qr_multiply(a, c) + assert_allclose(cq, np.empty((0, 0))) + + a = np.empty((0, 2)) + c = np.empty((2, 0)) + cq, r = qr_multiply(a, c) + assert_allclose(cq, np.empty((2, 0))) + + a = np.empty((2, 0)) + c = np.empty((0, 2)) + cq, r = qr_multiply(a, c) + assert_allclose(cq, np.empty((0, 2))) + + +class TestRQ: + def test_simple(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_r(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + r, q = rq(a) + r2 = rq(a, mode='r') + assert_array_almost_equal(r, r2) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_simple_trap(self): + a = [[8, 2, 3], [2, 9, 3]] + r, q = rq(a) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_simple_tall(self): + a = [[8, 2], [2, 9], [5, 3]] + r, q = rq(a) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(r @ q, a) + + def test_simple_fat(self): + a = [[8, 2, 5], [2, 9, 3]] + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_simple_complex(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + r, q = rq(a) + assert_array_almost_equal(q @ q.conj().T, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_random_tall(self): + rng = np.random.RandomState(1234) + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_random_trap(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_random_trap_economic(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + r, q = rq(a, mode='economic') + assert_array_almost_equal(q @ q.T, eye(m)) + assert_array_almost_equal(r @ q, a) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (m, m)) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.conj().T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_random_complex_economic(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + 1j*rng.random([m, n]) + r, q = rq(a, mode='economic') + assert_array_almost_equal(q @ q.conj().T, eye(m)) + assert_array_almost_equal(r @ q, a) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (m, m)) + + def test_check_finite(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + r, q = rq(a, check_finite=False) + assert_array_almost_equal(q @ q.T, eye(3)) + assert_array_almost_equal(r @ q, a) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, dtype): + k = min(m, n) + + a = np.zeros((m, n), dtype=dtype) + r, q = rq(a) + assert_equal(q.shape, (n, n)) + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + assert_equal(q.dtype, dtype) + + r = rq(a, mode='r') + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + + r, q = rq(a, mode='economic') + assert_equal(r.shape, (m, k)) + assert_equal(r.dtype, dtype) + assert_equal(q.shape, (k, n)) + assert_equal(q.dtype, dtype) + + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, m, n): + k = min(m, n) + + a = np.empty((m, n)) + r, q = rq(a) + assert_allclose(r, np.empty((m, n))) + assert_allclose(q, np.identity(n)) + + r = rq(a, mode='r') + assert_allclose(r, np.empty((m, n))) + + r, q = rq(a, mode='economic') + assert_allclose(r, np.empty((m, k))) + assert_allclose(q, np.empty((k, n))) + + +class TestSchur: + + def check_schur(self, a, t, u, rtol, atol): + # Check that the Schur decomposition is correct. + assert_allclose(u @ t @ u.conj().T, a, rtol=rtol, atol=atol, + err_msg="Schur decomposition does not match 'a'") + # The expected value of u @ u.H - I is all zeros, so test + # with absolute tolerance only. + assert_allclose(u @ u.conj().T - np.eye(len(u)), 0, rtol=0, atol=atol, + err_msg="u is not unitary") + + def test_simple(self): + a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]] + t, z = schur(a) + self.check_schur(a, t, z, rtol=1e-14, atol=5e-15) + tc, zc = schur(a, 'complex') + assert_(np.any(ravel(iscomplex(zc))) and np.any(ravel(iscomplex(tc)))) + self.check_schur(a, tc, zc, rtol=1e-14, atol=5e-15) + tc2, zc2 = rsf2csf(tc, zc) + self.check_schur(a, tc2, zc2, rtol=1e-14, atol=5e-15) + + @pytest.mark.parametrize( + 'sort, expected_diag', + [('lhp', [-np.sqrt(2), -0.5, np.sqrt(2), 0.5]), + ('rhp', [np.sqrt(2), 0.5, -np.sqrt(2), -0.5]), + ('iuc', [-0.5, 0.5, np.sqrt(2), -np.sqrt(2)]), + ('ouc', [np.sqrt(2), -np.sqrt(2), -0.5, 0.5]), + (lambda x: x >= 0.0, [np.sqrt(2), 0.5, -np.sqrt(2), -0.5])] + ) + def test_sort(self, sort, expected_diag): + # The exact eigenvalues of this matrix are + # -sqrt(2), sqrt(2), -1/2, 1/2. + a = [[4., 3., 1., -1.], + [-4.5, -3.5, -1., 1.], + [9., 6., -4., 4.5], + [6., 4., -3., 3.5]] + t, u, sdim = schur(a, sort=sort) + self.check_schur(a, t, u, rtol=1e-14, atol=5e-15) + assert_allclose(np.diag(t), expected_diag, rtol=1e-12) + assert_equal(2, sdim) + + def test_sort_errors(self): + a = [[4., 3., 1., -1.], + [-4.5, -3.5, -1., 1.], + [9., 6., -4., 4.5], + [6., 4., -3., 3.5]] + assert_raises(ValueError, schur, a, sort='unsupported') + assert_raises(ValueError, schur, a, sort=1) + + def test_check_finite(self): + a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]] + t, z = schur(a, check_finite=False) + assert_array_almost_equal(z @ t @ z.conj().T, a) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + t, z = schur(a) + t0, z0 = schur(np.eye(2, dtype=dt)) + assert_allclose(t, np.empty((0, 0))) + assert_allclose(z, np.empty((0, 0))) + assert t.dtype == t0.dtype + assert z.dtype == z0.dtype + + t, z, sdim = schur(a, sort='lhp') + assert_allclose(t, np.empty((0, 0))) + assert_allclose(z, np.empty((0, 0))) + assert_equal(sdim, 0) + assert t.dtype == t0.dtype + assert z.dtype == z0.dtype + + @pytest.mark.parametrize('sort', ['iuc', 'ouc']) + @pytest.mark.parametrize('output', ['real', 'complex']) + @pytest.mark.parametrize('dtype', [np.float32, np.float64, + np.complex64, np.complex128]) + def test_gh_13137_sort_str(self, sort, output, dtype): + # gh-13137 reported that sort values 'iuc' and 'ouc' were not + # correct because the callables assumed that the eigenvalues would + # always be expressed as a single complex number. + # In fact, when `output='real'` and the dtype is real, the + # eigenvalues are passed as separate real and imaginary components + # (yet no error is raised if the callable accepts only one argument). + # + # This tests these sort values by counting the number of eigenvalues + # `schur` reports as being inside/outside the unit circle. + + # Real matrix with eigenvalues 0.1 +- 2j + A = np.asarray([[0.1, -2], [2, 0.1]]) + + # Previously, this would fail for `output='real'` with real dtypes + sdim = schur(A.astype(dtype), sort=sort, output=output)[-1] + assert sdim == 0 if sort == 'iuc' else sdim == 2 + + @pytest.mark.parametrize('output', ['real', 'complex']) + @pytest.mark.parametrize('dtype', [np.float32, np.float64, + np.complex64, np.complex128]) + def test_gh_13137_sort_custom(self, output, dtype): + # This simply tests our understanding of how eigenvalues are + # passed to a sort callable. If `output='real'` and the dtype is real, + # real and imaginary parts are passed as separate real arguments; + # otherwise, they are passed a single complex argument. + # Also, if `output='real'` and the dtype is real, when either + # eigenvalue in a complex conjugate pair satisfies the sort condition, + # `sdim` is incremented by TWO. + + # Real matrix with eigenvalues 0.1 +- 2j + A = np.asarray([[0.1, -2], [2, 0.1]]) + + all_real = output=='real' and dtype in {np.float32, np.float64} + + def sort(x, y=None): + if all_real: + assert not np.iscomplexobj(x) + assert y is not None and np.isreal(y) + z = x + y*1j + else: + assert np.iscomplexobj(x) + assert y is None + z = x + return z.imag > 1e-15 + + # Only one complex eigenvalue satisfies the condition, but when + # `all_real` applies, both eigenvalues in the complex conjugate pair + # are counted. + sdim = schur(A.astype(dtype), sort=sort, output=output)[-1] + assert sdim == 2 if all_real else sdim == 1 + + +class TestHessenberg: + + def test_simple(self): + a = [[-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]] + h1 = [[-149.0000, 42.2037, -156.3165], + [-537.6783, 152.5511, -554.9272], + [0, 0.0728, 2.4489]] + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + assert_array_almost_equal(h, h1, decimal=4) + + def test_simple_complex(self): + a = [[-149, -50, -154], + [537, 180j, 546], + [-27j, -9, -25]] + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.conj().T @ a @ q, h) + + def test_simple2(self): + a = [[1, 2, 3, 4, 5, 6, 7], + [0, 2, 3, 4, 6, 7, 2], + [0, 2, 2, 3, 0, 3, 2], + [0, 0, 2, 8, 0, 0, 2], + [0, 3, 1, 2, 0, 1, 2], + [0, 1, 2, 3, 0, 1, 0], + [0, 0, 0, 0, 0, 1, 2]] + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + + def test_simple3(self): + a = np.eye(3) + a[-1, 0] = 2 + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.conj().T @ a @ q, h) + + def test_check_finite(self): + a = [[-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]] + h1 = [[-149.0000, 42.2037, -156.3165], + [-537.6783, 152.5511, -554.9272], + [0, 0.0728, 2.4489]] + h, q = hessenberg(a, calc_q=1, check_finite=False) + assert_array_almost_equal(q.T @ a @ q, h) + assert_array_almost_equal(h, h1, decimal=4) + + def test_2x2(self): + a = [[2, 1], [7, 12]] + + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q, np.eye(2)) + assert_array_almost_equal(h, a) + + b = [[2-7j, 1+2j], [7+3j, 12-2j]] + h2, q2 = hessenberg(b, calc_q=1) + assert_array_almost_equal(q2, np.eye(2)) + assert_array_almost_equal(h2, b) + + @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + h = hessenberg(a) + assert h.shape == (0, 0) + assert h.dtype == hessenberg(np.eye(3, dtype=dt)).dtype + + h, q = hessenberg(a, calc_q=True) + h3, q3 = hessenberg(a, calc_q=True) + assert h.shape == (0, 0) + assert h.dtype == h3.dtype + + assert q.shape == (0, 0) + assert q.dtype == q3.dtype + + +blas_provider = blas_version = None +blas_provider = CONFIG['Build Dependencies']['blas']['name'] +blas_version = CONFIG['Build Dependencies']['blas']['version'] + + +class TestQZ: + def test_qz_single(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]).astype(float32) + B = rng.random([n, n]).astype(float32) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.T, A, decimal=5) + assert_array_almost_equal(Q @ BB @ Z.T, B, decimal=5) + assert_array_almost_equal(Q @ Q.T, eye(n), decimal=5) + assert_array_almost_equal(Z @ Z.T, eye(n), decimal=5) + assert_(np.all(diag(BB) >= 0)) + + def test_qz_double(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + B = rng.random([n, n]) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.T, A) + assert_array_almost_equal(Q @ BB @ Z.T, B) + assert_array_almost_equal(Q @ Q.T, eye(n)) + assert_array_almost_equal(Z @ Z.T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + + def test_qz_complex(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + 1j*rng.random([n, n]) + B = rng.random([n, n]) + 1j*rng.random([n, n]) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.conj().T, A) + assert_array_almost_equal(Q @ BB @ Z.conj().T, B) + assert_array_almost_equal(Q @ Q.conj().T, eye(n)) + assert_array_almost_equal(Z @ Z.conj().T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + assert_(np.all(diag(BB).imag == 0)) + + def test_qz_complex64(self): + rng = np.random.RandomState(12345) + n = 5 + A = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64) + B = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.conj().T, A, decimal=5) + assert_array_almost_equal(Q @ BB @ Z.conj().T, B, decimal=5) + assert_array_almost_equal(Q @ Q.conj().T, eye(n), decimal=5) + assert_array_almost_equal(Z @ Z.conj().T, eye(n), decimal=5) + assert_(np.all(diag(BB) >= 0)) + assert_(np.all(diag(BB).imag == 0)) + + def test_qz_double_complex(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + B = rng.random([n, n]) + AA, BB, Q, Z = qz(A, B, output='complex') + aa = Q @ AA @ Z.conj().T + assert_array_almost_equal(aa.real, A) + assert_array_almost_equal(aa.imag, 0) + bb = Q @ BB @ Z.conj().T + assert_array_almost_equal(bb.real, B) + assert_array_almost_equal(bb.imag, 0) + assert_array_almost_equal(Q @ Q.conj().T, eye(n)) + assert_array_almost_equal(Z @ Z.conj().T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + + def test_qz_double_sort(self): + # from https://www.nag.com/lapack-ex/node119.html + # NOTE: These matrices may be ill-conditioned and lead to a + # seg fault on certain python versions when compiled with + # sse2 or sse3 older ATLAS/LAPACK binaries for windows + # A = np.array([[3.9, 12.5, -34.5, -0.5], + # [ 4.3, 21.5, -47.5, 7.5], + # [ 4.3, 21.5, -43.5, 3.5], + # [ 4.4, 26.0, -46.0, 6.0 ]]) + + # B = np.array([[ 1.0, 2.0, -3.0, 1.0], + # [1.0, 3.0, -5.0, 4.0], + # [1.0, 3.0, -4.0, 3.0], + # [1.0, 3.0, -4.0, 4.0]]) + A = np.array([[3.9, 12.5, -34.5, 2.5], + [4.3, 21.5, -47.5, 7.5], + [4.3, 1.5, -43.5, 3.5], + [4.4, 6.0, -46.0, 6.0]]) + + B = np.array([[1.0, 1.0, -3.0, 1.0], + [1.0, 3.0, -5.0, 4.4], + [1.0, 2.0, -4.0, 1.0], + [1.2, 3.0, -4.0, 4.0]]) + + assert_raises(ValueError, qz, A, B, sort=lambda ar, ai, beta: ai == 0) + if False: + AA, BB, Q, Z, sdim = qz(A, B, sort=lambda ar, ai, beta: ai == 0) + # assert_(sdim == 2) + assert_(sdim == 4) + assert_array_almost_equal(Q @ AA @ Z.T, A) + assert_array_almost_equal(Q @ BB @ Z.T, B) + + # test absolute values bc the sign is ambiguous and + # might be platform dependent + assert_array_almost_equal(np.abs(AA), np.abs(np.array( + [[35.7864, -80.9061, -12.0629, -9.498], + [0., 2.7638, -2.3505, 7.3256], + [0., 0., 0.6258, -0.0398], + [0., 0., 0., -12.8217]])), 4) + assert_array_almost_equal(np.abs(BB), np.abs(np.array( + [[4.5324, -8.7878, 3.2357, -3.5526], + [0., 1.4314, -2.1894, 0.9709], + [0., 0., 1.3126, -0.3468], + [0., 0., 0., 0.559]])), 4) + assert_array_almost_equal(np.abs(Q), np.abs(np.array( + [[-0.4193, -0.605, -0.1894, -0.6498], + [-0.5495, 0.6987, 0.2654, -0.3734], + [-0.4973, -0.3682, 0.6194, 0.4832], + [-0.5243, 0.1008, -0.7142, 0.4526]])), 4) + assert_array_almost_equal(np.abs(Z), np.abs(np.array( + [[-0.9471, -0.2971, -0.1217, 0.0055], + [-0.0367, 0.1209, 0.0358, 0.9913], + [0.3171, -0.9041, -0.2547, 0.1312], + [0.0346, 0.2824, -0.9587, 0.0014]])), 4) + + # test absolute values bc the sign is ambiguous and might be platform + # dependent + # assert_array_almost_equal(abs(AA), abs(np.array([ + # [3.8009, -69.4505, 50.3135, -43.2884], + # [0.0000, 9.2033, -0.2001, 5.9881], + # [0.0000, 0.0000, 1.4279, 4.4453], + # [0.0000, 0.0000, 0.9019, -1.1962]])), 4) + # assert_array_almost_equal(abs(BB), abs(np.array([ + # [1.9005, -10.2285, 0.8658, -5.2134], + # [0.0000, 2.3008, 0.7915, 0.4262], + # [0.0000, 0.0000, 0.8101, 0.0000], + # [0.0000, 0.0000, 0.0000, -0.2823]])), 4) + # assert_array_almost_equal(abs(Q), abs(np.array([ + # [0.4642, 0.7886, 0.2915, -0.2786], + # [0.5002, -0.5986, 0.5638, -0.2713], + # [0.5002, 0.0154, -0.0107, 0.8657], + # [0.5331, -0.1395, -0.7727, -0.3151]])), 4) + # assert_array_almost_equal(dot(Q,Q.T), eye(4)) + # assert_array_almost_equal(abs(Z), abs(np.array([ + # [0.9961, -0.0014, 0.0887, -0.0026], + # [0.0057, -0.0404, -0.0938, -0.9948], + # [0.0626, 0.7194, -0.6908, 0.0363], + # [0.0626, -0.6934, -0.7114, 0.0956]])), 4) + # assert_array_almost_equal(dot(Z,Z.T), eye(4)) + + # def test_qz_complex_sort(self): + # cA = np.array([ + # [-21.10+22.50*1j, 53.50+-50.50*1j, -34.50+127.50*1j, 7.50+ 0.50*1j], + # [-0.46+ -7.78*1j, -3.50+-37.50*1j, -15.50+ 58.50*1j,-10.50+ -1.50*1j], + # [ 4.30+ -5.50*1j, 39.70+-17.10*1j, -68.50+ 12.50*1j, -7.50+ -3.50*1j], + # [ 5.50+ 4.40*1j, 14.40+ 43.30*1j, -32.50+-46.00*1j,-19.00+-32.50*1j]]) + + # cB = np.array([ + # [1.00+ -5.00*1j, 1.60+ 1.20*1j,-3.00+ 0.00*1j, 0.00+ -1.00*1j], + # [0.80+ -0.60*1j, 3.00+ -5.00*1j,-4.00+ 3.00*1j,-2.40+ -3.20*1j], + # [1.00+ 0.00*1j, 2.40+ 1.80*1j,-4.00+ -5.00*1j, 0.00+ -3.00*1j], + # [0.00+ 1.00*1j,-1.80+ 2.40*1j, 0.00+ -4.00*1j, 4.00+ -5.00*1j]]) + + # AAS,BBS,QS,ZS,sdim = qz(cA,cB,sort='lhp') + + # eigenvalues = diag(AAS)/diag(BBS) + # assert_(np.all(np.real(eigenvalues[:sdim] < 0))) + # assert_(np.all(np.real(eigenvalues[sdim:] > 0))) + + def test_check_finite(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + B = rng.random([n, n]) + AA, BB, Q, Z = qz(A, B, check_finite=False) + assert_array_almost_equal(Q @ AA @ Z.T, A) + assert_array_almost_equal(Q @ BB @ Z.T, B) + assert_array_almost_equal(Q @ Q.T, eye(n)) + assert_array_almost_equal(Z @ Z.T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + + +class TestOrdQZ: + @classmethod + def setup_class(cls): + # https://www.nag.com/lapack-ex/node119.html + A1 = np.array([[-21.10 - 22.50j, 53.5 - 50.5j, -34.5 + 127.5j, + 7.5 + 0.5j], + [-0.46 - 7.78j, -3.5 - 37.5j, -15.5 + 58.5j, + -10.5 - 1.5j], + [4.30 - 5.50j, 39.7 - 17.1j, -68.5 + 12.5j, + -7.5 - 3.5j], + [5.50 + 4.40j, 14.4 + 43.3j, -32.5 - 46.0j, + -19.0 - 32.5j]]) + + B1 = np.array([[1.0 - 5.0j, 1.6 + 1.2j, -3 + 0j, 0.0 - 1.0j], + [0.8 - 0.6j, .0 - 5.0j, -4 + 3j, -2.4 - 3.2j], + [1.0 + 0.0j, 2.4 + 1.8j, -4 - 5j, 0.0 - 3.0j], + [0.0 + 1.0j, -1.8 + 2.4j, 0 - 4j, 4.0 - 5.0j]]) + + # https://www.nag.com/numeric/fl/nagdoc_fl23/xhtml/F08/f08yuf.xml + A2 = np.array([[3.9, 12.5, -34.5, -0.5], + [4.3, 21.5, -47.5, 7.5], + [4.3, 21.5, -43.5, 3.5], + [4.4, 26.0, -46.0, 6.0]]) + + B2 = np.array([[1, 2, -3, 1], + [1, 3, -5, 4], + [1, 3, -4, 3], + [1, 3, -4, 4]]) + + # example with the eigenvalues + # -0.33891648, 1.61217396+0.74013521j, 1.61217396-0.74013521j, + # 0.61244091 + # thus featuring: + # * one complex conjugate eigenvalue pair, + # * one eigenvalue in the lhp + # * 2 eigenvalues in the unit circle + # * 2 non-real eigenvalues + A3 = np.array([[5., 1., 3., 3.], + [4., 4., 2., 7.], + [7., 4., 1., 3.], + [0., 4., 8., 7.]]) + B3 = np.array([[8., 10., 6., 10.], + [7., 7., 2., 9.], + [9., 1., 6., 6.], + [5., 1., 4., 7.]]) + + # example with infinite eigenvalues + A4 = np.eye(2) + B4 = np.diag([0, 1]) + + # example with (alpha, beta) = (0, 0) + A5 = np.diag([1, 0]) + + cls.A = [A1, A2, A3, A4, A5] + cls.B = [B1, B2, B3, B4, A5] + + def qz_decomp(self, sort): + with np.errstate(all='raise'): + ret = [ordqz(Ai, Bi, sort=sort) for Ai, Bi in zip(self.A, self.B)] + return tuple(ret) + + def check(self, A, B, sort, AA, BB, alpha, beta, Q, Z): + Id = np.eye(*A.shape) + # make sure Q and Z are orthogonal + assert_array_almost_equal(Q @ Q.T.conj(), Id) + assert_array_almost_equal(Z @ Z.T.conj(), Id) + # check factorization + assert_array_almost_equal(Q @ AA, A @ Z) + assert_array_almost_equal(Q @ BB, B @ Z) + # check shape of AA and BB + assert_array_equal(np.tril(AA, -2), np.zeros(AA.shape)) + assert_array_equal(np.tril(BB, -1), np.zeros(BB.shape)) + # check eigenvalues + for i in range(A.shape[0]): + # does the current diagonal element belong to a 2-by-2 block + # that was already checked? + if i > 0 and A[i, i - 1] != 0: + continue + # take care of 2-by-2 blocks + if i < AA.shape[0] - 1 and AA[i + 1, i] != 0: + evals, _ = eig(AA[i:i + 2, i:i + 2], BB[i:i + 2, i:i + 2]) + # make sure the pair of complex conjugate eigenvalues + # is ordered consistently (positive imaginary part first) + if evals[0].imag < 0: + evals = evals[[1, 0]] + tmp = alpha[i:i + 2]/beta[i:i + 2] + if tmp[0].imag < 0: + tmp = tmp[[1, 0]] + assert_array_almost_equal(evals, tmp) + else: + if alpha[i] == 0 and beta[i] == 0: + assert_equal(AA[i, i], 0) + assert_equal(BB[i, i], 0) + elif beta[i] == 0: + assert_equal(BB[i, i], 0) + else: + assert_almost_equal(AA[i, i]/BB[i, i], alpha[i]/beta[i]) + sortfun = _select_function(sort) + lastsort = True + for i in range(A.shape[0]): + cursort = sortfun(np.array([alpha[i]]), np.array([beta[i]])) + # once the sorting criterion was not matched all subsequent + # eigenvalues also shouldn't match + if not lastsort: + assert not cursort + lastsort = cursort + + def check_all(self, sort): + ret = self.qz_decomp(sort) + + for reti, Ai, Bi in zip(ret, self.A, self.B): + self.check(Ai, Bi, sort, *reti) + + def test_lhp(self): + self.check_all('lhp') + + def test_rhp(self): + self.check_all('rhp') + + def test_iuc(self): + self.check_all('iuc') + + def test_ouc(self): + self.check_all('ouc') + + def test_ref(self): + # real eigenvalues first (top-left corner) + def sort(x, y): + out = np.empty_like(x, dtype=bool) + nonzero = (y != 0) + out[~nonzero] = False + out[nonzero] = (x[nonzero]/y[nonzero]).imag == 0 + return out + + self.check_all(sort) + + def test_cef(self): + # complex eigenvalues first (top-left corner) + def sort(x, y): + out = np.empty_like(x, dtype=bool) + nonzero = (y != 0) + out[~nonzero] = False + out[nonzero] = (x[nonzero]/y[nonzero]).imag != 0 + return out + + self.check_all(sort) + + def test_diff_input_types(self): + ret = ordqz(self.A[1], self.B[2], sort='lhp') + self.check(self.A[1], self.B[2], 'lhp', *ret) + + ret = ordqz(self.B[2], self.A[1], sort='lhp') + self.check(self.B[2], self.A[1], 'lhp', *ret) + + def test_sort_explicit(self): + # Test order of the eigenvalues in the 2 x 2 case where we can + # explicitly compute the solution + A1 = np.eye(2) + B1 = np.diag([-2, 0.5]) + expected1 = [('lhp', [-0.5, 2]), + ('rhp', [2, -0.5]), + ('iuc', [-0.5, 2]), + ('ouc', [2, -0.5])] + A2 = np.eye(2) + B2 = np.diag([-2 + 1j, 0.5 + 0.5j]) + expected2 = [('lhp', [1/(-2 + 1j), 1/(0.5 + 0.5j)]), + ('rhp', [1/(0.5 + 0.5j), 1/(-2 + 1j)]), + ('iuc', [1/(-2 + 1j), 1/(0.5 + 0.5j)]), + ('ouc', [1/(0.5 + 0.5j), 1/(-2 + 1j)])] + # 'lhp' is ambiguous so don't test it + A3 = np.eye(2) + B3 = np.diag([2, 0]) + expected3 = [('rhp', [0.5, np.inf]), + ('iuc', [0.5, np.inf]), + ('ouc', [np.inf, 0.5])] + # 'rhp' is ambiguous so don't test it + A4 = np.eye(2) + B4 = np.diag([-2, 0]) + expected4 = [('lhp', [-0.5, np.inf]), + ('iuc', [-0.5, np.inf]), + ('ouc', [np.inf, -0.5])] + A5 = np.diag([0, 1]) + B5 = np.diag([0, 0.5]) + # 'lhp' and 'iuc' are ambiguous so don't test them + expected5 = [('rhp', [2, np.nan]), + ('ouc', [2, np.nan])] + + A = [A1, A2, A3, A4, A5] + B = [B1, B2, B3, B4, B5] + expected = [expected1, expected2, expected3, expected4, expected5] + for Ai, Bi, expectedi in zip(A, B, expected): + for sortstr, expected_eigvals in expectedi: + _, _, alpha, beta, _, _ = ordqz(Ai, Bi, sort=sortstr) + azero = (alpha == 0) + bzero = (beta == 0) + x = np.empty_like(alpha) + x[azero & bzero] = np.nan + x[~azero & bzero] = np.inf + x[~bzero] = alpha[~bzero]/beta[~bzero] + assert_allclose(expected_eigvals, x) + + +class TestOrdQZWorkspaceSize: + @pytest.mark.fail_slow(5) + def test_decompose(self): + rng = np.random.RandomState(12345) + N = 202 + # raises error if lwork parameter to dtrsen is too small + for ddtype in [np.float32, np.float64]: + A = rng.random((N, N)).astype(ddtype) + B = rng.random((N, N)).astype(ddtype) + # sort = lambda ar, ai, b: ar**2 + ai**2 < b**2 + _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta, + output='real') + + for ddtype in [np.complex128, np.complex64]: + A = rng.random((N, N)).astype(ddtype) + B = rng.random((N, N)).astype(ddtype) + _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta, + output='complex') + + @pytest.mark.slow + def test_decompose_ouc(self): + rng = np.random.RandomState(12345) + N = 202 + # segfaults if lwork parameter to dtrsen is too small + for ddtype in [np.float32, np.float64, np.complex128, np.complex64]: + A = rng.random((N, N)).astype(ddtype) + B = rng.random((N, N)).astype(ddtype) + S, T, alpha, beta, U, V = ordqz(A, B, sort='ouc') + + +class TestDatacopied: + + def test_datacopied(self): + from scipy.linalg._decomp import _datacopied + + M = matrix([[0, 1], [2, 3]]) + A = asarray(M) + L = M.tolist() + M2 = M.copy() + + class Fake1: + def __array__(self, dtype=None, copy=None): + return A + + class Fake2: + __array_interface__ = A.__array_interface__ + + F1 = Fake1() + F2 = Fake2() + + for item, status in [(M, False), (A, False), (L, True), + (M2, False), (F1, False), (F2, False)]: + arr = asarray(item) + assert_equal(_datacopied(arr, item), status, + err_msg=repr(item)) + + +def test_aligned_mem_float(): + """Check linalg works with non-aligned memory (float32)""" + # Allocate 402 bytes of memory (allocated on boundary) + a = arange(402, dtype=np.uint8) + + # Create an array with boundary offset 4 + z = np.frombuffer(a.data, offset=2, count=100, dtype=float32) + z = z.reshape((10, 10)) + + eig(z, overwrite_a=True) + eig(z.T, overwrite_a=True) + + +@pytest.mark.skipif(platform.machine() == 'ppc64le', + reason="crashes on ppc64le") +def test_aligned_mem(): + """Check linalg works with non-aligned memory (float64)""" + # Allocate 804 bytes of memory (allocated on boundary) + a = arange(804, dtype=np.uint8) + + # Create an array with boundary offset 4 + z = np.frombuffer(a.data, offset=4, count=100, dtype=float) + z = z.reshape((10, 10)) + + eig(z, overwrite_a=True) + eig(z.T, overwrite_a=True) + + +def test_aligned_mem_complex(): + """Check that complex objects don't need to be completely aligned""" + # Allocate 1608 bytes of memory (allocated on boundary) + a = zeros(1608, dtype=np.uint8) + + # Create an array with boundary offset 8 + z = np.frombuffer(a.data, offset=8, count=100, dtype=complex) + z = z.reshape((10, 10)) + + eig(z, overwrite_a=True) + # This does not need special handling + eig(z.T, overwrite_a=True) + + +def check_lapack_misaligned(func, args, kwargs): + args = list(args) + for i in range(len(args)): + a = args[:] + if isinstance(a[i], np.ndarray): + # Try misaligning a[i] + aa = np.zeros(a[i].size*a[i].dtype.itemsize+8, dtype=np.uint8) + aa = np.frombuffer(aa.data, offset=4, count=a[i].size, + dtype=a[i].dtype) + aa = aa.reshape(a[i].shape) + aa[...] = a[i] + a[i] = aa + func(*a, **kwargs) + if len(a[i].shape) > 1: + a[i] = a[i].T + func(*a, **kwargs) + + +@pytest.mark.xfail(run=False, + reason="Ticket #1152, triggers a segfault in rare cases.") +def test_lapack_misaligned(): + M = np.eye(10, dtype=float) + R = np.arange(100).reshape((10, 10)) + S = np.arange(20000, dtype=np.uint8) + S = np.frombuffer(S.data, offset=4, count=100, dtype=float) + S = S.reshape((10, 10)) + b = np.ones(10) + LU, piv = lu_factor(S) + for (func, args, kwargs) in [ + (eig, (S,), dict(overwrite_a=True)), # crash + (eigvals, (S,), dict(overwrite_a=True)), # no crash + (lu, (S,), dict(overwrite_a=True)), # no crash + (lu_factor, (S,), dict(overwrite_a=True)), # no crash + (lu_solve, ((LU, piv), b), dict(overwrite_b=True)), + (solve, (S, b), dict(overwrite_a=True, overwrite_b=True)), + (svd, (M,), dict(overwrite_a=True)), # no crash + (svd, (R,), dict(overwrite_a=True)), # no crash + (svd, (S,), dict(overwrite_a=True)), # crash + (svdvals, (S,), dict()), # no crash + (svdvals, (S,), dict(overwrite_a=True)), # crash + (cholesky, (M,), dict(overwrite_a=True)), # no crash + (qr, (S,), dict(overwrite_a=True)), # crash + (rq, (S,), dict(overwrite_a=True)), # crash + (hessenberg, (S,), dict(overwrite_a=True)), # crash + (schur, (S,), dict(overwrite_a=True)), # crash + ]: + check_lapack_misaligned(func, args, kwargs) +# not properly tested +# cholesky, rsf2csf, lu_solve, solve, eig_banded, eigvals_banded, eigh, diagsvd + + +class TestOverwrite: + def test_eig(self): + assert_no_overwrite(eig, [(3, 3)]) + assert_no_overwrite(eig, [(3, 3), (3, 3)]) + + def test_eigh(self): + assert_no_overwrite(eigh, [(3, 3)]) + assert_no_overwrite(eigh, [(3, 3), (3, 3)]) + + def test_eig_banded(self): + assert_no_overwrite(eig_banded, [(3, 2)]) + + def test_eigvals(self): + assert_no_overwrite(eigvals, [(3, 3)]) + + def test_eigvalsh(self): + assert_no_overwrite(eigvalsh, [(3, 3)]) + + def test_eigvals_banded(self): + assert_no_overwrite(eigvals_banded, [(3, 2)]) + + def test_hessenberg(self): + assert_no_overwrite(hessenberg, [(3, 3)]) + + def test_lu_factor(self): + assert_no_overwrite(lu_factor, [(3, 3)]) + + def test_lu_solve(self): + x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]]) + xlu = lu_factor(x) + assert_no_overwrite(lambda b: lu_solve(xlu, b), [(3,)]) + + def test_lu(self): + assert_no_overwrite(lu, [(3, 3)]) + + def test_qr(self): + assert_no_overwrite(qr, [(3, 3)]) + + def test_rq(self): + assert_no_overwrite(rq, [(3, 3)]) + + def test_schur(self): + assert_no_overwrite(schur, [(3, 3)]) + + def test_schur_complex(self): + assert_no_overwrite(lambda a: schur(a, 'complex'), [(3, 3)], + dtypes=[np.float32, np.float64]) + + def test_svd(self): + assert_no_overwrite(svd, [(3, 3)]) + assert_no_overwrite(lambda a: svd(a, lapack_driver='gesvd'), [(3, 3)]) + + def test_svdvals(self): + assert_no_overwrite(svdvals, [(3, 3)]) + + +def _check_orth(n, dtype, skip_big=False): + X = np.ones((n, 2), dtype=float).astype(dtype) + + eps = np.finfo(dtype).eps + tol = 1000 * eps + + Y = orth(X) + assert_equal(Y.shape, (n, 1)) + assert_allclose(Y, Y.mean(), atol=tol, rtol=1.4e-7) + + Y = orth(X.T) + assert_equal(Y.shape, (2, 1)) + assert_allclose(Y, Y.mean(), atol=tol) + + if n > 5 and not skip_big: + rng = np.random.RandomState(1) + X = rng.rand(n, 5) @ rng.rand(5, n) + X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n) + X = X.astype(dtype) + + Y = orth(X, rcond=1e-3) + assert_equal(Y.shape, (n, 5)) + + Y = orth(X, rcond=1e-6) + assert_equal(Y.shape, (n, 5 + 1)) + + +@pytest.mark.slow +@pytest.mark.skipif(np.dtype(np.intp).itemsize < 8, + reason="test only on 64-bit, else too slow") +def test_orth_memory_efficiency(): + # Pick n so that 16*n bytes is reasonable but 8*n*n bytes is unreasonable. + # Keep in mind that @pytest.mark.slow tests are likely to be running + # under configurations that support 4Gb+ memory for tests related to + # 32 bit overflow. + n = 10*1000*1000 + try: + _check_orth(n, np.float64, skip_big=True) + except MemoryError as e: + raise AssertionError( + 'memory error perhaps caused by orth regression' + ) from e + + +def test_orth(): + dtypes = [np.float32, np.float64, np.complex64, np.complex128] + sizes = [1, 2, 3, 10, 100] + for dt, n in itertools.product(dtypes, sizes): + _check_orth(n, dt) + +@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) +def test_orth_empty(dt): + a = np.empty((0, 0), dtype=dt) + a0 = np.eye(2, dtype=dt) + + oa = orth(a) + assert oa.dtype == orth(a0).dtype + assert oa.shape == (0, 0) + + +class TestNullSpace: + def test_null_space(self): + rng = np.random.RandomState(1) + + dtypes = [np.float32, np.float64, np.complex64, np.complex128] + sizes = [1, 2, 3, 10, 100] + + for dt, n in itertools.product(dtypes, sizes): + X = np.ones((2, n), dtype=dt) + + eps = np.finfo(dt).eps + tol = 1000 * eps + + Y = null_space(X) + assert_equal(Y.shape, (n, n-1)) + assert_allclose(X @ Y, 0, atol=tol) + + Y = null_space(X.T) + assert_equal(Y.shape, (2, 1)) + assert_allclose(X.T @ Y, 0, atol=tol) + + X = rng.randn(1 + n//2, n) + Y = null_space(X) + assert_equal(Y.shape, (n, n - 1 - n//2)) + assert_allclose(X @ Y, 0, atol=tol) + + if n > 5: + rng = np.random.RandomState(1) + X = rng.rand(n, 5) @ rng.rand(5, n) + X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n) + X = X.astype(dt) + + Y = null_space(X, rcond=1e-3) + assert_equal(Y.shape, (n, n - 5)) + + Y = null_space(X, rcond=1e-6) + assert_equal(Y.shape, (n, n - 6)) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_null_space_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a0 = np.eye(2, dtype=dt) + nsa = null_space(a) + + assert nsa.shape == (0, 0) + assert nsa.dtype == null_space(a0).dtype + + @pytest.mark.parametrize("overwrite_a", [True, False]) + @pytest.mark.parametrize("check_finite", [True, False]) + @pytest.mark.parametrize("lapack_driver", ["gesdd", "gesvd"]) + def test_null_space_options(self, overwrite_a, check_finite, lapack_driver): + rng = np.random.default_rng(42887289350573064398746) + n = 10 + X = rng.standard_normal((1 + n//2, n)) + Y = null_space(X.copy(), overwrite_a=overwrite_a, check_finite=check_finite, + lapack_driver=lapack_driver) + assert_allclose(X @ Y, 0, atol=np.finfo(X.dtype).eps*100) + + +def test_subspace_angles(): + H = hadamard(8, float) + A = H[:, :3] + B = H[:, 3:] + assert_allclose(subspace_angles(A, B), [np.pi / 2.] * 3, atol=1e-14) + assert_allclose(subspace_angles(B, A), [np.pi / 2.] * 3, atol=1e-14) + for x in (A, B): + assert_allclose(subspace_angles(x, x), np.zeros(x.shape[1]), + atol=1e-14) + # From MATLAB function "subspace", which effectively only returns the + # last value that we calculate + x = np.array( + [[0.537667139546100, 0.318765239858981, 3.578396939725760, 0.725404224946106], # noqa: E501 + [1.833885014595086, -1.307688296305273, 2.769437029884877, -0.063054873189656], # noqa: E501 + [-2.258846861003648, -0.433592022305684, -1.349886940156521, 0.714742903826096], # noqa: E501 + [0.862173320368121, 0.342624466538650, 3.034923466331855, -0.204966058299775]]) # noqa: E501 + expected = 1.481454682101605 + assert_allclose(subspace_angles(x[:, :2], x[:, 2:])[0], expected, + rtol=1e-12) + assert_allclose(subspace_angles(x[:, 2:], x[:, :2])[0], expected, + rtol=1e-12) + expected = 0.746361174247302 + assert_allclose(subspace_angles(x[:, :2], x[:, [2]]), expected, rtol=1e-12) + assert_allclose(subspace_angles(x[:, [2]], x[:, :2]), expected, rtol=1e-12) + expected = 0.487163718534313 + assert_allclose(subspace_angles(x[:, :3], x[:, [3]]), expected, rtol=1e-12) + assert_allclose(subspace_angles(x[:, [3]], x[:, :3]), expected, rtol=1e-12) + expected = 0.328950515907756 + assert_allclose(subspace_angles(x[:, :2], x[:, 1:]), [expected, 0], + atol=1e-12) + # Degenerate conditions + assert_raises(ValueError, subspace_angles, x[0], x) + assert_raises(ValueError, subspace_angles, x, x[0]) + assert_raises(ValueError, subspace_angles, x[:-1], x) + + # Test branch if mask.any is True: + A = np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0, 0, 0], + [0, 0, 0]]) + B = np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 1]]) + expected = np.array([np.pi/2, 0, 0]) + assert_allclose(subspace_angles(A, B), expected, rtol=1e-12) + + # Complex + # second column in "b" does not affect result, just there so that + # b can have more cols than a, and vice-versa (both conditional code paths) + a = [[1 + 1j], [0]] + b = [[1 - 1j, 0], [0, 1]] + assert_allclose(subspace_angles(a, b), 0., atol=1e-14) + assert_allclose(subspace_angles(b, a), 0., atol=1e-14) + + # Empty + a = np.empty((0, 0)) + b = np.empty((0, 0)) + assert_allclose(subspace_angles(a, b), np.empty((0,))) + a = np.empty((2, 0)) + b = np.empty((2, 0)) + assert_allclose(subspace_angles(a, b), np.empty((0,))) + a = np.empty((0, 2)) + b = np.empty((0, 3)) + assert_allclose(subspace_angles(a, b), np.empty((0,))) + + +class TestCDF2RDF: + + def matmul(self, a, b): + return np.einsum('...ij,...jk->...ik', a, b) + + def assert_eig_valid(self, w, v, x): + assert_array_almost_equal( + self.matmul(v, w), + self.matmul(x, v) + ) + + def test_single_array0x0real(self): + # eig doesn't support 0x0 in old versions of numpy + X = np.empty((0, 0)) + w, v = np.empty(0), np.empty((0, 0)) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array2x2_real(self): + X = np.array([[1, 2], [3, -1]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array2x2_complex(self): + X = np.array([[1, 2], [-2, 1]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array3x3_real(self): + X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array3x3_complex(self): + X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_random_1d_stacked_arrays(self): + rng = np.random.default_rng(1234) + # cannot test M == 0 due to bug in old numpy + for M in range(1, 7): + X = rng.random((100, M, M)) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_random_2d_stacked_arrays(self): + rng = np.random.default_rng(1234) + # cannot test M == 0 due to bug in old numpy + for M in range(1, 7): + X = rng.random((10, 10, M, M)) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_low_dimensionality_error(self): + w, v = np.empty(()), np.array((2,)) + assert_raises(ValueError, cdf2rdf, w, v) + + def test_not_square_error(self): + # Check that passing a non-square array raises a ValueError. + w, v = np.arange(3), np.arange(6).reshape(3, 2) + assert_raises(ValueError, cdf2rdf, w, v) + + def test_swapped_v_w_error(self): + # Check that exchanging places of w and v raises ValueError. + X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]]) + w, v = np.linalg.eig(X) + assert_raises(ValueError, cdf2rdf, v, w) + + def test_non_associated_error(self): + # Check that passing non-associated eigenvectors raises a ValueError. + w, v = np.arange(3), np.arange(16).reshape(4, 4) + assert_raises(ValueError, cdf2rdf, w, v) + + def test_not_conjugate_pairs(self): + # Check that passing non-conjugate pairs raises a ValueError. + X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]]) + w, v = np.linalg.eig(X) + assert_raises(ValueError, cdf2rdf, w, v) + + # different arrays in the stack, so not conjugate + X = np.array([ + [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]], + [[1, 2, 3], [1, 2, 3], [2, 5, 6-1j]], + ]) + w, v = np.linalg.eig(X) + assert_raises(ValueError, cdf2rdf, w, v) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_cholesky.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_cholesky.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0dac2db8ca58621c22edd4b3a9ea034eed4d71 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_cholesky.py @@ -0,0 +1,268 @@ +import pytest +import numpy as np +from numpy.testing import assert_array_almost_equal +from pytest import raises as assert_raises + +from numpy import array, transpose, dot, conjugate, zeros_like, empty +from numpy.random import random +from scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded, + cho_factor, cho_solve) + +from scipy.linalg._testutils import assert_no_overwrite + + +class TestCholesky: + + def test_simple(self): + a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]] + c = cholesky(a) + assert_array_almost_equal(dot(transpose(c), c), a) + c = transpose(c) + a = dot(c, transpose(c)) + assert_array_almost_equal(cholesky(a, lower=1), c) + + def test_check_finite(self): + a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]] + c = cholesky(a, check_finite=False) + assert_array_almost_equal(dot(transpose(c), c), a) + c = transpose(c) + a = dot(c, transpose(c)) + assert_array_almost_equal(cholesky(a, lower=1, check_finite=False), c) + + def test_simple_complex(self): + m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]]) + a = dot(transpose(conjugate(m)), m) + c = cholesky(a) + a1 = dot(transpose(conjugate(c)), c) + assert_array_almost_equal(a, a1) + c = transpose(c) + a = dot(c, transpose(conjugate(c))) + assert_array_almost_equal(cholesky(a, lower=1), c) + + def test_random(self): + n = 20 + for k in range(2): + m = random([n, n]) + for i in range(n): + m[i, i] = 20*(.1+m[i, i]) + a = dot(transpose(m), m) + c = cholesky(a) + a1 = dot(transpose(c), c) + assert_array_almost_equal(a, a1) + c = transpose(c) + a = dot(c, transpose(c)) + assert_array_almost_equal(cholesky(a, lower=1), c) + + def test_random_complex(self): + n = 20 + for k in range(2): + m = random([n, n])+1j*random([n, n]) + for i in range(n): + m[i, i] = 20*(.1+abs(m[i, i])) + a = dot(transpose(conjugate(m)), m) + c = cholesky(a) + a1 = dot(transpose(conjugate(c)), c) + assert_array_almost_equal(a, a1) + c = transpose(c) + a = dot(c, transpose(conjugate(c))) + assert_array_almost_equal(cholesky(a, lower=1), c) + + @pytest.mark.xslow + def test_int_overflow(self): + # regression test for + # https://github.com/scipy/scipy/issues/17436 + # the problem was an int overflow in zeroing out + # the unused triangular part + n = 47_000 + x = np.eye(n, dtype=np.float64, order='F') + x[:4, :4] = np.array([[4, -2, 3, -1], + [-2, 4, -3, 1], + [3, -3, 5, 0], + [-1, 1, 0, 5]]) + + cholesky(x, check_finite=False, overwrite_a=True) # should not segfault + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt, dt_b): + a = empty((0, 0), dtype=dt) + + c = cholesky(a) + assert c.shape == (0, 0) + assert c.dtype == cholesky(np.eye(2, dtype=dt)).dtype + + c_and_lower = (c, True) + b = np.asarray([], dtype=dt_b) + x = cho_solve(c_and_lower, b) + assert x.shape == (0,) + assert x.dtype == cho_solve((np.eye(2, dtype=dt), True), + np.ones(2, dtype=dt_b)).dtype + + b = empty((0, 0), dtype=dt_b) + x = cho_solve(c_and_lower, b) + assert x.shape == (0, 0) + assert x.dtype == cho_solve((np.eye(2, dtype=dt), True), + np.ones(2, dtype=dt_b)).dtype + + a1 = array([]) + a2 = array([[]]) + a3 = [] + a4 = [[]] + for x in ([a1, a2, a3, a4]): + assert_raises(ValueError, cholesky, x) + + +class TestCholeskyBanded: + """Tests for cholesky_banded() and cho_solve_banded.""" + + def test_check_finite(self): + # Symmetric positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, 0.2], + [0.0, 0.0, 0.2, 4.0]]) + # Banded storage form of `a`. + ab = array([[-1.0, 1.0, 0.5, 0.2], + [4.0, 4.0, 4.0, 4.0]]) + c = cholesky_banded(ab, lower=False, check_finite=False) + ufac = zeros_like(a) + ufac[list(range(4)), list(range(4))] = c[-1] + ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] + assert_array_almost_equal(a, dot(ufac.T, ufac)) + + b = array([0.0, 0.5, 4.2, 4.2]) + x = cho_solve_banded((c, False), b, check_finite=False) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_upper_real(self): + # Symmetric positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, 0.2], + [0.0, 0.0, 0.2, 4.0]]) + # Banded storage form of `a`. + ab = array([[-1.0, 1.0, 0.5, 0.2], + [4.0, 4.0, 4.0, 4.0]]) + c = cholesky_banded(ab, lower=False) + ufac = zeros_like(a) + ufac[list(range(4)), list(range(4))] = c[-1] + ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] + assert_array_almost_equal(a, dot(ufac.T, ufac)) + + b = array([0.0, 0.5, 4.2, 4.2]) + x = cho_solve_banded((c, False), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_upper_complex(self): + # Hermitian positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, -0.2j], + [0.0, 0.0, 0.2j, 4.0]]) + # Banded storage form of `a`. + ab = array([[-1.0, 1.0, 0.5, -0.2j], + [4.0, 4.0, 4.0, 4.0]]) + c = cholesky_banded(ab, lower=False) + ufac = zeros_like(a) + ufac[list(range(4)), list(range(4))] = c[-1] + ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] + assert_array_almost_equal(a, dot(ufac.conj().T, ufac)) + + b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0]) + x = cho_solve_banded((c, False), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_lower_real(self): + # Symmetric positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, 0.2], + [0.0, 0.0, 0.2, 4.0]]) + # Banded storage form of `a`. + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 0.5, 0.2, -1.0]]) + c = cholesky_banded(ab, lower=True) + lfac = zeros_like(a) + lfac[list(range(4)), list(range(4))] = c[0] + lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3] + assert_array_almost_equal(a, dot(lfac, lfac.T)) + + b = array([0.0, 0.5, 4.2, 4.2]) + x = cho_solve_banded((c, True), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_lower_complex(self): + # Hermitian positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, -0.2j], + [0.0, 0.0, 0.2j, 4.0]]) + # Banded storage form of `a`. + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 0.5, 0.2j, -1.0]]) + c = cholesky_banded(ab, lower=True) + lfac = zeros_like(a) + lfac[list(range(4)), list(range(4))] = c[0] + lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3] + assert_array_almost_equal(a, dot(lfac, lfac.conj().T)) + + b = array([0.0, 0.5j, 3.8j, 3.8]) + x = cho_solve_banded((c, True), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0j, 1.0]) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt, dt_b): + ab = empty((0, 0), dtype=dt) + + cb = cholesky_banded(ab) + assert cb.shape == (0, 0) + + m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=dt)) + assert cb.dtype == m.dtype + + cb_and_lower = (cb, True) + b = np.asarray([], dtype=dt_b) + x = cho_solve_banded(cb_and_lower, b) + assert x.shape == (0,) + + dtype_nonempty = cho_solve_banded((m, True), np.ones(2, dtype=dt_b)).dtype + assert x.dtype == dtype_nonempty + + b = empty((0, 0), dtype=dt_b) + x = cho_solve_banded(cb_and_lower, b) + assert x.shape == (0, 0) + assert x.dtype == dtype_nonempty + + +class TestOverwrite: + def test_cholesky(self): + assert_no_overwrite(cholesky, [(3, 3)]) + + def test_cho_factor(self): + assert_no_overwrite(cho_factor, [(3, 3)]) + + def test_cho_solve(self): + x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]]) + xcho = cho_factor(x) + assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)]) + + def test_cholesky_banded(self): + assert_no_overwrite(cholesky_banded, [(2, 3)]) + + def test_cho_solve_banded(self): + x = array([[0, -1, -1], [2, 2, 2]]) + xcho = cholesky_banded(x) + assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b), + [(3,)]) + +class TestChoFactor: + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + x, lower = cho_factor(a) + + assert x.shape == (0, 0) + + xx, lower = cho_factor(np.eye(2, dtype=dt)) + assert x.dtype == xx.dtype diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_cossin.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_cossin.py new file mode 100644 index 0000000000000000000000000000000000000000..0433da23288588ba55daa28b28efb202e89d1773 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_cossin.py @@ -0,0 +1,314 @@ +import pytest +import numpy as np +from numpy.random import default_rng +from numpy.testing import assert_allclose + +from scipy import linalg +from scipy.linalg.lapack import _compute_lwork +from scipy.stats import ortho_group, unitary_group +from scipy.linalg import cossin, get_lapack_funcs + +REAL_DTYPES = (np.float32, np.float64) +COMPLEX_DTYPES = (np.complex64, np.complex128) +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +@pytest.mark.parametrize('dtype_', DTYPES) +@pytest.mark.parametrize('m, p, q', + [ + (2, 1, 1), + (3, 2, 1), + (3, 1, 2), + (4, 2, 2), + (4, 1, 2), + (40, 12, 20), + (40, 30, 1), + (40, 1, 30), + (100, 50, 1), + (100, 50, 50), + ]) +@pytest.mark.parametrize('swap_sign', [True, False]) +def test_cossin(dtype_, m, p, q, swap_sign): + rng = default_rng(1708093570726217) + if dtype_ in COMPLEX_DTYPES: + x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_) + else: + x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_) + + u, cs, vh = cossin(x, p, q, + swap_sign=swap_sign) + assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps) + assert u.dtype == dtype_ + # Test for float32 or float 64 + assert cs.dtype == np.real(u).dtype + assert vh.dtype == dtype_ + + u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]], + swap_sign=swap_sign) + assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps) + assert u.dtype == dtype_ + assert cs.dtype == np.real(u).dtype + assert vh.dtype == dtype_ + + _, cs2, vh2 = cossin(x, p, q, + compute_u=False, + swap_sign=swap_sign) + assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps) + assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps) + + u2, cs2, _ = cossin(x, p, q, + compute_vh=False, + swap_sign=swap_sign) + assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps) + assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps) + + _, cs2, _ = cossin(x, p, q, + compute_u=False, + compute_vh=False, + swap_sign=swap_sign) + assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps) + + +def test_cossin_mixed_types(): + rng = default_rng(1708093736390459) + x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64) + u, cs, vh = cossin([x[:2, :2], + np.array(x[:2, 2:], dtype=np.complex128), + x[2:, :2], + x[2:, 2:]]) + + assert u.dtype == np.complex128 + assert cs.dtype == np.float64 + assert vh.dtype == np.complex128 + assert_allclose(x, u @ cs @ vh, rtol=0., + atol=1e4 * np.finfo(np.complex128).eps) + + +def test_cossin_error_incorrect_subblocks(): + with pytest.raises(ValueError, match="be due to missing p, q arguments."): + cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10])) + + +def test_cossin_error_empty_subblocks(): + with pytest.raises(ValueError, match="x11.*empty"): + cossin(([], [], [], [])) + with pytest.raises(ValueError, match="x12.*empty"): + cossin(([1, 2], [], [6, 7], [8, 9, 10])) + with pytest.raises(ValueError, match="x21.*empty"): + cossin(([1, 2], [3, 4, 5], [], [8, 9, 10])) + with pytest.raises(ValueError, match="x22.*empty"): + cossin(([1, 2], [3, 4, 5], [2], [])) + + +def test_cossin_error_missing_partitioning(): + with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"): + cossin(unitary_group.rvs(2)) + + with pytest.raises(ValueError, match=".*might be due to missing p, q"): + cossin(unitary_group.rvs(4)) + + +def test_cossin_error_non_iterable(): + with pytest.raises(ValueError, match="containing the subblocks of X"): + cossin(12j) + +def test_cossin_error_invalid_shape(): + # Invalid x12 dimensions + p, q = 3, 4 + invalid_x12 = np.ones((p, q + 2)) + valid_ones = np.ones((p, q)) + with pytest.raises(ValueError, + match=r"Invalid x12 dimensions: desired \(3, 4\), got \(3, 6\)"): + cossin((valid_ones, invalid_x12, valid_ones, valid_ones)) + + # Invalid x21 dimensions + invalid_x21 = np.ones(p + 2) + with pytest.raises(ValueError, + match=r"Invalid x21 dimensions: desired \(3, 4\), got \(1, 5\)"): + cossin((valid_ones, valid_ones, invalid_x21, valid_ones)) + +def test_cossin_error_non_square(): + with pytest.raises(ValueError, match="only supports square"): + cossin(np.array([[1, 2]]), 1, 1) + + +def test_cossin_error_partitioning(): + x = np.array(ortho_group.rvs(4), dtype=np.float64) + with pytest.raises(ValueError, match="invalid p=0.*0= m) or (q >= m): + pytest.skip("`0 < p < m` and `0 < q < m` must hold") + + # Generate unitary input + rng = np.random.default_rng(329548272348596421) + X = unitary_group.rvs(m, random_state=rng) + np.testing.assert_allclose(X @ X.conj().T, np.eye(m), atol=1e-15) + + # Perform the decomposition + u0, cs0, vh0 = linalg.cossin(X, p=p, q=q, separate=True, swap_sign=swap_sign) + u1, u2 = u0 + v1, v2 = vh0 + v1, v2 = v1.conj().T, v2.conj().T + + # "U1, U2, V1, V2 are square orthogonal/unitary matrices + # of dimensions (p,p), (m-p,m-p), (q,q), and (m-q,m-q) respectively" + np.testing.assert_allclose(u1 @ u1.conj().T, np.eye(p), atol=1e-13) + np.testing.assert_allclose(u2 @ u2.conj().T, np.eye(m-p), atol=1e-13) + np.testing.assert_allclose(v1 @ v1.conj().T, np.eye(q), atol=1e-13) + np.testing.assert_allclose(v2 @ v2.conj().T, np.eye(m-q), atol=1e-13) + + # "and C and S are (r, r) nonnegative diagonal matrices..." + C = np.diag(np.cos(cs0)) + S = np.diag(np.sin(cs0)) + # "...satisfying C^2 + S^2 = I where r = min(p, m-p, q, m-q)." + r = min(p, m-p, q, m-q) + np.testing.assert_allclose(C**2 + S**2, np.eye(r)) + + # "Moreover, the rank of the identity matrices are + # min(p, q) - r, min(p, m - q) - r, min(m - p, q) - r, + # and min(m - p, m - q) - r respectively." + I11 = np.eye(min(p, q) - r) + I12 = np.eye(min(p, m - q) - r) + I21 = np.eye(min(m - p, q) - r) + I22 = np.eye(min(m - p, m - q) - r) + + # From: + # ┌ ┐ + # │ I 0 0 │ 0 0 0 │ + # ┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐* + # │ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │ + # │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│ + # │ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │ + # └ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘ + # │ 0 0 I │ 0 0 0 │ + # └ ┘ + + # We can see that U and V are block diagonal matrices like so: + U = linalg.block_diag(u1, u2) + V = linalg.block_diag(v1, v2) + + # And the center matrix, which we'll call Q here, must be: + Q11 = np.zeros((u1.shape[1], v1.shape[0])) + IC11 = linalg.block_diag(I11, C) + Q11[:IC11.shape[0], :IC11.shape[1]] = IC11 + + Q12 = np.zeros((u1.shape[1], v2.shape[0])) + SI12 = linalg.block_diag(S, I12) if swap_sign else linalg.block_diag(-S, -I12) + Q12[-SI12.shape[0]:, -SI12.shape[1]:] = SI12 + + Q21 = np.zeros((u2.shape[1], v1.shape[0])) + SI21 = linalg.block_diag(-S, -I21) if swap_sign else linalg.block_diag(S, I21) + Q21[-SI21.shape[0]:, -SI21.shape[1]:] = SI21 + + Q22 = np.zeros((u2.shape[1], v2.shape[0])) + IC22 = linalg.block_diag(I22, C) + Q22[:IC22.shape[0], :IC22.shape[1]] = IC22 + + Q = np.block([[Q11, Q12], [Q21, Q22]]) + + # Confirm that `cossin` decomposes `X` as shown + np.testing.assert_allclose(X, U @ Q @ V.conj().T) + + # And check that `separate=False` agrees + U0, CS0, Vh0 = linalg.cossin(X, p=p, q=q, swap_sign=swap_sign) + np.testing.assert_allclose(U, U0) + np.testing.assert_allclose(Q, CS0) + np.testing.assert_allclose(V, Vh0.conj().T) + + # Confirm that `compute_u`/`compute_vh` don't affect the results + kwargs = dict(p=p, q=q, swap_sign=swap_sign) + + # `compute_u=False` + u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, **kwargs) + assert u[0].shape == (0, 0) # probably not ideal, but this is what it does + assert u[1].shape == (0, 0) + assert_allclose(cs, cs0, rtol=1e-15) + assert_allclose(vh[0], vh0[0], rtol=1e-15) + assert_allclose(vh[1], vh0[1], rtol=1e-15) + + U, CS, Vh = linalg.cossin(X, compute_u=False, **kwargs) + assert U.shape == (0, 0) + assert_allclose(CS, CS0, rtol=1e-15) + assert_allclose(Vh, Vh0, rtol=1e-15) + + # `compute_vh=False` + u, cs, vh = linalg.cossin(X, separate=True, compute_vh=False, **kwargs) + assert_allclose(u[0], u[0], rtol=1e-15) + assert_allclose(u[1], u[1], rtol=1e-15) + assert_allclose(cs, cs0, rtol=1e-15) + assert vh[0].shape == (0, 0) + assert vh[1].shape == (0, 0) + + U, CS, Vh = linalg.cossin(X, compute_vh=False, **kwargs) + assert_allclose(U, U0, rtol=1e-15) + assert_allclose(CS, CS0, rtol=1e-15) + assert Vh.shape == (0, 0) + + # `compute_u=False, compute_vh=False` + u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, + compute_vh=False, **kwargs) + assert u[0].shape == (0, 0) + assert u[1].shape == (0, 0) + assert_allclose(cs, cs0, rtol=1e-15) + assert vh[0].shape == (0, 0) + assert vh[1].shape == (0, 0) + + U, CS, Vh = linalg.cossin(X, compute_u=False, compute_vh=False, **kwargs) + assert U.shape == (0, 0) + assert_allclose(CS, CS0, rtol=1e-15) + assert Vh.shape == (0, 0) + + +def test_indexing_bug_gh19365(): + # Regression test for gh-19365, which reported a bug with `separate=False` + rng = np.random.default_rng(32954827234421) + m = rng.integers(50, high=100) + p = rng.integers(10, 40) # always p < m + q = rng.integers(m - p + 1, m - 1) # always m-p < q < m + X = unitary_group.rvs(m, random_state=rng) # random unitary matrix + U, D, Vt = linalg.cossin(X, p=p, q=q, separate=False) + assert np.allclose(U @ D @ Vt, X) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_ldl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_ldl.py new file mode 100644 index 0000000000000000000000000000000000000000..d87a827f0e81a7bee4a962eb02b8a312fb809aa0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_ldl.py @@ -0,0 +1,136 @@ +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_allclose, assert_ +from numpy import (array, eye, zeros, empty_like, empty, tril_indices_from, + tril, triu_indices_from, spacing, float32, float64, + complex64, complex128) +from numpy.exceptions import ComplexWarning +from scipy.linalg import ldl +import pytest + + +def test_args(): + A = eye(3) + # Nonsquare array + with pytest.raises(ValueError): + ldl(A[:, :2]) + # Complex matrix with imaginary diagonal entries with "hermitian=True" + with pytest.warns(ComplexWarning): + ldl(A*1j) + + +def test_empty_array(): + a = empty((0, 0), dtype=complex) + l, d, p = ldl(empty((0, 0))) + assert_array_almost_equal(l, empty_like(a)) + assert_array_almost_equal(d, empty_like(a)) + assert_array_almost_equal(p, array([], dtype=int)) + + +def test_simple(): + a = array([[-0.39-0.71j, 5.14-0.64j, -7.86-2.96j, 3.80+0.92j], + [5.14-0.64j, 8.86+1.81j, -3.52+0.58j, 5.32-1.59j], + [-7.86-2.96j, -3.52+0.58j, -2.83-0.03j, -1.54-2.86j], + [3.80+0.92j, 5.32-1.59j, -1.54-2.86j, -0.56+0.12j]]) + b = array([[5., 10, 1, 18], + [10., 2, 11, 1], + [1., 11, 19, 9], + [18., 1, 9, 0]]) + c = array([[52., 97, 112, 107, 50], + [97., 114, 89, 98, 13], + [112., 89, 64, 33, 6], + [107., 98, 33, 60, 73], + [50., 13, 6, 73, 77]]) + + d = array([[2., 2, -4, 0, 4], + [2., -2, -2, 10, -8], + [-4., -2, 6, -8, -4], + [0., 10, -8, 6, -6], + [4., -8, -4, -6, 10]]) + e = array([[-1.36+0.00j, 0+0j, 0+0j, 0+0j], + [1.58-0.90j, -8.87+0j, 0+0j, 0+0j], + [2.21+0.21j, -1.84+0.03j, -4.63+0j, 0+0j], + [3.91-1.50j, -1.78-1.18j, 0.11-0.11j, -1.84+0.00j]]) + for x in (b, c, d): + l, d, p = ldl(x) + assert_allclose(l.dot(d).dot(l.T), x, atol=spacing(1000.), rtol=0) + + u, d, p = ldl(x, lower=False) + assert_allclose(u.dot(d).dot(u.T), x, atol=spacing(1000.), rtol=0) + + l, d, p = ldl(a, hermitian=False) + assert_allclose(l.dot(d).dot(l.T), a, atol=spacing(1000.), rtol=0) + + u, d, p = ldl(a, lower=False, hermitian=False) + assert_allclose(u.dot(d).dot(u.T), a, atol=spacing(1000.), rtol=0) + + # Use upper part for the computation and use the lower part for comparison + l, d, p = ldl(e.conj().T, lower=0) + assert_allclose(tril(l.dot(d).dot(l.conj().T)-e), zeros((4, 4)), + atol=spacing(1000.), rtol=0) + + +def test_permutations(): + rng = np.random.default_rng(1234) + for _ in range(10): + n = rng.integers(1, 100) + # Random real/complex array + x = rng.random((n, n)) + 0 if rng.integers(2) else rng.random((n, n))*1j + x = x + x.conj().T + x += eye(n)*rng.integers(5, 1e6) + l_ind = tril_indices_from(x, k=-1) + u_ind = triu_indices_from(x, k=1) + + # Test whether permutations lead to a triangular array + u, d, p = ldl(x, lower=0) + # lower part should be zero + assert_(not any(u[p, :][l_ind]), f'Spin {_} failed') + + l, d, p = ldl(x, lower=1) + # upper part should be zero + assert_(not any(l[p, :][u_ind]), f'Spin {_} failed') + + +@pytest.mark.parametrize("dtype", [float32, float64]) +@pytest.mark.parametrize("n", [30, 150]) +def test_ldl_type_size_combinations_real(n, dtype): + rng = np.random.default_rng(1234) + msg = (f"Failed for size: {n}, dtype: {dtype}") + + x = rng.random((n, n)).astype(dtype) + x = x + x.T + x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6)) + + l, d1, p = ldl(x) + u, d2, p = ldl(x, lower=0) + rtol = 1e-4 if dtype is float32 else 1e-10 + assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg) + assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg) + + +@pytest.mark.parametrize("dtype", [complex64, complex128]) +@pytest.mark.parametrize("n", [30, 150]) +def test_ldl_type_size_combinations_complex(n, dtype): + rng = np.random.default_rng(1234) + msg1 = (f"Her failed for size: {n}, dtype: {dtype}") + msg2 = (f"Sym failed for size: {n}, dtype: {dtype}") + + # Complex hermitian upper/lower + x = (rng.random((n, n))+1j*rng.random((n, n))).astype(dtype) + x = x+x.conj().T + x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6)) + + l, d1, p = ldl(x) + u, d2, p = ldl(x, lower=0) + rtol = 2e-4 if dtype is complex64 else 1e-10 + assert_allclose(l.dot(d1).dot(l.conj().T), x, rtol=rtol, err_msg=msg1) + assert_allclose(u.dot(d2).dot(u.conj().T), x, rtol=rtol, err_msg=msg1) + + # Complex symmetric upper/lower + x = (rng.random((n, n))+1j*rng.random((n, n))).astype(dtype) + x = x+x.T + x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6)) + + l, d1, p = ldl(x, hermitian=0) + u, d2, p = ldl(x, lower=0, hermitian=0) + assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg2) + assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg2) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_lu.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_lu.py new file mode 100644 index 0000000000000000000000000000000000000000..be518a8a1b459c0cb8fc425be009d758272388f8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_lu.py @@ -0,0 +1,308 @@ +import pytest +from pytest import raises as assert_raises + +import numpy as np +from scipy.linalg import lu, lu_factor, lu_solve, get_lapack_funcs, solve +from numpy.testing import assert_allclose, assert_array_equal, assert_equal + + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +class TestLU: + def setup_method(self): + self.rng = np.random.default_rng(1682281250228846) + + def test_old_lu_smoke_tests(self): + "Tests from old fortran based lu test suite" + a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + p, l, u = lu(a) + result_lu = np.array([[2., 5., 6.], [0.5, -0.5, 0.], [0.5, 1., 0.]]) + assert_allclose(p, np.rot90(np.eye(3))) + assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3)) + assert_allclose(u, np.triu(result_lu)) + + a = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]]) + p, l, u = lu(a) + result_lu = np.array([[2., 5.j, 6.], [0.5, 2-2.5j, 0.], [0.5, 1., 0.]]) + assert_allclose(p, np.rot90(np.eye(3))) + assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3)) + assert_allclose(u, np.triu(result_lu)) + + b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + p, l, u = lu(b) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]])) + assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]]), + rtol=0., atol=1e-14) + + cb = np.array([[1.j, 2.j, 3.j], [4j, 5j, 6j], [7j, 8j, 9j]]) + p, l, u = lu(cb) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]])) + assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]])*1j, + rtol=0., atol=1e-14) + + # Rectangular matrices + hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]]) + p, l, u = lu(hrect) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]])) + assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9], + [0, 0, -0.5, 0]]), rtol=0., atol=1e-14) + + chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])*1.j + p, l, u = lu(chrect) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]])) + assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9], + [0, 0, -0.5, 0]])*1j, rtol=0., atol=1e-14) + + vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]]) + p, l, u = lu(vrect) + assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :]) + assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1], + [0.4, 0.25, 0.5]])) + assert_allclose(u, np.array([[10, 12, 12], + [0, 0.8, 1.8], + [0, 0, 1.5]])) + + cvrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])*1j + p, l, u = lu(cvrect) + assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :]) + assert_allclose(l, np.array([[1., 0, 0], + [0.1, 1, 0], + [0.7, -0.5, 1], + [0.4, 0.25, 0.5]])) + assert_allclose(u, np.array([[10, 12, 12], + [0, 0.8, 1.8], + [0, 0, 1.5]])*1j) + + @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20], + [20, 4], [4, 20], [3, 2, 9, 9], + [2, 2, 17, 5], [2, 2, 11, 7]]) + def test_simple_lu_shapes_real_complex(self, shape): + a = self.rng.uniform(-10., 10., size=shape) + p, l, u = lu(a) + assert_allclose(a, p @ l @ u) + pl, u = lu(a, permute_l=True) + assert_allclose(a, pl @ u) + + b = self.rng.uniform(-10., 10., size=shape)*1j + b += self.rng.uniform(-10, 10, size=shape) + pl, u = lu(b, permute_l=True) + assert_allclose(b, pl @ u) + + @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20], + [20, 4], [4, 20]]) + def test_simple_lu_shapes_real_complex_2d_indices(self, shape): + a = self.rng.uniform(-10., 10., size=shape) + p, l, u = lu(a, p_indices=True) + assert_allclose(a, l[p, :] @ u) + + def test_1by1_input_output(self): + a = self.rng.random([4, 5, 1, 1], dtype=np.float32) + p, l, u = lu(a, p_indices=True) + assert_allclose(p, np.zeros(shape=(4, 5, 1), dtype=int)) + assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(u, a) + + a = self.rng.random([4, 5, 1, 1], dtype=np.float32) + p, l, u = lu(a) + assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(u, a) + + pl, u = lu(a, permute_l=True) + assert_allclose(pl, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(u, a) + + a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j) + p, l, u = lu(a) + assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64)) + assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64)) + assert_allclose(u, a) + + def test_empty_edge_cases(self): + a = np.empty([0, 0]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float64)) + assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.float64)) + + a = np.empty([0, 3], dtype=np.float16) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32)) + assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float32)) + assert_allclose(u, np.empty(shape=(0, 3), dtype=np.float32)) + + a = np.empty([3, 0], dtype=np.complex64) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32)) + assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) + p, l, u = lu(a, p_indices=True) + assert_allclose(p, np.empty(shape=(0,), dtype=int)) + assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) + pl, u = lu(a, permute_l=True) + assert_allclose(pl, np.empty(shape=(3, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) + + a = np.empty([3, 0, 0], dtype=np.complex64) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(3, 0, 0), dtype=np.float32)) + assert_allclose(l, np.empty(shape=(3, 0, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(3, 0, 0), dtype=np.complex64)) + + a = np.empty([0, 0, 3]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0, 0))) + assert_allclose(l, np.empty(shape=(0, 0, 0))) + assert_allclose(u, np.empty(shape=(0, 0, 3))) + + with assert_raises(ValueError, match='at least two-dimensional'): + lu(np.array([])) + + a = np.array([[]]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0))) + assert_allclose(l, np.empty(shape=(1, 0))) + assert_allclose(u, np.empty(shape=(0, 0))) + + a = np.array([[[]]]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(1, 0, 0))) + assert_allclose(l, np.empty(shape=(1, 1, 0))) + assert_allclose(u, np.empty(shape=(1, 0, 0))) + + +class TestLUFactor: + def setup_method(self): + self.rng = np.random.default_rng(1682281250228846) + + self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]]) + # Those matrices are more robust to detect problems in permutation + # matrices than the ones above + self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + self.cb = np.array([[1j, 2j, 3j], [4j, 5j, 6j], [7j, 8j, 9j]]) + + # Rectangular matrices + self.hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]]) + self.chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], + [9, 10, 12, 12]]) * 1.j + + self.vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]]) + self.cvrect = 1.j * np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [10, 12, 12]]) + + # Medium sizes matrices + self.med = self.rng.random((30, 40)) + self.cmed = self.rng.random((30, 40)) + 1.j*self.rng.random((30, 40)) + + def _test_common_lu_factor(self, data): + l_and_u1, piv1 = lu_factor(data) + (getrf,) = get_lapack_funcs(("getrf",), (data,)) + l_and_u2, piv2, _ = getrf(data, overwrite_a=False) + assert_allclose(l_and_u1, l_and_u2) + assert_allclose(piv1, piv2) + + # Simple tests. + # For lu_factor gives a LinAlgWarning because these matrices are singular + def test_hrectangular(self): + self._test_common_lu_factor(self.hrect) + + def test_vrectangular(self): + self._test_common_lu_factor(self.vrect) + + def test_hrectangular_complex(self): + self._test_common_lu_factor(self.chrect) + + def test_vrectangular_complex(self): + self._test_common_lu_factor(self.cvrect) + + # Bigger matrices + def test_medium1(self): + """Check lu decomposition on medium size, rectangular matrix.""" + self._test_common_lu_factor(self.med) + + def test_medium1_complex(self): + """Check lu decomposition on medium size, rectangular matrix.""" + self._test_common_lu_factor(self.cmed) + + def test_check_finite(self): + p, l, u = lu(self.a, check_finite=False) + assert_allclose(p @ l @ u, self.a) + + def test_simple_known(self): + # Ticket #1458 + for order in ['C', 'F']: + A = np.array([[2, 1], [0, 1.]], order=order) + LU, P = lu_factor(A) + assert_allclose(LU, np.array([[2, 1], [0, 1]])) + assert_array_equal(P, np.array([0, 1])) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, dtype): + k = min(m, n) + + a = np.eye(m, n, dtype=dtype) + lu, p = lu_factor(a) + assert_equal(lu.shape, (m, n)) + assert_equal(lu.dtype, dtype) + assert_equal(p.shape, (k,)) + assert_equal(p.dtype, np.int32) + + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, m, n): + a = np.zeros((m, n)) + lu, p = lu_factor(a) + assert_allclose(lu, np.empty((m, n))) + assert_allclose(p, np.arange(0)) + + +class TestLUSolve: + def setup_method(self): + self.rng = np.random.default_rng(1682281250228846) + + def test_lu(self): + a0 = self.rng.random((10, 10)) + b = self.rng.random((10,)) + + for order in ['C', 'F']: + a = np.array(a0, order=order) + x1 = solve(a, b) + lu_a = lu_factor(a) + x2 = lu_solve(lu_a, b) + assert_allclose(x1, x2) + + def test_check_finite(self): + a = self.rng.random((10, 10)) + b = self.rng.random((10,)) + x1 = solve(a, b) + lu_a = lu_factor(a, check_finite=False) + x2 = lu_solve(lu_a, b, check_finite=False) + assert_allclose(x1, x2) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt, dt_b): + lu_and_piv = (np.empty((0, 0), dtype=dt), np.array([])) + b = np.asarray([], dtype=dt_b) + x = lu_solve(lu_and_piv, b) + assert x.shape == (0,) + + m = lu_solve((np.eye(2, dtype=dt), [0, 1]), np.ones(2, dtype=dt_b)) + assert x.dtype == m.dtype + + b = np.empty((0, 0), dtype=dt_b) + x = lu_solve(lu_and_piv, b) + assert x.shape == (0, 0) + assert x.dtype == m.dtype diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_polar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_polar.py new file mode 100644 index 0000000000000000000000000000000000000000..4f02ef5a2c600ea597ecf395547b0631188d3174 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_polar.py @@ -0,0 +1,110 @@ +import pytest +import numpy as np +from numpy.linalg import norm +from numpy.testing import (assert_, assert_allclose, assert_equal) +from scipy.linalg import polar, eigh + + +diag2 = np.array([[2, 0], [0, 3]]) +a13 = np.array([[1, 2, 2]]) + +precomputed_cases = [ + [[[0]], 'right', [[1]], [[0]]], + [[[0]], 'left', [[1]], [[0]]], + [[[9]], 'right', [[1]], [[9]]], + [[[9]], 'left', [[1]], [[9]]], + [diag2, 'right', np.eye(2), diag2], + [diag2, 'left', np.eye(2), diag2], + [a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])], +] + +verify_cases = [ + [[1, 2], [3, 4]], + [[1, 2, 3]], + [[1], [2], [3]], + [[1, 2, 3], [3, 4, 0]], + [[1, 2], [3, 4], [5, 5]], + [[1, 2], [3, 4+5j]], + [[1, 2, 3j]], + [[1], [2], [3j]], + [[1, 2, 3+2j], [3, 4-1j, -4j]], + [[1, 2], [3-2j, 4+0.5j], [5, 5]], + [[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]], + np.empty((0, 0)), + np.empty((0, 2)), + np.empty((2, 0)), +] + + +def check_precomputed_polar(a, side, expected_u, expected_p): + # Compare the result of the polar decomposition to a + # precomputed result. + u, p = polar(a, side=side) + assert_allclose(u, expected_u, atol=1e-15) + assert_allclose(p, expected_p, atol=1e-15) + + +def verify_polar(a): + # Compute the polar decomposition, and then verify that + # the result has all the expected properties. + product_atol = np.sqrt(np.finfo(float).eps) + + aa = np.asarray(a) + m, n = aa.shape + + u, p = polar(a, side='right') + assert_equal(u.shape, (m, n)) + assert_equal(p.shape, (n, n)) + # a = up + assert_allclose(u.dot(p), a, atol=product_atol) + if m >= n: + assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15) + else: + assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15) + # p is Hermitian positive semidefinite. + assert_allclose(p.conj().T, p) + evals = eigh(p, eigvals_only=True) + nonzero_evals = evals[abs(evals) > 1e-14] + assert_((nonzero_evals >= 0).all()) + + u, p = polar(a, side='left') + assert_equal(u.shape, (m, n)) + assert_equal(p.shape, (m, m)) + # a = pu + assert_allclose(p.dot(u), a, atol=product_atol) + if m >= n: + assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15) + else: + assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15) + # p is Hermitian positive semidefinite. + assert_allclose(p.conj().T, p) + evals = eigh(p, eigvals_only=True) + nonzero_evals = evals[abs(evals) > 1e-14] + assert_((nonzero_evals >= 0).all()) + + +def test_precomputed_cases(): + for a, side, expected_u, expected_p in precomputed_cases: + check_precomputed_polar(a, side, expected_u, expected_p) + + +def test_verify_cases(): + for a in verify_cases: + verify_polar(a) + +@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) +@pytest.mark.parametrize('shape', [(0, 0), (0, 2), (2, 0)]) +@pytest.mark.parametrize('side', ['left', 'right']) +def test_empty(dt, shape, side): + a = np.empty(shape, dtype=dt) + m, n = shape + p_shape = (m, m) if side == 'left' else (n, n) + + u, p = polar(a, side=side) + u_n, p_n = polar(np.eye(5, dtype=dt)) + + assert_equal(u.dtype, u_n.dtype) + assert_equal(p.dtype, p_n.dtype) + assert u.shape == shape + assert p.shape == p_shape + assert np.all(p == 0) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_update.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_update.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a87f08cde0b789a328e0403221bdf97f3bf176 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_decomp_update.py @@ -0,0 +1,1700 @@ +import itertools + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal +from pytest import raises as assert_raises +from scipy import linalg +import scipy.linalg._decomp_update as _decomp_update +from scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert + +def assert_unitary(a, rtol=None, atol=None, assert_sqr=True): + if rtol is None: + rtol = 10.0 ** -(np.finfo(a.dtype).precision-2) + if atol is None: + atol = 10*np.finfo(a.dtype).eps + + if assert_sqr: + assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square') + aTa = np.dot(a.T.conj(), a) + assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol) + +def assert_upper_tri(a, rtol=None, atol=None): + if rtol is None: + rtol = 10.0 ** -(np.finfo(a.dtype).precision-2) + if atol is None: + atol = 2*np.finfo(a.dtype).eps + mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_) + assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol) + +def check_qr(q, r, a, rtol, atol, assert_sqr=True): + assert_unitary(q, rtol, atol, assert_sqr) + assert_upper_tri(r, rtol, atol) + assert_allclose(q.dot(r), a, rtol=rtol, atol=atol) + +def make_strided(arrs): + strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)] + kmax = len(strides) + k = 0 + ret = [] + for a in arrs: + if a.ndim == 1: + s = strides[k % kmax] + k += 1 + base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype) + view = base[s[1]::s[0]] + view[...] = a + elif a.ndim == 2: + s = strides[k % kmax] + t = strides[(k+1) % kmax] + k += 2 + base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]), + a.dtype) + view = base[s[1]::s[0], t[1]::t[0]] + view[...] = a + else: + raise ValueError('make_strided only works for ndim = 1 or' + ' 2 arrays') + ret.append(view) + return ret + +def negate_strides(arrs): + ret = [] + for a in arrs: + b = np.zeros_like(a) + if b.ndim == 2: + b = b[::-1, ::-1] + elif b.ndim == 1: + b = b[::-1] + else: + raise ValueError('negate_strides only works for ndim = 1 or' + ' 2 arrays') + b[...] = a + ret.append(b) + return ret + +def nonitemsize_strides(arrs): + out = [] + for a in arrs: + a_dtype = a.dtype + b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')]) + c = b.getfield(a_dtype) + c[...] = a + out.append(c) + return out + + +def make_nonnative(arrs): + return [a.astype(a.dtype.newbyteorder()) for a in arrs] + + +class BaseQRdeltas: + def setup_method(self): + self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2) + self.atol = 10 * np.finfo(self.dtype).eps + + def generate(self, type, mode='full'): + rng = np.random.default_rng(29382) + shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12), + 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type] + a = rng.random(shape) + if np.iscomplexobj(self.dtype.type(1)): + b = rng.random(shape) + a = a + 1j * b + a = a.astype(self.dtype) + q, r = linalg.qr(a, mode=mode) + return a, q, r + +class BaseQRdelete(BaseQRdeltas): + def test_sqr_1_row(self): + a, q, r = self.generate('sqr') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_row(self): + a, q, r = self.generate('sqr') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_1_col(self): + a, q, r = self.generate('sqr') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_col(self): + a, q, r = self.generate('sqr') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_row(self): + a, q, r = self.generate('tall') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_row(self): + a, q, r = self.generate('tall') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_col(self): + a, q, r = self.generate('tall') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_col(self): + a, q, r = self.generate('tall') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_1_row(self): + a, q, r = self.generate('fat') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_row(self): + a, q, r = self.generate('fat') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_1_col(self): + a, q, r = self.generate('fat') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_col(self): + a, q, r = self.generate('fat') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_economic_1_row(self): + # this test always starts and ends with an economic decomp. + a, q, r = self.generate('tall', 'economic') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + # for economic row deletes + # eco - prow = eco + # eco - prow = sqr + # eco - prow = fat + def base_economic_p_row_xxx(self, ndel): + a, q, r = self.generate('tall', 'economic') + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_row_economic(self): + # (12, 7) - (3, 7) = (9,7) --> stays economic + self.base_economic_p_row_xxx(3) + + def test_economic_p_row_sqr(self): + # (12, 7) - (5, 7) = (7, 7) --> becomes square + self.base_economic_p_row_xxx(5) + + def test_economic_p_row_fat(self): + # (12, 7) - (7,7) = (5, 7) --> becomes fat + self.base_economic_p_row_xxx(7) + + def test_economic_1_col(self): + a, q, r = self.generate('tall', 'economic') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_col(self): + a, q, r = self.generate('tall', 'economic') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_1_row(self): + a, q, r = self.generate('Mx1') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_p_row(self): + a, q, r = self.generate('Mx1') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_1_col(self): + a, q, r = self.generate('1xN') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_p_col(self): + a, q, r = self.generate('1xN') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_economic_1_row(self): + a, q, r = self.generate('Mx1', 'economic') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_p_row(self): + a, q, r = self.generate('Mx1', 'economic') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_delete_last_1_row(self): + # full and eco are the same for 1xN + a, q, r = self.generate('1xN') + q1, r1 = qr_delete(q, r, 0, 1, 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + def test_delete_last_p_row(self): + a, q, r = self.generate('tall', 'full') + q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + a, q, r = self.generate('tall', 'economic') + q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + def test_delete_last_1_col(self): + a, q, r = self.generate('Mx1', 'economic') + q1, r1 = qr_delete(q, r, 0, 1, 'col') + assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype)) + + a, q, r = self.generate('Mx1', 'full') + q1, r1 = qr_delete(q, r, 0, 1, 'col') + assert_unitary(q1) + assert_(q1.dtype == q.dtype) + assert_(q1.shape == q.shape) + assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype)) + + def test_delete_last_p_col(self): + a, q, r = self.generate('tall', 'full') + q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col') + assert_unitary(q1) + assert_(q1.dtype == q.dtype) + assert_(q1.shape == q.shape) + assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype)) + + a, q, r = self.generate('tall', 'economic') + q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col') + assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype)) + + def test_delete_1x1_row_col(self): + a, q, r = self.generate('1x1') + q1, r1 = qr_delete(q, r, 0, 1, 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + a, q, r = self.generate('1x1') + q1, r1 = qr_delete(q, r, 0, 1, 'col') + assert_unitary(q1) + assert_(q1.dtype == q.dtype) + assert_(q1.shape == q.shape) + assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype)) + + # all full qr, row deletes and single column deletes should be able to + # handle any non negative strides. (only row and column vector + # operations are used.) p column delete require fortran ordered + # Q and R and will make a copy as necessary. Economic qr row deletes + # require a contiguous q. + + def base_non_simple_strides(self, adjust_strides, ks, p, which, + overwriteable): + if which == 'row': + qind = (slice(p,None), slice(p,None)) + rind = (slice(p,None), slice(None)) + else: + qind = (slice(None), slice(None)) + rind = (slice(None), slice(None,-p)) + + for type, k in itertools.product(['sqr', 'tall', 'fat'], ks): + a, q0, r0, = self.generate(type) + qs, rs = adjust_strides((q0, r0)) + if p == 1: + a1 = np.delete(a, k, 0 if which == 'row' else 1) + else: + s = slice(k,k+p) + if k < 0: + s = slice(k, k + p + + (a.shape[0] if which == 'row' else a.shape[1])) + a1 = np.delete(a, s, 0 if which == 'row' else 1) + + # for each variable, q, r we try with it strided and + # overwrite=False. Then we try with overwrite=True, and make + # sure that q and r are still overwritten. + + q = q0.copy('F') + r = r0.copy('F') + q1, r1 = qr_delete(qs, r, k, p, which, False) + check_qr(q1, r1, a1, self.rtol, self.atol) + q1o, r1o = qr_delete(qs, r, k, p, which, True) + check_qr(q1o, r1o, a1, self.rtol, self.atol) + if overwriteable: + assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + q2, r2 = qr_delete(q, rs, k, p, which, False) + check_qr(q2, r2, a1, self.rtol, self.atol) + q2o, r2o = qr_delete(q, rs, k, p, which, True) + check_qr(q2o, r2o, a1, self.rtol, self.atol) + if overwriteable: + assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + # since some of these were consumed above + qs, rs = adjust_strides((q, r)) + q3, r3 = qr_delete(qs, rs, k, p, which, False) + check_qr(q3, r3, a1, self.rtol, self.atol) + q3o, r3o = qr_delete(qs, rs, k, p, which, True) + check_qr(q3o, r3o, a1, self.rtol, self.atol) + if overwriteable: + assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol) + + def test_non_unit_strides_1_row(self): + self.base_non_simple_strides(make_strided, [0], 1, 'row', True) + + def test_non_unit_strides_p_row(self): + self.base_non_simple_strides(make_strided, [0], 3, 'row', True) + + def test_non_unit_strides_1_col(self): + self.base_non_simple_strides(make_strided, [0], 1, 'col', True) + + def test_non_unit_strides_p_col(self): + self.base_non_simple_strides(make_strided, [0], 3, 'col', False) + + def test_neg_strides_1_row(self): + self.base_non_simple_strides(negate_strides, [0], 1, 'row', False) + + def test_neg_strides_p_row(self): + self.base_non_simple_strides(negate_strides, [0], 3, 'row', False) + + def test_neg_strides_1_col(self): + self.base_non_simple_strides(negate_strides, [0], 1, 'col', False) + + def test_neg_strides_p_col(self): + self.base_non_simple_strides(negate_strides, [0], 3, 'col', False) + + def test_non_itemize_strides_1_row(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False) + + def test_non_itemize_strides_p_row(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False) + + def test_non_itemize_strides_1_col(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False) + + def test_non_itemize_strides_p_col(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False) + + def test_non_native_byte_order_1_row(self): + self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False) + + def test_non_native_byte_order_p_row(self): + self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False) + + def test_non_native_byte_order_1_col(self): + self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False) + + def test_non_native_byte_order_p_col(self): + self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False) + + def test_neg_k(self): + a, q, r = self.generate('sqr') + for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']): + q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False) + if w == 'row': + a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0) + else: + a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'): + assert_sqr = True if mode == 'full' else False + if which == 'row': + qind = (slice(p,None), slice(p,None)) + rind = (slice(p,None), slice(None)) + else: + qind = (slice(None), slice(None)) + rind = (slice(None), slice(None,-p)) + a, q0, r0 = self.generate('sqr', mode) + if p == 1: + a1 = np.delete(a, 3, 0 if which == 'row' else 1) + else: + a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1) + + # don't overwrite + q = q0.copy('F') + r = r0.copy('F') + q1, r1 = qr_delete(q, r, 3, p, which, False) + check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr) + check_qr(q, r, a, self.rtol, self.atol, assert_sqr) + + if test_F: + q = q0.copy('F') + r = r0.copy('F') + q2, r2 = qr_delete(q, r, 3, p, which, True) + check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr) + # verify the overwriting + assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol) + + if test_C: + q = q0.copy('C') + r = r0.copy('C') + q3, r3 = qr_delete(q, r, 3, p, which, True) + check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr) + assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol) + + def test_overwrite_qr_1_row(self): + # any positively strided q and r. + self.base_overwrite_qr('row', 1, True, True) + + def test_overwrite_economic_qr_1_row(self): + # Any contiguous q and positively strided r. + self.base_overwrite_qr('row', 1, True, True, 'economic') + + def test_overwrite_qr_1_col(self): + # any positively strided q and r. + # full and eco share code paths + self.base_overwrite_qr('col', 1, True, True) + + def test_overwrite_qr_p_row(self): + # any positively strided q and r. + self.base_overwrite_qr('row', 3, True, True) + + def test_overwrite_economic_qr_p_row(self): + # any contiguous q and positively strided r + self.base_overwrite_qr('row', 3, True, True, 'economic') + + def test_overwrite_qr_p_col(self): + # only F ordered q and r can be overwritten for cols + # full and eco share code paths + self.base_overwrite_qr('col', 3, False, True) + + def test_bad_which(self): + a, q, r = self.generate('sqr') + assert_raises(ValueError, qr_delete, q, r, 0, which='foo') + + def test_bad_k(self): + a, q, r = self.generate('tall') + assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1) + assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1) + assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col') + assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col') + + def test_bad_p(self): + a, q, r = self.generate('tall') + # p must be positive + assert_raises(ValueError, qr_delete, q, r, 0, -1) + assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col') + + # and nonzero + assert_raises(ValueError, qr_delete, q, r, 0, 0) + assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col') + + # must have at least k+p rows or cols, depending. + assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2) + assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col') + + def test_empty_q(self): + a, q, r = self.generate('tall') + # same code path for 'row' and 'col' + assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1) + + def test_empty_r(self): + a, q, r = self.generate('tall') + # same code path for 'row' and 'col' + assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1) + + def test_mismatched_q_and_r(self): + a, q, r = self.generate('tall') + r = r[1:] + assert_raises(ValueError, qr_delete, q, r, 0, 1) + + def test_unsupported_dtypes(self): + dts = ['int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'float16', 'longdouble', 'clongdouble', + 'bool'] + a, q0, r0 = self.generate('tall') + for dtype in dts: + q = q0.real.astype(dtype) + with np.errstate(invalid="ignore"): + r = r0.real.astype(dtype) + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col') + + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col') + + def test_check_finite(self): + a0, q0, r0 = self.generate('tall') + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col') + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col') + + def test_qr_scalar(self): + a, q, r = self.generate('1x1') + assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row') + assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col') + +class TestQRdelete_f(BaseQRdelete): + dtype = np.dtype('f') + +class TestQRdelete_F(BaseQRdelete): + dtype = np.dtype('F') + +class TestQRdelete_d(BaseQRdelete): + dtype = np.dtype('d') + +class TestQRdelete_D(BaseQRdelete): + dtype = np.dtype('D') + +class BaseQRinsert(BaseQRdeltas): + def generate(self, type, mode='full', which='row', p=1): + a, q, r = super().generate(type, mode) + + assert_(p > 0) + rng = np.random.default_rng(1234) + + if which == 'row': + if p == 1: + u = rng.random(a.shape[1]) + else: + u = rng.random((p, a.shape[1])) + elif which == 'col': + if p == 1: + u = rng.random(a.shape[0]) + else: + u = rng.random((a.shape[0], p)) + else: + raise ValueError('which should be either "row" or "col"') + + if np.iscomplexobj(self.dtype.type(1)): + b = rng.random(u.shape) + u = u + 1j * b + + u = u.astype(self.dtype) + return a, q, r, u + + def test_sqr_1_row(self): + a, q, r, u = self.generate('sqr', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_row(self): + # sqr + rows --> fat always + a, q, r, u = self.generate('sqr', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_1_col(self): + a, q, r, u = self.generate('sqr', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_col(self): + # sqr + cols --> fat always + a, q, r, u = self.generate('sqr', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_row(self): + a, q, r, u = self.generate('tall', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_row(self): + # tall + rows --> tall always + a, q, r, u = self.generate('tall', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_col(self): + a, q, r, u = self.generate('tall', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + # for column adds to tall matrices there are three cases to test + # tall + pcol --> tall + # tall + pcol --> sqr + # tall + pcol --> fat + def base_tall_p_col_xxx(self, p): + a, q, r, u = self.generate('tall', which='col', p=p) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(p, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_col_tall(self): + # 12x7 + 12x3 = 12x10 --> stays tall + self.base_tall_p_col_xxx(3) + + def test_tall_p_col_sqr(self): + # 12x7 + 12x5 = 12x12 --> becomes sqr + self.base_tall_p_col_xxx(5) + + def test_tall_p_col_fat(self): + # 12x7 + 12x7 = 12x14 --> becomes fat + self.base_tall_p_col_xxx(7) + + def test_fat_1_row(self): + a, q, r, u = self.generate('fat', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + # for row adds to fat matrices there are three cases to test + # fat + prow --> fat + # fat + prow --> sqr + # fat + prow --> tall + def base_fat_p_row_xxx(self, p): + a, q, r, u = self.generate('fat', which='row', p=p) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(p, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_row_fat(self): + # 7x12 + 3x12 = 10x12 --> stays fat + self.base_fat_p_row_xxx(3) + + def test_fat_p_row_sqr(self): + # 7x12 + 5x12 = 12x12 --> becomes sqr + self.base_fat_p_row_xxx(5) + + def test_fat_p_row_tall(self): + # 7x12 + 7x12 = 14x12 --> becomes tall + self.base_fat_p_row_xxx(7) + + def test_fat_1_col(self): + a, q, r, u = self.generate('fat', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_col(self): + # fat + cols --> fat always + a, q, r, u = self.generate('fat', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_economic_1_row(self): + a, q, r, u = self.generate('tall', 'economic', 'row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_row(self): + # tall + rows --> tall always + a, q, r, u = self.generate('tall', 'economic', 'row', 3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_1_col(self): + a, q, r, u = self.generate('tall', 'economic', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_1_col_bad_update(self): + # When the column to be added lies in the span of Q, the update is + # not meaningful. This is detected, and a LinAlgError is issued. + q = np.eye(5, 3, dtype=self.dtype) + r = np.eye(3, dtype=self.dtype) + u = np.array([1, 0, 0, 0, 0], self.dtype) + assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col') + + # for column adds to economic matrices there are three cases to test + # eco + pcol --> eco + # eco + pcol --> sqr + # eco + pcol --> fat + def base_economic_p_col_xxx(self, p): + a, q, r, u = self.generate('tall', 'economic', which='col', p=p) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(p, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_col_eco(self): + # 12x7 + 12x3 = 12x10 --> stays eco + self.base_economic_p_col_xxx(3) + + def test_economic_p_col_sqr(self): + # 12x7 + 12x5 = 12x12 --> becomes sqr + self.base_economic_p_col_xxx(5) + + def test_economic_p_col_fat(self): + # 12x7 + 12x7 = 12x14 --> becomes fat + self.base_economic_p_col_xxx(7) + + def test_Mx1_1_row(self): + a, q, r, u = self.generate('Mx1', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_p_row(self): + a, q, r, u = self.generate('Mx1', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_1_col(self): + a, q, r, u = self.generate('Mx1', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_p_col(self): + a, q, r, u = self.generate('Mx1', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_economic_1_row(self): + a, q, r, u = self.generate('Mx1', 'economic', 'row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_p_row(self): + a, q, r, u = self.generate('Mx1', 'economic', 'row', 3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_1_col(self): + a, q, r, u = self.generate('Mx1', 'economic', 'col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_p_col(self): + a, q, r, u = self.generate('Mx1', 'economic', 'col', 3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_1xN_1_row(self): + a, q, r, u = self.generate('1xN', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_p_row(self): + a, q, r, u = self.generate('1xN', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_1_col(self): + a, q, r, u = self.generate('1xN', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_p_col(self): + a, q, r, u = self.generate('1xN', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_1_row(self): + a, q, r, u = self.generate('1x1', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_p_row(self): + a, q, r, u = self.generate('1x1', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_1_col(self): + a, q, r, u = self.generate('1x1', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_p_col(self): + a, q, r, u = self.generate('1x1', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_1_scalar(self): + a, q, r, u = self.generate('1x1', which='row') + assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row') + + assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col') + + def base_non_simple_strides(self, adjust_strides, k, p, which): + for type in ['sqr', 'tall', 'fat']: + a, q0, r0, u0 = self.generate(type, which=which, p=p) + qs, rs, us = adjust_strides((q0, r0, u0)) + if p == 1: + ai = np.insert(a, k, u0, 0 if which == 'row' else 1) + else: + ai = np.insert(a, np.full(p, k, np.intp), + u0 if which == 'row' else u0, + 0 if which == 'row' else 1) + + # for each variable, q, r, u we try with it strided and + # overwrite=False. Then we try with overwrite=True. Nothing + # is checked to see if it can be overwritten, since only + # F ordered Q can be overwritten when adding columns. + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False) + check_qr(q1, r1, ai, self.rtol, self.atol) + q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True) + check_qr(q1o, r1o, ai, self.rtol, self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False) + check_qr(q2, r2, ai, self.rtol, self.atol) + q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True) + check_qr(q2o, r2o, ai, self.rtol, self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False) + check_qr(q3, r3, ai, self.rtol, self.atol) + q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True) + check_qr(q3o, r3o, ai, self.rtol, self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + # since some of these were consumed above + qs, rs, us = adjust_strides((q, r, u)) + q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False) + check_qr(q5, r5, ai, self.rtol, self.atol) + q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True) + check_qr(q5o, r5o, ai, self.rtol, self.atol) + + def test_non_unit_strides_1_row(self): + self.base_non_simple_strides(make_strided, 0, 1, 'row') + + def test_non_unit_strides_p_row(self): + self.base_non_simple_strides(make_strided, 0, 3, 'row') + + def test_non_unit_strides_1_col(self): + self.base_non_simple_strides(make_strided, 0, 1, 'col') + + def test_non_unit_strides_p_col(self): + self.base_non_simple_strides(make_strided, 0, 3, 'col') + + def test_neg_strides_1_row(self): + self.base_non_simple_strides(negate_strides, 0, 1, 'row') + + def test_neg_strides_p_row(self): + self.base_non_simple_strides(negate_strides, 0, 3, 'row') + + def test_neg_strides_1_col(self): + self.base_non_simple_strides(negate_strides, 0, 1, 'col') + + def test_neg_strides_p_col(self): + self.base_non_simple_strides(negate_strides, 0, 3, 'col') + + def test_non_itemsize_strides_1_row(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row') + + def test_non_itemsize_strides_p_row(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row') + + def test_non_itemsize_strides_1_col(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col') + + def test_non_itemsize_strides_p_col(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col') + + def test_non_native_byte_order_1_row(self): + self.base_non_simple_strides(make_nonnative, 0, 1, 'row') + + def test_non_native_byte_order_p_row(self): + self.base_non_simple_strides(make_nonnative, 0, 3, 'row') + + def test_non_native_byte_order_1_col(self): + self.base_non_simple_strides(make_nonnative, 0, 1, 'col') + + def test_non_native_byte_order_p_col(self): + self.base_non_simple_strides(make_nonnative, 0, 3, 'col') + + def test_overwrite_qu_rank_1(self): + # when inserting rows, the size of both Q and R change, so only + # column inserts can overwrite q. Only complex column inserts + # with C ordered Q overwrite u. Any contiguous Q is overwritten + # when inserting 1 column + a, q0, r, u, = self.generate('sqr', which='col', p=1) + q = q0.copy('C') + u0 = u.copy() + # don't overwrite + q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False) + a1 = np.insert(a, 0, u0, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + # try overwriting + q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True) + check_qr(q2, r2, a1, self.rtol, self.atol) + # verify the overwriting + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(u, u0.conj(), self.rtol, self.atol) + + # now try with a fortran ordered Q + qF = q0.copy('F') + u1 = u0.copy() + q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False) + check_qr(q3, r3, a1, self.rtol, self.atol) + check_qr(qF, r, a, self.rtol, self.atol) + + # try overwriting + q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True) + check_qr(q4, r4, a1, self.rtol, self.atol) + assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol) + + def test_overwrite_qu_rank_p(self): + # when inserting rows, the size of both Q and R change, so only + # column inserts can potentially overwrite Q. In practice, only + # F ordered Q are overwritten with a rank p update. + a, q0, r, u, = self.generate('sqr', which='col', p=3) + q = q0.copy('F') + a1 = np.insert(a, np.zeros(3, np.intp), u, 1) + + # don't overwrite + q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + # try overwriting + q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True) + check_qr(q2, r2, a1, self.rtol, self.atol) + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + + def test_empty_inputs(self): + a, q, r, u = self.generate('sqr', which='row') + assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row') + assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row') + assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col') + assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col') + + def test_mismatched_shapes(self): + a, q, r, u = self.generate('tall', which='row') + assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row') + assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row') + assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col') + assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col') + + def test_unsupported_dtypes(self): + dts = ['int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'float16', 'longdouble', 'clongdouble', + 'bool'] + a, q0, r0, u0 = self.generate('sqr', which='row') + for dtype in dts: + q = q0.real.astype(dtype) + with np.errstate(invalid="ignore"): + r = r0.real.astype(dtype) + u = u0.real.astype(dtype) + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col') + + def test_check_finite(self): + a0, q0, r0, u0 = self.generate('sqr', which='row', p=3) + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row') + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col') + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col') + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col') + + u = u0.copy('F') + u[0,0] = np.nan + assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col') + +class TestQRinsert_f(BaseQRinsert): + dtype = np.dtype('f') + +class TestQRinsert_F(BaseQRinsert): + dtype = np.dtype('F') + +class TestQRinsert_d(BaseQRinsert): + dtype = np.dtype('d') + +class TestQRinsert_D(BaseQRinsert): + dtype = np.dtype('D') + +class BaseQRupdate(BaseQRdeltas): + def generate(self, type, mode='full', p=1): + a, q, r = super().generate(type, mode) + + rng = np.random.default_rng(1234) + if p == 1: + u = rng.random(q.shape[0]) + v = rng.random(r.shape[1]) + else: + u = rng.random((q.shape[0], p)) + v = rng.random((r.shape[1], p)) + + if np.iscomplexobj(self.dtype.type(1)): + b = rng.random(u.shape) + u = u + 1j * b + + c = rng.random(v.shape) + v = v + 1j * c + + u = u.astype(self.dtype) + v = v.astype(self.dtype) + return a, q, r, u, v + + def test_sqr_rank_1(self): + a, q, r, u, v = self.generate('sqr') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_rank_p(self): + # test ndim = 2, rank 1 updates here too + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('sqr', p=p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_rank_1(self): + a, q, r, u, v = self.generate('tall') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_rank_p(self): + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('tall', p=p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_rank_1(self): + a, q, r, u, v = self.generate('fat') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_rank_p(self): + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('fat', p=p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_economic_rank_1(self): + a, q, r, u, v = self.generate('tall', 'economic') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_rank_p(self): + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('tall', 'economic', p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_rank_1(self): + a, q, r, u, v = self.generate('Mx1') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('Mx1', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_economic_rank_1(self): + a, q, r, u, v = self.generate('Mx1', 'economic') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('Mx1', 'economic', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_1xN_rank_1(self): + a, q, r, u, v = self.generate('1xN') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('1xN', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_rank_1(self): + a, q, r, u, v = self.generate('1x1') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('1x1', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_rank_1_scalar(self): + a, q, r, u, v = self.generate('1x1') + assert_raises(ValueError, qr_update, q[0, 0], r, u, v) + assert_raises(ValueError, qr_update, q, r[0, 0], u, v) + assert_raises(ValueError, qr_update, q, r, u[0], v) + assert_raises(ValueError, qr_update, q, r, u, v[0]) + + def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable): + assert_sqr = False if mode == 'economic' else True + for type in ['sqr', 'tall', 'fat']: + a, q0, r0, u0, v0 = self.generate(type, mode, p) + qs, rs, us, vs = adjust_strides((q0, r0, u0, v0)) + if p == 1: + aup = a + np.outer(u0, v0.conj()) + else: + aup = a + np.dot(u0, v0.T.conj()) + + # for each variable, q, r, u, v we try with it strided and + # overwrite=False. Then we try with overwrite=True, and make + # sure that if p == 1, r and v are still overwritten. + # a strided q and u must always be copied. + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q1, r1 = qr_update(qs, r, u, v, False) + check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr) + q1o, r1o = qr_update(qs, r, u, v, True) + check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol) + assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q2, r2 = qr_update(q, rs, u, v, False) + check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr) + q2o, r2o = qr_update(q, rs, u, v, True) + check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol) + assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q3, r3 = qr_update(q, r, us, v, False) + check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr) + q3o, r3o = qr_update(q, r, us, v, True) + check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol) + assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q4, r4 = qr_update(q, r, u, vs, False) + check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr) + q4o, r4o = qr_update(q, r, u, vs, True) + check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol) + assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + # since some of these were consumed above + qs, rs, us, vs = adjust_strides((q, r, u, v)) + q5, r5 = qr_update(qs, rs, us, vs, False) + check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr) + q5o, r5o = qr_update(qs, rs, us, vs, True) + check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol) + assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol) + + def test_non_unit_strides_rank_1(self): + self.base_non_simple_strides(make_strided, 'full', 1, True) + + def test_non_unit_strides_economic_rank_1(self): + self.base_non_simple_strides(make_strided, 'economic', 1, True) + + def test_non_unit_strides_rank_p(self): + self.base_non_simple_strides(make_strided, 'full', 3, False) + + def test_non_unit_strides_economic_rank_p(self): + self.base_non_simple_strides(make_strided, 'economic', 3, False) + + def test_neg_strides_rank_1(self): + self.base_non_simple_strides(negate_strides, 'full', 1, False) + + def test_neg_strides_economic_rank_1(self): + self.base_non_simple_strides(negate_strides, 'economic', 1, False) + + def test_neg_strides_rank_p(self): + self.base_non_simple_strides(negate_strides, 'full', 3, False) + + def test_neg_strides_economic_rank_p(self): + self.base_non_simple_strides(negate_strides, 'economic', 3, False) + + def test_non_itemsize_strides_rank_1(self): + self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False) + + def test_non_itemsize_strides_economic_rank_1(self): + self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False) + + def test_non_itemsize_strides_rank_p(self): + self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False) + + def test_non_itemsize_strides_economic_rank_p(self): + self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False) + + def test_non_native_byte_order_rank_1(self): + self.base_non_simple_strides(make_nonnative, 'full', 1, False) + + def test_non_native_byte_order_economic_rank_1(self): + self.base_non_simple_strides(make_nonnative, 'economic', 1, False) + + def test_non_native_byte_order_rank_p(self): + self.base_non_simple_strides(make_nonnative, 'full', 3, False) + + def test_non_native_byte_order_economic_rank_p(self): + self.base_non_simple_strides(make_nonnative, 'economic', 3, False) + + def test_overwrite_qruv_rank_1(self): + # Any positive strided q, r, u, and v can be overwritten for a rank 1 + # update, only checking C and F contiguous. + a, q0, r0, u0, v0 = self.generate('sqr') + a1 = a + np.outer(u0, v0.conj()) + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('F') + + # don't overwrite + q1, r1 = qr_update(q, r, u, v, False) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + q2, r2 = qr_update(q, r, u, v, True) + check_qr(q2, r2, a1, self.rtol, self.atol) + # verify the overwriting, no good way to check u and v. + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r, rtol=self.rtol, atol=self.atol) + + q = q0.copy('C') + r = r0.copy('C') + u = u0.copy('C') + v = v0.copy('C') + q3, r3 = qr_update(q, r, u, v, True) + check_qr(q3, r3, a1, self.rtol, self.atol) + assert_allclose(q3, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r3, r, rtol=self.rtol, atol=self.atol) + + def test_overwrite_qruv_rank_1_economic(self): + # updating economic decompositions can overwrite any contiguous r, + # and positively strided r and u. V is only ever read. + # only checking C and F contiguous. + a, q0, r0, u0, v0 = self.generate('tall', 'economic') + a1 = a + np.outer(u0, v0.conj()) + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('F') + + # don't overwrite + q1, r1 = qr_update(q, r, u, v, False) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + check_qr(q, r, a, self.rtol, self.atol, False) + + q2, r2 = qr_update(q, r, u, v, True) + check_qr(q2, r2, a1, self.rtol, self.atol, False) + # verify the overwriting, no good way to check u and v. + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r, rtol=self.rtol, atol=self.atol) + + q = q0.copy('C') + r = r0.copy('C') + u = u0.copy('C') + v = v0.copy('C') + q3, r3 = qr_update(q, r, u, v, True) + check_qr(q3, r3, a1, self.rtol, self.atol, False) + assert_allclose(q3, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r3, r, rtol=self.rtol, atol=self.atol) + + def test_overwrite_qruv_rank_p(self): + # for rank p updates, q r must be F contiguous, v must be C (v.T --> F) + # and u can be C or F, but is only overwritten if Q is C and complex + a, q0, r0, u0, v0 = self.generate('sqr', p=3) + a1 = a + np.dot(u0, v0.T.conj()) + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + + # don't overwrite + q1, r1 = qr_update(q, r, u, v, False) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + q2, r2 = qr_update(q, r, u, v, True) + check_qr(q2, r2, a1, self.rtol, self.atol) + # verify the overwriting, no good way to check u and v. + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r, rtol=self.rtol, atol=self.atol) + + def test_empty_inputs(self): + a, q, r, u, v = self.generate('tall') + assert_raises(ValueError, qr_update, np.array([]), r, u, v) + assert_raises(ValueError, qr_update, q, np.array([]), u, v) + assert_raises(ValueError, qr_update, q, r, np.array([]), v) + assert_raises(ValueError, qr_update, q, r, u, np.array([])) + + def test_mismatched_shapes(self): + a, q, r, u, v = self.generate('tall') + assert_raises(ValueError, qr_update, q, r[1:], u, v) + assert_raises(ValueError, qr_update, q[:-2], r, u, v) + assert_raises(ValueError, qr_update, q, r, u[1:], v) + assert_raises(ValueError, qr_update, q, r, u, v[1:]) + + def test_unsupported_dtypes(self): + dts = ['int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'float16', 'longdouble', 'clongdouble', + 'bool'] + a, q0, r0, u0, v0 = self.generate('tall') + for dtype in dts: + q = q0.real.astype(dtype) + with np.errstate(invalid="ignore"): + r = r0.real.astype(dtype) + u = u0.real.astype(dtype) + v = v0.real.astype(dtype) + assert_raises(ValueError, qr_update, q, r0, u0, v0) + assert_raises(ValueError, qr_update, q0, r, u0, v0) + assert_raises(ValueError, qr_update, q0, r0, u, v0) + assert_raises(ValueError, qr_update, q0, r0, u0, v) + + def test_integer_input(self): + q = np.arange(16).reshape(4, 4) + r = q.copy() # doesn't matter + u = q[:, 0].copy() + v = r[0, :].copy() + assert_raises(ValueError, qr_update, q, r, u, v) + + def test_check_finite(self): + a0, q0, r0, u0, v0 = self.generate('tall', p=3) + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q, r0, u0, v0) + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r, u0, v0) + + u = u0.copy('F') + u[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v0) + + v = v0.copy('F') + v[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v) + + def test_economic_check_finite(self): + a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3) + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q, r0, u0, v0) + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r, u0, v0) + + u = u0.copy('F') + u[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v0) + + v = v0.copy('F') + v[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v) + + def test_u_exactly_in_span_q(self): + q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype) + r = np.array([[1, 0], [0, 1]], self.dtype) + u = np.array([0, 0, 0, -1], self.dtype) + v = np.array([1, 2], self.dtype) + q1, r1 = qr_update(q, r, u, v) + a1 = np.dot(q, r) + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + +class TestQRupdate_f(BaseQRupdate): + dtype = np.dtype('f') + +class TestQRupdate_F(BaseQRupdate): + dtype = np.dtype('F') + +class TestQRupdate_d(BaseQRupdate): + dtype = np.dtype('d') + +class TestQRupdate_D(BaseQRupdate): + dtype = np.dtype('D') + +def test_form_qTu(): + # We want to ensure that all of the code paths through this function are + # tested. Most of them should be hit with the rest of test suite, but + # explicit tests make clear precisely what is being tested. + # + # This function expects that Q is either C or F contiguous and square. + # Economic mode decompositions (Q is (M, N), M != N) do not go through this + # function. U may have any positive strides. + # + # Some of these test are duplicates, since contiguous 1d arrays are both C + # and F. + + q_order = ['F', 'C'] + q_shape = [(8, 8), ] + u_order = ['F', 'C', 'A'] # here A means is not F not C + u_shape = [1, 3] + dtype = ['f', 'd', 'F', 'D'] + + for qo, qs, uo, us, d in \ + itertools.product(q_order, q_shape, u_order, u_shape, dtype): + if us == 1: + check_form_qTu(qo, qs, uo, us, 1, d) + check_form_qTu(qo, qs, uo, us, 2, d) + else: + check_form_qTu(qo, qs, uo, us, 2, d) + +def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype): + rng = np.random.default_rng(47) + if u_shape == 1 and u_ndim == 1: + u_shape = (q_shape[0],) + else: + u_shape = (q_shape[0], u_shape) + dtype = np.dtype(dtype) + + if dtype.char in 'fd': + q = rng.random(q_shape) + u = rng.random(u_shape) + elif dtype.char in 'FD': + q = rng.random(q_shape) + 1j*rng.random(q_shape) + u = rng.random(u_shape) + 1j*rng.random(u_shape) + else: + raise ValueError("form_qTu doesn't support this dtype") + + q = np.require(q, dtype, q_order) + if u_order != 'A': + u = np.require(u, dtype, u_order) + else: + u, = make_strided((u.astype(dtype),)) + + rtol = 10.0 ** -(np.finfo(dtype).precision-2) + atol = 2*np.finfo(dtype).eps + + expected = np.dot(q.T.conj(), u) + res = _decomp_update._form_qTu(q, u) + assert_allclose(res, expected, rtol=rtol, atol=atol) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_extending.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_extending.py new file mode 100644 index 0000000000000000000000000000000000000000..9fde33a87d2d0c8293d50e75b0db453c4c587cd5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_extending.py @@ -0,0 +1,47 @@ +import os +import platform +import sysconfig + +import numpy as np +import pytest + +from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython +from scipy.linalg.blas import cdotu # type: ignore[attr-defined] +from scipy.linalg.lapack import dgtsv # type: ignore[attr-defined] + + +@pytest.mark.parallel_threads_limit(4) # 0.35 GiB per thread RAM usage +@pytest.mark.fail_slow(120) +# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247 +@pytest.mark.skipif(IS_EDITABLE, + reason='Editable install cannot find .pxd headers.') +@pytest.mark.skipif((platform.system() == 'Windows' and + sysconfig.get_config_var('Py_GIL_DISABLED')), + reason='gh-22039') +@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"], + reason="Can't start subprocess") +@pytest.mark.skipif(cython is None, reason="requires cython") +def test_cython(tmp_path): + srcdir = os.path.dirname(os.path.dirname(__file__)) + extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir) + # actually test the cython c-extensions + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x = np.ones(9) + _, _, _, x, _ = dgtsv(a, b, c, x) + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x_c = np.ones(9) + extensions.tridiag(a, b, c, x_c) + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x_cpp = np.ones(9) + extensions_cpp.tridiag(a, b, c, x_cpp) + np.testing.assert_array_equal(x, x_cpp) + cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64) + cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64) + np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy)) + np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_fblas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_fblas.py new file mode 100644 index 0000000000000000000000000000000000000000..317762fd7a0a04d22566de82107b9f3c7a2c2235 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_fblas.py @@ -0,0 +1,602 @@ +# Test interfaces to fortran blas. +# +# The tests are more of interface than they are of the underlying blas. +# Only very small matrices checked -- N=3 or so. +# +# !! Complex calculations really aren't checked that carefully. +# !! Only real valued complex numbers are used in tests. +from itertools import product +import sys + +import numpy as np +from numpy import float32, float64, complex64, complex128, arange, array, \ + zeros, shape, transpose, newaxis, common_type, conjugate + +from scipy.linalg import _fblas as fblas + +from numpy.testing import assert_array_equal, \ + assert_allclose, assert_array_almost_equal, assert_ + +import pytest + +# decimal accuracy to require between Python and LAPACK/BLAS calculations +accuracy = 5 + +# Since numpy.dot likely uses the same blas, use this routine +# to check. + + +def matrixmultiply(a, b): + if len(b.shape) == 1: + b_is_vector = True + b = b[:, newaxis] + else: + b_is_vector = False + assert_(a.shape[1] == b.shape[0]) + c = zeros((a.shape[0], b.shape[1]), common_type(a, b)) + for i in range(a.shape[0]): + for j in range(b.shape[1]): + s = 0 + for k in range(a.shape[1]): + s += a[i, k] * b[k, j] + c[i, j] = s + if b_is_vector: + c = c.reshape((a.shape[0],)) + return c + +################################################## +# Test blas ?axpy + + +class BaseAxpy: + ''' Mixin class for axpy tests ''' + + def test_default_a(self): + x = arange(3., dtype=self.dtype) + y = arange(3., dtype=x.dtype) + real_y = x*1.+y + y = self.blas_func(x, y) + assert_array_equal(real_y, y) + + def test_simple(self): + x = arange(3., dtype=self.dtype) + y = arange(3., dtype=x.dtype) + real_y = x*3.+y + y = self.blas_func(x, y, a=3.) + assert_array_equal(real_y, y) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + y = zeros(3, x.dtype) + y = arange(3., dtype=x.dtype) + real_y = x[::2]*3.+y + y = self.blas_func(x, y, a=3., n=3, incx=2) + assert_array_equal(real_y, y) + + def test_y_stride(self): + x = arange(3., dtype=self.dtype) + y = zeros(6, x.dtype) + real_y = x*3.+y[::2] + y = self.blas_func(x, y, a=3., n=3, incy=2) + assert_array_equal(real_y, y[::2]) + + def test_x_and_y_stride(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + real_y = x[::4]*3.+y[::2] + y = self.blas_func(x, y, a=3., n=3, incx=4, incy=2) + assert_array_equal(real_y, y[::2]) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=4, incx=5) + + def test_y_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=3, incy=5) + + +try: + class TestSaxpy(BaseAxpy): + blas_func = fblas.saxpy + dtype = float32 +except AttributeError: + class TestSaxpy: + pass + + +class TestDaxpy(BaseAxpy): + blas_func = fblas.daxpy + dtype = float64 + + +try: + class TestCaxpy(BaseAxpy): + blas_func = fblas.caxpy + dtype = complex64 +except AttributeError: + class TestCaxpy: + pass + + +class TestZaxpy(BaseAxpy): + blas_func = fblas.zaxpy + dtype = complex128 + + +################################################## +# Test blas ?scal + +class BaseScal: + ''' Mixin class for scal testing ''' + + def test_simple(self): + x = arange(3., dtype=self.dtype) + real_x = x*3. + x = self.blas_func(3., x) + assert_array_equal(real_x, x) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + real_x = x.copy() + real_x[::2] = x[::2]*array(3., self.dtype) + x = self.blas_func(3., x, n=3, incx=2) + assert_array_equal(real_x, x) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(2., x, n=4, incx=5) + + +try: + class TestSscal(BaseScal): + blas_func = fblas.sscal + dtype = float32 +except AttributeError: + class TestSscal: + pass + + +class TestDscal(BaseScal): + blas_func = fblas.dscal + dtype = float64 + + +try: + class TestCscal(BaseScal): + blas_func = fblas.cscal + dtype = complex64 +except AttributeError: + class TestCscal: + pass + + +class TestZscal(BaseScal): + blas_func = fblas.zscal + dtype = complex128 + + +################################################## +# Test blas ?copy + +class BaseCopy: + ''' Mixin class for copy testing ''' + + def test_simple(self): + x = arange(3., dtype=self.dtype) + y = zeros(shape(x), x.dtype) + y = self.blas_func(x, y) + assert_array_equal(x, y) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + y = zeros(3, x.dtype) + y = self.blas_func(x, y, n=3, incx=2) + assert_array_equal(x[::2], y) + + def test_y_stride(self): + x = arange(3., dtype=self.dtype) + y = zeros(6, x.dtype) + y = self.blas_func(x, y, n=3, incy=2) + assert_array_equal(x, y[::2]) + + def test_x_and_y_stride(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + y = self.blas_func(x, y, n=3, incx=4, incy=2) + assert_array_equal(x[::4], y[::2]) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=4, incx=5) + + def test_y_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=3, incy=5) + + # def test_y_bad_type(self): + ## Hmmm. Should this work? What should be the output. + # x = arange(3.,dtype=self.dtype) + # y = zeros(shape(x)) + # self.blas_func(x,y) + # assert_array_equal(x,y) + + +try: + class TestScopy(BaseCopy): + blas_func = fblas.scopy + dtype = float32 +except AttributeError: + class TestScopy: + pass + + +class TestDcopy(BaseCopy): + blas_func = fblas.dcopy + dtype = float64 + + +try: + class TestCcopy(BaseCopy): + blas_func = fblas.ccopy + dtype = complex64 +except AttributeError: + class TestCcopy: + pass + + +class TestZcopy(BaseCopy): + blas_func = fblas.zcopy + dtype = complex128 + + +################################################## +# Test blas ?swap + +class BaseSwap: + ''' Mixin class for swap tests ''' + + def test_simple(self): + x = arange(3., dtype=self.dtype) + y = zeros(shape(x), x.dtype) + desired_x = y.copy() + desired_y = x.copy() + x, y = self.blas_func(x, y) + assert_array_equal(desired_x, x) + assert_array_equal(desired_y, y) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + y = zeros(3, x.dtype) + desired_x = y.copy() + desired_y = x.copy()[::2] + x, y = self.blas_func(x, y, n=3, incx=2) + assert_array_equal(desired_x, x[::2]) + assert_array_equal(desired_y, y) + + def test_y_stride(self): + x = arange(3., dtype=self.dtype) + y = zeros(6, x.dtype) + desired_x = y.copy()[::2] + desired_y = x.copy() + x, y = self.blas_func(x, y, n=3, incy=2) + assert_array_equal(desired_x, x) + assert_array_equal(desired_y, y[::2]) + + def test_x_and_y_stride(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + desired_x = y.copy()[::2] + desired_y = x.copy()[::4] + x, y = self.blas_func(x, y, n=3, incx=4, incy=2) + assert_array_equal(desired_x, x[::4]) + assert_array_equal(desired_y, y[::2]) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=4, incx=5) + + def test_y_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=3, incy=5) + + +try: + class TestSswap(BaseSwap): + blas_func = fblas.sswap + dtype = float32 +except AttributeError: + class TestSswap: + pass + + +class TestDswap(BaseSwap): + blas_func = fblas.dswap + dtype = float64 + + +try: + class TestCswap(BaseSwap): + blas_func = fblas.cswap + dtype = complex64 +except AttributeError: + class TestCswap: + pass + + +class TestZswap(BaseSwap): + blas_func = fblas.zswap + dtype = complex128 + +################################################## +# Test blas ?gemv +# This will be a mess to test all cases. + + +class BaseGemv: + ''' Mixin class for gemv tests ''' + + def get_data(self, x_stride=1, y_stride=1): + rng = np.random.default_rng(1234) + mult = array(1, dtype=self.dtype) + if self.dtype in [complex64, complex128]: + mult = array(1+1j, dtype=self.dtype) + alpha = array(1., dtype=self.dtype) * mult + beta = array(1., dtype=self.dtype) * mult + a = rng.normal(0., 1., (3, 3)).astype(self.dtype) * mult + x = arange(shape(a)[0]*x_stride, dtype=self.dtype) * mult + y = arange(shape(a)[1]*y_stride, dtype=self.dtype) * mult + return alpha, beta, a, x, y + + def test_simple(self): + alpha, beta, a, x, y = self.get_data() + desired_y = alpha*matrixmultiply(a, x)+beta*y + y = self.blas_func(alpha, a, x, beta, y) + assert_array_almost_equal(desired_y, y) + + def test_default_beta_y(self): + alpha, beta, a, x, y = self.get_data() + desired_y = matrixmultiply(a, x) + y = self.blas_func(1, a, x) + assert_array_almost_equal(desired_y, y) + + def test_simple_transpose(self): + alpha, beta, a, x, y = self.get_data() + desired_y = alpha*matrixmultiply(transpose(a), x)+beta*y + y = self.blas_func(alpha, a, x, beta, y, trans=1) + assert_array_almost_equal(desired_y, y) + + def test_simple_transpose_conj(self): + alpha, beta, a, x, y = self.get_data() + desired_y = alpha*matrixmultiply(transpose(conjugate(a)), x)+beta*y + y = self.blas_func(alpha, a, x, beta, y, trans=2) + assert_array_almost_equal(desired_y, y) + + def test_x_stride(self): + alpha, beta, a, x, y = self.get_data(x_stride=2) + desired_y = alpha*matrixmultiply(a, x[::2])+beta*y + y = self.blas_func(alpha, a, x, beta, y, incx=2) + assert_array_almost_equal(desired_y, y) + + def test_x_stride_transpose(self): + alpha, beta, a, x, y = self.get_data(x_stride=2) + desired_y = alpha*matrixmultiply(transpose(a), x[::2])+beta*y + y = self.blas_func(alpha, a, x, beta, y, trans=1, incx=2) + assert_array_almost_equal(desired_y, y) + + def test_x_stride_assert(self): + # What is the use of this test? + alpha, beta, a, x, y = self.get_data(x_stride=2) + with pytest.raises(Exception, match='failed for 3rd argument'): + y = self.blas_func(1, a, x, 1, y, trans=0, incx=3) + with pytest.raises(Exception, match='failed for 3rd argument'): + y = self.blas_func(1, a, x, 1, y, trans=1, incx=3) + + def test_y_stride(self): + alpha, beta, a, x, y = self.get_data(y_stride=2) + desired_y = y.copy() + desired_y[::2] = alpha*matrixmultiply(a, x)+beta*y[::2] + y = self.blas_func(alpha, a, x, beta, y, incy=2) + assert_array_almost_equal(desired_y, y) + + def test_y_stride_transpose(self): + alpha, beta, a, x, y = self.get_data(y_stride=2) + desired_y = y.copy() + desired_y[::2] = alpha*matrixmultiply(transpose(a), x)+beta*y[::2] + y = self.blas_func(alpha, a, x, beta, y, trans=1, incy=2) + assert_array_almost_equal(desired_y, y) + + def test_y_stride_assert(self): + # What is the use of this test? + alpha, beta, a, x, y = self.get_data(y_stride=2) + with pytest.raises(Exception, match='failed for 2nd keyword'): + y = self.blas_func(1, a, x, 1, y, trans=0, incy=3) + with pytest.raises(Exception, match='failed for 2nd keyword'): + y = self.blas_func(1, a, x, 1, y, trans=1, incy=3) + + +try: + class TestSgemv(BaseGemv): + blas_func = fblas.sgemv + dtype = float32 + + @pytest.mark.skipif(sys.platform != 'darwin', reason="MacOS specific test") + def test_sgemv_on_osx(self): + def aligned_array(shape, align, dtype, order='C'): + # Make array shape `shape` with aligned at `align` bytes + d = dtype() + # Make array of correct size with `align` extra bytes + N = np.prod(shape) + tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8) + address = tmp.__array_interface__["data"][0] + # Find offset into array giving desired alignment + for offset in range(align): + if (address + offset) % align == 0: + break + tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype) + return tmp.reshape(shape, order=order) + + def as_aligned(arr, align, dtype, order='C'): + # Copy `arr` into an aligned array with same shape + aligned = aligned_array(arr.shape, align, dtype, order) + aligned[:] = arr[:] + return aligned + + def assert_dot_close(A, X, desired): + assert_allclose(self.blas_func(1.0, A, X), desired, + rtol=1e-5, atol=1e-7) + + testdata = product((15, 32), (10000,), (200, 89), ('C', 'F')) + rng = np.random.default_rng(1234) + for align, m, n, a_order in testdata: + A_d = rng.random((m, n)) + X_d = rng.random(n) + desired = np.dot(A_d, X_d) + # Calculation with aligned single precision + A_f = as_aligned(A_d, align, np.float32, order=a_order) + X_f = as_aligned(X_d, align, np.float32, order=a_order) + assert_dot_close(A_f, X_f, desired) + +except AttributeError: + class TestSgemv: + pass + + +class TestDgemv(BaseGemv): + blas_func = fblas.dgemv + dtype = float64 + + +try: + class TestCgemv(BaseGemv): + blas_func = fblas.cgemv + dtype = complex64 +except AttributeError: + class TestCgemv: + pass + + +class TestZgemv(BaseGemv): + blas_func = fblas.zgemv + dtype = complex128 + + +""" +################################################## +### Test blas ?ger +### This will be a mess to test all cases. + +class BaseGer: + def get_data(self,x_stride=1,y_stride=1): + rng = np.random.default_rng(1234) + alpha = array(1., dtype = self.dtype) + a = rng.normal(0.,1.,(3,3)).astype(self.dtype) + x = arange(shape(a)[0]*x_stride,dtype=self.dtype) + y = arange(shape(a)[1]*y_stride,dtype=self.dtype) + return alpha,a,x,y + def test_simple(self): + alpha,a,x,y = self.get_data() + # transpose takes care of Fortran vs. C(and Python) memory layout + desired_a = alpha*transpose(x[:,newaxis]*y) + a + self.blas_func(x,y,a) + assert_array_almost_equal(desired_a,a) + def test_x_stride(self): + alpha,a,x,y = self.get_data(x_stride=2) + desired_a = alpha*transpose(x[::2,newaxis]*y) + a + self.blas_func(x,y,a,incx=2) + assert_array_almost_equal(desired_a,a) + def test_x_stride_assert(self): + alpha,a,x,y = self.get_data(x_stride=2) + with pytest.raises(ValueError, match='foo'): + self.blas_func(x,y,a,incx=3) + def test_y_stride(self): + alpha,a,x,y = self.get_data(y_stride=2) + desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a + self.blas_func(x,y,a,incy=2) + assert_array_almost_equal(desired_a,a) + + def test_y_stride_assert(self): + alpha,a,x,y = self.get_data(y_stride=2) + with pytest.raises(ValueError, match='foo'): + self.blas_func(a,x,y,incy=3) + +class TestSger(BaseGer): + blas_func = fblas.sger + dtype = float32 +class TestDger(BaseGer): + blas_func = fblas.dger + dtype = float64 +""" +################################################## +# Test blas ?gerc +# This will be a mess to test all cases. + +""" +class BaseGerComplex(BaseGer): + def get_data(self,x_stride=1,y_stride=1): + rng = np.random.default_rng(1234) + alpha = array(1+1j, dtype = self.dtype) + a = rng.normal(0.,1.,(3,3)).astype(self.dtype) + a = a + rng.normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype) + x = rng.normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype) + x = x + x * array(1j, dtype = self.dtype) + y = rng.normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype) + y = y + y * array(1j, dtype = self.dtype) + return alpha,a,x,y + def test_simple(self): + alpha,a,x,y = self.get_data() + # transpose takes care of Fortran vs. C(and Python) memory layout + a = a * array(0.,dtype = self.dtype) + #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a + desired_a = alpha*transpose(x[:,newaxis]*y) + a + #self.blas_func(x,y,a,alpha = alpha) + fblas.cgeru(x,y,a,alpha = alpha) + assert_array_almost_equal(desired_a,a) + + #def test_x_stride(self): + # alpha,a,x,y = self.get_data(x_stride=2) + # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a + # self.blas_func(x,y,a,incx=2) + # assert_array_almost_equal(desired_a,a) + #def test_y_stride(self): + # alpha,a,x,y = self.get_data(y_stride=2) + # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a + # self.blas_func(x,y,a,incy=2) + # assert_array_almost_equal(desired_a,a) + +class TestCgeru(BaseGerComplex): + blas_func = fblas.cgeru + dtype = complex64 + def transform(self,x): + return x +class TestZgeru(BaseGerComplex): + blas_func = fblas.zgeru + dtype = complex128 + def transform(self,x): + return x + +class TestCgerc(BaseGerComplex): + blas_func = fblas.cgerc + dtype = complex64 + def transform(self,x): + return conjugate(x) + +class TestZgerc(BaseGerComplex): + blas_func = fblas.zgerc + dtype = complex128 + def transform(self,x): + return conjugate(x) +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_interpolative.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_interpolative.py new file mode 100644 index 0000000000000000000000000000000000000000..483899d1a1d9d8b8cabfd8eda5cd0a71a40390e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_interpolative.py @@ -0,0 +1,232 @@ +# ****************************************************************************** +# Copyright (C) 2013 Kenneth L. Ho +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. Redistributions in binary +# form must reproduce the above copyright notice, this list of conditions and +# the following disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# None of the names of the copyright holders may be used to endorse or +# promote products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# ****************************************************************************** + +import scipy.linalg.interpolative as pymatrixid +import numpy as np +from scipy.linalg import hilbert, svdvals, norm +from scipy.sparse.linalg import aslinearoperator +from scipy.linalg.interpolative import interp_decomp + +from numpy.testing import (assert_, assert_allclose, assert_equal, + assert_array_equal) +import pytest +from pytest import raises as assert_raises + + +@pytest.fixture() +def eps(): + yield 1e-12 + + +@pytest.fixture() +def rng(): + rng = np.random.default_rng(1718313768084012) + yield rng + + +@pytest.fixture(params=[np.float64, np.complex128]) +def A(request): + # construct Hilbert matrix + # set parameters + n = 300 + yield hilbert(n).astype(request.param) + + +@pytest.fixture() +def L(A): + yield aslinearoperator(A) + + +@pytest.fixture() +def rank(A, eps): + S = np.linalg.svd(A, compute_uv=False) + try: + rank = np.nonzero(S < eps)[0][0] + except IndexError: + rank = A.shape[0] + return rank + + +class TestInterpolativeDecomposition: + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng): + # Test ID routines on a Hilbert matrix. + A_or_L = A if not lin_op else L + + k, idx, proj = pymatrixid.interp_decomp(A_or_L, eps, rand=rand, rng=rng) + B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) + assert_allclose(A, B, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_real_id_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng): + k = rank + A_or_L = A if not lin_op else L + + idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng) + B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) + assert_allclose(A, B, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize("rand,lin_op", [(False, False)]) + def test_real_id_skel_and_interp_matrices( + self, A, L, eps, rank, rand, lin_op, rng): + k = rank + A_or_L = A if not lin_op else L + + idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng) + P = pymatrixid.reconstruct_interp_matrix(idx, proj) + B = pymatrixid.reconstruct_skel_matrix(A, k, idx) + assert_allclose(B, A[:, idx[:k]], rtol=eps, atol=1e-08) + assert_allclose(B @ P, A, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_svd_fixed_precision(self, A, L, eps, rand, lin_op, rng): + A_or_L = A if not lin_op else L + + U, S, V = pymatrixid.svd(A_or_L, eps, rand=rand, rng=rng) + B = U * S @ V.T.conj() + assert_allclose(A, B, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_svd_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng): + k = rank + A_or_L = A if not lin_op else L + + U, S, V = pymatrixid.svd(A_or_L, k, rand=rand, rng=rng) + B = U * S @ V.T.conj() + assert_allclose(A, B, rtol=eps, atol=1e-08) + + def test_id_to_svd(self, A, eps, rank): + k = rank + + idx, proj = pymatrixid.interp_decomp(A, k, rand=False) + U, S, V = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj) + B = U * S @ V.T.conj() + assert_allclose(A, B, rtol=eps, atol=1e-08) + + def test_estimate_spectral_norm(self, A, rng): + s = svdvals(A) + norm_2_est = pymatrixid.estimate_spectral_norm(A, rng=rng) + assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8) + + def test_estimate_spectral_norm_diff(self, A, rng): + B = A.copy() + B[:, 0] *= 1.2 + s = svdvals(A - B) + norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B, rng=rng) + assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8) + + def test_rank_estimates_array(self, A, rng): + B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype) + + for M in [A, B]: + rank_tol = 1e-9 + rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol) + rank_est = pymatrixid.estimate_rank(M, rank_tol, rng=rng) + assert_(rank_est >= rank_np) + assert_(rank_est <= rank_np + 10) + + def test_rank_estimates_lin_op(self, A, rng): + B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype) + + for M in [A, B]: + ML = aslinearoperator(M) + rank_tol = 1e-9 + rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol) + rank_est = pymatrixid.estimate_rank(ML, rank_tol, rng=rng) + assert_(rank_est >= rank_np - 4) + assert_(rank_est <= rank_np + 4) + + def test_badcall(self): + A = hilbert(5).astype(np.float32) + with assert_raises(ValueError): + pymatrixid.interp_decomp(A, 1e-6, rand=False) + + def test_rank_too_large(self): + # svd(array, k) should not segfault + a = np.ones((4, 3)) + with assert_raises(ValueError): + pymatrixid.svd(a, 4) + + def test_full_rank(self): + eps = 1.0e-12 + rng = np.random.default_rng(1234) + # fixed precision + A = rng.random((16, 8)) + k, idx, proj = pymatrixid.interp_decomp(A, eps) + assert_equal(k, A.shape[1]) + + P = pymatrixid.reconstruct_interp_matrix(idx, proj) + B = pymatrixid.reconstruct_skel_matrix(A, k, idx) + assert_allclose(A, B @ P) + + # fixed rank + idx, proj = pymatrixid.interp_decomp(A, k) + + P = pymatrixid.reconstruct_interp_matrix(idx, proj) + B = pymatrixid.reconstruct_skel_matrix(A, k, idx) + assert_allclose(A, B @ P) + + @pytest.mark.parametrize("dtype", [np.float64, np.complex128]) + @pytest.mark.parametrize("rand", [True, False]) + @pytest.mark.parametrize("eps", [1, 0.1]) + def test_bug_9793(self, dtype, rand, eps): + A = np.array([[-1, -1, -1, 0, 0, 0], + [0, 0, 0, 1, 1, 1], + [1, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 1]], + dtype=dtype, order="C") + B = A.copy() + interp_decomp(A.T, eps, rand=rand) + assert_array_equal(A, B) + + def test_svd_aslinearoperator_shape_check(self): + # See gh-issue #22451 + rng = np.random.default_rng(1744580941832515) + x = rng.uniform(size=[7, 5]) + xl = aslinearoperator(x) + u, s, v = pymatrixid.svd(xl, 3) + assert_equal(u.shape, (7, 3)) + assert_equal(s.shape, (3,)) + assert_equal(v.shape, (5, 3)) + + x = rng.uniform(size=[4, 9]) + xl = aslinearoperator(x) + u, s, v = pymatrixid.svd(xl, 2) + assert_equal(u.shape, (4, 2)) + assert_equal(s.shape, (2,)) + assert_equal(v.shape, (9, 2)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_lapack.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_lapack.py new file mode 100644 index 0000000000000000000000000000000000000000..529e0e3b27128426e15c94e4adfb8982680a94fc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_lapack.py @@ -0,0 +1,3616 @@ +# +# Created by: Pearu Peterson, September 2002 +# + +from functools import reduce +import sysconfig + +from numpy.testing import (assert_equal, assert_array_almost_equal, assert_, + assert_allclose, assert_almost_equal, + assert_array_equal) +import pytest +from pytest import raises as assert_raises + +import numpy as np +from numpy import (eye, ones, zeros, zeros_like, triu, tril, tril_indices, + triu_indices) + +from scipy.linalg import (_flapack as flapack, lapack, inv, svd, cholesky, + solve, ldl, norm, block_diag, qr, eigh, qz) +from scipy.linalg._basic import _to_banded +from scipy.linalg.lapack import _compute_lwork +from scipy.stats import ortho_group, unitary_group + +import scipy.sparse as sps + +try: + from scipy.linalg import _clapack as clapack +except ImportError: + clapack = None +from scipy.linalg.lapack import get_lapack_funcs +from scipy.linalg.blas import get_blas_funcs + +from scipy.__config__ import CONFIG +blas_provider = blas_version = None +blas_provider = CONFIG['Build Dependencies']['blas']['name'] +blas_version = CONFIG['Build Dependencies']['blas']['version'] + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +def generate_random_dtype_array(shape, dtype, rng): + # generates a random matrix of desired data type of shape + if dtype in COMPLEX_DTYPES: + return (rng.rand(*shape) + + rng.rand(*shape)*1.0j).astype(dtype) + return rng.rand(*shape).astype(dtype) + + +def test_lapack_documented(): + """Test that all entries are in the doc.""" + if lapack.__doc__ is None: # just in case there is a python -OO + pytest.skip('lapack.__doc__ is None') + names = set(lapack.__doc__.split()) + ignore_list = { + "absolute_import", + "clapack", + "division", + "find_best_lapack_type", + "flapack", + "print_function", + "HAS_ILP64", + "np", + } + missing = list() + for name in dir(lapack): + if (not name.startswith('_') and name not in ignore_list and + name not in names): + missing.append(name) + assert missing == [], 'Name(s) missing from lapack.__doc__ or ignore_list' + + +def test_ilp64_blas_lapack_both_or_none(): + from scipy.linalg.blas import HAS_ILP64 as blas_has_ilp64 + from scipy.linalg.lapack import HAS_ILP64 as lapack_has_ilp64 + assert blas_has_ilp64 == lapack_has_ilp64 + + +class TestFlapackSimple: + + def test_gebal(self): + a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + a1 = [[1, 0, 0, 3e-4], + [4, 0, 0, 2e-3], + [7, 1, 0, 0], + [0, 1, 0, 0]] + for p in 'sdzc': + f = getattr(flapack, p+'gebal', None) + if f is None: + continue + ba, lo, hi, pivscale, info = f(a) + assert_(not info, repr(info)) + assert_array_almost_equal(ba, a) + assert_equal((lo, hi), (0, len(a[0])-1)) + assert_array_almost_equal(pivscale, np.ones(len(a))) + + ba, lo, hi, pivscale, info = f(a1, permute=1, scale=1) + assert_(not info, repr(info)) + # print(a1) + # print(ba, lo, hi, pivscale) + + def test_gehrd(self): + a = [[-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]] + for p in 'd': + f = getattr(flapack, p+'gehrd', None) + if f is None: + continue + ht, tau, info = f(a) + assert_(not info, repr(info)) + + def test_trsyl(self): + a = np.array([[1, 2], [0, 4]]) + b = np.array([[5, 6], [0, 8]]) + c = np.array([[9, 10], [11, 12]]) + trans = 'T' + + # Test single and double implementations, including most + # of the options + for dtype in 'fdFD': + a1, b1, c1 = a.astype(dtype), b.astype(dtype), c.astype(dtype) + trsyl, = get_lapack_funcs(('trsyl',), (a1,)) + if dtype.isupper(): # is complex dtype + a1[0] += 1j + trans = 'C' + + x, scale, info = trsyl(a1, b1, c1) + assert_array_almost_equal(np.dot(a1, x) + np.dot(x, b1), + scale * c1) + + x, scale, info = trsyl(a1, b1, c1, trana=trans, tranb=trans) + assert_array_almost_equal( + np.dot(a1.conjugate().T, x) + np.dot(x, b1.conjugate().T), + scale * c1, decimal=4) + + x, scale, info = trsyl(a1, b1, c1, isgn=-1) + assert_array_almost_equal(np.dot(a1, x) - np.dot(x, b1), + scale * c1, decimal=4) + + def test_lange(self): + a = np.array([ + [-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]]) + + for dtype in 'fdFD': + for norm_str in 'Mm1OoIiFfEe': + a1 = a.astype(dtype) + if dtype.isupper(): + # is complex dtype + a1[0, 0] += 1j + + lange, = get_lapack_funcs(('lange',), (a1,)) + value = lange(norm_str, a1) + + if norm_str in 'FfEe': + if dtype in 'Ff': + decimal = 3 + else: + decimal = 7 + ref = np.sqrt(np.sum(np.square(np.abs(a1)))) + assert_almost_equal(value, ref, decimal) + else: + if norm_str in 'Mm': + ref = np.max(np.abs(a1)) + elif norm_str in '1Oo': + ref = np.max(np.sum(np.abs(a1), axis=0)) + elif norm_str in 'Ii': + ref = np.max(np.sum(np.abs(a1), axis=1)) + + assert_equal(value, ref) + + +class TestLapack: + + def test_flapack(self): + if hasattr(flapack, 'empty_module'): + # flapack module is empty + pass + + def test_clapack(self): + if hasattr(clapack, 'empty_module'): + # clapack module is empty + pass + + +class TestLeastSquaresSolvers: + + def test_gels(self): + rng = np.random.default_rng(1234) + # Test fat/tall matrix argument handling - gh-issue #8329 + for ind, dtype in enumerate(DTYPES): + m = 10 + n = 20 + nrhs = 1 + a1 = rng.random((m, n)).astype(dtype) + b1 = rng.random(n).astype(dtype) + gls, glslw = get_lapack_funcs(('gels', 'gels_lwork'), dtype=dtype) + + # Request of sizes + lwork = _compute_lwork(glslw, m, n, nrhs) + _, _, info = gls(a1, b1, lwork=lwork) + assert_(info >= 0) + _, _, info = gls(a1, b1, trans='TTCC'[ind], lwork=lwork) + assert_(info >= 0) + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gels, gels_lwork, geqrf = get_lapack_funcs( + ('gels', 'gels_lwork', 'geqrf'), (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + lwork = _compute_lwork(gels_lwork, m, n, nrhs) + + lqr, x, info = gels(a1, b1, lwork=lwork) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + lqr_truth, _, _, _ = geqrf(a1) + assert_array_equal(lqr, lqr_truth) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gels, gels_lwork, geqrf = get_lapack_funcs( + ('gels', 'gels_lwork', 'geqrf'), (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + lwork = _compute_lwork(gels_lwork, m, n, nrhs) + + lqr, x, info = gels(a1, b1, lwork=lwork) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + lqr_truth, _, _, _ = geqrf(a1) + assert_array_equal(lqr, lqr_truth) + + def test_gelsd(self): + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, iwork, info = gelsd_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + iwork_size = iwork + + x, s, rank, info = gelsd(a1, b1, lwork, iwork_size, + -1, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([12.596017180511966, + 0.583396253199685], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, rwork, iwork, info = gelsd_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + rwork_size = int(rwork) + iwork_size = iwork + + x, s, rank, info = gelsd(a1, b1, lwork, rwork_size, iwork_size, + -1, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + assert_allclose(s, + np.array([13.035514762572043, 4.337666985231382], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + + def test_gelss(self): + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelss_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + + v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([12.596017180511966, + 0.583396253199685], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelss_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + + v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([13.035514762572043, + 4.337666985231382], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + def test_gelsy(self): + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps) + lwork = int(np.real(work)) + + jptv = np.zeros((a1.shape[1], 1), dtype=np.int32) + v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps, + lwork, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps) + lwork = int(np.real(work)) + + jptv = np.zeros((a1.shape[1], 1), dtype=np.int32) + v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps, + lwork, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('shape', [(3, 4), (5, 2), (2**18, 2**18)]) +def test_geqrf_lwork(dtype, shape): + geqrf_lwork = get_lapack_funcs(('geqrf_lwork'), dtype=dtype) + m, n = shape + lwork, info = geqrf_lwork(m=m, n=n) + assert_equal(info, 0) + + +class TestRegression: + + def test_ticket_1645(self): + # Check that RQ routines have correct lwork + for dtype in DTYPES: + a = np.zeros((300, 2), dtype=dtype) + + gerqf, = get_lapack_funcs(['gerqf'], [a]) + assert_raises(Exception, gerqf, a, lwork=2) + rq, tau, work, info = gerqf(a) + + if dtype in REAL_DTYPES: + orgrq, = get_lapack_funcs(['orgrq'], [a]) + assert_raises(Exception, orgrq, rq[-2:], tau, lwork=1) + orgrq(rq[-2:], tau, lwork=2) + elif dtype in COMPLEX_DTYPES: + ungrq, = get_lapack_funcs(['ungrq'], [a]) + assert_raises(Exception, ungrq, rq[-2:], tau, lwork=1) + ungrq(rq[-2:], tau, lwork=2) + + +class TestDpotr: + # 'lower' argument of dportf/dpotri + @pytest.mark.parametrize("lower", [True, False]) + @pytest.mark.parametrize("clean", [True, False]) + def test_gh_2691(self, lower, clean): + rng = np.random.default_rng(42) + x = rng.normal(size=(3, 3)) + a = x.dot(x.T) + + dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, )) + + c, _ = dpotrf(a, lower, clean=clean) + dpt = dpotri(c, lower)[0] + + if lower: + assert_allclose(np.tril(dpt), np.tril(inv(a))) + else: + assert_allclose(np.triu(dpt), np.triu(inv(a))) + + +class TestDlasd4: + def test_sing_val_update(self): + + sigmas = np.array([4., 3., 2., 0]) + m_vec = np.array([3.12, 5.7, -4.8, -2.2]) + + M = np.hstack((np.vstack((np.diag(sigmas[0:-1]), + np.zeros((1, len(m_vec) - 1)))), + m_vec[:, np.newaxis])) + SM = svd(M, full_matrices=False, compute_uv=False, overwrite_a=False, + check_finite=False) + + it_len = len(sigmas) + sgm = np.concatenate((sigmas[::-1], [sigmas[0] + it_len*norm(m_vec)])) + mvc = np.concatenate((m_vec[::-1], (0,))) + + lasd4 = get_lapack_funcs('lasd4', (sigmas,)) + + roots = [] + for i in range(0, it_len): + res = lasd4(i, sgm, mvc) + roots.append(res[1]) + + assert_( + (res[3] <= 0), + f"LAPACK root finding dlasd4 failed to find the singular value {i}" + ) + roots = np.array(roots)[::-1] + + assert_((not np.any(np.isnan(roots)), "There are NaN roots")) + assert_allclose(SM, roots, atol=100*np.finfo(np.float64).eps, + rtol=100*np.finfo(np.float64).eps) + + +class TestTbtrs: + + @pytest.mark.parametrize('dtype', DTYPES) + def test_nag_example_f07vef_f07vsf(self, dtype): + """Test real (f07vef) and complex (f07vsf) examples from NAG + + Examples available from: + * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vef.html + * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vsf.html + + """ + if dtype in REAL_DTYPES: + ab = np.array([[-4.16, 4.78, 6.32, 0.16], + [-2.25, 5.86, -4.82, 0]], + dtype=dtype) + b = np.array([[-16.64, -4.16], + [-13.78, -16.59], + [13.10, -4.94], + [-14.14, -9.96]], + dtype=dtype) + x_out = np.array([[4, 1], + [-1, -3], + [3, 2], + [2, -2]], + dtype=dtype) + elif dtype in COMPLEX_DTYPES: + ab = np.array([[-1.94+4.43j, 4.12-4.27j, 0.43-2.66j, 0.44+0.1j], + [-3.39+3.44j, -1.84+5.52j, 1.74 - 0.04j, 0], + [1.62+3.68j, -2.77-1.93j, 0, 0]], + dtype=dtype) + b = np.array([[-8.86 - 3.88j, -24.09 - 5.27j], + [-15.57 - 23.41j, -57.97 + 8.14j], + [-7.63 + 22.78j, 19.09 - 29.51j], + [-14.74 - 2.40j, 19.17 + 21.33j]], + dtype=dtype) + x_out = np.array([[2j, 1 + 5j], + [1 - 3j, -7 - 2j], + [-4.001887 - 4.988417j, 3.026830 + 4.003182j], + [1.996158 - 1.045105j, -6.103357 - 8.986653j]], + dtype=dtype) + else: + raise ValueError(f"Datatype {dtype} not understood.") + + tbtrs = get_lapack_funcs(('tbtrs'), dtype=dtype) + x, info = tbtrs(ab=ab, b=b, uplo='L') + assert_equal(info, 0) + assert_allclose(x, x_out, rtol=0, atol=1e-5) + + @pytest.mark.parametrize('dtype,trans', + [(dtype, trans) + for dtype in DTYPES for trans in ['N', 'T', 'C'] + if not (trans == 'C' and dtype in REAL_DTYPES)]) + @pytest.mark.parametrize('uplo', ['U', 'L']) + @pytest.mark.parametrize('diag', ['N', 'U']) + def test_random_matrices(self, dtype, trans, uplo, diag): + rng = np.random.RandomState(1724) + + # n, nrhs, kd are used to specify A and b. + # A is of shape n x n with kd super/sub-diagonals + # b is of shape n x nrhs matrix + n, nrhs, kd = 4, 3, 2 + tbtrs = get_lapack_funcs('tbtrs', dtype=dtype) + + is_upper = (uplo == 'U') + ku = kd * is_upper + kl = kd - ku + + # Construct the diagonal and kd super/sub diagonals of A with + # the corresponding offsets. + band_offsets = range(ku, -kl - 1, -1) + band_widths = [n - abs(x) for x in band_offsets] + bands = [generate_random_dtype_array((width,), dtype, rng) + for width in band_widths] + + if diag == 'U': # A must be unit triangular + bands[ku] = np.ones(n, dtype=dtype) + + # Construct the diagonal banded matrix A from the bands and offsets. + a = sps.diags(bands, band_offsets, format='dia') + + # Convert A into banded storage form + ab = np.zeros((kd + 1, n), dtype) + for row, k in enumerate(band_offsets): + ab[row, max(k, 0):min(n+k, n)] = a.diagonal(k) + + # The RHS values. + b = generate_random_dtype_array((n, nrhs), dtype, rng) + + x, info = tbtrs(ab=ab, b=b, uplo=uplo, trans=trans, diag=diag) + assert_equal(info, 0) + + if trans == 'N': + assert_allclose(a @ x, b, rtol=5e-5) + elif trans == 'T': + assert_allclose(a.T @ x, b, rtol=5e-5) + elif trans == 'C': + assert_allclose(a.T.conjugate() @ x, b, rtol=5e-5) + else: + raise ValueError('Invalid trans argument') + + @pytest.mark.parametrize('uplo,trans,diag', + [['U', 'N', 'Invalid'], + ['U', 'Invalid', 'N'], + ['Invalid', 'N', 'N']]) + def test_invalid_argument_raises_exception(self, uplo, trans, diag): + """Test if invalid values of uplo, trans and diag raise exceptions""" + # Argument checks occur independently of used datatype. + # This mean we must not parameterize all available datatypes. + tbtrs = get_lapack_funcs('tbtrs', dtype=np.float64) + rng = np.random.default_rng(1234) + ab = rng.random((4, 2)) + b = rng.random((2, 4)) + assert_raises(Exception, tbtrs, ab, b, uplo, trans, diag) + + def test_zero_element_in_diagonal(self): + """Test if a matrix with a zero diagonal element is singular + + If the i-th diagonal of A is zero, ?tbtrs should return `i` in `info` + indicating the provided matrix is singular. + + Note that ?tbtrs requires the matrix A to be stored in banded form. + In this form the diagonal corresponds to the last row.""" + ab = np.ones((3, 4), dtype=float) + b = np.ones(4, dtype=float) + tbtrs = get_lapack_funcs('tbtrs', dtype=float) + + ab[-1, 3] = 0 + _, info = tbtrs(ab=ab, b=b, uplo='U') + assert_equal(info, 4) + + @pytest.mark.parametrize('ldab,n,ldb,nrhs', [ + (5, 5, 0, 5), + (5, 5, 3, 5) + ]) + def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs): + """Test ?tbtrs fails correctly if shapes are invalid.""" + ab = np.ones((ldab, n), dtype=float) + b = np.ones((ldb, nrhs), dtype=float) + tbtrs = get_lapack_funcs('tbtrs', dtype=float) + assert_raises(Exception, tbtrs, ab, b) + + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('norm', ['I', '1', 'O']) +@pytest.mark.parametrize('uplo', ['U', 'L']) +@pytest.mark.parametrize('diag', ['N', 'U']) +@pytest.mark.parametrize('n', [3, 10]) +def test_trcon(dtype, norm, uplo, diag, n): + # Simple way to get deterministic (unlike `hash`) seed based on arguments + seed = list(f"{dtype}{norm}{uplo}{diag}{n}".encode()) + rng = np.random.default_rng(seed) + + A = rng.random(size=(n, n)) + rng.random(size=(n, n))*1j + # make the condition numbers more interesting + offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n)) + A += offset + A = A.real if np.issubdtype(dtype, np.floating) else A + A = np.triu(A) if uplo == 'U' else np.tril(A) + if diag == 'U': + A /= np.diag(A)[:, np.newaxis] + A = A.astype(dtype) + + trcon = get_lapack_funcs('trcon', (A,)) + res, _ = trcon(A, norm=norm, uplo=uplo, diag=diag) + + if norm == 'I': + norm_A = np.linalg.norm(A, ord=np.inf) + norm_inv_A = np.linalg.norm(np.linalg.inv(A), ord=np.inf) + ref = 1 / (norm_A * norm_inv_A) + else: + anorm = np.linalg.norm(A, ord=1) + gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,)) + lu, ipvt, info = getrf(A) + ref, _ = gecon(lu, anorm, norm=norm) + + # This is an estimate of reciprocal condition number; we just need order of + # magnitude. In testing, we observed that much smaller rtol is OK in almost + # all cases... but sometimes it isn't. + rtol = 1 # np.finfo(dtype).eps**0.75 + assert_allclose(res, ref, rtol=rtol) + + +def test_lartg(): + for dtype in 'fdFD': + lartg = get_lapack_funcs('lartg', dtype=dtype) + + f = np.array(3, dtype) + g = np.array(4, dtype) + + if np.iscomplexobj(g): + g *= 1j + + cs, sn, r = lartg(f, g) + + assert_allclose(cs, 3.0/5.0) + assert_allclose(r, 5.0) + + if np.iscomplexobj(g): + assert_allclose(sn, -4.0j/5.0) + assert_(isinstance(r, complex)) + assert_(isinstance(cs, float)) + else: + assert_allclose(sn, 4.0/5.0) + + +def test_rot(): + # srot, drot from blas and crot and zrot from lapack. + + for dtype in 'fdFD': + c = 0.6 + s = 0.8 + + u = np.full(4, 3, dtype) + v = np.full(4, 4, dtype) + atol = 10**-(np.finfo(dtype).precision-1) + + if dtype in 'fd': + rot = get_blas_funcs('rot', dtype=dtype) + f = 4 + else: + rot = get_lapack_funcs('rot', dtype=dtype) + s *= -1j + v *= 1j + f = 4j + + assert_allclose(rot(u, v, c, s), [[5, 5, 5, 5], + [0, 0, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, n=2), [[5, 5, 3, 3], + [0, 0, f, f]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, offy=2), + [[3, 3, 5, 5], [f, f, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, incx=2, offy=2, n=2), + [[5, 3, 5, 3], [f, f, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, incy=2, n=2), + [[3, 3, 5, 5], [0, f, 0, f]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, incx=2, offy=2, incy=2, n=1), + [[3, 3, 5, 3], [f, f, 0, f]], atol=atol) + assert_allclose(rot(u, v, c, s, incx=-2, incy=-2, n=2), + [[5, 3, 5, 3], [0, f, 0, f]], atol=atol) + + a, b = rot(u, v, c, s, overwrite_x=1, overwrite_y=1) + assert_(a is u) + assert_(b is v) + assert_allclose(a, [5, 5, 5, 5], atol=atol) + assert_allclose(b, [0, 0, 0, 0], atol=atol) + + +def test_larfg_larf(): + rng = np.random.default_rng(1234) + a0 = rng.random((4, 4)) + a0 = a0.T.dot(a0) + + a0j = rng.random((4, 4)) + 1j*rng.random((4, 4)) + a0j = a0j.T.conj().dot(a0j) + + # our test here will be to do one step of reducing a hermetian matrix to + # tridiagonal form using householder transforms. + + for dtype in 'fdFD': + larfg, larf = get_lapack_funcs(['larfg', 'larf'], dtype=dtype) + + if dtype in 'FD': + a = a0j.copy() + else: + a = a0.copy() + + # generate a householder transform to clear a[2:,0] + alpha, x, tau = larfg(a.shape[0]-1, a[1, 0], a[2:, 0]) + + # create expected output + expected = np.zeros_like(a[:, 0]) + expected[0] = a[0, 0] + expected[1] = alpha + + # assemble householder vector + v = np.zeros_like(a[1:, 0]) + v[0] = 1.0 + v[1:] = x + + # apply transform from the left + a[1:, :] = larf(v, tau.conjugate(), a[1:, :], np.zeros(a.shape[1])) + + # apply transform from the right + a[:, 1:] = larf(v, tau, a[:, 1:], np.zeros(a.shape[0]), side='R') + + assert_allclose(a[:, 0], expected, atol=1e-5) + assert_allclose(a[0, :], expected, atol=1e-5) + + +def test_sgesdd_lwork_bug_workaround(): + # Test that SGESDD lwork is sufficiently large for LAPACK. + # + # This checks that _compute_lwork() correctly works around a bug in + # LAPACK versions older than 3.10.1. + + sgesdd_lwork = get_lapack_funcs('gesdd_lwork', dtype=np.float32, + ilp64='preferred') + n = 9537 + lwork = _compute_lwork(sgesdd_lwork, n, n, + compute_uv=True, full_matrices=True) + # If we called the Fortran function SGESDD directly with IWORK=-1, the + # LAPACK bug would result in lwork being 272929856, which was too small. + # (The result was returned in a single precision float, which does not + # have sufficient precision to represent the exact integer value that it + # computed internally.) The work-around implemented in _compute_lwork() + # will convert that to 272929888. If we are using LAPACK 3.10.1 or later + # (such as in OpenBLAS 0.3.21 or later), the work-around will return + # 272929920, because it does not know which version of LAPACK is being + # used, so it always applies the correction to whatever it is given. We + # will accept either 272929888 or 272929920. + # Note that the acceptable values are a LAPACK implementation detail. + # If a future version of LAPACK changes how SGESDD works, and therefore + # changes the required LWORK size, the acceptable values might have to + # be updated. + assert lwork == 272929888 or lwork == 272929920 + + +class TestSytrd: + @pytest.mark.parametrize('dtype', REAL_DTYPES) + def test_sytrd_with_zero_dim_array(self, dtype): + # Assert that a 0x0 matrix raises an error + A = np.zeros((0, 0), dtype=dtype) + sytrd = get_lapack_funcs('sytrd', (A,)) + assert_raises(ValueError, sytrd, A) + + @pytest.mark.parametrize('dtype', REAL_DTYPES) + @pytest.mark.parametrize('n', (1, 3)) + def test_sytrd(self, dtype, n): + A = np.zeros((n, n), dtype=dtype) + + sytrd, sytrd_lwork = \ + get_lapack_funcs(('sytrd', 'sytrd_lwork'), (A,)) + + # some upper triangular array + A[np.triu_indices_from(A)] = \ + np.arange(1, n*(n+1)//2+1, dtype=dtype) + + # query lwork + lwork, info = sytrd_lwork(n) + assert_equal(info, 0) + + # check lower=1 behavior (shouldn't do much since the matrix is + # upper triangular) + data, d, e, tau, info = sytrd(A, lower=1, lwork=lwork) + assert_equal(info, 0) + + assert_allclose(data, A, atol=5*np.finfo(dtype).eps, rtol=1.0) + assert_allclose(d, np.diag(A)) + assert_allclose(e, 0.0) + assert_allclose(tau, 0.0) + + # and now for the proper test (lower=0 is the default) + data, d, e, tau, info = sytrd(A, lwork=lwork) + assert_equal(info, 0) + + # assert Q^T*A*Q = tridiag(e, d, e) + + # build tridiagonal matrix + T = np.zeros_like(A, dtype=dtype) + k = np.arange(A.shape[0]) + T[k, k] = d + k2 = np.arange(A.shape[0]-1) + T[k2+1, k2] = e + T[k2, k2+1] = e + + # build Q + Q = np.eye(n, n, dtype=dtype) + for i in range(n-1): + v = np.zeros(n, dtype=dtype) + v[:i] = data[:i, i+1] + v[i] = 1.0 + H = np.eye(n, n, dtype=dtype) - tau[i] * np.outer(v, v) + Q = np.dot(H, Q) + + # Make matrix fully symmetric + i_lower = np.tril_indices(n, -1) + A[i_lower] = A.T[i_lower] + + QTAQ = np.dot(Q.T, np.dot(A, Q)) + + # disable rtol here since some values in QTAQ and T are very close + # to 0. + assert_allclose(QTAQ, T, atol=5*np.finfo(dtype).eps, rtol=1.0) + + +class TestHetrd: + @pytest.mark.parametrize('complex_dtype', COMPLEX_DTYPES) + def test_hetrd_with_zero_dim_array(self, complex_dtype): + # Assert that a 0x0 matrix raises an error + A = np.zeros((0, 0), dtype=complex_dtype) + hetrd = get_lapack_funcs('hetrd', (A,)) + assert_raises(ValueError, hetrd, A) + + @pytest.mark.parametrize('real_dtype,complex_dtype', + zip(REAL_DTYPES, COMPLEX_DTYPES)) + @pytest.mark.parametrize('n', (1, 3)) + def test_hetrd(self, n, real_dtype, complex_dtype): + A = np.zeros((n, n), dtype=complex_dtype) + hetrd, hetrd_lwork = \ + get_lapack_funcs(('hetrd', 'hetrd_lwork'), (A,)) + + # some upper triangular array + A[np.triu_indices_from(A)] = ( + np.arange(1, n*(n+1)//2+1, dtype=real_dtype) + + 1j * np.arange(1, n*(n+1)//2+1, dtype=real_dtype) + ) + np.fill_diagonal(A, np.real(np.diag(A))) + + # test query lwork + for x in [0, 1]: + _, info = hetrd_lwork(n, lower=x) + assert_equal(info, 0) + # lwork returns complex which segfaults hetrd call (gh-10388) + # use the safe and recommended option + lwork = _compute_lwork(hetrd_lwork, n) + + # check lower=1 behavior (shouldn't do much since the matrix is + # upper triangular) + data, d, e, tau, info = hetrd(A, lower=1, lwork=lwork) + assert_equal(info, 0) + + assert_allclose(data, A, atol=5*np.finfo(real_dtype).eps, rtol=1.0) + + assert_allclose(d, np.real(np.diag(A))) + assert_allclose(e, 0.0) + assert_allclose(tau, 0.0) + + # and now for the proper test (lower=0 is the default) + data, d, e, tau, info = hetrd(A, lwork=lwork) + assert_equal(info, 0) + + # assert Q^T*A*Q = tridiag(e, d, e) + + # build tridiagonal matrix + T = np.zeros_like(A, dtype=real_dtype) + k = np.arange(A.shape[0], dtype=int) + T[k, k] = d + k2 = np.arange(A.shape[0]-1, dtype=int) + T[k2+1, k2] = e + T[k2, k2+1] = e + + # build Q + Q = np.eye(n, n, dtype=complex_dtype) + for i in range(n-1): + v = np.zeros(n, dtype=complex_dtype) + v[:i] = data[:i, i+1] + v[i] = 1.0 + H = np.eye(n, n, dtype=complex_dtype) \ + - tau[i] * np.outer(v, np.conj(v)) + Q = np.dot(H, Q) + + # Make matrix fully Hermitian + i_lower = np.tril_indices(n, -1) + A[i_lower] = np.conj(A.T[i_lower]) + + QHAQ = np.dot(np.conj(Q.T), np.dot(A, Q)) + + # disable rtol here since some values in QTAQ and T are very close + # to 0. + assert_allclose( + QHAQ, T, atol=10*np.finfo(real_dtype).eps, rtol=1.0 + ) + + +def test_gglse(): + # Example data taken from NAG manual + for ind, dtype in enumerate(DTYPES): + # DTYPES = gglse + func, func_lwork = get_lapack_funcs(('gglse', 'gglse_lwork'), + dtype=dtype) + lwork = _compute_lwork(func_lwork, m=6, n=4, p=2) + # For gglse + if ind < 2: + a = np.array([[-0.57, -1.28, -0.39, 0.25], + [-1.93, 1.08, -0.31, -2.14], + [2.30, 0.24, 0.40, -0.35], + [-1.93, 0.64, -0.66, 0.08], + [0.15, 0.30, 0.15, -2.13], + [-0.02, 1.03, -1.43, 0.50]], dtype=dtype) + c = np.array([-1.50, -2.14, 1.23, -0.54, -1.68, 0.82], dtype=dtype) + d = np.array([0., 0.], dtype=dtype) + # For gglse + else: + a = np.array([[0.96-0.81j, -0.03+0.96j, -0.91+2.06j, -0.05+0.41j], + [-0.98+1.98j, -1.20+0.19j, -0.66+0.42j, -0.81+0.56j], + [0.62-0.46j, 1.01+0.02j, 0.63-0.17j, -1.11+0.60j], + [0.37+0.38j, 0.19-0.54j, -0.98-0.36j, 0.22-0.20j], + [0.83+0.51j, 0.20+0.01j, -0.17-0.46j, 1.47+1.59j], + [1.08-0.28j, 0.20-0.12j, -0.07+1.23j, 0.26+0.26j]]) + c = np.array([[-2.54+0.09j], + [1.65-2.26j], + [-2.11-3.96j], + [1.82+3.30j], + [-6.41+3.77j], + [2.07+0.66j]]) + d = np.zeros(2, dtype=dtype) + + b = np.array([[1., 0., -1., 0.], [0., 1., 0., -1.]], dtype=dtype) + + _, _, _, result, _ = func(a, b, c, d, lwork=lwork) + if ind < 2: + expected = np.array([0.48904455, + 0.99754786, + 0.48904455, + 0.99754786]) + else: + expected = np.array([1.08742917-1.96205783j, + -0.74093902+3.72973919j, + 1.08742917-1.96205759j, + -0.74093896+3.72973895j]) + assert_array_almost_equal(result, expected, decimal=4) + + +def test_sycon_hecon(): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): + # DTYPES + COMPLEX DTYPES = sycon + hecon + n = 10 + # For sycon + if ind < 4: + func_lwork = get_lapack_funcs('sytrf_lwork', dtype=dtype) + funcon, functrf = get_lapack_funcs(('sycon', 'sytrf'), dtype=dtype) + A = (rng.random((n, n))).astype(dtype) + # For hecon + else: + func_lwork = get_lapack_funcs('hetrf_lwork', dtype=dtype) + funcon, functrf = get_lapack_funcs(('hecon', 'hetrf'), dtype=dtype) + A = (rng.random((n, n)) + rng.random((n, n))*1j).astype(dtype) + + # Since sycon only refers to upper/lower part, conj() is safe here. + A = (A + A.conj().T)/2 + 2*np.eye(n, dtype=dtype) + + anorm = norm(A, 1) + lwork = _compute_lwork(func_lwork, n) + ldu, ipiv, _ = functrf(A, lwork=lwork, lower=1) + rcond, _ = funcon(a=ldu, ipiv=ipiv, anorm=anorm, lower=1) + # The error is at most 1-fold + assert_(abs(1/rcond - np.linalg.cond(A, p=1))*rcond < 1) + + +def test_sygst(): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(REAL_DTYPES): + # DTYPES = sygst + n = 10 + + potrf, sygst, syevd, sygvd = get_lapack_funcs(('potrf', 'sygst', + 'syevd', 'sygvd'), + dtype=dtype) + + A = rng.random((n, n)).astype(dtype) + A = (A + A.T)/2 + # B must be positive definite + B = rng.random((n, n)).astype(dtype) + B = (B + B.T)/2 + 2 * np.eye(n, dtype=dtype) + + # Perform eig (sygvd) + eig_gvd, _, info = sygvd(A, B) + assert_(info == 0) + + # Convert to std problem potrf + b, info = potrf(B) + assert_(info == 0) + a, info = sygst(A, b) + assert_(info == 0) + + eig, _, info = syevd(a) + assert_(info == 0) + assert_allclose(eig, eig_gvd, rtol=1.2e-4) + + +def test_hegst(): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(COMPLEX_DTYPES): + # DTYPES = hegst + n = 10 + + potrf, hegst, heevd, hegvd = get_lapack_funcs(('potrf', 'hegst', + 'heevd', 'hegvd'), + dtype=dtype) + + A = rng.random((n, n)).astype(dtype) + 1j * rng.random((n, n)).astype(dtype) + A = (A + A.conj().T)/2 + # B must be positive definite + B = rng.random((n, n)).astype(dtype) + 1j * rng.random((n, n)).astype(dtype) + B = (B + B.conj().T)/2 + 2 * np.eye(n, dtype=dtype) + + # Perform eig (hegvd) + eig_gvd, _, info = hegvd(A, B) + assert_(info == 0) + + # Convert to std problem potrf + b, info = potrf(B) + assert_(info == 0) + a, info = hegst(A, b) + assert_(info == 0) + + eig, _, info = heevd(a) + assert_(info == 0) + assert_allclose(eig, eig_gvd, rtol=1e-4) + + +def test_tzrzf(): + """ + This test performs an RZ decomposition in which an m x n upper trapezoidal + array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular + and Z is unitary. + """ + rng = np.random.RandomState(1234) + m, n = 10, 15 + for ind, dtype in enumerate(DTYPES): + tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'), + dtype=dtype) + lwork = _compute_lwork(tzrzf_lw, m, n) + + if ind < 2: + A = triu(rng.rand(m, n).astype(dtype)) + else: + A = triu((rng.rand(m, n) + rng.rand(m, n)*1j).astype(dtype)) + + # assert wrong shape arg, f2py returns generic error + assert_raises(Exception, tzrzf, A.T) + rz, tau, info = tzrzf(A, lwork=lwork) + # Check success + assert_(info == 0) + + # Get Z manually for comparison + R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype))) + V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:])) + Id = np.eye(n, dtype=dtype) + ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)] + Z = reduce(np.dot, ref) + assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype), + atol=10*np.spacing(dtype(1.0).real), rtol=0.) + + +def test_tfsm(): + """ + Test for solving a linear system with the coefficient matrix is a + triangular array stored in Full Packed (RFP) format. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = triu(rng.rand(n, n) + rng.rand(n, n)*1j + eye(n)).astype(dtype) + trans = 'C' + else: + A = triu(rng.rand(n, n) + eye(n)).astype(dtype) + trans = 'T' + + trttf, tfttr, tfsm = get_lapack_funcs(('trttf', 'tfttr', 'tfsm'), + dtype=dtype) + + Afp, _ = trttf(A) + B = rng.rand(n, 2).astype(dtype) + soln = tfsm(-1, Afp, B) + assert_array_almost_equal(soln, solve(-A, B), + decimal=4 if ind % 2 == 0 else 6) + + soln = tfsm(-1, Afp, B, trans=trans) + assert_array_almost_equal(soln, solve(-A.conj().T, B), + decimal=4 if ind % 2 == 0 else 6) + + # Make A, unit diagonal + A[np.arange(n), np.arange(n)] = dtype(1.) + soln = tfsm(-1, Afp, B, trans=trans, diag='U') + assert_array_almost_equal(soln, solve(-A.conj().T, B), + decimal=4 if ind % 2 == 0 else 6) + + # Change side + B2 = rng.rand(3, n).astype(dtype) + soln = tfsm(-1, Afp, B2, trans=trans, diag='U', side='R') + assert_array_almost_equal(soln, solve(-A, B2.T).conj().T, + decimal=4 if ind % 2 == 0 else 6) + + +def test_ormrz_unmrz(): + """ + This test performs a matrix multiplication with an arbitrary m x n matrix C + and a unitary matrix Q without explicitly forming the array. The array data + is encoded in the rectangular part of A which is obtained from ?TZRZF. Q + size is inferred by m, n, side keywords. + """ + rng = np.random.RandomState(1234) + qm, qn, cn = 10, 15, 15 + for ind, dtype in enumerate(DTYPES): + tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'), + dtype=dtype) + lwork_rz = _compute_lwork(tzrzf_lw, qm, qn) + + if ind < 2: + A = triu(rng.random((qm, qn)).astype(dtype)) + C = rng.random((cn, cn)).astype(dtype) + orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'), + dtype=dtype) + else: + A = triu((rng.random((qm, qn)) + rng.random((qm, qn))*1j).astype(dtype)) + C = (rng.random((cn, cn)) + rng.random((cn, cn))*1j).astype(dtype) + orun_mrz, orun_mrz_lw = get_lapack_funcs(('unmrz', 'unmrz_lwork'), + dtype=dtype) + + lwork_mrz = _compute_lwork(orun_mrz_lw, cn, cn) + rz, tau, info = tzrzf(A, lwork=lwork_rz) + + # Get Q manually for comparison + V = np.hstack((np.eye(qm, dtype=dtype), rz[:, qm:])) + Id = np.eye(qn, dtype=dtype) + ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(qm)] + Q = reduce(np.dot, ref) + + # Now that we have Q, we can test whether lapack results agree with + # each case of CQ, CQ^H, QC, and QC^H + trans = 'T' if ind < 2 else 'C' + tol = 10*np.spacing(dtype(1.0).real) + + cq, info = orun_mrz(rz, tau, C, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - Q.dot(C), zeros_like(C), atol=tol, rtol=0.) + + cq, info = orun_mrz(rz, tau, C, trans=trans, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - Q.conj().T.dot(C), zeros_like(C), atol=tol, + rtol=0.) + + cq, info = orun_mrz(rz, tau, C, side='R', lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - C.dot(Q), zeros_like(C), atol=tol, rtol=0.) + + cq, info = orun_mrz(rz, tau, C, side='R', trans=trans, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - C.dot(Q.conj().T), zeros_like(C), atol=tol, + rtol=0.) + + +def test_tfttr_trttf(): + """ + Test conversion routines between the Rectangular Full Packed (RFP) format + and Standard Triangular Array (TR) + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transr = 'C' + else: + A_full = (rng.rand(n, n)).astype(dtype) + transr = 'T' + + trttf, tfttr = get_lapack_funcs(('trttf', 'tfttr'), dtype=dtype) + A_tf_U, info = trttf(A_full) + assert_(info == 0) + A_tf_L, info = trttf(A_full, uplo='L') + assert_(info == 0) + A_tf_U_T, info = trttf(A_full, transr=transr, uplo='U') + assert_(info == 0) + A_tf_L_T, info = trttf(A_full, transr=transr, uplo='L') + assert_(info == 0) + + # Create the RFP array manually (n is even!) + A_tf_U_m = zeros((n+1, n//2), dtype=dtype) + A_tf_U_m[:-1, :] = triu(A_full)[:, n//2:] + A_tf_U_m[n//2+1:, :] += triu(A_full)[:n//2, :n//2].conj().T + + A_tf_L_m = zeros((n+1, n//2), dtype=dtype) + A_tf_L_m[1:, :] = tril(A_full)[:, :n//2] + A_tf_L_m[:n//2, :] += tril(A_full)[n//2:, n//2:].conj().T + + assert_array_almost_equal(A_tf_U, A_tf_U_m.reshape(-1, order='F')) + assert_array_almost_equal(A_tf_U_T, + A_tf_U_m.conj().T.reshape(-1, order='F')) + + assert_array_almost_equal(A_tf_L, A_tf_L_m.reshape(-1, order='F')) + assert_array_almost_equal(A_tf_L_T, + A_tf_L_m.conj().T.reshape(-1, order='F')) + + # Get the original array from RFP + A_tr_U, info = tfttr(n, A_tf_U) + assert_(info == 0) + A_tr_L, info = tfttr(n, A_tf_L, uplo='L') + assert_(info == 0) + A_tr_U_T, info = tfttr(n, A_tf_U_T, transr=transr, uplo='U') + assert_(info == 0) + A_tr_L_T, info = tfttr(n, A_tf_L_T, transr=transr, uplo='L') + assert_(info == 0) + + assert_array_almost_equal(A_tr_U, triu(A_full)) + assert_array_almost_equal(A_tr_U_T, triu(A_full)) + assert_array_almost_equal(A_tr_L, tril(A_full)) + assert_array_almost_equal(A_tr_L_T, tril(A_full)) + + +def test_tpttr_trttp(): + """ + Test conversion routines between the Rectangular Full Packed (RFP) format + and Standard Triangular Array (TR) + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A_full = (rng.rand(n, n)).astype(dtype) + + trttp, tpttr = get_lapack_funcs(('trttp', 'tpttr'), dtype=dtype) + A_tp_U, info = trttp(A_full) + assert_(info == 0) + A_tp_L, info = trttp(A_full, uplo='L') + assert_(info == 0) + + # Create the TP array manually + inds = tril_indices(n) + A_tp_U_m = zeros(n*(n+1)//2, dtype=dtype) + A_tp_U_m[:] = (triu(A_full).T)[inds] + + inds = triu_indices(n) + A_tp_L_m = zeros(n*(n+1)//2, dtype=dtype) + A_tp_L_m[:] = (tril(A_full).T)[inds] + + assert_array_almost_equal(A_tp_U, A_tp_U_m) + assert_array_almost_equal(A_tp_L, A_tp_L_m) + + # Get the original array from TP + A_tr_U, info = tpttr(n, A_tp_U) + assert_(info == 0) + A_tr_L, info = tpttr(n, A_tp_L, uplo='L') + assert_(info == 0) + + assert_array_almost_equal(A_tr_U, triu(A_full)) + assert_array_almost_equal(A_tr_L, tril(A_full)) + + +def test_pftrf(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + pftrf, trttf, tfttr = get_lapack_funcs(('pftrf', 'trttf', 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + Achol_rfp, info = pftrf(n, Afp) + assert_(info == 0) + A_chol_r, _ = tfttr(n, Achol_rfp) + Achol = cholesky(A) + assert_array_almost_equal(A_chol_r, Achol) + + +def test_pftri(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array to find its inverse + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + pftri, pftrf, trttf, tfttr = get_lapack_funcs(('pftri', + 'pftrf', + 'trttf', + 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + A_chol_rfp, info = pftrf(n, Afp) + A_inv_rfp, info = pftri(n, A_chol_rfp) + assert_(info == 0) + A_inv_r, _ = tfttr(n, A_inv_rfp) + Ainv = inv(A) + assert_array_almost_equal(A_inv_r, triu(Ainv), + decimal=4 if ind % 2 == 0 else 6) + + +def test_pftrs(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array and solve a linear system + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + B = ones((n, 3), dtype=dtype) + Bf1 = ones((n+2, 3), dtype=dtype) + Bf2 = ones((n-2, 3), dtype=dtype) + pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs', + 'pftrf', + 'trttf', + 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + A_chol_rfp, info = pftrf(n, Afp) + # larger B arrays shouldn't segfault + soln, info = pftrs(n, A_chol_rfp, Bf1) + assert_(info == 0) + assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2) + soln, info = pftrs(n, A_chol_rfp, B) + assert_(info == 0) + assert_array_almost_equal(solve(A, B), soln, + decimal=4 if ind % 2 == 0 else 6) + + +def test_sfrk_hfrk(): + """ + Test for performing a symmetric rank-k operation for matrix in RFP format. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + prefix = 's'if ind < 2 else 'h' + trttf, tfttr, shfrk = get_lapack_funcs(('trttf', 'tfttr', f'{prefix}frk'), + dtype=dtype) + + Afp, _ = trttf(A) + C = rng.rand(n, 2).astype(dtype) + Afp_out = shfrk(n, 2, -1, C, 2, Afp) + A_out, _ = tfttr(n, Afp_out) + assert_array_almost_equal(A_out, triu(-C.dot(C.conj().T) + 2*A), + decimal=4 if ind % 2 == 0 else 6) + + +def test_syconv(): + """ + Test for going back and forth between the returned format of he/sytrf to + L and D factors/permutations. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 10 + + if ind > 1: + A = (rng.randint(-30, 30, (n, n)) + + rng.randint(-30, 30, (n, n))*1j).astype(dtype) + + A = A + A.conj().T + else: + A = rng.randint(-30, 30, (n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + tol = 100*np.spacing(dtype(1.0).real) + syconv, trf, trf_lwork = get_lapack_funcs(('syconv', 'sytrf', + 'sytrf_lwork'), dtype=dtype) + lw = _compute_lwork(trf_lwork, n, lower=1) + L, D, perm = ldl(A, lower=1, hermitian=False) + lw = _compute_lwork(trf_lwork, n, lower=1) + ldu, ipiv, info = trf(A, lower=1, lwork=lw) + a, e, info = syconv(ldu, ipiv, lower=1) + assert_allclose(tril(a, -1,), tril(L[perm, :], -1), atol=tol, rtol=0.) + + # Test also upper + U, D, perm = ldl(A, lower=0, hermitian=False) + ldu, ipiv, info = trf(A, lower=0) + a, e, info = syconv(ldu, ipiv, lower=0) + assert_allclose(triu(a, 1), triu(U[perm, :], 1), atol=tol, rtol=0.) + + +class TestBlockedQR: + """ + Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt + and tpmqr. + """ + + def test_geqrt_gemqrt(self): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A = (rng.rand(n, n)).astype(dtype) + + tol = 100*np.spacing(dtype(1.0).real) + geqrt, gemqrt = get_lapack_funcs(('geqrt', 'gemqrt'), dtype=dtype) + + a, t, info = geqrt(n, A) + assert info == 0 + + # Extract elementary reflectors from lower triangle, adding the + # main diagonal of ones. + v = np.tril(a, -1) + np.eye(n, dtype=dtype) + # Generate the block Householder transform I - VTV^H + Q = np.eye(n, dtype=dtype) - v @ t @ v.T.conj() + R = np.triu(a) + + # Test columns of Q are orthogonal + assert_allclose(Q.T.conj() @ Q, np.eye(n, dtype=dtype), atol=tol, + rtol=0.) + assert_allclose(Q @ R, A, atol=tol, rtol=0.) + + if ind > 1: + C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transpose = 'C' + else: + C = (rng.rand(n, n)).astype(dtype) + transpose = 'T' + + for side in ('L', 'R'): + for trans in ('N', transpose): + c, info = gemqrt(a, t, C, side=side, trans=trans) + assert info == 0 + + if trans == transpose: + q = Q.T.conj() + else: + q = Q + + if side == 'L': + qC = q @ C + else: + qC = C @ q + + assert_allclose(c, qC, atol=tol, rtol=0.) + + # Test default arguments + if (side, trans) == ('L', 'N'): + c_default, info = gemqrt(a, t, C) + assert info == 0 + assert_equal(c_default, c) + + # Test invalid side/trans + assert_raises(Exception, gemqrt, a, t, C, side='A') + assert_raises(Exception, gemqrt, a, t, C, trans='A') + + def test_tpqrt_tpmqrt(self): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + B = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A = (rng.rand(n, n)).astype(dtype) + B = (rng.rand(n, n)).astype(dtype) + + tol = 100*np.spacing(dtype(1.0).real) + tpqrt, tpmqrt = get_lapack_funcs(('tpqrt', 'tpmqrt'), dtype=dtype) + + # Test for the range of pentagonal B, from square to upper + # triangular + for l in (0, n // 2, n): + a, b, t, info = tpqrt(l, n, A, B) + assert info == 0 + + # Check that lower triangular part of A has not been modified + assert_equal(np.tril(a, -1), np.tril(A, -1)) + # Check that elements not part of the pentagonal portion of B + # have not been modified. + assert_equal(np.tril(b, l - n - 1), np.tril(B, l - n - 1)) + + # Extract pentagonal portion of B + B_pent, b_pent = np.triu(B, l - n), np.triu(b, l - n) + + # Generate elementary reflectors + v = np.concatenate((np.eye(n, dtype=dtype), b_pent)) + # Generate the block Householder transform I - VTV^H + Q = np.eye(2 * n, dtype=dtype) - v @ t @ v.T.conj() + R = np.concatenate((np.triu(a), np.zeros_like(a))) + + # Test columns of Q are orthogonal + assert_allclose(Q.T.conj() @ Q, np.eye(2 * n, dtype=dtype), + atol=tol, rtol=0.) + assert_allclose(Q @ R, np.concatenate((np.triu(A), B_pent)), + atol=tol, rtol=0.) + + if ind > 1: + C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + D = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transpose = 'C' + else: + C = (rng.rand(n, n)).astype(dtype) + D = (rng.rand(n, n)).astype(dtype) + transpose = 'T' + + for side in ('L', 'R'): + for trans in ('N', transpose): + c, d, info = tpmqrt(l, b, t, C, D, side=side, + trans=trans) + assert info == 0 + + if trans == transpose: + q = Q.T.conj() + else: + q = Q + + if side == 'L': + cd = np.concatenate((c, d), axis=0) + CD = np.concatenate((C, D), axis=0) + qCD = q @ CD + else: + cd = np.concatenate((c, d), axis=1) + CD = np.concatenate((C, D), axis=1) + qCD = CD @ q + + assert_allclose(cd, qCD, atol=tol, rtol=0.) + + if (side, trans) == ('L', 'N'): + c_default, d_default, info = tpmqrt(l, b, t, C, D) + assert info == 0 + assert_equal(c_default, c) + assert_equal(d_default, d) + + # Test invalid side/trans + assert_raises(Exception, tpmqrt, l, b, t, C, D, side='A') + assert_raises(Exception, tpmqrt, l, b, t, C, D, trans='A') + + +def test_pstrf(): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + # DTYPES = pstrf + n = 10 + r = 2 + pstrf = get_lapack_funcs('pstrf', dtype=dtype) + + # Create positive semidefinite A + if ind > 1: + A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype) + A = A @ A.conj().T + else: + A = rng.rand(n, n-r).astype(dtype) + A = A @ A.T + + c, piv, r_c, info = pstrf(A) + U = triu(c) + U[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # python-dbg 3.5.2 runs cause trouble with the following assertion. + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol) + + c, piv, r_c, info = pstrf(A, lower=1) + L = tril(c) + L[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol) + + +def test_pstf2(): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + # DTYPES = pstf2 + n = 10 + r = 2 + pstf2 = get_lapack_funcs('pstf2', dtype=dtype) + + # Create positive semidefinite A + if ind > 1: + A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype) + A = A @ A.conj().T + else: + A = rng.rand(n, n-r).astype(dtype) + A = A @ A.T + + c, piv, r_c, info = pstf2(A) + U = triu(c) + U[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # python-dbg 3.5.2 runs cause trouble with the commented assertions. + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol) + + c, piv, r_c, info = pstf2(A, lower=1) + L = tril(c) + L[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol) + + +def test_geequ(): + desired_real = np.array([[0.6250, 1.0000, 0.0393, -0.4269], + [1.0000, -0.5619, -1.0000, -1.0000], + [0.5874, -1.0000, -0.0596, -0.5341], + [-1.0000, -0.5946, -0.0294, 0.9957]]) + + desired_cplx = np.array([[-0.2816+0.5359*1j, + 0.0812+0.9188*1j, + -0.7439-0.2561*1j], + [-0.3562-0.2954*1j, + 0.9566-0.0434*1j, + -0.0174+0.1555*1j], + [0.8607+0.1393*1j, + -0.2759+0.7241*1j, + -0.1642-0.1365*1j]]) + + for ind, dtype in enumerate(DTYPES): + if ind < 2: + # Use examples from the NAG documentation + A = np.array([[1.80e+10, 2.88e+10, 2.05e+00, -8.90e+09], + [5.25e+00, -2.95e+00, -9.50e-09, -3.80e+00], + [1.58e+00, -2.69e+00, -2.90e-10, -1.04e+00], + [-1.11e+00, -6.60e-01, -5.90e-11, 8.00e-01]]) + A = A.astype(dtype) + else: + A = np.array([[-1.34e+00, 0.28e+10, -6.39e+00], + [-1.70e+00, 3.31e+10, -0.15e+00], + [2.41e-10, -0.56e+00, -0.83e-10]], dtype=dtype) + A += np.array([[2.55e+00, 3.17e+10, -2.20e+00], + [-1.41e+00, -0.15e+10, 1.34e+00], + [0.39e-10, 1.47e+00, -0.69e-10]])*1j + + A = A.astype(dtype) + + geequ = get_lapack_funcs('geequ', dtype=dtype) + r, c, rowcnd, colcnd, amax, info = geequ(A) + + if ind < 2: + assert_allclose(desired_real.astype(dtype), r[:, None]*A*c, + rtol=0, atol=1e-4) + else: + assert_allclose(desired_cplx.astype(dtype), r[:, None]*A*c, + rtol=0, atol=1e-4) + + +def test_syequb(): + desired_log2s = np.array([0, 0, 0, 0, 0, 0, -1, -1, -2, -3]) + + for ind, dtype in enumerate(DTYPES): + A = np.eye(10, dtype=dtype) + alpha = dtype(1. if ind < 2 else 1.j) + d = np.array([alpha * 2.**x for x in range(-5, 5)], dtype=dtype) + A += np.rot90(np.diag(d)) + + syequb = get_lapack_funcs('syequb', dtype=dtype) + s, scond, amax, info = syequb(A) + + assert_equal(np.log2(s).astype(int), desired_log2s) + + +@pytest.mark.skipif(True, + reason="Failing on some OpenBLAS version, see gh-12276") +def test_heequb(): + # zheequb has a bug for versions =< LAPACK 3.9.0 + # See Reference-LAPACK gh-61 and gh-408 + # Hence the zheequb test is customized accordingly to avoid + # work scaling. + A = np.diag([2]*5 + [1002]*5) + np.diag(np.ones(9), k=1)*1j + s, scond, amax, info = lapack.zheequb(A) + assert_equal(info, 0) + assert_allclose(np.log2(s), [0., -1.]*2 + [0.] + [-4]*5) + + A = np.diag(2**np.abs(np.arange(-5, 6)) + 0j) + A[5, 5] = 1024 + A[5, 0] = 16j + s, scond, amax, info = lapack.cheequb(A.astype(np.complex64), lower=1) + assert_equal(info, 0) + assert_allclose(np.log2(s), [-2, -1, -1, 0, 0, -5, 0, -1, -1, -2, -2]) + + +def test_getc2_gesc2(): + rng = np.random.RandomState(42) + n = 10 + desired_real = rng.rand(n) + desired_cplx = rng.rand(n) + rng.rand(n)*1j + + for ind, dtype in enumerate(DTYPES): + if ind < 2: + A = rng.rand(n, n) + A = A.astype(dtype) + b = A @ desired_real + b = b.astype(dtype) + else: + A = rng.rand(n, n) + rng.rand(n, n)*1j + A = A.astype(dtype) + b = A @ desired_cplx + b = b.astype(dtype) + + getc2 = get_lapack_funcs('getc2', dtype=dtype) + gesc2 = get_lapack_funcs('gesc2', dtype=dtype) + lu, ipiv, jpiv, info = getc2(A, overwrite_a=0) + x, scale = gesc2(lu, b, ipiv, jpiv, overwrite_rhs=0) + + if ind < 2: + assert_array_almost_equal(desired_real.astype(dtype), + x/scale, decimal=4) + else: + assert_array_almost_equal(desired_cplx.astype(dtype), + x/scale, decimal=4) + + +@pytest.mark.parametrize('size', [(6, 5), (5, 5)]) +@pytest.mark.parametrize('dtype', REAL_DTYPES) +@pytest.mark.parametrize('joba', range(6)) # 'C', 'E', 'F', 'G', 'A', 'R' +@pytest.mark.parametrize('jobu', range(4)) # 'U', 'F', 'W', 'N' +@pytest.mark.parametrize('jobv', range(4)) # 'V', 'J', 'W', 'N' +@pytest.mark.parametrize('jobr', [0, 1]) +@pytest.mark.parametrize('jobp', [0, 1]) +def test_gejsv_general(size, dtype, joba, jobu, jobv, jobr, jobp, jobt=0): + """Test the lapack routine ?gejsv. + + This function tests that a singular value decomposition can be performed + on the random M-by-N matrix A. The test performs the SVD using ?gejsv + then performs the following checks: + + * ?gejsv exist successfully (info == 0) + * The returned singular values are correct + * `A` can be reconstructed from `u`, `SIGMA`, `v` + * Ensure that u.T @ u is the identity matrix + * Ensure that v.T @ v is the identity matrix + * The reported matrix rank + * The reported number of singular values + * If denormalized floats are required + + Notes + ----- + joba specifies several choices effecting the calculation's accuracy + Although all arguments are tested, the tests only check that the correct + solution is returned - NOT that the prescribed actions are performed + internally. + + jobt is, as of v3.9.0, still experimental and removed to cut down number of + test cases. However keyword itself is tested externally. + """ + rng = np.random.RandomState(42) + + # Define some constants for later use: + m, n = size + atol = 100 * np.finfo(dtype).eps + A = generate_random_dtype_array(size, dtype, rng) + gejsv = get_lapack_funcs('gejsv', dtype=dtype) + + # Set up checks for invalid job? combinations + # if an invalid combination occurs we set the appropriate + # exit status. + lsvec = jobu < 2 # Calculate left singular vectors + rsvec = jobv < 2 # Calculate right singular vectors + l2tran = (jobt == 1) and (m == n) + is_complex = np.iscomplexobj(A) + + invalid_real_jobv = (jobv == 1) and (not lsvec) and (not is_complex) + invalid_cplx_jobu = (jobu == 2) and not (rsvec and l2tran) and is_complex + invalid_cplx_jobv = (jobv == 2) and not (lsvec and l2tran) and is_complex + + # Set the exit status to the expected value. + # Here we only check for invalid combinations, not individual + # parameters. + if invalid_cplx_jobu: + exit_status = -2 + elif invalid_real_jobv or invalid_cplx_jobv: + exit_status = -3 + else: + exit_status = 0 + + if (jobu > 1) and (jobv == 1): + assert_raises(Exception, gejsv, A, joba, jobu, jobv, jobr, jobt, jobp) + else: + sva, u, v, work, iwork, info = gejsv(A, + joba=joba, + jobu=jobu, + jobv=jobv, + jobr=jobr, + jobt=jobt, + jobp=jobp) + + # Check that ?gejsv exited successfully/as expected + assert_equal(info, exit_status) + + # If exit_status is non-zero the combination of jobs is invalid. + # We test this above but no calculations are performed. + if not exit_status: + + # Check the returned singular values + sigma = (work[0] / work[1]) * sva[:n] + assert_allclose(sigma, svd(A, compute_uv=False), atol=atol) + + if jobu == 1: + # If JOBU = 'F', then u contains the M-by-M matrix of + # the left singular vectors, including an ONB of the orthogonal + # complement of the Range(A) + # However, to recalculate A we are concerned about the + # first n singular values and so can ignore the latter. + # TODO: Add a test for ONB? + u = u[:, :n] + + if lsvec and rsvec: + assert_allclose(u @ np.diag(sigma) @ v.conj().T, A, atol=atol) + if lsvec: + assert_allclose(u.conj().T @ u, np.identity(n), atol=atol) + if rsvec: + assert_allclose(v.conj().T @ v, np.identity(n), atol=atol) + + assert_equal(iwork[0], np.linalg.matrix_rank(A)) + assert_equal(iwork[1], np.count_nonzero(sigma)) + # iwork[2] is non-zero if requested accuracy is not warranted for + # the data. This should never occur for these tests. + assert_equal(iwork[2], 0) + + +@pytest.mark.parametrize('dtype', REAL_DTYPES) +def test_gejsv_edge_arguments(dtype): + """Test edge arguments return expected status""" + gejsv = get_lapack_funcs('gejsv', dtype=dtype) + + # scalar A + sva, u, v, work, iwork, info = gejsv(1.) + assert_equal(info, 0) + assert_equal(u.shape, (1, 1)) + assert_equal(v.shape, (1, 1)) + assert_equal(sva, np.array([1.], dtype=dtype)) + + # 1d A + A = np.ones((1,), dtype=dtype) + sva, u, v, work, iwork, info = gejsv(A) + assert_equal(info, 0) + assert_equal(u.shape, (1, 1)) + assert_equal(v.shape, (1, 1)) + assert_equal(sva, np.array([1.], dtype=dtype)) + + # 2d empty A + A = np.ones((1, 0), dtype=dtype) + sva, u, v, work, iwork, info = gejsv(A) + assert_equal(info, 0) + assert_equal(u.shape, (1, 0)) + assert_equal(v.shape, (1, 0)) + assert_equal(sva, np.array([], dtype=dtype)) + + # make sure "overwrite_a" is respected - user reported in gh-13191 + A = np.sin(np.arange(100).reshape(10, 10)).astype(dtype) + A = np.asfortranarray(A + A.T) # make it symmetric and column major + Ac = A.copy('A') + _ = gejsv(A) + assert_allclose(A, Ac) + + +@pytest.mark.parametrize(('kwargs'), + ({'joba': 9}, + {'jobu': 9}, + {'jobv': 9}, + {'jobr': 9}, + {'jobt': 9}, + {'jobp': 9}) + ) +def test_gejsv_invalid_job_arguments(kwargs): + """Test invalid job arguments raise an Exception""" + A = np.ones((2, 2), dtype=float) + gejsv = get_lapack_funcs('gejsv', dtype=float) + assert_raises(Exception, gejsv, A, **kwargs) + + +@pytest.mark.parametrize("A,sva_expect,u_expect,v_expect", + [(np.array([[2.27, -1.54, 1.15, -1.94], + [0.28, -1.67, 0.94, -0.78], + [-0.48, -3.09, 0.99, -0.21], + [1.07, 1.22, 0.79, 0.63], + [-2.35, 2.93, -1.45, 2.30], + [0.62, -7.39, 1.03, -2.57]]), + np.array([9.9966, 3.6831, 1.3569, 0.5000]), + np.array([[0.2774, -0.6003, -0.1277, 0.1323], + [0.2020, -0.0301, 0.2805, 0.7034], + [0.2918, 0.3348, 0.6453, 0.1906], + [-0.0938, -0.3699, 0.6781, -0.5399], + [-0.4213, 0.5266, 0.0413, -0.0575], + [0.7816, 0.3353, -0.1645, -0.3957]]), + np.array([[0.1921, -0.8030, 0.0041, -0.5642], + [-0.8794, -0.3926, -0.0752, 0.2587], + [0.2140, -0.2980, 0.7827, 0.5027], + [-0.3795, 0.3351, 0.6178, -0.6017]]))]) +def test_gejsv_NAG(A, sva_expect, u_expect, v_expect): + """ + This test implements the example found in the NAG manual, f08khf. + An example was not found for the complex case. + """ + # NAG manual provides accuracy up to 4 decimals + atol = 1e-4 + gejsv = get_lapack_funcs('gejsv', dtype=A.dtype) + + sva, u, v, work, iwork, info = gejsv(A) + + assert_allclose(sva_expect, sva, atol=atol) + assert_allclose(u_expect, u, atol=atol) + assert_allclose(v_expect, v, atol=atol) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_gttrf_gttrs(dtype): + # The test uses ?gttrf and ?gttrs to solve a random system for each dtype, + # tests that the output of ?gttrf define LU matrices, that input + # parameters are unmodified, transposal options function correctly, that + # incompatible matrix shapes raise an error, and singular matrices return + # non zero info. + + rng = np.random.RandomState(42) + n = 10 + atol = 100 * np.finfo(dtype).eps + + # create the matrix in accordance with the data type + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + + diag_cpy = [dl.copy(), d.copy(), du.copy()] + + A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1) + x = rng.random(n) + b = A @ x + + gttrf, gttrs = get_lapack_funcs(('gttrf', 'gttrs'), dtype=dtype) + + _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du) + # test to assure that the inputs of ?gttrf are unmodified + assert_array_equal(dl, diag_cpy[0]) + assert_array_equal(d, diag_cpy[1]) + assert_array_equal(du, diag_cpy[2]) + + # generate L and U factors from ?gttrf return values + # L/U are lower/upper triangular by construction (initially and at end) + U = np.diag(_d, 0) + np.diag(_du, 1) + np.diag(du2, 2) + L = np.eye(n, dtype=dtype) + + for i, m in enumerate(_dl): + # L is given in a factored form. + # See + # www.hpcavf.uclan.ac.uk/softwaredoc/sgi_scsl_html/sgi_html/ch03.html + piv = ipiv[i] - 1 + # right multiply by permutation matrix + L[:, [i, piv]] = L[:, [piv, i]] + # right multiply by Li, rank-one modification of identity + L[:, i] += L[:, i+1]*m + + # one last permutation + i, piv = -1, ipiv[-1] - 1 + # right multiply by final permutation matrix + L[:, [i, piv]] = L[:, [piv, i]] + + # check that the outputs of ?gttrf define an LU decomposition of A + assert_allclose(A, L @ U, atol=atol) + + b_cpy = b.copy() + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b) + # test that the inputs of ?gttrs are unmodified + assert_array_equal(b, b_cpy) + # test that the result of ?gttrs matches the expected input + assert_allclose(x, x_gttrs, atol=atol) + + # test that ?gttrf and ?gttrs work with transposal options + if dtype in REAL_DTYPES: + trans = "T" + b_trans = A.T @ x + else: + trans = "C" + b_trans = A.conj().T @ x + + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b_trans, trans=trans) + assert_allclose(x, x_gttrs, atol=atol) + + # test that ValueError is raised with incompatible matrix shapes + with assert_raises(ValueError): + gttrf(dl[:-1], d, du) + with assert_raises(ValueError): + gttrf(dl, d[:-1], du) + with assert_raises(ValueError): + gttrf(dl, d, du[:-1]) + + # test that matrix of size n=2 raises exception + with assert_raises(ValueError): + gttrf(dl[0], d[:1], du[0]) + + # test that singular (row of all zeroes) matrix fails via info + du[0] = 0 + d[0] = 0 + __dl, __d, __du, _du2, _ipiv, _info = gttrf(dl, d, du) + np.testing.assert_(__d[info - 1] == 0, (f"?gttrf: _d[info-1] is {__d[info - 1]}," + " not the illegal value :0.")) + + +@pytest.mark.parametrize("du, d, dl, du_exp, d_exp, du2_exp, ipiv_exp, b, x", + [(np.array([2.1, -1.0, 1.9, 8.0]), + np.array([3.0, 2.3, -5.0, -.9, 7.1]), + np.array([3.4, 3.6, 7.0, -6.0]), + np.array([2.3, -5, -.9, 7.1]), + np.array([3.4, 3.6, 7, -6, -1.015373]), + np.array([-1, 1.9, 8]), + np.array([2, 3, 4, 5, 5]), + np.array([[2.7, 6.6], + [-0.5, 10.8], + [2.6, -3.2], + [0.6, -11.2], + [2.7, 19.1] + ]), + np.array([[-4, 5], + [7, -4], + [3, -3], + [-4, -2], + [-3, 1]])), + ( + np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]), + np.array([-1.3 + 1.3j, -1.3 + 1.3j, + -1.3 + 3.3j, - .3 + 4.3j, + -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]), + # du exp + np.array([-1.3 + 1.3j, -1.3 + 3.3j, + -0.3 + 4.3j, -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j, + -1.3399 + 0.2875j]), + np.array([2 + 1j, -1 + 1j, 1 - 1j]), + np.array([2, 3, 4, 5, 5]), + np.array([[2.4 - 5j, 2.7 + 6.9j], + [3.4 + 18.2j, - 6.9 - 5.3j], + [-14.7 + 9.7j, - 6 - .6j], + [31.9 - 7.7j, -3.9 + 9.3j], + [-1 + 1.6j, -3 + 12.2j]]), + np.array([[1 + 1j, 2 - 1j], + [3 - 1j, 1 + 2j], + [4 + 5j, -1 + 1j], + [-1 - 2j, 2 + 1j], + [1 - 1j, 2 - 2j]]) + )]) +def test_gttrf_gttrs_NAG_f07cdf_f07cef_f07crf_f07csf(du, d, dl, du_exp, d_exp, + du2_exp, ipiv_exp, b, x): + # test to assure that wrapper is consistent with NAG Library Manual Mark 26 + # example problems: f07cdf and f07cef (real) + # examples: f07crf and f07csf (complex) + # (Links may expire, so search for "NAG Library Manual Mark 26" online) + + gttrf, gttrs = get_lapack_funcs(('gttrf', "gttrs"), (du[0], du[0])) + + _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du) + assert_allclose(du2, du2_exp) + assert_allclose(_du, du_exp) + assert_allclose(_d, d_exp, atol=1e-4) # NAG examples provide 4 decimals. + assert_allclose(ipiv, ipiv_exp) + + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b) + + assert_allclose(x_gttrs, x) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('norm', ['1', 'I', 'O']) +@pytest.mark.parametrize('n', [3, 10]) +def test_gtcon(dtype, norm, n): + rng = np.random.default_rng(23498324) + + d = rng.random(n) + rng.random(n)*1j + dl = rng.random(n - 1) + rng.random(n - 1)*1j + du = rng.random(n - 1) + rng.random(n - 1)*1j + A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1) + if np.issubdtype(dtype, np.floating): + A, d, dl, du = A.real, d.real, dl.real, du.real + A, d, dl, du = A.astype(dtype), d.astype(dtype), dl.astype(dtype), du.astype(dtype) + + anorm = np.linalg.norm(A, ord=np.inf if norm == 'I' else 1) + + gttrf, gtcon = get_lapack_funcs(('gttrf', 'gtcon'), (A,)) + dl, d, du, du2, ipiv, info = gttrf(dl, d, du) + res, _ = gtcon(dl, d, du, du2, ipiv, anorm, norm=norm) + + gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,)) + lu, ipvt, info = getrf(A) + ref, _ = gecon(lu, anorm, norm=norm) + + rtol = np.finfo(dtype).eps**0.75 + assert_allclose(res, ref, rtol=rtol) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('shape', [(3, 7), (7, 3), (2**18, 2**18)]) +def test_geqrfp_lwork(dtype, shape): + geqrfp_lwork = get_lapack_funcs(('geqrfp_lwork'), dtype=dtype) + m, n = shape + lwork, info = geqrfp_lwork(m=m, n=n) + assert_equal(info, 0) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs(ddtype, dtype): + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100*np.finfo(dtype).eps + # n is the length diagonal of A + n = 10 + # create diagonals according to size and dtype + + # diagonal d should always be real. + # add 4 to d so it will be dominant for all dtypes + d = generate_random_dtype_array((n,), ddtype, rng) + 4 + # diagonal e may be real or complex. + e = generate_random_dtype_array((n-1,), dtype, rng) + + # assemble diagonals together into matrix + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + # store a copy of diagonals to later verify + diag_cpy = [d.copy(), e.copy()] + + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + + _d, _e, info = pttrf(d, e) + # test to assure that the inputs of ?pttrf are unmodified + assert_array_equal(d, diag_cpy[0]) + assert_array_equal(e, diag_cpy[1]) + assert_equal(info, 0, err_msg=f"pttrf: info = {info}, should be 0") + + # test that the factors from pttrf can be recombined to make A + L = np.diag(_e, -1) + np.diag(np.ones(n)) + D = np.diag(_d) + + assert_allclose(A, L@D@L.conjugate().T, atol=atol) + + # generate random solution x + x = generate_random_dtype_array((n,), dtype, rng) + # determine accompanying b to get soln x + b = A@x + + # determine _x from pttrs + pttrs = get_lapack_funcs('pttrs', dtype=dtype) + _x, info = pttrs(_d, _e.conj(), b) + assert_equal(info, 0, err_msg=f"pttrs: info = {info}, should be 0") + + # test that _x from pttrs matches the expected x + assert_allclose(x, _x, atol=atol) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs_errors_incompatible_shape(ddtype, dtype): + n = 10 + rng = np.random.RandomState(1234) + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + d = generate_random_dtype_array((n,), ddtype, rng) + 2 + e = generate_random_dtype_array((n-1,), dtype, rng) + # test that ValueError is raised with incompatible matrix shapes + assert_raises(ValueError, pttrf, d[:-1], e) + assert_raises(ValueError, pttrf, d, e[:-1]) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs_errors_singular_nonSPD(ddtype, dtype): + n = 10 + rng = np.random.RandomState(42) + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + d = generate_random_dtype_array((n,), ddtype, rng) + 2 + e = generate_random_dtype_array((n-1,), dtype, rng) + # test that singular (row of all zeroes) matrix fails via info + d[0] = 0 + e[0] = 0 + _d, _e, info = pttrf(d, e) + assert_equal(_d[info - 1], 0, + f"?pttrf: _d[info-1] is {_d[info - 1]}, not the illegal value :0.") + + # test with non-spd matrix + d = generate_random_dtype_array((n,), ddtype, rng) + _d, _e, info = pttrf(d, e) + assert_(info != 0, "?pttrf should fail with non-spd matrix, but didn't") + + +@pytest.mark.parametrize(("d, e, d_expect, e_expect, b, x_expect"), [ + (np.array([4, 10, 29, 25, 5]), + np.array([-2, -6, 15, 8]), + np.array([4, 9, 25, 16, 1]), + np.array([-.5, -.6667, .6, .5]), + np.array([[6, 10], [9, 4], [2, 9], [14, 65], + [7, 23]]), + np.array([[2.5, 2], [2, -1], [1, -3], [-1, 6], + [3, -5]]) + ), ( + np.array([16, 41, 46, 21]), + np.array([16 + 16j, 18 - 9j, 1 - 4j]), + np.array([16, 9, 1, 4]), + np.array([1+1j, 2-1j, 1-4j]), + np.array([[64+16j, -16-32j], [93+62j, 61-66j], + [78-80j, 71-74j], [14-27j, 35+15j]]), + np.array([[2+1j, -3-2j], [1+1j, 1+1j], [1-2j, 1-2j], + [1-1j, 2+1j]]) + )]) +def test_pttrf_pttrs_NAG(d, e, d_expect, e_expect, b, x_expect): + # test to assure that wrapper is consistent with NAG Manual Mark 26 + # example problems: f07jdf and f07jef (real) + # examples: f07jrf and f07csf (complex) + # NAG examples provide 4 decimals. + # (Links expire, so please search for "NAG Library Manual Mark 26" online) + + atol = 1e-4 + pttrf = get_lapack_funcs('pttrf', dtype=e[0]) + _d, _e, info = pttrf(d, e) + assert_allclose(_d, d_expect, atol=atol) + assert_allclose(_e, e_expect, atol=atol) + + pttrs = get_lapack_funcs('pttrs', dtype=e[0]) + _x, info = pttrs(_d, _e.conj(), b) + assert_allclose(_x, x_expect, atol=atol) + + # also test option `lower` + if e.dtype in COMPLEX_DTYPES: + _x, info = pttrs(_d, _e, b, lower=1) + assert_allclose(_x, x_expect, atol=atol) + + +def pteqr_get_d_e_A_z(dtype, realtype, n, compute_z): + # used by ?pteqr tests to build parameters + # returns tuple of (d, e, A, z) + rng = np.random.RandomState(42) + if compute_z == 1: + # build Hermitian A from Q**T * tri * Q = A by creating Q and tri + A_eig = generate_random_dtype_array((n, n), dtype, rng) + A_eig = A_eig + np.diag(np.zeros(n) + 4*n) + A_eig = (A_eig + A_eig.conj().T) / 2 + # obtain right eigenvectors (orthogonal) + vr = eigh(A_eig)[1] + # create tridiagonal matrix + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), realtype, rng) + tri = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + # Build A using these factors that sytrd would: (Q**T * tri * Q = A) + A = vr @ tri @ vr.conj().T + # vr is orthogonal + z = vr + + else: + # d and e are always real per lapack docs. + d = generate_random_dtype_array((n,), realtype, rng) + e = generate_random_dtype_array((n-1,), realtype, rng) + + # make SPD + d = d + 4 + A = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + z = np.diag(d) + np.diag(e, -1) + np.diag(e, 1) + return (d, e, A, z) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr(dtype, realtype, compute_z): + ''' + Tests the ?pteqr lapack routine for all dtypes and compute_z parameters. + It generates random SPD matrix diagonals d and e, and then confirms + correct eigenvalues with scipy.linalg.eig. With applicable compute_z=2 it + tests that z can reform A. + ''' + atol = 1000*np.finfo(dtype).eps + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + + n = 10 + + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d=d, e=e, z=z, compute_z=compute_z) + assert_equal(info, 0, f"info = {info}, should be 0.") + + # compare the routine's eigenvalues with scipy.linalg.eig's. + assert_allclose(np.sort(eigh(A)[0]), np.sort(d_pteqr), atol=atol) + + if compute_z: + # verify z_pteqr as orthogonal + assert_allclose(z_pteqr @ np.conj(z_pteqr).T, np.identity(n), + atol=atol) + # verify that z_pteqr recombines to A + assert_allclose(z_pteqr @ np.diag(d_pteqr) @ np.conj(z_pteqr).T, + A, atol=atol) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_error_non_spd(dtype, realtype, compute_z): + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + + # test with non-spd matrix + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d - 4, e, z=z, compute_z=compute_z) + assert info > 0 + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z): + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + # test with incorrect/incompatible array sizes + assert_raises(ValueError, pteqr, d[:-1], e, z=z, compute_z=compute_z) + assert_raises(ValueError, pteqr, d, e[:-1], z=z, compute_z=compute_z) + if compute_z: + assert_raises(ValueError, pteqr, d, e, z=z[:-1], compute_z=compute_z) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_error_singular(dtype, realtype, compute_z): + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + # test with singular matrix + d[0] = 0 + e[0] = 0 + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d, e, z=z, compute_z=compute_z) + assert info > 0 + + +@pytest.mark.parametrize("compute_z,d,e,d_expect,z_expect", + [(2, # "I" + np.array([4.16, 5.25, 1.09, .62]), + np.array([3.17, -.97, .55]), + np.array([8.0023, 1.9926, 1.0014, 0.1237]), + np.array([[0.6326, 0.6245, -0.4191, 0.1847], + [0.7668, -0.4270, 0.4176, -0.2352], + [-0.1082, 0.6071, 0.4594, -0.6393], + [-0.0081, 0.2432, 0.6625, 0.7084]])), + ]) +def test_pteqr_NAG_f08jgf(compute_z, d, e, d_expect, z_expect): + ''' + Implements real (f08jgf) example from NAG Manual Mark 26. + Tests for correct outputs. + ''' + # the NAG manual has 4 decimals accuracy + atol = 1e-4 + pteqr = get_lapack_funcs(('pteqr'), dtype=d.dtype) + + z = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + _d, _e, _z, info = pteqr(d=d, e=e, z=z, compute_z=compute_z) + assert_allclose(_d, d_expect, atol=atol) + assert_allclose(np.abs(_z), np.abs(z_expect), atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('matrix_size', [(3, 4), (7, 6), (6, 6)]) +def test_geqrfp(dtype, matrix_size): + # Tests for all dytpes, tall, wide, and square matrices. + # Using the routine with random matrix A, Q and R are obtained and then + # tested such that R is upper triangular and non-negative on the diagonal, + # and Q is an orthogonal matrix. Verifies that A=Q@R. It also + # tests against a matrix that for which the linalg.qr method returns + # negative diagonals, and for error messaging. + + # set test tolerance appropriate for dtype + rng = np.random.RandomState(42) + rtol = 250*np.finfo(dtype).eps + atol = 100*np.finfo(dtype).eps + # get appropriate ?geqrfp for dtype + geqrfp = get_lapack_funcs(('geqrfp'), dtype=dtype) + gqr = get_lapack_funcs(("orgqr"), dtype=dtype) + + m, n = matrix_size + + # create random matrix of dimensions m x n + A = generate_random_dtype_array((m, n), dtype=dtype, rng=rng) + # create qr matrix using geqrfp + qr_A, tau, info = geqrfp(A) + + # obtain r from the upper triangular area + r = np.triu(qr_A) + + # obtain q from the orgqr lapack routine + # based on linalg.qr's extraction strategy of q with orgqr + + if m > n: + # this adds an extra column to the end of qr_A + # let qqr be an empty m x m matrix + qqr = np.zeros((m, m), dtype=dtype) + # set first n columns of qqr to qr_A + qqr[:, :n] = qr_A + # determine q from this qqr + # note that m is a sufficient for lwork based on LAPACK documentation + q = gqr(qqr, tau=tau, lwork=m)[0] + else: + q = gqr(qr_A[:, :m], tau=tau, lwork=m)[0] + + # test that q and r still make A + assert_allclose(q@r, A, rtol=rtol) + # ensure that q is orthogonal (that q @ transposed q is the identity) + assert_allclose(np.eye(q.shape[0]), q@(q.conj().T), rtol=rtol, + atol=atol) + # ensure r is upper tri by comparing original r to r as upper triangular + assert_allclose(r, np.triu(r), rtol=rtol) + # make sure diagonals of r are positive for this random solution + assert_(np.all(np.diag(r) > np.zeros(len(np.diag(r))))) + # ensure that info is zero for this success + assert_(info == 0) + + # test that this routine gives r diagonals that are positive for a + # matrix that returns negatives in the diagonal with scipy.linalg.rq + A_negative = generate_random_dtype_array((n, m), dtype=dtype, rng=rng) * -1 + r_rq_neg, q_rq_neg = qr(A_negative) + rq_A_neg, tau_neg, info_neg = geqrfp(A_negative) + # assert that any of the entries on the diagonal from linalg.qr + # are negative and that all of geqrfp are positive. + assert_(np.any(np.diag(r_rq_neg) < 0) and + np.all(np.diag(r) > 0)) + + +def test_geqrfp_errors_with_empty_array(): + # check that empty array raises good error message + A_empty = np.array([]) + geqrfp = get_lapack_funcs('geqrfp', dtype=A_empty.dtype) + assert_raises(Exception, geqrfp, A_empty) + + +@pytest.mark.parametrize("driver", ['ev', 'evd', 'evr', 'evx']) +@pytest.mark.parametrize("pfx", ['sy', 'he']) +def test_standard_eigh_lworks(pfx, driver): + n = 1200 # Some sufficiently big arbitrary number + dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES + sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0]) + dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1]) + try: + _compute_lwork(sc_dlw, n, lower=1) + _compute_lwork(dz_dlw, n, lower=1) + except Exception as e: + pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}") + + +@pytest.mark.parametrize("driver", ['gv', 'gvx']) +@pytest.mark.parametrize("pfx", ['sy', 'he']) +def test_generalized_eigh_lworks(pfx, driver): + n = 1200 # Some sufficiently big arbitrary number + dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES + sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0]) + dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1]) + # Shouldn't raise any exceptions + try: + _compute_lwork(sc_dlw, n, uplo="L") + _compute_lwork(dz_dlw, n, uplo="L") + except Exception as e: + pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}") + + +@pytest.mark.parametrize("dtype_", DTYPES) +@pytest.mark.parametrize("m", [1, 10, 100, 1000]) +def test_orcsd_uncsd_lwork(dtype_, m): + rng = np.random.default_rng(1234) + p = rng.integers(0, m) + q = m - p + pfx = 'or' if dtype_ in REAL_DTYPES else 'un' + dlw = pfx + 'csd_lwork' + lw = get_lapack_funcs(dlw, dtype=dtype_) + lwval = _compute_lwork(lw, m, p, q) + lwval = lwval if pfx == 'un' else (lwval,) + assert all([x > 0 for x in lwval]) + + +@pytest.mark.parametrize("dtype_", DTYPES) +def test_orcsd_uncsd(dtype_): + m, p, q = 250, 80, 170 + + pfx = 'or' if dtype_ in REAL_DTYPES else 'un' + X = ortho_group.rvs(m) if pfx == 'or' else unitary_group.rvs(m) + + drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), dtype=dtype_) + lwval = _compute_lwork(dlw, m, p, q) + lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork', + 'lrwork'], lwval)) + + cs11, cs12, cs21, cs22, theta, u1, u2, v1t, v2t, info =\ + drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals) + + assert info == 0 + + U = block_diag(u1, u2) + VH = block_diag(v1t, v2t) + r = min(min(p, q), min(m-p, m-q)) + n11 = min(p, q) - r + n12 = min(p, m-q) - r + n21 = min(m-p, q) - r + n22 = min(m-p, m-q) - r + + S = np.zeros((m, m), dtype=dtype_) + one = dtype_(1.) + for i in range(n11): + S[i, i] = one + for i in range(n22): + S[p+i, q+i] = one + for i in range(n12): + S[i+n11+r, i+n11+r+n21+n22+r] = -one + for i in range(n21): + S[p+n22+r+i, n11+r+i] = one + + for i in range(r): + S[i+n11, i+n11] = np.cos(theta[i]) + S[p+n22+i, i+r+n21+n22] = np.cos(theta[i]) + + S[i+n11, i+n11+n21+n22+r] = -np.sin(theta[i]) + S[p+n22+i, i+n11] = np.sin(theta[i]) + + Xc = U @ S @ VH + assert_allclose(X, Xc, rtol=0., atol=1e4*np.finfo(dtype_).eps) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("trans_bool", [False, True]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx(dtype, trans_bool, fact): + """ + These tests uses ?gtsvx to solve a random Ax=b system for each dtype. + It tests that the outputs define an LU matrix, that inputs are unmodified, + transposal options, incompatible shapes, singular matrices, and + singular factorizations. It parametrizes DTYPES and the 'fact' value along + with the fact related inputs. + """ + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100 * np.finfo(dtype).eps + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = ("T" if dtype in REAL_DTYPES else "C") if trans_bool else "N" + b = (A.conj().T if trans_bool else A) @ x + + # store a copy of the inputs to check they haven't been modified later + inputs_cpy = [dl.copy(), d.copy(), du.copy(), b.copy()] + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + assert_(info == 0, f"?gtsvx info = {info}, should be zero") + + # assure that inputs are unmodified + assert_array_equal(dl, inputs_cpy[0]) + assert_array_equal(d, inputs_cpy[1]) + assert_array_equal(du, inputs_cpy[2]) + assert_array_equal(b, inputs_cpy[3]) + + # test that x_soln matches the expected x + assert_allclose(x, x_soln, atol=atol) + + # assert that the outputs are of correct type or shape + # rcond should be a scalar + assert_(hasattr(rcond, "__len__") is not True, + f"rcond should be scalar but is {rcond}") + # ferr should be length of # of cols in x + assert_(ferr.shape[0] == b.shape[1], (f"ferr.shape is {ferr.shape[0]} but should" + f" be {b.shape[1]}")) + # berr should be length of # of cols in x + assert_(berr.shape[0] == b.shape[1], (f"berr.shape is {berr.shape[0]} but should" + f" be {b.shape[1]}")) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("trans_bool", [0, 1]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx_error_singular(dtype, trans_bool, fact): + rng = np.random.RandomState(42) + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = "T" if dtype in REAL_DTYPES else "C" + b = (A.conj().T if trans_bool else A) @ x + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # test with singular matrix + # no need to test inputs with fact "F" since ?gttrf already does. + if fact == "N": + # Construct a singular example manually + d[-1] = 0 + dl[-1] = 0 + # solve using routine + gtsvx_out = gtsvx(dl, d, du, b) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # test for the singular matrix. + assert info > 0, "info should be > 0 for singular matrix" + + elif fact == 'F': + # assuming that a singular factorization is input + df_[-1] = 0 + duf_[-1] = 0 + du2f_[-1] = 0 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, dlf=dlf_, df=df_, duf=duf_, + du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # info should not be zero and should provide index of illegal value + assert info > 0, "info should be > 0 for singular matrix" + + +@pytest.mark.parametrize("dtype", DTYPES*2) +@pytest.mark.parametrize("trans_bool", [False, True]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx_error_incompatible_size(dtype, trans_bool, fact): + rng = np.random.RandomState(42) + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = "T" if dtype in REAL_DTYPES else "C" + b = (A.conj().T if trans_bool else A) @ x + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + if fact == "N": + assert_raises(ValueError, gtsvx, dl[:-1], d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d[:-1], du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du[:-1], b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(Exception, gtsvx, dl, d, du, b[:-1], + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + else: + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_[:-1], df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_[:-1], + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_[:-1], du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_[:-1], ipiv=ipiv_) + + +@pytest.mark.parametrize("du,d,dl,b,x", + [(np.array([2.1, -1.0, 1.9, 8.0]), + np.array([3.0, 2.3, -5.0, -0.9, 7.1]), + np.array([3.4, 3.6, 7.0, -6.0]), + np.array([[2.7, 6.6], [-.5, 10.8], [2.6, -3.2], + [.6, -11.2], [2.7, 19.1]]), + np.array([[-4, 5], [7, -4], [3, -3], [-4, -2], + [-3, 1]])), + (np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]), + np.array([-1.3 + 1.3j, -1.3 + 1.3j, -1.3 + 3.3j, + -.3 + 4.3j, -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]), + np.array([[2.4 - 5j, 2.7 + 6.9j], + [3.4 + 18.2j, -6.9 - 5.3j], + [-14.7 + 9.7j, -6 - .6j], + [31.9 - 7.7j, -3.9 + 9.3j], + [-1 + 1.6j, -3 + 12.2j]]), + np.array([[1 + 1j, 2 - 1j], [3 - 1j, 1 + 2j], + [4 + 5j, -1 + 1j], [-1 - 2j, 2 + 1j], + [1 - 1j, 2 - 2j]]))]) +def test_gtsvx_NAG(du, d, dl, b, x): + # Test to ensure wrapper is consistent with NAG Manual Mark 26 + # example problems: real (f07cbf) and complex (f07cpf) + gtsvx = get_lapack_funcs('gtsvx', dtype=d.dtype) + + gtsvx_out = gtsvx(dl, d, du, b) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + + assert_array_almost_equal(x, x_soln) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx(dtype, realtype, fact, df_de_lambda): + ''' + This tests the ?ptsvx lapack routine wrapper to solve a random system + Ax = b for all dtypes and input variations. Tests for: unmodified + input parameters, fact options, incompatible matrix shapes raise an error, + and singular matrices return info of illegal value. + ''' + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100 * np.finfo(dtype).eps + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + # create copy to later test that they are unmodified + diag_cpy = [d.copy(), e.copy(), b.copy()] + + # solve using routine + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact, + df=df, ef=ef) + # d, e, and b should be unmodified + assert_array_equal(d, diag_cpy[0]) + assert_array_equal(e, diag_cpy[1]) + assert_array_equal(b, diag_cpy[2]) + assert_(info == 0, f"info should be 0 but is {info}.") + assert_array_almost_equal(x_soln, x) + + # test that the factors from ptsvx can be recombined to make A + L = np.diag(ef, -1) + np.diag(np.ones(n)) + D = np.diag(df) + assert_allclose(A, L@D@(np.conj(L).T), atol=atol) + + # assert that the outputs are of correct type or shape + # rcond should be a scalar + assert not hasattr(rcond, "__len__"), \ + f"rcond should be scalar but is {rcond}" + # ferr should be length of # of cols in x + assert_(ferr.shape == (2,), (f"ferr.shape is {ferr.shape} but should be " + "({x_soln.shape[1]},)")) + # berr should be length of # of cols in x + assert_(berr.shape == (2,), (f"berr.shape is {berr.shape} but should be " + "({x_soln.shape[1]},)")) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx_error_raise_errors(dtype, realtype, fact, df_de_lambda): + rng = np.random.RandomState(42) + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + # test with malformatted array sizes + assert_raises(ValueError, ptsvx, d[:-1], e, b, fact=fact, df=df, ef=ef) + assert_raises(ValueError, ptsvx, d, e[:-1], b, fact=fact, df=df, ef=ef) + assert_raises(Exception, ptsvx, d, e, b[:-1], fact=fact, df=df, ef=ef) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx_non_SPD_singular(dtype, realtype, fact, df_de_lambda): + rng = np.random.RandomState(42) + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + if fact == "N": + d[3] = 0 + # obtain new df, ef + df, ef, info = df_de_lambda(d, e) + # solve using routine + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b) + # test for the singular matrix. + assert info > 0 and info <= n + + # non SPD matrix + d = generate_random_dtype_array((n,), realtype, rng) + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b) + assert info > 0 and info <= n + else: + # assuming that someone is using a singular factorization + df, ef, info = df_de_lambda(d, e) + df[0] = 0 + ef[0] = 0 + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact, + df=df, ef=ef) + assert info > 0 + + +@pytest.mark.parametrize('d,e,b,x', + [(np.array([4, 10, 29, 25, 5]), + np.array([-2, -6, 15, 8]), + np.array([[6, 10], [9, 4], [2, 9], [14, 65], + [7, 23]]), + np.array([[2.5, 2], [2, -1], [1, -3], + [-1, 6], [3, -5]])), + (np.array([16, 41, 46, 21]), + np.array([16 + 16j, 18 - 9j, 1 - 4j]), + np.array([[64 + 16j, -16 - 32j], + [93 + 62j, 61 - 66j], + [78 - 80j, 71 - 74j], + [14 - 27j, 35 + 15j]]), + np.array([[2 + 1j, -3 - 2j], + [1 + 1j, 1 + 1j], + [1 - 2j, 1 - 2j], + [1 - 1j, 2 + 1j]]))]) +def test_ptsvx_NAG(d, e, b, x): + # test to assure that wrapper is consistent with NAG Manual Mark 26 + # example problems: f07jbf, f07jpf + # (Links expire, so please search for "NAG Library Manual Mark 26" online) + + # obtain routine with correct type based on e.dtype + ptsvx = get_lapack_funcs('ptsvx', dtype=e.dtype) + # solve using routine + df, ef, x_ptsvx, rcond, ferr, berr, info = ptsvx(d, e, b) + # determine ptsvx's solution and x are the same. + assert_array_almost_equal(x, x_ptsvx) + + +@pytest.mark.parametrize('lower', [False, True]) +@pytest.mark.parametrize('dtype', DTYPES) +def test_pptrs_pptri_pptrf_ppsv_ppcon(dtype, lower): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + # Manual conversion to/from packed format is feasible here. + n, nrhs = 10, 4 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, nrhs], dtype=dtype, rng=rng) + + a = a.conj().T + a + np.eye(n, dtype=dtype) * dtype(5.) + if lower: + inds = ([x for y in range(n) for x in range(y, n)], + [y for y in range(n) for x in range(y, n)]) + else: + inds = ([x for y in range(1, n+1) for x in range(y)], + [y-1 for y in range(1, n+1) for x in range(y)]) + ap = a[inds] + ppsv, pptrf, pptrs, pptri, ppcon = get_lapack_funcs( + ('ppsv', 'pptrf', 'pptrs', 'pptri', 'ppcon'), + dtype=dtype, + ilp64="preferred") + + ul, info = pptrf(n, ap, lower=lower) + assert_equal(info, 0) + aul = cholesky(a, lower=lower)[inds] + assert_allclose(ul, aul, rtol=0, atol=atol) + + uli, info = pptri(n, ul, lower=lower) + assert_equal(info, 0) + auli = inv(a)[inds] + assert_allclose(uli, auli, rtol=0, atol=atol) + + x, info = pptrs(n, ul, b, lower=lower) + assert_equal(info, 0) + bx = solve(a, b) + assert_allclose(x, bx, rtol=0, atol=atol) + + xv, info = ppsv(n, ap, b, lower=lower) + assert_equal(info, 0) + assert_allclose(xv, bx, rtol=0, atol=atol) + + anorm = np.linalg.norm(a, 1) + rcond, info = ppcon(n, ap, anorm=anorm, lower=lower) + assert_equal(info, 0) + assert_(abs(1/rcond - np.linalg.cond(a, p=1))*rcond < 1) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gees_trexc(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gees, trexc = get_lapack_funcs(('gees', 'trexc'), dtype=dtype) + + result = gees(lambda x: None, a, overwrite_a=False) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-3] + + d2 = t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + result = trexc(t, z, 7, 1) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-2] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + assert_allclose(t[0, 0], d2, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "t, expect, ifst, ilst", + [(np.array([[0.80, -0.11, 0.01, 0.03], + [0.00, -0.10, 0.25, 0.35], + [0.00, -0.65, -0.10, 0.20], + [0.00, 0.00, 0.00, -0.10]]), + np.array([[-0.1000, -0.6463, 0.0874, 0.2010], + [0.2514, -0.1000, 0.0927, 0.3505], + [0.0000, 0.0000, 0.8000, -0.0117], + [0.0000, 0.0000, 0.0000, -0.1000]]), + 2, 1), + (np.array([[-6.00 - 7.00j, 0.36 - 0.36j, -0.19 + 0.48j, 0.88 - 0.25j], + [0.00 + 0.00j, -5.00 + 2.00j, -0.03 - 0.72j, -0.23 + 0.13j], + [0.00 + 0.00j, 0.00 + 0.00j, 8.00 - 1.00j, 0.94 + 0.53j], + [0.00 + 0.00j, 0.00 + 0.00j, 0.00 + 0.00j, 3.00 - 4.00j]]), + np.array([[-5.0000 + 2.0000j, -0.1574 + 0.7143j, + 0.1781 - 0.1913j, 0.3950 + 0.3861j], + [0.0000 + 0.0000j, 8.0000 - 1.0000j, + 1.0742 + 0.1447j, 0.2515 - 0.3397j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 3.0000 - 4.0000j, 0.2264 + 0.8962j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 0.0000 + 0.0000j, -6.0000 - 7.0000j]]), + 1, 4)]) +def test_trexc_NAG(t, ifst, ilst, expect): + """ + This test implements the example found in the NAG manual, + f08qfc, f08qtc, f08qgc, f08quc. + """ + # NAG manual provides accuracy up to 4 decimals + atol = 1e-4 + trexc = get_lapack_funcs('trexc', dtype=t.dtype) + + result = trexc(t, t, ifst, ilst, wantq=0) + assert_equal(result[-1], 0) + + t = result[0] + assert_allclose(expect, t, atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gges_tgexc(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gges, tgexc = get_lapack_funcs(('gges', 'tgexc'), dtype=dtype) + + result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-4] + z = result[-3] + + d1 = s[0, 0] / t[0, 0] + d2 = s[6, 6] / t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + result = tgexc(s, t, q, z, 7, 1) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[2] + z = result[3] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol) + assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gees_trsen(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gees, trsen, trsen_lwork = get_lapack_funcs( + ('gees', 'trsen', 'trsen_lwork'), dtype=dtype) + + result = gees(lambda x: None, a, overwrite_a=False) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-3] + + d2 = t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + select = np.zeros(n) + select[6] = 1 + + lwork = _compute_lwork(trsen_lwork, select, t) + + if dtype in COMPLEX_DTYPES: + result = trsen(select, t, z, lwork=lwork) + else: + result = trsen(select, t, z, lwork=lwork, liwork=lwork[1]) + assert_equal(result[-1], 0) + + t = result[0] + z = result[1] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + assert_allclose(t[0, 0], d2, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "t, q, expect, select, expect_s, expect_sep", + [(np.array([[0.7995, -0.1144, 0.0060, 0.0336], + [0.0000, -0.0994, 0.2478, 0.3474], + [0.0000, -0.6483, -0.0994, 0.2026], + [0.0000, 0.0000, 0.0000, -0.1007]]), + np.array([[0.6551, 0.1037, 0.3450, 0.6641], + [0.5236, -0.5807, -0.6141, -0.1068], + [-0.5362, -0.3073, -0.2935, 0.7293], + [0.0956, 0.7467, -0.6463, 0.1249]]), + np.array([[0.3500, 0.4500, -0.1400, -0.1700], + [0.0900, 0.0700, -0.5399, 0.3500], + [-0.4400, -0.3300, -0.0300, 0.1700], + [0.2500, -0.3200, -0.1300, 0.1100]]), + np.array([1, 0, 0, 1]), + 1.75e+00, 3.22e+00), + (np.array([[-6.0004 - 6.9999j, 0.3637 - 0.3656j, + -0.1880 + 0.4787j, 0.8785 - 0.2539j], + [0.0000 + 0.0000j, -5.0000 + 2.0060j, + -0.0307 - 0.7217j, -0.2290 + 0.1313j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 7.9982 - 0.9964j, 0.9357 + 0.5359j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 0.0000 + 0.0000j, 3.0023 - 3.9998j]]), + np.array([[-0.8347 - 0.1364j, -0.0628 + 0.3806j, + 0.2765 - 0.0846j, 0.0633 - 0.2199j], + [0.0664 - 0.2968j, 0.2365 + 0.5240j, + -0.5877 - 0.4208j, 0.0835 + 0.2183j], + [-0.0362 - 0.3215j, 0.3143 - 0.5473j, + 0.0576 - 0.5736j, 0.0057 - 0.4058j], + [0.0086 + 0.2958j, -0.3416 - 0.0757j, + -0.1900 - 0.1600j, 0.8327 - 0.1868j]]), + np.array([[-3.9702 - 5.0406j, -4.1108 + 3.7002j, + -0.3403 + 1.0098j, 1.2899 - 0.8590j], + [0.3397 - 1.5006j, 1.5201 - 0.4301j, + 1.8797 - 5.3804j, 3.3606 + 0.6498j], + [3.3101 - 3.8506j, 2.4996 + 3.4504j, + 0.8802 - 1.0802j, 0.6401 - 1.4800j], + [-1.0999 + 0.8199j, 1.8103 - 1.5905j, + 3.2502 + 1.3297j, 1.5701 - 3.4397j]]), + np.array([1, 0, 0, 1]), + 1.02e+00, 1.82e-01)]) +def test_trsen_NAG(t, q, select, expect, expect_s, expect_sep): + """ + This test implements the example found in the NAG manual, + f08qgc, f08quc. + """ + # NAG manual provides accuracy up to 4 and 2 decimals + atol = 1e-4 + atol2 = 1e-2 + trsen, trsen_lwork = get_lapack_funcs( + ('trsen', 'trsen_lwork'), dtype=t.dtype) + + lwork = _compute_lwork(trsen_lwork, select, t) + + if t.dtype in COMPLEX_DTYPES: + result = trsen(select, t, q, lwork=lwork) + else: + result = trsen(select, t, q, lwork=lwork, liwork=lwork[1]) + assert_equal(result[-1], 0) + + t = result[0] + q = result[1] + if t.dtype in COMPLEX_DTYPES: + s = result[4] + sep = result[5] + else: + s = result[5] + sep = result[6] + + assert_allclose(expect, q @ t @ q.conj().T, atol=atol) + assert_allclose(expect_s, 1 / s, atol=atol2) + assert_allclose(expect_sep, 1 / sep, atol=atol2) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gges_tgsen(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gges, tgsen, tgsen_lwork = get_lapack_funcs( + ('gges', 'tgsen', 'tgsen_lwork'), dtype=dtype) + + result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-4] + z = result[-3] + + d1 = s[0, 0] / t[0, 0] + d2 = s[6, 6] / t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + select = np.zeros(n) + select[6] = 1 + + lwork = _compute_lwork(tgsen_lwork, select, s, t) + + # off-by-one error in LAPACK, see gh-issue #13397 + lwork = (lwork[0]+1, lwork[1]) + + result = tgsen(select, s, t, q, z, lwork=lwork) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-7] + z = result[-6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol) + assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "a, b, c, d, e, f, rans, lans", + [(np.array([[4.0, 1.0, 1.0, 2.0], + [0.0, 3.0, 4.0, 1.0], + [0.0, 1.0, 3.0, 1.0], + [0.0, 0.0, 0.0, 6.0]]), + np.array([[1.0, 1.0, 1.0, 1.0], + [0.0, 3.0, 4.0, 1.0], + [0.0, 1.0, 3.0, 1.0], + [0.0, 0.0, 0.0, 4.0]]), + np.array([[-4.0, 7.0, 1.0, 12.0], + [-9.0, 2.0, -2.0, -2.0], + [-4.0, 2.0, -2.0, 8.0], + [-7.0, 7.0, -6.0, 19.0]]), + np.array([[2.0, 1.0, 1.0, 3.0], + [0.0, 1.0, 2.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 2.0]]), + np.array([[1.0, 1.0, 1.0, 2.0], + [0.0, 1.0, 4.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0]]), + np.array([[-7.0, 5.0, 0.0, 7.0], + [-5.0, 1.0, -8.0, 0.0], + [-1.0, 2.0, -3.0, 5.0], + [-3.0, 2.0, 0.0, 5.0]]), + np.array([[1.0, 1.0, 1.0, 1.0], + [-1.0, 2.0, -1.0, -1.0], + [-1.0, 1.0, 3.0, 1.0], + [-1.0, 1.0, -1.0, 4.0]]), + np.array([[4.0, -1.0, 1.0, -1.0], + [1.0, 3.0, -1.0, 1.0], + [-1.0, 1.0, 2.0, -1.0], + [1.0, -1.0, 1.0, 1.0]]))]) +@pytest.mark.parametrize('dtype', REAL_DTYPES) +def test_tgsyl_NAG(a, b, c, d, e, f, rans, lans, dtype): + atol = 1e-4 + + tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype) + rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f) + + assert_equal(info, 0) + assert_allclose(scale, 1.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="SCALE must be 1.0") + assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="DIF must be nearly 0") + assert_allclose(rout, rans, atol=atol, + err_msg="Solution for R is incorrect") + assert_allclose(lout, lans, atol=atol, + err_msg="Solution for L is incorrect") + + +@pytest.mark.parametrize('dtype', REAL_DTYPES) +@pytest.mark.parametrize('trans', ('N', 'T')) +@pytest.mark.parametrize('ijob', [0, 1, 2, 3, 4]) +def test_tgsyl(dtype, trans, ijob): + + atol = 1e-3 if dtype == np.float32 else 1e-10 + rng = np.random.default_rng(1685779866898198) + m, n = 10, 15 + + a, d, *_ = qz(rng.uniform(-10, 10, [m, m]).astype(dtype), + rng.uniform(-10, 10, [m, m]).astype(dtype), + output='real') + + b, e, *_ = qz(rng.uniform(-10, 10, [n, n]).astype(dtype), + rng.uniform(-10, 10, [n, n]).astype(dtype), + output='real') + + c = rng.uniform(-2, 2, [m, n]).astype(dtype) + f = rng.uniform(-2, 2, [m, n]).astype(dtype) + + tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype) + rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f, + trans=trans, ijob=ijob) + + assert info == 0, "INFO is non-zero" + assert scale >= 0.0, "SCALE must be non-negative" + if ijob == 0: + assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="DIF must be 0 for ijob =0") + else: + assert dif >= 0.0, "DIF must be non-negative" + + # Only DIF is calculated for ijob = 3/4 + if ijob <= 2: + if trans == 'N': + lhs1 = a @ rout - lout @ b + rhs1 = scale*c + lhs2 = d @ rout - lout @ e + rhs2 = scale*f + elif trans == 'T': + lhs1 = np.transpose(a) @ rout + np.transpose(d) @ lout + rhs1 = scale*c + lhs2 = rout @ np.transpose(b) + lout @ np.transpose(e) + rhs2 = -1.0*scale*f + + assert_allclose(lhs1, rhs1, atol=atol, rtol=0., + err_msg='lhs1 and rhs1 do not match') + assert_allclose(lhs2, rhs2, atol=atol, rtol=0., + err_msg='lhs2 and rhs2 do not match') + + +@pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('lower', (0, 1)) +def test_sy_hetrs(mtype, dtype, lower): + if mtype == 'he' and dtype in REAL_DTYPES: + pytest.skip("hetrs not for real dtypes.") + rng = np.random.default_rng(1723059677121834) + n, nrhs = 20, 5 + if dtype in COMPLEX_DTYPES: + A = (rng.uniform(size=(n, n)) + rng.uniform(size=(n, n))*1j).astype(dtype) + else: + A = rng.uniform(size=(n, n)).astype(dtype) + + A = A + A.T if mtype == 'sy' else A + A.conj().T + b = rng.uniform(size=(n, nrhs)).astype(dtype) + names = f'{mtype}trf', f'{mtype}trf_lwork', f'{mtype}trs' + trf, trf_lwork, trs = get_lapack_funcs(names, dtype=dtype) + lwork = trf_lwork(n, lower=lower) + ldu, ipiv, info = trf(A, lwork=lwork, lower=lower) + assert info == 0 + x, info = trs(a=ldu, ipiv=ipiv, b=b, lower=lower) + assert info == 0 + eps = np.finfo(dtype).eps + assert_allclose(A@x, b, atol=100*n*eps) + + +@pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('lower', (0, 1)) +def test_sy_he_tri(dtype, lower, mtype): + if mtype == 'he' and dtype in REAL_DTYPES: + pytest.skip("hetri not for real dtypes.") + if sysconfig.get_platform() == 'win-arm64' and dtype in COMPLEX_DTYPES: + pytest.skip("Test segfaulting on win-arm64 in CI, see gh-23133") + + rng = np.random.default_rng(1723059677121834) + n = 20 + A = rng.random((n, n)) + rng.random((n, n))*1j + if np.issubdtype(dtype, np.floating): + A = A.real + A = A.astype(dtype) + A = A + A.T if mtype == 'sy' else A + A.conj().T + names = f'{mtype}trf', f'{mtype}tri' + trf, tri = get_lapack_funcs(names, dtype=dtype) + ldu, ipiv, info = trf(A, lower=lower) + assert info == 0 + A_inv, info = tri(a=ldu, ipiv=ipiv, lower=lower) + assert info == 0 + eps = np.finfo(dtype).eps + ref = np.linalg.inv(A) + if lower: + assert_allclose(np.tril(A_inv), np.tril(ref), atol=100*n*eps) + else: + assert_allclose(np.triu(A_inv), np.triu(ref), atol=100*n*eps) + + +@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe')) +@pytest.mark.parametrize('uplo, m, n', [('U', 5, 10), ('U', 10, 10), + ('L', 10, 5), ('L', 10, 10)]) +@pytest.mark.parametrize('diag', ['N', 'U']) +@pytest.mark.parametrize('dtype', DTYPES) +def test_lantr(norm, uplo, m, n, diag, dtype): + rng = np.random.default_rng(98426598246982456) + A = rng.random(size=(m, n)).astype(dtype) + lantr, lange = get_lapack_funcs(('lantr', 'lange'), (A,)) + res = lantr(norm, A, uplo=uplo, diag=diag) + + # now modify the matrix according to assumptions made by `lantr` + A = np.triu(A) if uplo == 'U' else np.tril(A) + if diag == 'U': + i = np.arange(min(m, n)) + A[i, i] = 1 + ref = lange(norm, A) + + assert_allclose(res, ref, rtol=2e-6) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('norm', ['1', 'I', 'O']) +def test_gbcon(dtype, norm): + rng = np.random.default_rng(17273783424) + + # A is of shape n x n with ku/kl super/sub-diagonals + n, ku, kl = 10, 2, 2 + A = rng.random((n, n)) + rng.random((n, n))*1j + # make the condition numbers more interesting + offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n)) + A += offset + if np.issubdtype(dtype, np.floating): + A = A.real + A = A.astype(dtype) + A[np.triu_indices(n, ku + 1)] = 0 + A[np.tril_indices(n, -kl - 1)] = 0 + + # construct banded form + tmp = _to_banded(kl, ku, A) + # add rows required by ?gbtrf + LDAB = 2*kl + ku + 1 + ab = np.zeros((LDAB, n), dtype=dtype) + ab[kl:, :] = tmp + + anorm = np.linalg.norm(A, ord=np.inf if norm == 'I' else 1) + gbcon, gbtrf = get_lapack_funcs(("gbcon", "gbtrf"), (ab,)) + lu_band, ipiv, _ = gbtrf(ab, kl, ku) + res = gbcon(norm=norm, kl=kl, ku=ku, ab=lu_band, ipiv=ipiv, + anorm=anorm)[0] + + gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,)) + lu = getrf(A)[0] + ref = gecon(lu, anorm, norm=norm)[0] + # This is an estimate of reciprocal condition number; we just need order of + # magnitude. + assert_allclose(res, ref, rtol=1) + + +@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe')) +@pytest.mark.parametrize('dtype', DTYPES) +def test_langb(dtype, norm): + rng = np.random.default_rng(17273783424) + + # A is of shape n x n with ku/kl super/sub-diagonals + n, ku, kl = 10, 2, 2 + A = rng.random((n, n)) + rng.random((n, n))*1j + if np.issubdtype(dtype, np.floating): + A = A.real + A = A.astype(dtype) + A[np.triu_indices(n, ku + 1)] = 0 + A[np.tril_indices(n, -kl - 1)] = 0 + ab = _to_banded(kl, ku, A) + + langb, lange = get_lapack_funcs(('langb', 'lange'), (A,)) + ref = lange(norm, A) + res = langb(norm, kl, ku, ab) + assert_allclose(res, ref, rtol=2e-6) + + +@pytest.mark.parametrize('dtype', REAL_DTYPES) +@pytest.mark.parametrize('compute_v', (0, 1)) +def test_stevd(dtype, compute_v): + rng = np.random.default_rng(266474747488348746) + n = 10 + d = rng.random(n, dtype=dtype) + e = rng.random(n - 1, dtype=dtype) + A = np.diag(e, -1) + np.diag(d) + np.diag(e, 1) + ref = np.linalg.eigvalsh(A) + + stevd = get_lapack_funcs('stevd') + U, V, info = stevd(d, e, compute_v=compute_v) + assert info == 0 + assert_allclose(np.sort(U), np.sort(ref)) + if compute_v: + eps = np.finfo(dtype).eps + assert_allclose(V @ np.diag(U) @ V.T, A, atol=eps**0.8) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_matfuncs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_matfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..29b87d9cbab24eb53919a6d9cd19c6ee8921f987 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_matfuncs.py @@ -0,0 +1,1121 @@ +# +# Created by: Pearu Peterson, March 2002 +# +""" Test functions for linalg.matfuncs module + +""" +import functools +import pytest +import warnings + +import numpy as np +from numpy import array, identity, sqrt +from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_, + assert_array_less, assert_array_equal) + +import scipy.linalg +from scipy.linalg import (funm, signm, logm, sqrtm, fractional_matrix_power, + expm, expm_frechet, expm_cond, norm, khatri_rao, + cosm, sinm, tanm, coshm, sinhm, tanhm) + +from scipy.linalg import _matfuncs_inv_ssq +from scipy.linalg._matfuncs import pick_pade_structure +from scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarning +import scipy.linalg._expm_frechet +from scipy.linalg import LinAlgWarning +from scipy.optimize import minimize + + +def _get_al_mohy_higham_2012_experiment_1(): + """ + Return the test matrix from Experiment (1) of [1]_. + + References + ---------- + .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012) + "Improved Inverse Scaling and Squaring Algorithms + for the Matrix Logarithm." + SIAM Journal on Scientific Computing, 34 (4). C152-C169. + ISSN 1095-7197 + + """ + A = np.array([ + [3.2346e-1, 3e4, 3e4, 3e4], + [0, 3.0089e-1, 3e4, 3e4], + [0, 0, 3.2210e-1, 3e4], + [0, 0, 0, 3.0744e-1]], dtype=float) + return A + + +class TestSignM: + + def test_nils(self): + a = array([[29.2, -24.2, 69.5, 49.8, 7.], + [-9.2, 5.2, -18., -16.8, -2.], + [-10., 6., -20., -18., -2.], + [-9.6, 9.6, -25.5, -15.4, -2.], + [9.8, -4.8, 18., 18.2, 2.]]) + cr = array([[11.94933333,-2.24533333,15.31733333,21.65333333,-2.24533333], + [-3.84266667,0.49866667,-4.59066667,-7.18666667,0.49866667], + [-4.08,0.56,-4.92,-7.6,0.56], + [-4.03466667,1.04266667,-5.59866667,-7.02666667,1.04266667], + [4.15733333,-0.50133333,4.90933333,7.81333333,-0.50133333]]) + r = signm(a) + assert_array_almost_equal(r,cr) + + def test_defective1(self): + a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]]) + signm(a) + #XXX: what would be the correct result? + + def test_defective2(self): + a = array(( + [29.2,-24.2,69.5,49.8,7.0], + [-9.2,5.2,-18.0,-16.8,-2.0], + [-10.0,6.0,-20.0,-18.0,-2.0], + [-9.6,9.6,-25.5,-15.4,-2.0], + [9.8,-4.8,18.0,18.2,2.0])) + signm(a) + #XXX: what would be the correct result? + + def test_defective3(self): + a = array([[-2., 25., 0., 0., 0., 0., 0.], + [0., -3., 10., 3., 3., 3., 0.], + [0., 0., 2., 15., 3., 3., 0.], + [0., 0., 0., 0., 15., 3., 0.], + [0., 0., 0., 0., 3., 10., 0.], + [0., 0., 0., 0., 0., -2., 25.], + [0., 0., 0., 0., 0., 0., -3.]]) + signm(a) + #XXX: what would be the correct result? + + +class TestLogM: + @pytest.mark.filterwarnings("ignore:.*inaccurate.*:RuntimeWarning") + def test_nils(self): + a = array([[-2., 25., 0., 0., 0., 0., 0.], + [0., -3., 10., 3., 3., 3., 0.], + [0., 0., 2., 15., 3., 3., 0.], + [0., 0., 0., 0., 15., 3., 0.], + [0., 0., 0., 0., 3., 10., 0.], + [0., 0., 0., 0., 0., -2., 25.], + [0., 0., 0., 0., 0., 0., -3.]]) + m = (identity(7)*3.1+0j)-a + logm(m) + #XXX: what would be the correct result? + + @pytest.mark.filterwarnings("ignore:.*inaccurate.*:RuntimeWarning") + def test_al_mohy_higham_2012_experiment_1_logm(self): + # The logm completes the round trip successfully. + # Note that the expm leg of the round trip is badly conditioned. + A = _get_al_mohy_higham_2012_experiment_1() + A_logm = logm(A) + A_round_trip = expm(A_logm) + assert_allclose(A_round_trip, A, rtol=5e-5, atol=1e-14) + + def test_al_mohy_higham_2012_experiment_1_funm_log(self): + # The raw funm with np.log does not complete the round trip. + # Note that the expm leg of the round trip is badly conditioned. + A = _get_al_mohy_higham_2012_experiment_1() + A_funm_log = funm(A, np.log) + A_round_trip = expm(A_funm_log) + assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14)) + + def test_round_trip_random_float(self): + rng = np.random.default_rng(1738098768840254) + for n in range(1, 6): + M_unscaled = rng.uniform(size=(n, n)) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + + # Eigenvalues are related to the branch cut. + W = np.linalg.eigvals(M) + err_msg = f'M:{M} eivals:{W}' + + # Check sqrtm round trip because it is used within logm. + M_sqrtm = sqrtm(M) + M_sqrtm_round_trip = M_sqrtm @ M_sqrtm + assert_allclose(M_sqrtm_round_trip, M) + + # Check logm round trip. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + + M_logm = logm(M) + M_logm_round_trip = expm(M_logm) + assert_allclose(M_logm_round_trip, M, err_msg=err_msg) + + def test_round_trip_random_complex(self): + rng = np.random.default_rng(1738098768840254) + for n in range(1, 6): + M_unscaled = (rng.standard_normal((n, n)) + + 1j*rng.standard_normal((n, n))) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_logm = logm(M) + M_round_trip = expm(M_logm) + assert_allclose(M_round_trip, M) + + def test_logm_type_preservation_and_conversion(self): + # The logm matrix function should preserve the type of a matrix + # whose eigenvalues are positive with zero imaginary part. + # Test this preservation for variously structured matrices. + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, 1]], + [[1, 0], [1, 1]], + [[2, 1], [1, 1]], + [[2, 3], [1, 2]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(not any(w.imag or w.real < 0 for w in W)) + + # check float type preservation + A = np.array(matrix_as_list, dtype=float) + A_logm = logm(A) + assert_(A_logm.dtype.char not in complex_dtype_chars) + + # check complex type preservation + A = np.array(matrix_as_list, dtype=complex) + A_logm = logm(A) + assert_(A_logm.dtype.char in complex_dtype_chars) + + # check float->complex type conversion for the matrix negation + A = -np.array(matrix_as_list, dtype=float) + A_logm = logm(A) + assert_(A_logm.dtype.char in complex_dtype_chars) + + def test_complex_spectrum_real_logm(self): + # This matrix has complex eigenvalues and real logm. + # Its output dtype depends on its input dtype. + M = [[1, 1, 2], [2, 1, 1], [1, 2, 1]] + for dt in float, complex: + X = np.array(M, dtype=dt) + w = scipy.linalg.eigvals(X) + assert_(1e-2 < np.absolute(w.imag).sum()) + Y = logm(X) + assert_(np.issubdtype(Y.dtype, np.inexact)) + assert_allclose(expm(Y), X) + + def test_real_mixed_sign_spectrum(self): + # These matrices have real eigenvalues with mixed signs. + # The output logm dtype is complex, regardless of input dtype. + for M in ( + [[1, 0], [0, -1]], + [[0, 1], [1, 0]]): + for dt in float, complex: + A = np.array(M, dtype=dt) + A_logm, info = logm(A) + assert_(np.issubdtype(A_logm.dtype, np.complexfloating)) + + def test_exactly_singular(self): + A = np.array([[0, 0], [1j, 1j]]) + B = np.asarray([[1, 1], [0, 0]]) + for M in A, A.T, B, B.T: + with pytest.warns(_matfuncs_inv_ssq.LogmExactlySingularWarning): + L = logm(M) + E = expm(L) + assert_allclose(E, M, atol=1e-14) + + def test_nearly_singular(self): + M = np.array([[1e-100]]) + with pytest.warns(_matfuncs_inv_ssq.LogmNearlySingularWarning): + L = logm(M) + E = expm(L) + assert_allclose(E, M, atol=1e-14) + + def test_opposite_sign_complex_eigenvalues(self): + # See gh-6113 + E = [[0, 1], [-1, 0]] + L = [[0, np.pi*0.5], [-np.pi*0.5, 0]] + assert_allclose(expm(L), E, atol=1e-14) + assert_allclose(logm(E), L, atol=1e-14) + E = [[1j, 4], [0, -1j]] + L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]] + assert_allclose(expm(L), E, atol=1e-14) + assert_allclose(logm(E), L, atol=1e-14) + E = [[1j, 0], [0, -1j]] + L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]] + assert_allclose(expm(L), E, atol=1e-14) + assert_allclose(logm(E), L, atol=1e-14) + + def test_readonly(self): + n = 5 + a = np.ones((n, n)) + np.identity(n) + a.flags.writeable = False + logm(a) + + @pytest.mark.xfail(reason="ValueError: attempt to get argmax of an empty sequence") + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + log_a = logm(a) + a0 = np.eye(2, dtype=dt) + log_a0 = logm(a0) + + assert log_a.shape == (0, 0) + assert log_a.dtype == log_a0.dtype + + @pytest.mark.parametrize('dtype', [int, float, np.float32, complex, np.complex64]) + def test_no_ZeroDivisionError(self, dtype): + # gh-17136 reported inconsistent behavior in `logm` depending on input dtype: + # sometimes it raised an error, and sometimes it printed a warning message. + # check that this is resolved and that the warning is emitted properly. + with (pytest.warns(RuntimeWarning, match="logm result may be inaccurate"), + pytest.warns(LogmExactlySingularWarning)): + logm(np.zeros((2, 2), dtype=dtype)) + + +class TestSqrtM: + + def test_round_trip_random_float(self): + rng = np.random.default_rng(1738151906092735) + for n in range(1, 6): + M_unscaled = rng.standard_normal((n, n)) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_sqrtm = sqrtm(M) + M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) + assert_allclose(M_sqrtm_round_trip, M) + + def test_round_trip_random_complex(self): + rng = np.random.default_rng(1738151906092736) + for n in range(1, 6): + M_unscaled = (rng.standard_normal((n, n)) + + 1j * rng.standard_normal((n, n))) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_sqrtm = sqrtm(M) + M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) + assert_allclose(M_sqrtm_round_trip, M) + + def test_bad(self): + # See https://web.archive.org/web/20051220232650/http://www.maths.man.ac.uk/~nareports/narep336.ps.gz + e = 2**-5 + se = sqrt(e) + a = array([[1.0,0,0,1], + [0,e,0,0], + [0,0,e,0], + [0,0,0,1]]) + sa = array([[1,0,0,0.5], + [0,se,0,0], + [0,0,se,0], + [0,0,0,1]]) + assert_array_almost_equal(sa @ sa, a) + # Check default sqrtm. + esa = sqrtm(a) + assert_array_almost_equal(esa @ esa, a) + + def test_sqrtm_type_preservation_and_conversion(self): + # The sqrtm matrix function should preserve the type of a matrix + # whose eigenvalues are nonnegative with zero imaginary part. + # Test this preservation for variously structured matrices. + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, 1]], + [[1, 0], [1, 1]], + [[2, 1], [1, 1]], + [[2, 3], [1, 2]], + [[1, 1], [1, 1]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(not any(w.imag or w.real < 0 for w in W)) + + # Last test matrix is singular so suppress the warning + with warnings.catch_warnings(): + warnings.simplefilter("ignore", LinAlgWarning) + + # check float type preservation + A = np.array(matrix_as_list, dtype=float) + A_sqrtm = sqrtm(A) + assert_(A_sqrtm.dtype.char not in complex_dtype_chars) + + # check complex type preservation + A = np.array(matrix_as_list, dtype=complex) + A_sqrtm = sqrtm(A) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + # check float->complex type conversion for the matrix negation + A = -np.array(matrix_as_list, dtype=float) + A_sqrtm = sqrtm(A) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self): + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, -1]], + [[0, 1], [1, 0]], + [[0, 1, 0], [0, 0, -1], [1, 0, 0]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(any(w.imag or w.real < 0 for w in W)) + + # check complex->complex + A = np.array(matrix_as_list, dtype=complex) + A_sqrtm = sqrtm(A) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + # check float->complex + A = np.array(matrix_as_list, dtype=float) + A_sqrtm = sqrtm(A) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + def test_al_mohy_higham_2012_experiment_1(self): + # Matrix square root of a tricky upper triangular matrix. + A = _get_al_mohy_higham_2012_experiment_1() + A_sqrtm = sqrtm(A) + A_round_trip = A_sqrtm @ A_sqrtm + assert_allclose(A_round_trip, A, rtol=1e-5) + assert_allclose(np.tril(A_round_trip), np.tril(A)) + + def test_strict_upper_triangular(self): + # This matrix has no square root but upper triangular hence upper + # triangle will be filled with junk values. + for dt in int, float: + A = np.array([ + [0, 3, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 3], + [0, 0, 0, 0]], dtype=dt) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", LinAlgWarning) + + A_sqrtm = sqrtm(A) + assert_allclose(np.tril(A_sqrtm), np.zeros((4, 4))) + assert np.isnan(A_sqrtm).any() + assert np.isinf(A_sqrtm).any() + + # Future edit: This squareroot is not possible to find algorithmically + # with the current methods. Now sqrtm docstring has another example of + # such matrix whose squareroot is not a polynomial in it. Hence no need + # to test it here. + """ + def test_weird_matrix(self): + # The square root of matrix B exists. + for dt in int, float: + A = np.array([ + [0, 0, 1], + [0, 0, 0], + [0, 1, 0]], dtype=dt) + B = np.array([ + [0, 1, 0], + [0, 0, 0], + [0, 0, 0]], dtype=dt) + assert_array_equal(B, A @ A) + + # But scipy sqrtm is not clever enough to find it. + B_sqrtm, info = sqrtm(B, disp=False) + assert_(np.isnan(B_sqrtm).all()) + """ + + def test_opposite_sign_complex_eigenvalues(self): + M = [[2j, 4], [0, -2j]] + R = [[1+1j, 2], [0, 1-1j]] + assert_allclose(np.dot(R, R), M, atol=1e-14) + assert_allclose(sqrtm(M), R, atol=1e-14) + + def test_gh4866(self): + M = np.array([[1, 0, 0, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 0, 0, 1]]) + R = np.array([[sqrt(0.5), 0, 0, sqrt(0.5)], + [0, 0, 0, 0], + [0, 0, 0, 0], + [sqrt(0.5), 0, 0, sqrt(0.5)]]) + assert_allclose(R @ R, M, atol=1e-14) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", LinAlgWarning) + + assert_allclose(sqrtm(M), R, atol=1e-14) + + def test_gh5336(self): + M = np.diag([2, 1, 0]) + R = np.diag([sqrt(2), 1, 0]) + assert_allclose(R @ R, M, atol=1e-14) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=LinAlgWarning) + assert_allclose(sqrtm(M), R, atol=1e-14) + + def test_gh7839(self): + M = np.zeros((2, 2)) + R = np.zeros((2, 2)) + # Catch and silence LinAlgWarning + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=LinAlgWarning) + + assert_allclose(sqrtm(M), R, atol=1e-14) + + def test_gh17918(self): + M = np.empty((19, 19)) + M.fill(0.94) + np.fill_diagonal(M, 1) + assert np.isrealobj(sqrtm(M)) + + def test_gh23278(self): + M = np.array([[1., 0., 0.], [0, 1, -1j], [0, 1j, 2]]) + sq = sqrtm(M) + assert_allclose(sq @ sq, M, atol=1e-14) + sq = sqrtm(M.astype(np.complex64)) + assert_allclose(sq @ sq, M, atol=1e-6) + + def test_data_size_preservation_uint_in_float_out(self): + M = np.eye(10, dtype=np.uint8) + assert sqrtm(M).dtype == np.float64 + M = np.eye(10, dtype=np.uint16) + assert sqrtm(M).dtype == np.float64 + M = np.eye(10, dtype=np.uint32) + assert sqrtm(M).dtype == np.float64 + M = np.eye(10, dtype=np.uint64) + assert sqrtm(M).dtype == np.float64 + + def test_data_size_preservation_int_in_float_out(self): + M = np.eye(10, dtype=np.int8) + assert sqrtm(M).dtype == np.float64 + M = np.eye(10, dtype=np.int16) + assert sqrtm(M).dtype == np.float64 + M = np.eye(10, dtype=np.int32) + assert sqrtm(M).dtype == np.float64 + M = np.eye(10, dtype=np.int64) + assert sqrtm(M).dtype == np.float64 + + def test_data_size_preservation_int_in_comp_out(self): + M = np.array([[2, 4], [0, -2]], dtype=np.int8) + assert sqrtm(M).dtype == np.complex128 + M = np.array([[2, 4], [0, -2]], dtype=np.int16) + assert sqrtm(M).dtype == np.complex128 + M = np.array([[2, 4], [0, -2]], dtype=np.int32) + assert sqrtm(M).dtype == np.complex128 + M = np.array([[2, 4], [0, -2]], dtype=np.int64) + assert sqrtm(M).dtype == np.complex128 + + def test_data_size_preservation_float_in_float_out(self): + M = np.eye(10, dtype=np.float16) + assert sqrtm(M).dtype == np.float32 + M = np.eye(10, dtype=np.float32) + assert sqrtm(M).dtype == np.float32 + M = np.eye(10, dtype=np.float64) + assert sqrtm(M).dtype == np.float64 + if hasattr(np, 'float128'): + M = np.eye(10, dtype=np.float128) + assert sqrtm(M).dtype == np.float64 + + def test_data_size_preservation_float_in_comp_out(self): + M = np.array([[2, 4], [0, -2]], dtype=np.float16) + assert sqrtm(M).dtype == np.complex64 + M = np.array([[2, 4], [0, -2]], dtype=np.float32) + assert sqrtm(M).dtype == np.complex64 + M = np.array([[2, 4], [0, -2]], dtype=np.float64) + assert sqrtm(M).dtype == np.complex128 + if hasattr(np, 'float128') and hasattr(np, 'complex256'): + M = np.array([[2, 4], [0, -2]], dtype=np.float128) + assert sqrtm(M).dtype == np.complex128 + + def test_data_size_preservation_comp_in_comp_out(self): + M = np.array([[2j, 4], [0, -2j]], dtype=np.complex64) + assert sqrtm(M).dtype == np.complex64 + M = np.array([[2j, 4], [0, -2j]], dtype=np.complex128) + assert sqrtm(M).dtype == np.complex128 + if hasattr(np, 'complex256'): + M = np.array([[2j, 4], [0, -2j]], dtype=np.complex256) + assert sqrtm(M).dtype == np.complex128 + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + s = sqrtm(a) + a0 = np.eye(2, dtype=dt) + s0 = sqrtm(a0) + + assert s.shape == (0, 0) + assert s.dtype == s0.dtype + + def test_cf_noncontig_nd_inputs(self): + # Check that non-contiguous arrays are handled correctly. + # Generate an L, U pair for invertible random matrix. + rng = np.random.default_rng(1738151906092737) + n = 13 + A = rng.uniform(size=(3, 2*n, 2*n)) + L, U = np.tril(A, k=-1) + np.eye(2*n), np.triu(A) + A = L @ U + # Create strided views of 3D array. + A_noncontig_c = A[:, ::2, ::2] + A_noncontig_f = np.asfortranarray(A)[:, 1::2, 1::2] + assert_allclose(sqrtm(A[:, ::2, ::2]), sqrtm(A_noncontig_c)) + assert_allclose(sqrtm(A[:, 1::2, 1::2]), sqrtm(A_noncontig_f)) + + def test_empty_sizes(self): + A = np.empty(shape=[4, 0, 5, 5], dtype=float) + assert_array_equal(sqrtm(A), A) + + def test_negative_strides(self): + rng = np.random.default_rng(1738151906092738) + A = rng.uniform(size=(3, 5, 5)) + A_negneg_orig = A[:, ::-1, ::-1] + A_negneg_copy = A[:, ::-1, ::-1].copy() + assert_allclose(sqrtm(A_negneg_orig), sqrtm(A_negneg_copy)) + + A_posneg_orig = A[:, :, ::-1] + A_posneg_copy = A[:, :, ::-1].copy() + assert_allclose(sqrtm(A_posneg_orig), sqrtm(A_posneg_copy)) + + A_negpos_orig = A[:, ::-1, :] + A_negpos_copy = A[:, ::-1, :].copy() + assert_allclose(sqrtm(A_negpos_orig), sqrtm(A_negpos_copy)) + + +class TestFractionalMatrixPower: + def test_round_trip_random_complex(self): + rng = np.random.default_rng(1234) + for p in range(1, 5): + for n in range(1, 5): + M_unscaled = (rng.standard_normal((n, n)) + + 1j * rng.standard_normal((n, n))) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_root = fractional_matrix_power(M, 1/p) + M_round_trip = np.linalg.matrix_power(M_root, p) + assert_allclose(M_round_trip, M) + + def test_round_trip_random_float(self): + # This test is more annoying because it can hit the branch cut; + # this happens when the matrix has an eigenvalue + # with no imaginary component and with a real negative component, + # and it means that the principal branch does not exist. + rng = np.random.default_rng(1234) + for p in range(1, 5): + for n in range(1, 5): + M_unscaled = rng.standard_normal((n, n)) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_root = fractional_matrix_power(M, 1/p) + M_round_trip = np.linalg.matrix_power(M_root, p) + assert_allclose(M_round_trip, M) + + def test_larger_abs_fractional_matrix_powers(self): + rng = np.random.default_rng(1234) + for n in (2, 3, 5): + for i in range(10): + M = rng.standard_normal((n, n)) + 1j * rng.standard_normal((n, n)) + M_one_fifth = fractional_matrix_power(M, 0.2) + # Test the round trip. + M_round_trip = np.linalg.matrix_power(M_one_fifth, 5) + assert_allclose(M, M_round_trip) + # Test a large abs fractional power. + X = fractional_matrix_power(M, -5.4) + Y = np.linalg.matrix_power(M_one_fifth, -27) + assert_allclose(X, Y) + # Test another large abs fractional power. + X = fractional_matrix_power(M, 3.8) + Y = np.linalg.matrix_power(M_one_fifth, 19) + assert_allclose(X, Y) + + def test_random_matrices_and_powers(self): + # Each independent iteration of this fuzz test picks random parameters. + # It tries to hit some edge cases. + rng = np.random.default_rng(1726500458620605) + nsamples = 20 + for i in range(nsamples): + # Sample a matrix size and a random real power. + n = rng.integers(1, 5) + p = rng.random() + + # Sample a random real or complex matrix. + matrix_scale = np.exp(rng.integers(-4, 5)) + A = rng.random(size=[n, n]) + if [True, False][rng.choice(2)]: + A = A + 1j * rng.random(size=[n, n]) + A = A * matrix_scale + + # Check a couple of analytically equivalent ways + # to compute the fractional matrix power. + # These can be compared because they both use the principal branch. + A_power = fractional_matrix_power(A, p) + A_logm = logm(A) + A_power_expm_logm = expm(A_logm * p) + assert_allclose(A_power, A_power_expm_logm) + + def test_al_mohy_higham_2012_experiment_1(self): + # Fractional powers of a tricky upper triangular matrix. + A = _get_al_mohy_higham_2012_experiment_1() + + # Test remainder matrix power. + A_funm_sqrt = funm(A, np.sqrt) + A_sqrtm = sqrtm(A) + A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5) + A_power = fractional_matrix_power(A, 0.5) + assert_allclose(A_rem_power, A_power, rtol=1e-11) + assert_allclose(A_sqrtm, A_power) + assert_allclose(A_sqrtm, A_funm_sqrt) + + # Test more fractional powers. + for p in (1/2, 5/3): + A_power = fractional_matrix_power(A, p) + A_round_trip = fractional_matrix_power(A_power, 1/p) + assert_allclose(A_round_trip, A, rtol=1e-2) + assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1)) + + def test_briggs_helper_function(self): + rng = np.random.default_rng(1234) + for a in rng.standard_normal(10) + 1j * rng.standard_normal(10): + for k in range(5): + x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k) + x_expected = a ** np.exp2(-k) - 1 + assert_allclose(x_observed, x_expected) + + def test_type_preservation_and_conversion(self): + # The fractional_matrix_power matrix function should preserve + # the type of a matrix whose eigenvalues + # are positive with zero imaginary part. + # Test this preservation for variously structured matrices. + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, 1]], + [[1, 0], [1, 1]], + [[2, 1], [1, 1]], + [[2, 3], [1, 2]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(not any(w.imag or w.real < 0 for w in W)) + + # Check various positive and negative powers + # with absolute values bigger and smaller than 1. + for p in (-2.4, -0.9, 0.2, 3.3): + + # check float type preservation + A = np.array(matrix_as_list, dtype=float) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char not in complex_dtype_chars) + + # check complex type preservation + A = np.array(matrix_as_list, dtype=complex) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + # check float->complex for the matrix negation + A = -np.array(matrix_as_list, dtype=float) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + def test_type_conversion_mixed_sign_or_complex_spectrum(self): + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, -1]], + [[0, 1], [1, 0]], + [[0, 1, 0], [0, 0, 1], [1, 0, 0]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(any(w.imag or w.real < 0 for w in W)) + + # Check various positive and negative powers + # with absolute values bigger and smaller than 1. + for p in (-2.4, -0.9, 0.2, 3.3): + + # check complex->complex + A = np.array(matrix_as_list, dtype=complex) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + # check float->complex + A = np.array(matrix_as_list, dtype=float) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + @pytest.mark.xfail(reason='Too unstable across LAPACKs.') + def test_singular(self): + # Negative fractional powers do not work with singular matrices. + for matrix_as_list in ( + [[0, 0], [0, 0]], + [[1, 1], [1, 1]], + [[1, 2], [3, 6]], + [[0, 0, 0], [0, 1, 1], [0, -1, 1]]): + + # Check fractional powers both for float and for complex types. + for newtype in (float, complex): + A = np.array(matrix_as_list, dtype=newtype) + for p in (-0.7, -0.9, -2.4, -1.3): + A_power = fractional_matrix_power(A, p) + assert_(np.isnan(A_power).all()) + for p in (0.2, 1.43): + A_power = fractional_matrix_power(A, p) + A_round_trip = fractional_matrix_power(A_power, 1/p) + assert_allclose(A_round_trip, A) + + def test_opposite_sign_complex_eigenvalues(self): + M = [[2j, 4], [0, -2j]] + R = [[1+1j, 2], [0, 1-1j]] + assert_allclose(np.dot(R, R), M, atol=1e-14) + assert_allclose(fractional_matrix_power(M, 0.5), R, atol=1e-14) + + +class TestExpM: + def test_zero(self): + a = array([[0.,0],[0,0]]) + assert_array_almost_equal(expm(a),[[1,0],[0,1]]) + + def test_single_elt(self): + elt = expm(1) + assert_allclose(elt, np.array([[np.e]])) + + @pytest.mark.parametrize('func', [expm, cosm, sinm, tanm, coshm, sinhm, tanhm]) + @pytest.mark.parametrize('dt',[int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('shape', [(0, 0), (1, 1)]) + def test_small_empty_matrix_input(self, func, dt, shape): + # regression test for gh-11082 / gh-20372 - test behavior of expm + # and related functions for small and zero-sized arrays. + A = np.zeros(shape, dtype=dt) + A0 = np.zeros((10, 10), dtype=dt) + result = func(A) + result0 = func(A0) + assert result.shape == shape + assert result.dtype == result0.dtype + + def test_2x2_input(self): + E = np.e + a = array([[1, 4], [1, 1]]) + aa = (E**4 + 1)/(2*E) + bb = (E**4 - 1)/E + assert_allclose(expm(a), array([[aa, bb], [bb/4, aa]])) + assert expm(a.astype(np.complex64)).dtype.char == 'F' + assert expm(a.astype(np.float32)).dtype.char == 'f' + + def test_nx2x2_input(self): + E = np.e + # These are integer matrices with integer eigenvalues + a = np.array([[[1, 4], [1, 1]], + [[1, 3], [1, -1]], + [[1, 3], [4, 5]], + [[1, 3], [5, 3]], + [[4, 5], [-3, -4]]], order='F') + # Exact results are computed symbolically + a_res = np.array([ + [[(E**4+1)/(2*E), (E**4-1)/E], + [(E**4-1)/4/E, (E**4+1)/(2*E)]], + [[1/(4*E**2)+(3*E**2)/4, (3*E**2)/4-3/(4*E**2)], + [E**2/4-1/(4*E**2), 3/(4*E**2)+E**2/4]], + [[3/(4*E)+E**7/4, -3/(8*E)+(3*E**7)/8], + [-1/(2*E)+E**7/2, 1/(4*E)+(3*E**7)/4]], + [[5/(8*E**2)+(3*E**6)/8, -3/(8*E**2)+(3*E**6)/8], + [-5/(8*E**2)+(5*E**6)/8, 3/(8*E**2)+(5*E**6)/8]], + [[-3/(2*E)+(5*E)/2, -5/(2*E)+(5*E)/2], + [3/(2*E)-(3*E)/2, 5/(2*E)-(3*E)/2]] + ]) + assert_allclose(expm(a), a_res) + + def test_readonly(self): + n = 7 + a = np.ones((n, n)) + a.flags.writeable = False + expm(a) + + @pytest.mark.fail_slow(5) + def test_gh18086(self): + A = np.zeros((400, 400), dtype=float) + rng = np.random.default_rng(100) + i = rng.integers(0, 399, 500) + j = rng.integers(0, 399, 500) + A[i, j] = rng.random(500) + # Problem appears when m = 9 + Am = np.empty((5, 400, 400), dtype=float) + Am[0] = A.copy() + m, s = pick_pade_structure(Am) + assert m == 9 + # Check that result is accurate + first_res = expm(A) + np.testing.assert_array_almost_equal(logm(first_res), A) + # Check that result is consistent + for i in range(5): + next_res = expm(A) + np.testing.assert_array_almost_equal(first_res, next_res) + + +class TestExpmFrechet: + + def test_expm_frechet(self): + # a test of the basic functionality + M = np.array([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [0, 0, 1, 2], + [0, 0, 5, 6], + ], dtype=float) + A = np.array([ + [1, 2], + [5, 6], + ], dtype=float) + E = np.array([ + [3, 4], + [7, 8], + ], dtype=float) + expected_expm = scipy.linalg.expm(A) + expected_frechet = scipy.linalg.expm(M)[:2, 2:] + for kwargs in ({}, {'method':'SPS'}, {'method':'blockEnlarge'}): + observed_expm, observed_frechet = expm_frechet(A, E, **kwargs) + assert_allclose(expected_expm, observed_expm) + assert_allclose(expected_frechet, observed_frechet) + + def test_small_norm_expm_frechet(self): + # methodically test matrices with a range of norms, for better coverage + M_original = np.array([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [0, 0, 1, 2], + [0, 0, 5, 6], + ], dtype=float) + A_original = np.array([ + [1, 2], + [5, 6], + ], dtype=float) + E_original = np.array([ + [3, 4], + [7, 8], + ], dtype=float) + A_original_norm_1 = scipy.linalg.norm(A_original, 1) + selected_m_list = [1, 3, 5, 7, 9, 11, 13, 15] + m_neighbor_pairs = zip(selected_m_list[:-1], selected_m_list[1:]) + for ma, mb in m_neighbor_pairs: + ell_a = scipy.linalg._expm_frechet.ell_table_61[ma] + ell_b = scipy.linalg._expm_frechet.ell_table_61[mb] + target_norm_1 = 0.5 * (ell_a + ell_b) + scale = target_norm_1 / A_original_norm_1 + M = scale * M_original + A = scale * A_original + E = scale * E_original + expected_expm = scipy.linalg.expm(A) + expected_frechet = scipy.linalg.expm(M)[:2, 2:] + observed_expm, observed_frechet = expm_frechet(A, E) + assert_allclose(expected_expm, observed_expm) + assert_allclose(expected_frechet, observed_frechet) + + def test_fuzz(self): + rng = np.random.default_rng(1726500908359153) + # try a bunch of crazy inputs + rfuncs = ( + rng.uniform, + rng.normal, + rng.standard_cauchy, + rng.exponential) + ntests = 100 + for i in range(ntests): + rfunc = rfuncs[rng.choice(4)] + target_norm_1 = rng.exponential() + n = rng.integers(2, 16) + A_original = rfunc(size=(n,n)) + E_original = rfunc(size=(n,n)) + A_original_norm_1 = scipy.linalg.norm(A_original, 1) + scale = target_norm_1 / A_original_norm_1 + A = scale * A_original + E = scale * E_original + M = np.vstack([ + np.hstack([A, E]), + np.hstack([np.zeros_like(A), A])]) + expected_expm = scipy.linalg.expm(A) + expected_frechet = scipy.linalg.expm(M)[:n, n:] + observed_expm, observed_frechet = expm_frechet(A, E) + assert_allclose(expected_expm, observed_expm, atol=5e-8) + assert_allclose(expected_frechet, observed_frechet, atol=1e-7) + + def test_problematic_matrix(self): + # this test case uncovered a bug which has since been fixed + A = np.array([ + [1.50591997, 1.93537998], + [0.41203263, 0.23443516], + ], dtype=float) + E = np.array([ + [1.87864034, 2.07055038], + [1.34102727, 0.67341123], + ], dtype=float) + scipy.linalg.norm(A, 1) + sps_expm, sps_frechet = expm_frechet( + A, E, method='SPS') + blockEnlarge_expm, blockEnlarge_frechet = expm_frechet( + A, E, method='blockEnlarge') + assert_allclose(sps_expm, blockEnlarge_expm) + assert_allclose(sps_frechet, blockEnlarge_frechet) + + @pytest.mark.slow + @pytest.mark.skip(reason='this test is deliberately slow') + def test_medium_matrix(self): + # profile this to see the speed difference + n = 1000 + rng = np.random.default_rng(1234) + A = rng.exponential(size=(n, n)) + E = rng.exponential(size=(n, n)) + sps_expm, sps_frechet = expm_frechet( + A, E, method='SPS') + blockEnlarge_expm, blockEnlarge_frechet = expm_frechet( + A, E, method='blockEnlarge') + assert_allclose(sps_expm, blockEnlarge_expm) + assert_allclose(sps_frechet, blockEnlarge_frechet) + + +def _help_expm_cond_search(A, A_norm, X, X_norm, eps, p): + p = np.reshape(p, A.shape) + p_norm = norm(p) + perturbation = eps * p * (A_norm / p_norm) + X_prime = expm(A + perturbation) + scaled_relative_error = norm(X_prime - X) / (X_norm * eps) + return -scaled_relative_error + + +def _normalized_like(A, B): + return A * (scipy.linalg.norm(B) / scipy.linalg.norm(A)) + + +def _relative_error(f, A, perturbation): + X = f(A) + X_prime = f(A + perturbation) + return norm(X_prime - X) / norm(X) + + +class TestExpmConditionNumber: + def test_expm_cond_smoke(self): + rng = np.random.default_rng(1234) + for n in range(1, 4): + A = rng.standard_normal((n, n)) + kappa = expm_cond(A) + assert_array_less(0, kappa) + + def test_expm_bad_condition_number(self): + A = np.array([ + [-1.128679820, 9.614183771e4, -4.524855739e9, 2.924969411e14], + [0, -1.201010529, 9.634696872e4, -4.681048289e9], + [0, 0, -1.132893222, 9.532491830e4], + [0, 0, 0, -1.179475332], + ]) + kappa = expm_cond(A) + assert_array_less(1e36, kappa) + + def test_univariate(self): + rng = np.random.default_rng(1234) + for x in np.linspace(-5, 5, num=11): + A = np.array([[x]]) + assert_allclose(expm_cond(A), abs(x)) + for x in np.logspace(-2, 2, num=11): + A = np.array([[x]]) + assert_allclose(expm_cond(A), abs(x)) + for i in range(10): + A = rng.standard_normal((1, 1)) + assert_allclose(expm_cond(A), np.absolute(A)[0, 0]) + + @pytest.mark.slow + def test_expm_cond_fuzz(self): + rng = np.random.RandomState(12345) + eps = 1e-5 + nsamples = 10 + for i in range(nsamples): + n = rng.randint(2, 5) + A = rng.randn(n, n) + A_norm = scipy.linalg.norm(A) + X = expm(A) + X_norm = scipy.linalg.norm(X) + kappa = expm_cond(A) + + # Look for the small perturbation that gives the greatest + # relative error. + f = functools.partial(_help_expm_cond_search, + A, A_norm, X, X_norm, eps) + guess = np.ones(n*n) + out = minimize(f, guess, method='L-BFGS-B') + xopt = out.x + yopt = f(xopt) + p_best = eps * _normalized_like(np.reshape(xopt, A.shape), A) + p_best_relerr = _relative_error(expm, A, p_best) + assert_allclose(p_best_relerr, -yopt * eps) + + # Check that the identified perturbation indeed gives greater + # relative error than random perturbations with similar norms. + for j in range(5): + p_rand = eps * _normalized_like(rng.randn(*A.shape), A) + assert_allclose(norm(p_best), norm(p_rand)) + p_rand_relerr = _relative_error(expm, A, p_rand) + assert_array_less(p_rand_relerr, p_best_relerr) + + # The greatest relative error should not be much greater than + # eps times the condition number kappa. + # In the limit as eps approaches zero it should never be greater. + assert_array_less(p_best_relerr, (1 + 2*eps) * eps * kappa) + + +class TestKhatriRao: + + def test_basic(self): + a = khatri_rao(array([[1, 2], [3, 4]]), + array([[5, 6], [7, 8]])) + + assert_array_equal(a, array([[5, 12], + [7, 16], + [15, 24], + [21, 32]])) + + b = khatri_rao(np.empty([2, 2]), np.empty([2, 2])) + assert_array_equal(b.shape, (4, 2)) + + def test_number_of_columns_equality(self): + with pytest.raises(ValueError): + a = array([[1, 2, 3], + [4, 5, 6]]) + b = array([[1, 2], + [3, 4]]) + khatri_rao(a, b) + + def test_to_assure_2d_array(self): + with pytest.raises(ValueError): + # both arrays are 1-D + a = array([1, 2, 3]) + b = array([4, 5, 6]) + khatri_rao(a, b) + + with pytest.raises(ValueError): + # first array is 1-D + a = array([1, 2, 3]) + b = array([ + [1, 2, 3], + [4, 5, 6] + ]) + khatri_rao(a, b) + + with pytest.raises(ValueError): + # second array is 1-D + a = array([ + [1, 2, 3], + [7, 8, 9] + ]) + b = array([4, 5, 6]) + khatri_rao(a, b) + + def test_equality_of_two_equations(self): + a = array([[1, 2], [3, 4]]) + b = array([[5, 6], [7, 8]]) + + res1 = khatri_rao(a, b) + res2 = np.vstack([np.kron(a[:, k], b[:, k]) + for k in range(b.shape[1])]).T + + assert_array_equal(res1, res2) + + def test_empty(self): + a = np.empty((0, 2)) + b = np.empty((3, 2)) + res = khatri_rao(a, b) + assert_allclose(res, np.empty((0, 2))) + + a = np.empty((3, 0)) + b = np.empty((5, 0)) + res = khatri_rao(a, b) + assert_allclose(res, np.empty((15, 0))) + +@pytest.mark.parametrize('func', + [logm, sqrtm, signm]) +def test_disp_dep(func): + with pytest.deprecated_call(): + func(np.eye(2), disp=False) + +def test_blocksize_dep(): + with pytest.deprecated_call(): + sqrtm(np.eye(2), blocksize=10) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py new file mode 100644 index 0000000000000000000000000000000000000000..ad8f0b6f9ab99138ae9275abacc4be8613460b8a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py @@ -0,0 +1,136 @@ +"""Test functions for linalg.matmul_toeplitz function +""" + +import numpy as np +from scipy.linalg import toeplitz, matmul_toeplitz + +from pytest import raises as assert_raises +from numpy.testing import assert_allclose + + +class TestMatmulToeplitz: + + def setup_method(self): + self.rng = np.random.RandomState(42) + self.tolerance = 1.5e-13 + + def test_real(self): + cases = [] + + n = 1 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, False)) + + n = 2 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, False)) + + n = 101 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, True)) + + n = 1000 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, False)) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, self.rng.randint(1, 10))) + cases.append((x, c, r, False)) + + n = 100 + c = self.rng.normal(size=(n, 1)) + r = self.rng.normal(size=(n, 1)) + x = self.rng.normal(size=(n, self.rng.randint(1, 10))) + cases.append((x, c, r, True)) + + n = 100 + c = self.rng.normal(size=(n, 1)) + r = None + x = self.rng.normal(size=(n, self.rng.randint(1, 10))) + cases.append((x, c, r, True, -1)) + + n = 100 + c = self.rng.normal(size=(n, 1)) + r = None + x = self.rng.normal(size=n) + cases.append((x, c, r, False)) + + n = 101 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n-27) + x = self.rng.normal(size=(n-27, 1)) + cases.append((x, c, r, True)) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n//4) + x = self.rng.normal(size=(n//4, self.rng.randint(1, 10))) + cases.append((x, c, r, True)) + + [self.do(*i) for i in cases] + + def test_complex(self): + n = 127 + c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j + r = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j + x = self.rng.normal(size=(n, 3)) + self.rng.normal(size=(n, 3))*1j + self.do(x, c, r, False) + + n = 100 + c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j + r = self.rng.normal(size=(n//2, 1)) +\ + self.rng.normal(size=(n//2, 1))*1j + x = self.rng.normal(size=(n//2, 3)) +\ + self.rng.normal(size=(n//2, 3))*1j + self.do(x, c, r, False) + + def test_empty(self): + c = [] + r = [] + x = [] + self.do(x, c, r, False) + + x = np.empty((0, 0)) + self.do(x, c, r, False) + + def test_exceptions(self): + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=2*n) + x = self.rng.normal(size=n) + assert_raises(ValueError, matmul_toeplitz, (c, r), x, True) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=n-1) + assert_raises(ValueError, matmul_toeplitz, (c, r), x, True) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n//2) + x = self.rng.normal(size=n//2-1) + assert_raises(ValueError, matmul_toeplitz, (c, r), x, True) + + # For toeplitz matrices, matmul_toeplitz() should be equivalent to @. + def do(self, x, c, r=None, check_finite=False, workers=None): + c = np.ravel(c) + if r is None: + actual = matmul_toeplitz(c, x, check_finite, workers) + else: + r = np.ravel(r) + actual = matmul_toeplitz((c, r), x, check_finite) + desired = toeplitz(c, r) @ x + assert_allclose(actual, desired, + rtol=self.tolerance, atol=self.tolerance) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_procrustes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..d5fe6ff026241779291114683503378cfb9c04ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_procrustes.py @@ -0,0 +1,209 @@ +from itertools import product, permutations + +import numpy as np +import pytest +from numpy.testing import assert_allclose +from pytest import raises as assert_raises + +from scipy.linalg import orthogonal_procrustes +from scipy.sparse._sputils import matrix +from scipy._lib._array_api import make_xp_test_case, xp_assert_close +from scipy.conftest import skip_xp_invalid_arg + +def _centered(A, xp): + mu = xp.mean(A, axis=0) + return A - mu, mu + +@make_xp_test_case(orthogonal_procrustes) +class TestOrthogonalProcrustes: + def test_orthogonal_procrustes_ndim_too_small(self, xp): + rng = np.random.RandomState(1234) + A = xp.asarray(rng.randn(3)) + B = xp.asarray(rng.randn(3)) + assert_raises(ValueError, orthogonal_procrustes, A, B) + + def test_orthogonal_procrustes_shape_mismatch(self, xp): + rng = np.random.RandomState(1234) + shapes = ((3, 3), (3, 4), (4, 3), (4, 4)) + for a, b in permutations(shapes, 2): + A = xp.asarray(rng.randn(*a)) + B = xp.asarray(rng.randn(*b)) + assert_raises(ValueError, orthogonal_procrustes, A, B) + + def test_orthogonal_procrustes_checkfinite_exception(self, xp): + rng = np.random.RandomState(1234) + m, n = 2, 3 + A_good = rng.randn(m, n) + B_good = rng.randn(m, n) + for bad_value in np.inf, -np.inf, np.nan: + A_bad = A_good.copy() + A_bad[1, 2] = bad_value + B_bad = B_good.copy() + B_bad[1, 2] = bad_value + for A, B in ((A_good, B_bad), (A_bad, B_good), (A_bad, B_bad)): + assert_raises(ValueError, orthogonal_procrustes, xp.asarray(A), + xp.asarray(B)) + + def test_orthogonal_procrustes_scale_invariance(self, xp): + rng = np.random.RandomState(1234) + m, n = 4, 3 + for i in range(3): + A_orig = xp.asarray(rng.randn(m, n)) + B_orig = xp.asarray(rng.randn(m, n)) + R_orig, s = orthogonal_procrustes(A_orig, B_orig) + for A_scale in np.square(rng.randn(3)): + for B_scale in np.square(rng.randn(3)): + R, s = orthogonal_procrustes(A_orig * xp.asarray(A_scale), + B_orig * xp.asarray(B_scale)) + xp_assert_close(R, R_orig) + + @skip_xp_invalid_arg() + def test_orthogonal_procrustes_array_conversion(self): + rng = np.random.RandomState(1234) + for m, n in ((6, 4), (4, 4), (4, 6)): + A_arr = rng.randn(m, n) + B_arr = rng.randn(m, n) + As = (A_arr, A_arr.tolist(), matrix(A_arr)) + Bs = (B_arr, B_arr.tolist(), matrix(B_arr)) + R_arr, s = orthogonal_procrustes(A_arr, B_arr) + AR_arr = A_arr.dot(R_arr) + for A, B in product(As, Bs): + R, s = orthogonal_procrustes(A, B) + AR = A_arr.dot(R) + assert_allclose(AR, AR_arr) + + def test_orthogonal_procrustes(self, xp): + rng = np.random.RandomState(1234) + for m, n in ((6, 4), (4, 4), (4, 6)): + # Sample a random target matrix. + B = xp.asarray(rng.randn(m, n)) + # Sample a random orthogonal matrix + # by computing eigh of a sampled symmetric matrix. + X = xp.asarray(rng.randn(n, n)) + w, V = xp.linalg.eigh(X.T + X) + xp_assert_close(xp.linalg.inv(V), V.T) + # Compute a matrix with a known orthogonal transformation that gives B. + A = B @ V.T + # Check that an orthogonal transformation from A to B can be recovered. + R, s = orthogonal_procrustes(A, B) + xp_assert_close(xp.linalg.inv(R), R.T) + xp_assert_close(A @ R, B) + # Create a perturbed input matrix. + A_perturbed = A + 1e-2 * xp.asarray(rng.randn(m, n)) + # Check that the orthogonal procrustes function can find an orthogonal + # transformation that is better than the orthogonal transformation + # computed from the original input matrix. + R_prime, s = orthogonal_procrustes(A_perturbed, B) + xp_assert_close(xp.linalg.inv(R_prime), R_prime.T) + # Compute the naive and optimal transformations of the perturbed input. + naive_approx = A_perturbed @ R + optim_approx = A_perturbed @ R_prime + # Compute the Frobenius norm errors of the matrix approximations. + naive_approx_error = xp.linalg.matrix_norm(naive_approx - B, ord='fro') + optim_approx_error = xp.linalg.matrix_norm(optim_approx - B, ord='fro') + # Check that the orthogonal Procrustes approximation is better. + assert xp.all(optim_approx_error < naive_approx_error) + + def test_orthogonal_procrustes_exact_example(self, xp): + # Check a small application. + # It uses translation, scaling, reflection, and rotation. + # + # | + # a b | + # | + # d c | w + # | + # --------+--- x ----- z --- + # | + # | y + # | + # + A_orig = xp.asarray([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=xp.float64) + B_orig = xp.asarray([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=xp.float64) + A, A_mu = _centered(A_orig, xp) + B, B_mu = _centered(B_orig, xp) + R, s = orthogonal_procrustes(A, B) + scale = s / xp.linalg.matrix_norm(A)**2 + B_approx = scale * A @ R + B_mu + xp_assert_close(B_approx, B_orig, atol=1e-8) + + def test_orthogonal_procrustes_stretched_example(self, xp): + # Try again with a target with a stretched y axis. + A_orig = xp.asarray([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=xp.float64) + B_orig = xp.asarray([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=xp.float64) + A, A_mu = _centered(A_orig, xp) + B, B_mu = _centered(B_orig, xp) + R, s = orthogonal_procrustes(A, B) + scale = s / xp.linalg.matrix_norm(A)**2 + B_approx = scale * A @ R + B_mu + expected = xp.asarray([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=xp.float64) + xp_assert_close(B_approx, expected, atol=1e-8) + # Check disparity symmetry. + expected_disparity = xp.asarray(0.4501246882793018, dtype=xp.float64)[()] + AB_disparity = (xp.linalg.matrix_norm(B_approx - B_orig) + / xp.linalg.matrix_norm(B))**2 + xp_assert_close(AB_disparity, expected_disparity) + R, s = orthogonal_procrustes(B, A) + scale = s / xp.linalg.matrix_norm(B)**2 + A_approx = scale * B @ R + A_mu + BA_disparity = (xp.linalg.matrix_norm(A_approx - A_orig) + / xp.linalg.matrix_norm(A))**2 + xp_assert_close(BA_disparity, expected_disparity) + + def test_orthogonal_procrustes_skbio_example(self, xp): + # This transformation is also exact. + # It uses translation, scaling, and reflection. + # + # | + # | a + # | b + # | c d + # --+--------- + # | + # | w + # | + # | x + # | + # | z y + # | + # + A_orig = xp.asarray([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=xp.float64) + B_orig = xp.asarray([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=xp.float64) + B_standardized = xp.asarray([[-0.13363062, 0.6681531], + [-0.13363062, 0.13363062], + [-0.13363062, -0.40089186], + [0.40089186, -0.40089186]], dtype=xp.float64) + A, A_mu = _centered(A_orig, xp) + B, B_mu = _centered(B_orig, xp) + R, s = orthogonal_procrustes(A, B) + scale = s / xp.linalg.matrix_norm(A)**2 + B_approx = scale * A @ R + B_mu + xp_assert_close(B_approx, B_orig) + xp_assert_close(B / xp.linalg.matrix_norm(B), B_standardized) + + def test_empty(self, xp): + a = xp.empty((0, 0)) + r, s = orthogonal_procrustes(a, a) + xp_assert_close(r, xp.empty((0, 0))) + + a = xp.empty((0, 3)) + r, s = orthogonal_procrustes(a, a) + xp_assert_close(r, xp.eye(3)) + + @pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)]) + def test_unitary(self, shape, xp): + # gh-12071 added support for unitary matrices; check that it + # works as intended. + m, n = shape + rng = np.random.default_rng(589234981235) + A = xp.asarray(rng.random(shape) + rng.random(shape) * 1j) + Q = xp.asarray(rng.random((n, n)) + rng.random((n, n)) * 1j) + Q, _ = xp.linalg.qr(Q) + B = A @ Q + R, scale = orthogonal_procrustes(A, B) + xp_assert_close(R @ xp.conj(R).T, xp.eye(n, dtype=xp.complex128), atol=1e-14) + xp_assert_close(A @ Q, B) + if shape != (4, 5): # solution is unique + xp_assert_close(R, Q) + _, s, _ = xp.linalg.svd(xp.conj(A).T @ B) + xp_assert_close(scale, xp.sum(s)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_sketches.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_sketches.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce87d6fea79f52f6db3f9723e8a6a03a8be4a84 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_sketches.py @@ -0,0 +1,119 @@ +"""Tests for _sketches.py.""" + +import numpy as np +from numpy.testing import assert_, assert_equal +from scipy.linalg import clarkson_woodruff_transform +from scipy.linalg._sketches import cwt_matrix +from scipy.sparse import issparse, rand +from scipy.sparse.linalg import norm + + +class TestClarksonWoodruffTransform: + """ + Testing the Clarkson Woodruff Transform + """ + # set seed for generating test matrices + rng = np.random.default_rng(1179103485) + + # Test matrix parameters + n_rows = 2000 + n_cols = 100 + density = 0.1 + + # Sketch matrix dimensions + n_sketch_rows = 200 + + # Seeds to test with + seeds = [1755490010, 934377150, 1391612830, 1752708722, 2008891431, + 1302443994, 1521083269, 1501189312, 1126232505, 1533465685] + + A_dense = rng.random((n_rows, n_cols)) + A_csc = rand( + n_rows, n_cols, density=density, format='csc', random_state=rng, + ) + A_csr = rand( + n_rows, n_cols, density=density, format='csr', random_state=rng, + ) + A_coo = rand( + n_rows, n_cols, density=density, format='coo', random_state=rng, + ) + + # Collect the test matrices + test_matrices = [ + A_dense, A_csc, A_csr, A_coo, + ] + + # Test vector with norm ~1 + x = rng.random((n_rows, 1)) / np.sqrt(n_rows) + del rng # Not deterministic in pytest-run-parallel + + def test_sketch_dimensions(self): + for A in self.test_matrices: + for seed in self.seeds: + # seed to ensure backwards compatibility post SPEC7 + sketch = clarkson_woodruff_transform( + A, self.n_sketch_rows, seed=seed + ) + assert_(sketch.shape == (self.n_sketch_rows, self.n_cols)) + + def test_seed_returns_identical_transform_matrix(self): + for seed in self.seeds: + S1 = cwt_matrix( + self.n_sketch_rows, self.n_rows, rng=seed + ).toarray() + S2 = cwt_matrix( + self.n_sketch_rows, self.n_rows, rng=seed + ).toarray() + assert_equal(S1, S2) + + def test_seed_returns_identically(self): + for A in self.test_matrices: + for seed in self.seeds: + sketch1 = clarkson_woodruff_transform( + A, self.n_sketch_rows, rng=seed + ) + sketch2 = clarkson_woodruff_transform( + A, self.n_sketch_rows, rng=seed + ) + if issparse(sketch1): + sketch1 = sketch1.toarray() + if issparse(sketch2): + sketch2 = sketch2.toarray() + assert_equal(sketch1, sketch2) + + def test_sketch_preserves_frobenius_norm(self): + # Given the probabilistic nature of the sketches + # we run the test multiple times and check that + # we pass all/almost all the tries. + n_errors = 0 + for A in self.test_matrices: + if issparse(A): + true_norm = norm(A) + else: + true_norm = np.linalg.norm(A) + for seed in self.seeds: + sketch = clarkson_woodruff_transform( + A, self.n_sketch_rows, rng=seed, + ) + if issparse(sketch): + sketch_norm = norm(sketch) + else: + sketch_norm = np.linalg.norm(sketch) + + if np.abs(true_norm - sketch_norm) > 0.1 * true_norm: + n_errors += 1 + assert_(n_errors == 0) + + def test_sketch_preserves_vector_norm(self): + n_errors = 0 + n_sketch_rows = int(np.ceil(2. / (0.01 * 0.5**2))) + true_norm = np.linalg.norm(self.x) + for seed in self.seeds: + sketch = clarkson_woodruff_transform( + self.x, n_sketch_rows, rng=seed, + ) + sketch_norm = np.linalg.norm(sketch) + + if np.abs(true_norm - sketch_norm) > 0.5 * true_norm: + n_errors += 1 + assert_(n_errors == 0) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_solve_toeplitz.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_solve_toeplitz.py new file mode 100644 index 0000000000000000000000000000000000000000..61333c92cea93d070a109f4af0acb78128e97fa7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_solve_toeplitz.py @@ -0,0 +1,137 @@ +"""Test functions for linalg._solve_toeplitz module +""" +import numpy as np +from scipy.linalg._solve_toeplitz import levinson +from scipy.linalg import solve, toeplitz, solve_toeplitz +from numpy.testing import assert_equal, assert_allclose + +import pytest +from pytest import raises as assert_raises + + +def test_solve_equivalence(): + # For toeplitz matrices, solve_toeplitz() should be equivalent to solve(). + random = np.random.RandomState(1234) + for n in (1, 2, 3, 10): + c = random.randn(n) + if random.rand() < 0.5: + c = c + 1j * random.randn(n) + r = random.randn(n) + if random.rand() < 0.5: + r = r + 1j * random.randn(n) + y = random.randn(n) + if random.rand() < 0.5: + y = y + 1j * random.randn(n) + + # Check equivalence when both the column and row are provided. + actual = solve_toeplitz((c,r), y) + desired = solve(toeplitz(c, r=r), y) + assert_allclose(actual, desired) + + # Check equivalence when the column is provided but not the row. + actual = solve_toeplitz(c, b=y) + desired = solve(toeplitz(c), y) + assert_allclose(actual, desired) + + +def test_multiple_rhs(): + random = np.random.RandomState(1234) + c = random.randn(4) + r = random.randn(4) + for offset in [0, 1j]: + for yshape in ((4,), (4, 3)): + y = random.randn(*yshape) + offset + actual = solve_toeplitz((c,r), b=y) + desired = solve(toeplitz(c, r=r), y) + assert_equal(actual.shape, yshape) + assert_equal(desired.shape, yshape) + assert_allclose(actual, desired) + + +def test_native_list_arguments(): + c = [1,2,4,7] + r = [1,3,9,12] + y = [5,1,4,2] + actual = solve_toeplitz((c,r), y) + desired = solve(toeplitz(c, r=r), y) + assert_allclose(actual, desired) + + +def test_zero_diag_error(): + # The Levinson-Durbin implementation fails when the diagonal is zero. + random = np.random.RandomState(1234) + n = 4 + c = random.randn(n) + r = random.randn(n) + y = random.randn(n) + c[0] = 0 + assert_raises(np.linalg.LinAlgError, + solve_toeplitz, (c, r), b=y) + + +def test_wikipedia_counterexample(): + # The Levinson-Durbin implementation also fails in other cases. + # This example is from the talk page of the wikipedia article. + random = np.random.RandomState(1234) + c = [2, 2, 1] + y = random.randn(3) + assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y) + + +def test_reflection_coeffs(): + # check that the partial solutions are given by the reflection + # coefficients + + random = np.random.RandomState(1234) + y_d = random.randn(10) + y_z = random.randn(10) + 1j + reflection_coeffs_d = [1] + reflection_coeffs_z = [1] + for i in range(2, 10): + reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1]) + reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1]) + + y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1])) + y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1])) + _, ref_d = levinson(y_d_concat, b=y_d[1:]) + _, ref_z = levinson(y_z_concat, b=y_z[1:]) + + assert_allclose(reflection_coeffs_d, ref_d[:-1]) + assert_allclose(reflection_coeffs_z, ref_z[:-1]) + + +@pytest.mark.xfail(reason='Instability of Levinson iteration') +def test_unstable(): + # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of + # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with + # Partial Pivoting for Matrices with Displacement Structure" + # Mathematics of Computation, 64, 212 (1995), pp 1557-1576 + # which can be unstable for levinson recursion. + + # other fast toeplitz solvers such as GKO or Burg should be better. + random = np.random.RandomState(1234) + n = 100 + c = 0.9 ** (np.arange(n)**2) + y = random.randn(n) + + solution1 = solve_toeplitz(c, b=y) + solution2 = solve(toeplitz(c), y) + + assert_allclose(solution1, solution2) + + +@pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64]) +@pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) +def test_empty(dt_c, dt_b): + c = np.array([], dtype=dt_c) + b = np.array([], dtype=dt_b) + x = solve_toeplitz(c, b) + assert x.shape == (0,) + assert x.dtype == solve_toeplitz(np.array([2, 1], dtype=dt_c), + np.ones(2, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x1 = solve_toeplitz(c, b) + assert x1.shape == (0, 0) + assert x1.dtype == x.dtype + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_solvers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..557f2658c510a405e562965d10ff3f6607d38046 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_solvers.py @@ -0,0 +1,862 @@ +import os +import numpy as np + +from numpy.testing import assert_array_almost_equal, assert_allclose +import pytest +from pytest import raises as assert_raises + +from scipy.linalg import solve_sylvester +from scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunov +from scipy.linalg import solve_continuous_are, solve_discrete_are +from scipy.linalg import block_diag, solve, LinAlgError +from scipy.sparse._sputils import matrix +from scipy.conftest import skip_xp_invalid_arg + + +# dtypes for testing size-0 case following precedent set in gh-20295 +dtypes = [int, float, np.float32, complex, np.complex64] + + +def _load_data(name): + """ + Load npz data file under data/ + Returns a copy of the data, rather than keeping the npz file open. + """ + filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', name) + with np.load(filename) as f: + return dict(f.items()) + + +class TestSolveLyapunov: + + cases = [ + # empty case + (np.empty((0, 0)), + np.empty((0, 0))), + (np.array([[1, 2], [3, 4]]), + np.array([[9, 10], [11, 12]])), + # a, q all complex. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a real; q complex. + (np.array([[1.0, 2.0], [3.0, 5.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a complex; q real. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[2.0, 2.0], [-1.0, 2.0]])), + # An example from Kitagawa, 1977 + (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3], + [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]), + np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3], + [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])), + # Companion matrix example. a complex; q real; a.shape[0] = 11 + (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j, + 0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j, + 0.010+0.j], + [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, + 0.000+0.j]]), + np.eye(11)), + # https://github.com/scipy/scipy/issues/4176 + (matrix([[0, 1], [-1/2, -1]]), + (matrix([0, 3]).T @ matrix([0, 3]).T.T)), + # https://github.com/scipy/scipy/issues/4176 + (matrix([[0, 1], [-1/2, -1]]), + (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))), + ] + + def test_continuous_squareness_and_shape(self): + nsq = np.ones((3, 2)) + sq = np.eye(3) + assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq) + assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq) + assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2)) + + def check_continuous_case(self, a, q): + x = solve_continuous_lyapunov(a, q) + assert_array_almost_equal( + np.dot(a, x) + np.dot(x, a.conj().transpose()), q) + + def check_discrete_case(self, a, q, method=None): + x = solve_discrete_lyapunov(a, q, method=method) + assert_array_almost_equal( + np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q) + + @skip_xp_invalid_arg + def test_cases(self): + for case in self.cases: + self.check_continuous_case(case[0], case[1]) + self.check_discrete_case(case[0], case[1]) + self.check_discrete_case(case[0], case[1], method='direct') + self.check_discrete_case(case[0], case[1], method='bilinear') + + @pytest.mark.parametrize("dtype_a", dtypes) + @pytest.mark.parametrize("dtype_q", dtypes) + def test_size_0(self, dtype_a, dtype_q): + rng = np.random.default_rng(234598235) + + a = np.zeros((0, 0), dtype=dtype_a) + q = np.zeros((0, 0), dtype=dtype_q) + res = solve_continuous_lyapunov(a, q) + + a = (rng.random((5, 5))*100).astype(dtype_a) + q = (rng.random((5, 5))*100).astype(dtype_q) + ref = solve_continuous_lyapunov(a, q) + + assert res.shape == (0, 0) + assert res.dtype == ref.dtype + + +class TestSolveContinuousAre: + mat6 = _load_data('carex_6_data.npz') + mat15 = _load_data('carex_15_data.npz') + mat18 = _load_data('carex_18_data.npz') + mat19 = _load_data('carex_19_data.npz') + mat20 = _load_data('carex_20_data.npz') + cases = [ + # Carex examples taken from (with default parameters): + # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark + # Examples for the Numerical Solution of Algebraic Riccati + # Equations II: Continuous-Time Case', Tech. Report SPC 95_23, + # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995. + # + # The format of the data is (a, b, q, r, knownfailure), where + # knownfailure is None if the test passes or a string + # indicating the reason for failure. + # + # Test Case 0: carex #1 + (np.diag([1.], 1), + np.array([[0], [1]]), + block_diag(1., 2.), + 1, + None), + # Test Case 1: carex #2 + (np.array([[4, 3], [-4.5, -3.5]]), + np.array([[1], [-1]]), + np.array([[9, 6], [6, 4.]]), + 1, + None), + # Test Case 2: carex #3 + (np.array([[0, 1, 0, 0], + [0, -1.89, 0.39, -5.53], + [0, -0.034, -2.98, 2.43], + [0.034, -0.0011, -0.99, -0.21]]), + np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]), + np.array([[2.313, 2.727, 0.688, 0.023], + [2.727, 4.271, 1.148, 0.323], + [0.688, 1.148, 0.313, 0.102], + [0.023, 0.323, 0.102, 0.083]]), + np.eye(2), + None), + # Test Case 3: carex #4 + (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0], + [0.522, -1.051, 0.596, 0, 0, 0, 0, 0], + [0, 0.522, -1.118, 0.596, 0, 0, 0, 0], + [0, 0, 0.522, -1.548, 0.718, 0, 0, 0], + [0, 0, 0, 0.922, -1.64, 0.799, 0, 0], + [0, 0, 0, 0, 0.922, -1.721, 0.901, 0], + [0, 0, 0, 0, 0, 0.922, -1.823, 1.021], + [0, 0, 0, 0, 0, 0, 0.922, -1.943]]), + np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00], + [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]] + ).T * 0.001, + np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1], + [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0], + [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0], + [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]), + np.eye(2), + None), + # Test Case 4: carex #5 + (np.array( + [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870], + [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970], + [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680], + [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390], + [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400], + [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.], + [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0], + [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0], + [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]), + np.array([[0.010, -0.011, -0.151], + [0.003, -0.021, 0.000], + [0.009, -0.059, 0.000], + [0.024, -0.162, 0.000], + [0.068, -0.445, 0.000], + [0.000, 0.000, 0.000], + [0.000, 0.000, 0.000], + [0.000, 0.000, 0.000], + [0.000, 0.000, 0.000]]), + np.eye(9), + np.eye(3), + None), + # Test Case 5: carex #6 + (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None), + # Test Case 6: carex #7 + (np.array([[1, 0], [0, -2.]]), + np.array([[1e-6], [0]]), + np.ones((2, 2)), + 1., + 'Bad residual accuracy'), + # Test Case 7: carex #8 + (block_diag(-0.1, -0.02), + np.array([[0.100, 0.000], [0.001, 0.010]]), + np.array([[100, 1000], [1000, 10000]]), + np.ones((2, 2)) + block_diag(1e-6, 0), + None), + # Test Case 8: carex #9 + (np.array([[0, 1e6], [0, 0]]), + np.array([[0], [1.]]), + np.eye(2), + 1., + None), + # Test Case 9: carex #10 + (np.array([[1.0000001, 1], [1., 1.0000001]]), + np.eye(2), + np.eye(2), + np.eye(2), + None), + # Test Case 10: carex #11 + (np.array([[3, 1.], [4, 2]]), + np.array([[1], [1]]), + np.array([[-11, -5], [-5, -2.]]), + 1., + None), + # Test Case 11: carex #12 + (np.array([[7000000., 2000000., -0.], + [2000000., 6000000., -2000000.], + [0., -2000000., 5000000.]]) / 3, + np.eye(3), + np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot( + np.diag([1e-6, 1, 1e6])).dot( + np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9, + np.eye(3) * 1e6, + 'Bad Residual Accuracy'), + # Test Case 12: carex #13 + (np.array([[0, 0.4, 0, 0], + [0, 0, 0.345, 0], + [0, -0.524e6, -0.465e6, 0.262e6], + [0, 0, 0, -1e6]]), + np.array([[0, 0, 0, 1e6]]).T, + np.diag([1, 0, 1, 0]), + 1., + None), + # Test Case 13: carex #14 + (np.array([[-1e-6, 1, 0, 0], + [-1, -1e-6, 0, 0], + [0, 0, 1e-6, 1], + [0, 0, -1, 1e-6]]), + np.ones((4, 1)), + np.ones((4, 4)), + 1., + None), + # Test Case 14: carex #15 + (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None), + # Test Case 15: carex #16 + (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90( + block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1), + np.eye(64), + np.eye(64), + np.eye(64), + None), + # Test Case 16: carex #17 + (np.diag(np.ones((20, )), 1), + np.flipud(np.eye(21, 1)), + np.eye(21, 1) * np.eye(21, 1).T, + 1, + 'Bad Residual Accuracy'), + # Test Case 17: carex #18 + (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None), + # Test Case 18: carex #19 + (mat19['A'], mat19['B'], mat19['Q'], mat19['R'], + 'Bad Residual Accuracy'), + # Test Case 19: carex #20 + (mat20['A'], mat20['B'], mat20['Q'], mat20['R'], + 'Bad Residual Accuracy') + ] + # Makes the minimum precision requirements customized to the test. + # Here numbers represent the number of decimals that agrees with zero + # matrix when the solution x is plugged in to the equation. + # + # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2 + # + # If the test is failing use "None" for that entry. + # + min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14, + None, 9, 14, 13, 14, None, 12, None, None) + + @pytest.mark.parametrize("j, case", enumerate(cases)) + def test_solve_continuous_are(self, j, case): + """Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true""" + a, b, q, r, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + dec = self.min_decimal[j] + x = solve_continuous_are(a, b, q, r) + res = x @ a + a.conj().T @ x + q + out_fact = x @ b + res -= out_fact @ solve(np.atleast_2d(r), out_fact.conj().T) + assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + + +class TestSolveDiscreteAre: + cases = [ + # Darex examples taken from (with default parameters): + # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark + # Examples for the Numerical Solution of Algebraic Riccati + # Equations II: Discrete-Time Case', Tech. Report SPC 95_23, + # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995. + # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the + # Discrete-Time Algebraic Riccati Equation to Enhance Stability + # of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4) + # + # The format of the data is (a, b, q, r, knownfailure), where + # knownfailure is None if the test passes or a string + # indicating the reason for failure. + # + # TEST CASE 0 : Complex a; real b, q, r + (np.array([[2, 1-2j], [0, -3j]]), + np.array([[0], [1]]), + np.array([[1, 0], [0, 2]]), + np.array([[1]]), + None), + # TEST CASE 1 :Real a, q, r; complex b + (np.array([[2, 1], [0, -1]]), + np.array([[-2j], [1j]]), + np.array([[1, 0], [0, 2]]), + np.array([[1]]), + None), + # TEST CASE 2 : Real a, b; complex q, r + (np.array([[3, 1], [0, -1]]), + np.array([[1, 2], [1, 3]]), + np.array([[1, 1+1j], [1-1j, 2]]), + np.array([[2, -2j], [2j, 3]]), + None), + # TEST CASE 3 : User-reported gh-2251 (Trac #1732) + (np.array([[0.63399379, 0.54906824, 0.76253406], + [0.5404729, 0.53745766, 0.08731853], + [0.27524045, 0.84922129, 0.4681622]]), + np.array([[0.96861695], [0.05532739], [0.78934047]]), + np.eye(3), + np.eye(1), + None), + # TEST CASE 4 : darex #1 + (np.array([[4, 3], [-4.5, -3.5]]), + np.array([[1], [-1]]), + np.array([[9, 6], [6, 4]]), + np.array([[1]]), + None), + # TEST CASE 5 : darex #2 + (np.array([[0.9512, 0], [0, 0.9048]]), + np.array([[4.877, 4.877], [-1.1895, 3.569]]), + np.array([[0.005, 0], [0, 0.02]]), + np.array([[1/3, 0], [0, 3]]), + None), + # TEST CASE 6 : darex #3 + (np.array([[2, -1], [1, 0]]), + np.array([[1], [0]]), + np.array([[0, 0], [0, 1]]), + np.array([[0]]), + None), + # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S) + (np.array([[0, 1], [0, -1]]), + np.array([[1, 0], [2, 1]]), + np.array([[-4, -4], [-4, 7]]) * (1/11), + np.array([[9, 3], [3, 1]]), + None), + # TEST CASE 8 : darex #5 + (np.array([[0, 1], [0, 0]]), + np.array([[0], [1]]), + np.array([[1, 2], [2, 4]]), + np.array([[1]]), + None), + # TEST CASE 9 : darex #6 + (np.array([[0.998, 0.067, 0, 0], + [-.067, 0.998, 0, 0], + [0, 0, 0.998, 0.153], + [0, 0, -.153, 0.998]]), + np.array([[0.0033, 0.0200], + [0.1000, -.0007], + [0.0400, 0.0073], + [-.0028, 0.1000]]), + np.array([[1.87, 0, 0, -0.244], + [0, 0.744, 0.205, 0], + [0, 0.205, 0.589, 0], + [-0.244, 0, 0, 1.048]]), + np.eye(2), + None), + # TEST CASE 10 : darex #7 + (np.array([[0.984750, -.079903, 0.0009054, -.0010765], + [0.041588, 0.998990, -.0358550, 0.0126840], + [-.546620, 0.044916, -.3299100, 0.1931800], + [2.662400, -.100450, -.9245500, -.2632500]]), + np.array([[0.0037112, 0.0007361], + [-.0870510, 9.3411e-6], + [-1.198440, -4.1378e-4], + [-3.192700, 9.2535e-4]]), + np.eye(4)*1e-2, + np.eye(2), + None), + # TEST CASE 11 : darex #8 + (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180], + [1.0000000, 0.6000000, 0.8000000, 3.3999820], + [0.0000000, 1.0000000, 1.8000000, 3.7999820], + [0.0000000, 0.0000000, 0.0000000, -0.9999820]]), + np.array([[1.0, -1.0, -1.0, -1.0], + [0.0, 1.0, -1.0, -1.0], + [0.0, 0.0, 1.0, -1.0], + [0.0, 0.0, 0.0, 1.0]]), + np.array([[2, 1, 3, 6], + [1, 2, 2, 5], + [3, 2, 6, 11], + [6, 5, 11, 22]]), + np.eye(4), + None), + # TEST CASE 12 : darex #9 + (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190], + [40.8490, 41.3170, 16.0840, 4.4679, 1.1971], + [12.2170, 26.3260, 36.1490, 15.9300, 12.3830], + [4.1118, 12.8580, 27.2090, 21.4420, 40.9760], + [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01, + np.array([[0.0434, -0.0122], + [2.6606, -1.0453], + [3.7530, -5.5100], + [3.6076, -6.6000], + [0.4617, -0.9148]]) * 0.01, + np.eye(5), + np.eye(2), + None), + # TEST CASE 13 : darex #10 + (np.kron(np.eye(2), np.diag([1, 1], k=1)), + np.kron(np.eye(2), np.array([[0], [0], [1]])), + np.array([[1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, -1, 0], + [0, 0, 0, -1, 1, 0], + [0, 0, 0, 0, 0, 0]]), + np.array([[3, 0], [0, 1]]), + None), + # TEST CASE 14 : darex #11 + (0.001 * np.array( + [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249], + [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499], + [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72], + [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82], + [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9], + [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6], + [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67], + [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54], + [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]), + np.array([[4.7600, -0.5701, -83.6800], + [0.8790, -4.7730, -2.7300], + [1.4820, -13.1200, 8.8760], + [3.8920, -35.1300, 24.8000], + [10.3400, -92.7500, 66.8000], + [7.2030, -61.5900, 38.3400], + [4.4540, -36.8300, 20.2900], + [1.9710, -15.5400, 6.9370], + [3.7730, -30.2800, 14.6900]]) * 0.001, + np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]), + np.eye(3), + None), + # TEST CASE 15 : darex #12 - numerically least accurate example + (np.array([[0, 1e6], [0, 0]]), + np.array([[0], [1]]), + np.eye(2), + np.array([[1]]), + None), + # TEST CASE 16 : darex #13 + (np.array([[16, 10, -2], + [10, 13, -8], + [-2, -8, 7]]) * (1/9), + np.eye(3), + 1e6 * np.eye(3), + 1e6 * np.eye(3), + None), + # TEST CASE 17 : darex #14 + (np.array([[1 - 1/1e8, 0, 0, 0], + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0]]), + np.array([[1e-08], [0], [0], [0]]), + np.diag([0, 0, 0, 1]), + np.array([[0.25]]), + None), + # TEST CASE 18 : darex #15 + (np.eye(100, k=1), + np.flipud(np.eye(100, 1)), + np.eye(100), + np.array([[1]]), + None) + ] + + # Makes the minimum precision requirements customized to the test. + # Here numbers represent the number of decimals that agrees with zero + # matrix when the solution x is plugged in to the equation. + # + # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2 + # + # If the test is failing use "None" for that entry. + # + min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13, + 14, 13, 13, 14, 12, 2, 4, 6, 10) + max_tol = [1.5 * 10**-ind for ind in min_decimal] + # relaxed tolerance in gh-18012 after bump to OpenBLAS + max_tol[11] = 2.5e-13 + + # relaxed tolerance in gh-20335 for linux-aarch64 build on Cirrus + # with OpenBLAS from ubuntu jammy + max_tol[15] = 2.0e-2 + + # relaxed tolerance in gh-20335 for OpenBLAS 3.20 on ubuntu jammy + # bump not needed for OpenBLAS 3.26 + max_tol[16] = 2.0e-4 + + @pytest.mark.parametrize("j, case", enumerate(cases)) + def test_solve_discrete_are(self, j, case): + """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" + a, b, q, r, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + atol = self.max_tol[j] + + x = solve_discrete_are(a, b, q, r) + bH = b.conj().T + xa, xb = x @ a, x @ b + + res = a.conj().T @ xa - x + q + res -= a.conj().T @ xb @ (solve(r + bH @ xb, bH) @ xa) + + # changed from + # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + # in gh-18012 as it's easier to relax a tolerance and allclose is + # preferred + assert_allclose(res, np.zeros_like(res), atol=atol) + + def test_infeasible(self): + # An infeasible example taken from https://arxiv.org/abs/1505.04861v1 + A = np.triu(np.ones((3, 3))) + A[0, 1] = -1 + B = np.array([[1, 1, 0], [0, 0, 1]]).T + Q = np.full_like(A, -2) + np.diag([8, -1, -1.9]) + R = np.diag([-10, 0.1]) + assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R) + + +class TestSolveCommonAre: + @pytest.mark.parametrize("solver", [solve_continuous_are, solve_discrete_are]) + def test_with_skipped_array_argument_gh23336(self, solver): + # gh-23336 reported a failure when optional argument `e` was skipped + A = np.array([[-0.9, 0.25], [0, -1.1]]) + B = np.array([[0.23], [0.45]]) + Q = np.eye(2) + R = np.atleast_2d(0.45) + E = np.eye(2) + S = np.array([[0.1], [0.2]]) + + res = solver(A, B, Q, R, s=S) + ref = solver(A, B, Q, R, E, S) + np.testing.assert_allclose(res, ref) + + +def test_solve_generalized_continuous_are(): + cases = [ + # Two random examples differ by s term + # in the absence of any literature for demanding examples. + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.zeros((3, 2)), + None), + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.ones((3, 2)), + None) + ] + + min_decimal = (10, 10) + + def _test_factory(case, dec): + """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" + a, b, q, r, e, s, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + x = solve_continuous_are(a, b, q, r, e, s) + res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q + out_fact = e.conj().T.dot(x).dot(b) + s + res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T)) + assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + + for ind, case in enumerate(cases): + _test_factory(case, min_decimal[ind]) + + +def test_solve_generalized_discrete_are(): + mat20170120 = _load_data('gendare_20170120_data.npz') + + cases = [ + # Two random examples differ by s term + # in the absence of any literature for demanding examples. + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.zeros((3, 2)), + None), + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.ones((3, 2)), + None), + # user-reported (under PR-6616) 20-Jan-2017 + # tests against the case where E is None but S is provided + (mat20170120['A'], + mat20170120['B'], + mat20170120['Q'], + mat20170120['R'], + None, + mat20170120['S'], + None), + ] + + max_atol = (1.5e-11, 1.5e-11, 3.5e-16) + + def _test_factory(case, atol): + """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" + a, b, q, r, e, s, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + x = solve_discrete_are(a, b, q, r, e, s) + if e is None: + e = np.eye(a.shape[0]) + if s is None: + s = np.zeros_like(b) + res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q + res -= (a.conj().T.dot(x.dot(b)) + s).dot( + solve(r+b.conj().T.dot(x.dot(b)), + (b.conj().T.dot(x.dot(a)) + s.conj().T) + ) + ) + # changed from: + # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + # in gh-17950 because of a Linux 32 bit fail. + assert_allclose(res, np.zeros_like(res), atol=atol) + + for ind, case in enumerate(cases): + _test_factory(case, max_atol[ind]) + + +def test_are_validate_args(): + + def test_square_shape(): + nsq = np.ones((3, 2)) + sq = np.eye(3) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, nsq, 1, 1, 1) + assert_raises(ValueError, x, sq, sq, nsq, 1) + assert_raises(ValueError, x, sq, sq, sq, nsq) + assert_raises(ValueError, x, sq, sq, sq, sq, nsq) + + def test_compatible_sizes(): + nsq = np.ones((3, 2)) + sq = np.eye(4) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, sq, nsq, 1, 1) + assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq) + assert_raises(ValueError, x, sq, sq, np.eye(3), sq) + assert_raises(ValueError, x, sq, sq, sq, np.eye(3)) + assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3)) + + def test_symmetry(): + nsym = np.arange(9).reshape(3, 3) + sym = np.eye(3) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, sym, sym, nsym, sym) + assert_raises(ValueError, x, sym, sym, sym, nsym) + + def test_singularity(): + sing = np.full((3, 3), 1e12) + sing[2, 2] -= 1 + sq = np.eye(3) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, sq, sq, sq, sq, sing) + + assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing) + + def test_finiteness(): + nm = np.full((2, 2), np.nan) + sq = np.eye(2) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, nm, sq, sq, sq) + assert_raises(ValueError, x, sq, nm, sq, sq) + assert_raises(ValueError, x, sq, sq, nm, sq) + assert_raises(ValueError, x, sq, sq, sq, nm) + assert_raises(ValueError, x, sq, sq, sq, sq, nm) + assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm) + + +class TestSolveSylvester: + cases = [ + # empty cases + (np.empty((0, 0)), + np.empty((0, 0)), + np.empty((0, 0))), + (np.empty((0, 0)), + np.empty((2, 2)), + np.empty((0, 2))), + (np.empty((2, 2)), + np.empty((0, 0)), + np.empty((2, 0))), + # a, b, c all real. + (np.array([[1, 2], [0, 4]]), + np.array([[5, 6], [0, 8]]), + np.array([[9, 10], [11, 12]])), + # a, b, c all real, 4x4. a and b have non-trivial 2x2 blocks in their + # quasi-triangular form. + (np.array([[1.0, 0, 0, 0], + [0, 1.0, 2.0, 0.0], + [0, 0, 3.0, -4], + [0, 0, 2, 5]]), + np.array([[2.0, 0, 0, 1.0], + [0, 1.0, 0.0, 0.0], + [0, 0, 1.0, -1], + [0, 0, 1, 1]]), + np.array([[1.0, 0, 0, 0], + [0, 1.0, 0, 0], + [0, 0, 1.0, 0], + [0, 0, 0, 1.0]])), + # a, b, c all complex. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[-1.0, 2j], [3.0, 4.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a and b real; c complex. + (np.array([[1.0, 2.0], [3.0, 5.0]]), + np.array([[-1.0, 0], [3.0, 4.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a and c complex; b real. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[-1.0, 0], [3.0, 4.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a complex; b and c real. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[-1.0, 0], [3.0, 4.0]]), + np.array([[2.0, 2.0], [-1.0, 2.0]])), + # not square matrices, real + (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]), + np.array([[2, 3], [4, 5]]), + np.array([[1, 2], [3, 4], [5, 6]])), + # not square matrices, complex + (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]), + np.array([[2, 3], [4, 5-1j]]), + np.array([[1, 2j], [3, 4j], [5j, 6+7j]])), + ] + + def check_case(self, a, b, c): + x = solve_sylvester(a, b, c) + assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c) + + def test_cases(self): + for case in self.cases: + self.check_case(case[0], case[1], case[2]) + + def test_trivial(self): + a = np.array([[1.0, 0.0], [0.0, 1.0]]) + b = np.array([[1.0]]) + c = np.array([2.0, 2.0]).reshape(-1, 1) + x = solve_sylvester(a, b, c) + assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1)) + + # Feel free to adjust this to test fewer dtypes or random selections rather than + # the Cartesian product. It doesn't take very long to test all combinations, + # though, so we'll start there and trim it down as we see fit. + @pytest.mark.parametrize("dtype_a", dtypes) + @pytest.mark.parametrize("dtype_b", dtypes) + @pytest.mark.parametrize("dtype_q", dtypes) + @pytest.mark.parametrize("m", [0, 3]) + @pytest.mark.parametrize("n", [0, 3]) + def test_size_0(self, m, n, dtype_a, dtype_b, dtype_q): + if m == n != 0: + pytest.skip('m = n != 0 is not a case that needs to be tested here.') + + rng = np.random.default_rng(598435298262546) + + a = np.zeros((m, m), dtype=dtype_a) + b = np.zeros((n, n), dtype=dtype_b) + q = np.zeros((m, n), dtype=dtype_q) + res = solve_sylvester(a, b, q) + + a = (rng.random((5, 5))*100).astype(dtype_a) + b = (rng.random((6, 6))*100).astype(dtype_b) + q = (rng.random((5, 6))*100).astype(dtype_q) + ref = solve_sylvester(a, b, q) + + assert res.shape == (m, n) + assert res.dtype == ref.dtype diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_special_matrices.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_special_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..b58e3e90ed2a1c2d4de9e4b8477921f3d0f6727c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/linalg/tests/test_special_matrices.py @@ -0,0 +1,617 @@ +import pytest +import numpy as np +from numpy import arange, array, eye, copy, sqrt +from numpy.testing import (assert_equal, assert_array_equal, + assert_array_almost_equal, assert_allclose) +from pytest import raises as assert_raises + +from scipy.fft import fft +from scipy.special import comb +from scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft, + companion, block_diag, + helmert, hilbert, invhilbert, pascal, invpascal, + fiedler, fiedler_companion, eigvals, + convolution_matrix) +from numpy.linalg import cond +from scipy._lib._array_api import (make_xp_test_case, xp_assert_equal, xp_size, + xp_default_dtype) + + +class TestToeplitz: + + def test_basic(self): + y = toeplitz([1, 2, 3]) + assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]]) + y = toeplitz([1, 2, 3], [1, 4, 5]) + assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]]) + + def test_complex_01(self): + data = (1.0 + arange(3.0)) * (1.0 + 1.0j) + x = copy(data) + t = toeplitz(x) + # Calling toeplitz should not change x. + assert_array_equal(x, data) + # According to the docstring, x should be the first column of t. + col0 = t[:, 0] + assert_array_equal(col0, data) + assert_array_equal(t[0, 1:], data[1:].conj()) + + def test_scalar_00(self): + """Scalar arguments still produce a 2D array.""" + t = toeplitz(10) + assert_array_equal(t, [[10]]) + t = toeplitz(10, 20) + assert_array_equal(t, [[10]]) + + def test_scalar_01(self): + c = array([1, 2, 3]) + t = toeplitz(c, 1) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_02(self): + c = array([1, 2, 3]) + t = toeplitz(c, array(1)) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_03(self): + c = array([1, 2, 3]) + t = toeplitz(c, array([1])) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_04(self): + r = array([10, 2, 3]) + t = toeplitz(1, r) + assert_array_equal(t, [[1, 2, 3]]) + + +class TestHankel: + def test_basic(self): + y = hankel([1, 2, 3]) + assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]]) + y = hankel([1, 2, 3], [3, 4, 5]) + assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]]) + + +class TestCirculant: + def test_basic(self): + y = circulant([1, 2, 3]) + assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]]) + + +class TestHadamard: + + def test_basic(self): + + y = hadamard(1) + assert_array_equal(y, [[1]]) + + y = hadamard(2, dtype=float) + assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]]) + + y = hadamard(4) + assert_array_equal(y, [[1, 1, 1, 1], + [1, -1, 1, -1], + [1, 1, -1, -1], + [1, -1, -1, 1]]) + + assert_raises(ValueError, hadamard, 0) + assert_raises(ValueError, hadamard, 5) + + +class TestLeslie: + + def test_bad_shapes(self): + assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5]) + assert_raises(ValueError, leslie, [1, 2], [1, 2]) + assert_raises(ValueError, leslie, [1], []) + + def test_basic(self): + a = leslie([1, 2, 3], [0.25, 0.5]) + expected = array([[1.0, 2.0, 3.0], + [0.25, 0.0, 0.0], + [0.0, 0.5, 0.0]]) + assert_array_equal(a, expected) + + +class TestCompanion: + + def test_bad_shapes(self): + assert_raises(ValueError, companion, [0, 4, 5]) + assert_raises(ValueError, companion, [1]) + assert_raises(ValueError, companion, []) + + def test_basic(self): + c = companion([1, 2, 3]) + expected = array([ + [-2.0, -3.0], + [1.0, 0.0]]) + assert_array_equal(c, expected) + + c = companion([2.0, 5.0, -10.0]) + expected = array([ + [-2.5, 5.0], + [1.0, 0.0]]) + assert_array_equal(c, expected) + + c = companion([(1.0, 2.0, 3.0), + (4.0, 5.0, 6.0)]) + expected = array([ + ([-2.00, -3.00], + [+1.00, +0.00]), + ([-1.25, -1.50], + [+1.00, +0.00]) + ]) + assert_array_equal(c, expected) + + +@make_xp_test_case(block_diag) +class TestBlockDiag: + def test_basic(self, xp): + dtype = xp.asarray(1).dtype + x = block_diag(xp.eye(2, dtype=dtype), xp.asarray([[1, 2], [3, 4], [5, 6]]), + xp.asarray([[1, 2, 3]])) + xp_assert_equal(x, xp.asarray([[1, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 2, 0, 0, 0], + [0, 0, 3, 4, 0, 0, 0], + [0, 0, 5, 6, 0, 0, 0], + [0, 0, 0, 0, 1, 2, 3]])) + + def test_dtype(self, xp): + x = block_diag(xp.asarray([[1.5]])) + assert x.dtype == xp_default_dtype(xp) + + x = block_diag(xp.asarray([[True]])) + assert x.dtype == xp.bool + + def test_mixed_dtypes(self, xp): + actual = block_diag(xp.asarray([[1.]]), xp.asarray([[1j]])) + desired = xp.asarray([[1, 0], [0, 1j]]) + xp_assert_equal(actual, desired) + + def test_scalar_and_1d_args(self, xp): + a = block_diag(xp.asarray(1)) + assert a.shape == (1, 1) + xp_assert_equal(a, xp.asarray([[1]])) + + a = block_diag(xp.asarray([2, 3]), xp.asarray(4)) + xp_assert_equal(a, xp.asarray([[2, 3, 0], [0, 0, 4]])) + + def test_no_args(self): + a = block_diag() + assert a.ndim == 2 + assert a.nbytes == 0 + + def test_empty_matrix_arg(self, xp): + # regression test for gh-4596: check the shape of the result + # for empty matrix inputs. Empty matrices are no longer ignored + # (gh-4908) it is viewed as a shape (1, 0) matrix. + dtype = xp.asarray(1).dtype + a = block_diag(xp.asarray([[1, 0], [0, 1]]), + xp.asarray([], dtype=dtype), + xp.asarray([[2, 3], [4, 5], [6, 7]])) + xp_assert_equal(a, xp.asarray([[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0], + [0, 0, 2, 3], + [0, 0, 4, 5], + [0, 0, 6, 7]])) + + @pytest.mark.skip_xp_backends("dask.array", reason="dask/dask#11800") + def test_zerosized_matrix_arg(self, xp): + # test for gh-4908: check the shape of the result for + # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0). + # note that [[]] takes shape (1,0) + dtype = xp.asarray(1).dtype + a = block_diag(xp.asarray([[1, 0], [0, 1]]), + xp.asarray([[]], dtype=dtype), + xp.asarray([[2, 3], [4, 5], [6, 7]]), + xp.zeros([0, 2], dtype=dtype)) + xp_assert_equal(a, xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 2, 3, 0, 0], + [0, 0, 4, 5, 0, 0], + [0, 0, 6, 7, 0, 0]])) + + +class TestHelmert: + + def test_orthogonality(self): + for n in range(1, 7): + H = helmert(n, full=True) + Id = np.eye(n) + assert_allclose(H.dot(H.T), Id, atol=1e-12) + assert_allclose(H.T.dot(H), Id, atol=1e-12) + + def test_subspace(self): + for n in range(2, 7): + H_full = helmert(n, full=True) + H_partial = helmert(n) + for U in H_full[1:, :].T, H_partial.T: + C = np.eye(n) - np.full((n, n), 1 / n) + assert_allclose(U.dot(U.T), C) + assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12) + + +class TestHilbert: + + def test_basic(self): + h3 = array([[1.0, 1/2., 1/3.], + [1/2., 1/3., 1/4.], + [1/3., 1/4., 1/5.]]) + assert_array_almost_equal(hilbert(3), h3) + + assert_array_equal(hilbert(1), [[1.0]]) + + h0 = hilbert(0) + assert_equal(h0.shape, (0, 0)) + + +class TestInvHilbert: + + def test_basic(self): + invh1 = array([[1]]) + assert_array_equal(invhilbert(1, exact=True), invh1) + assert_array_equal(invhilbert(1), invh1) + + invh2 = array([[4, -6], + [-6, 12]]) + assert_array_equal(invhilbert(2, exact=True), invh2) + assert_array_almost_equal(invhilbert(2), invh2) + + invh3 = array([[9, -36, 30], + [-36, 192, -180], + [30, -180, 180]]) + assert_array_equal(invhilbert(3, exact=True), invh3) + assert_array_almost_equal(invhilbert(3), invh3) + + invh4 = array([[16, -120, 240, -140], + [-120, 1200, -2700, 1680], + [240, -2700, 6480, -4200], + [-140, 1680, -4200, 2800]]) + assert_array_equal(invhilbert(4, exact=True), invh4) + assert_array_almost_equal(invhilbert(4), invh4) + + invh5 = array([[25, -300, 1050, -1400, 630], + [-300, 4800, -18900, 26880, -12600], + [1050, -18900, 79380, -117600, 56700], + [-1400, 26880, -117600, 179200, -88200], + [630, -12600, 56700, -88200, 44100]]) + assert_array_equal(invhilbert(5, exact=True), invh5) + assert_array_almost_equal(invhilbert(5), invh5) + + invh17 = array([ + [289, -41616, 1976760, -46124400, 629598060, -5540462928, + 33374693352, -143034400080, 446982500250, -1033026222800, + 1774926873720, -2258997839280, 2099709530100, -1384423866000, + 613101997800, -163493866080, 19835652870], + [-41616, 7990272, -426980160, 10627061760, -151103534400, + 1367702848512, -8410422724704, 36616806420480, -115857864064800, + 270465047424000, -468580694662080, 600545887119360, + -561522320049600, 372133135180800, -165537539406000, + 44316454993920, -5395297580640], + [1976760, -426980160, 24337869120, -630981792000, 9228108708000, + -85267724461920, 532660105897920, -2348052711713280, + 7504429831470000, -17664748409880000, 30818191841236800, + -39732544853164800, 37341234283298400, -24857330514030000, + 11100752642520000, -2982128117299200, 364182586693200], + [-46124400, 10627061760, -630981792000, 16826181120000, + -251209625940000, 2358021022156800, -14914482965141760, + 66409571644416000, -214015221119700000, 507295338950400000, + -890303319857952000, 1153715376477081600, -1089119333262870000, + 727848632044800000, -326170262829600000, 87894302404608000, + -10763618673376800], + [629598060, -151103534400, 9228108708000, + -251209625940000, 3810012660090000, -36210360321495360, + 231343968720664800, -1038687206500944000, 3370739732635275000, + -8037460526495400000, 14178080368737885600, -18454939322943942000, + 17489975175339030000, -11728977435138600000, 5272370630081100000, + -1424711708039692800, 174908803442373000], + [-5540462928, 1367702848512, -85267724461920, 2358021022156800, + -36210360321495360, 347619459086355456, -2239409617216035264, + 10124803292907663360, -33052510749726468000, + 79217210949138662400, -140362995650505067440, + 183420385176741672960, -174433352415381259200, + 117339159519533952000, -52892422160973595200, + 14328529177999196160, -1763080738699119840], + [33374693352, -8410422724704, 532660105897920, + -14914482965141760, 231343968720664800, -2239409617216035264, + 14527452132196331328, -66072377044391477760, + 216799987176909536400, -521925895055522958000, + 928414062734059661760, -1217424500995626443520, + 1161358898976091015200, -783401860847777371200, + 354015418167362952000, -96120549902411274240, + 11851820521255194480], + [-143034400080, 36616806420480, -2348052711713280, + 66409571644416000, -1038687206500944000, 10124803292907663360, + -66072377044391477760, 302045152202932469760, + -995510145200094810000, 2405996923185123840000, + -4294704507885446054400, 5649058909023744614400, + -5403874060541811254400, 3654352703663101440000, + -1655137020003255360000, 450325202737117593600, + -55630994283442749600], + [446982500250, -115857864064800, 7504429831470000, + -214015221119700000, 3370739732635275000, -33052510749726468000, + 216799987176909536400, -995510145200094810000, + 3293967392206196062500, -7988661659013106500000, + 14303908928401362270000, -18866974090684772052000, + 18093328327706957325000, -12263364009096700500000, + 5565847995255512250000, -1517208935002984080000, + 187754605706619279900], + [-1033026222800, 270465047424000, -17664748409880000, + 507295338950400000, -8037460526495400000, 79217210949138662400, + -521925895055522958000, 2405996923185123840000, + -7988661659013106500000, 19434404971634224000000, + -34894474126569249192000, 46141453390504792320000, + -44349976506971935800000, 30121928988527376000000, + -13697025107665828500000, 3740200989399948902400, + -463591619028689580000], + [1774926873720, -468580694662080, + 30818191841236800, -890303319857952000, 14178080368737885600, + -140362995650505067440, 928414062734059661760, + -4294704507885446054400, 14303908928401362270000, + -34894474126569249192000, 62810053427824648545600, + -83243376594051600326400, 80177044485212743068000, + -54558343880470209780000, 24851882355348879230400, + -6797096028813368678400, 843736746632215035600], + [-2258997839280, 600545887119360, -39732544853164800, + 1153715376477081600, -18454939322943942000, 183420385176741672960, + -1217424500995626443520, 5649058909023744614400, + -18866974090684772052000, 46141453390504792320000, + -83243376594051600326400, 110552468520163390156800, + -106681852579497947388000, 72720410752415168870400, + -33177973900974346080000, 9087761081682520473600, + -1129631016152221783200], + [2099709530100, -561522320049600, 37341234283298400, + -1089119333262870000, 17489975175339030000, + -174433352415381259200, 1161358898976091015200, + -5403874060541811254400, 18093328327706957325000, + -44349976506971935800000, 80177044485212743068000, + -106681852579497947388000, 103125790826848015808400, + -70409051543137015800000, 32171029219823375700000, + -8824053728865840192000, 1098252376814660067000], + [-1384423866000, 372133135180800, + -24857330514030000, 727848632044800000, -11728977435138600000, + 117339159519533952000, -783401860847777371200, + 3654352703663101440000, -12263364009096700500000, + 30121928988527376000000, -54558343880470209780000, + 72720410752415168870400, -70409051543137015800000, + 48142941226076592000000, -22027500987368499000000, + 6049545098753157120000, -753830033789944188000], + [613101997800, -165537539406000, + 11100752642520000, -326170262829600000, 5272370630081100000, + -52892422160973595200, 354015418167362952000, + -1655137020003255360000, 5565847995255512250000, + -13697025107665828500000, 24851882355348879230400, + -33177973900974346080000, 32171029219823375700000, + -22027500987368499000000, 10091416708498869000000, + -2774765838662800128000, 346146444087219270000], + [-163493866080, 44316454993920, -2982128117299200, + 87894302404608000, -1424711708039692800, + 14328529177999196160, -96120549902411274240, + 450325202737117593600, -1517208935002984080000, + 3740200989399948902400, -6797096028813368678400, + 9087761081682520473600, -8824053728865840192000, + 6049545098753157120000, -2774765838662800128000, + 763806510427609497600, -95382575704033754400], + [19835652870, -5395297580640, 364182586693200, -10763618673376800, + 174908803442373000, -1763080738699119840, 11851820521255194480, + -55630994283442749600, 187754605706619279900, + -463591619028689580000, 843736746632215035600, + -1129631016152221783200, 1098252376814660067000, + -753830033789944188000, 346146444087219270000, + -95382575704033754400, 11922821963004219300] + ]) + assert_array_equal(invhilbert(17, exact=True), invh17) + assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12) + + def test_inverse(self): + for n in range(1, 10): + a = hilbert(n) + b = invhilbert(n) + # The Hilbert matrix is increasingly badly conditioned, + # so take that into account in the test + c = cond(a) + assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c) + + +class TestPascal: + + cases = [ + (1, array([[1]]), array([[1]])), + (2, array([[1, 1], + [1, 2]]), + array([[1, 0], + [1, 1]])), + (3, array([[1, 1, 1], + [1, 2, 3], + [1, 3, 6]]), + array([[1, 0, 0], + [1, 1, 0], + [1, 2, 1]])), + (4, array([[1, 1, 1, 1], + [1, 2, 3, 4], + [1, 3, 6, 10], + [1, 4, 10, 20]]), + array([[1, 0, 0, 0], + [1, 1, 0, 0], + [1, 2, 1, 0], + [1, 3, 3, 1]])), + ] + + def check_case(self, n, sym, low): + assert_array_equal(pascal(n), sym) + assert_array_equal(pascal(n, kind='lower'), low) + assert_array_equal(pascal(n, kind='upper'), low.T) + assert_array_almost_equal(pascal(n, exact=False), sym) + assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low) + assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T) + + def test_cases(self): + for n, sym, low in self.cases: + self.check_case(n, sym, low) + + def test_big(self): + p = pascal(50) + assert p[-1, -1] == comb(98, 49, exact=True) + + def test_threshold(self): + # Regression test. An early version of `pascal` returned an + # array of type np.uint64 for n=35, but that data type is too small + # to hold p[-1, -1]. The second assert_equal below would fail + # because p[-1, -1] overflowed. + p = pascal(34) + assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34") + p = pascal(35) + assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35") + + +def test_invpascal(): + + def check_invpascal(n, kind, exact): + ip = invpascal(n, kind=kind, exact=exact) + p = pascal(n, kind=kind, exact=exact) + # Matrix-multiply ip and p, and check that we get the identity matrix. + # We can't use the simple expression e = ip.dot(p), because when + # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is + # np.int64. The product of those dtypes is np.float64, which loses + # precision when n is greater than 18. Instead we'll cast both to + # object arrays, and then multiply. + e = ip.astype(object).dot(p.astype(object)) + assert_array_equal(e, eye(n), err_msg=f"n={n} kind={kind!r} exact={exact!r}") + + kinds = ['symmetric', 'lower', 'upper'] + + ns = [1, 2, 5, 18] + for n in ns: + for kind in kinds: + for exact in [True, False]: + check_invpascal(n, kind, exact) + + ns = [19, 34, 35, 50] + for n in ns: + for kind in kinds: + check_invpascal(n, kind, True) + + +def test_dft(): + m = dft(2) + expected = array([[1.0, 1.0], [1.0, -1.0]]) + assert_array_almost_equal(m, expected) + m = dft(2, scale='n') + assert_array_almost_equal(m, expected/2.0) + m = dft(2, scale='sqrtn') + assert_array_almost_equal(m, expected/sqrt(2.0)) + + x = array([0, 1, 2, 3, 4, 5, 0, 1]) + m = dft(8) + mx = m.dot(x) + fx = fft(x) + assert_array_almost_equal(mx, fx) + + +@make_xp_test_case(fiedler) +def test_fiedler(xp): + f = fiedler(xp.asarray([])) + assert xp_size(f) == 0 + + f = fiedler(xp.asarray([123.])) + xp_assert_equal(f, xp.asarray([[0.]])) + + f = fiedler(xp.arange(1, 7)) + des = xp.asarray([[0, 1, 2, 3, 4, 5], + [1, 0, 1, 2, 3, 4], + [2, 1, 0, 1, 2, 3], + [3, 2, 1, 0, 1, 2], + [4, 3, 2, 1, 0, 1], + [5, 4, 3, 2, 1, 0]]) + xp_assert_equal(f, des) + + +def test_fiedler_companion(): + fc = fiedler_companion([]) + assert_equal(fc.size, 0) + fc = fiedler_companion([1.]) + assert_equal(fc.size, 0) + fc = fiedler_companion([1., 2.]) + assert_array_equal(fc, np.array([[-2.]])) + fc = fiedler_companion([1e-12, 2., 3.]) + assert_array_almost_equal(fc, companion([1e-12, 2., 3.])) + with assert_raises(ValueError): + fiedler_companion([0, 1, 2]) + fc = fiedler_companion([1., -16., 86., -176., 105.]) + assert_array_almost_equal(eigvals(fc), + np.array([7., 5., 3., 1.])) + + +class TestConvolutionMatrix: + """ + Test convolution_matrix vs. numpy.convolve for various parameters. + """ + + def create_vector(self, n, cpx): + """Make a complex or real test vector of length n.""" + x = np.linspace(-2.5, 2.2, n) + if cpx: + x = x + 1j*np.linspace(-1.5, 3.1, n) + return x + + def test_bad_n(self): + # n must be a positive integer + with pytest.raises(ValueError, match='n must be a positive integer'): + convolution_matrix([1, 2, 3], 0) + + def test_empty_first_arg(self): + # first arg must have at least one value + with pytest.raises(ValueError, match=r'len\(a\)'): + convolution_matrix([], 4) + + def test_bad_mode(self): + # mode must be in ('full', 'valid', 'same') + with pytest.raises(ValueError, match='mode.*must be one of'): + convolution_matrix((1, 1), 4, mode='invalid argument') + + @pytest.mark.parametrize('cpx', [False, True]) + @pytest.mark.parametrize('na', [1, 2, 9]) + @pytest.mark.parametrize('nv', [1, 2, 9]) + @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same']) + def test_against_numpy_convolve(self, cpx, na, nv, mode): + a = self.create_vector(na, cpx) + v = self.create_vector(nv, cpx) + if mode is None: + y1 = np.convolve(v, a) + A = convolution_matrix(a, nv) + else: + y1 = np.convolve(v, a, mode) + A = convolution_matrix(a, nv, mode) + y2 = A @ v + assert_array_almost_equal(y1, y2) + + +@pytest.mark.fail_slow(5) # `leslie` has an import in the function +@pytest.mark.parametrize('f, args', [(circulant, ()), + (companion, ()), + (convolution_matrix, (5, 'same')), + (fiedler, ()), + (fiedler_companion, ()), + (hankel, (np.arange(9),)), + (leslie, (np.arange(9),)), + (toeplitz, (np.arange(9),)), + ]) +def test_batch(f, args): + rng = np.random.default_rng(283592436523456) + batch_shape = (2, 3) + m = 10 + A = rng.random(batch_shape + (m,)) + + if f in {hankel}: + message = "Beginning in SciPy 1.19, multidimensional input will be..." + with pytest.warns(FutureWarning, match=message): + f(A, *args) + return + + res = f(A, *args) + ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)]) + ref = ref.reshape(A.shape[:-1] + ref.shape[-2:]) + assert_allclose(res, ref) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58b2970896770024fb727f6d1d3ecd68263d08a3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ddf7bd26d438a0c5c5756f2203a8e4749129510 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/doccer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/doccer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6b4f101e053cdec974b4532a5aaa26a5ca15bbd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/misc/__pycache__/doccer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9e49319a4cbd20316acd252d91d3517211ef54d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27d941aa9aeb70fbc63d41c4fb3c670d3506f420 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_filters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..724105a270798fc3fd42a542b2f6ae863c397772 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_filters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98d2ae2496f82651d5f47025c0e9bdb06cb06f6c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c57288aa45c0a26e2abb3c4b96d2baa9325a2637 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1334daff7bf320f7f80113c3cbbc87f24efeb8a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb7bdec3cdccfddc5267754b54a33650b54f8aa0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6948fdb2f7827fe9111a8bcdec93f37b67b1300b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d80af8207e683d897a3f35b603dce37d7fec137 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f343d608055add554c38e90bec5b28e102aef97 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/filters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bfb7867fd7f6d49d03217ef6675a28f6246fedc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/filters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/fourier.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/fourier.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dce775e38e7f32b15e46e4805eaa0392cc1deb2d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/fourier.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0307bb57c1e54c46489d72a3db22bcfbc6f8db98 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/measurements.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/measurements.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3a87aaf5dc3342def79391b558ae0a92958a3d9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/measurements.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/morphology.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/morphology.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19a14e67cdfa3fd803785201d96d7a739c82bdb2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/__pycache__/morphology.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd01c6c1ecc2600dba33d434a7f70690ac95e40 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__init__.py @@ -0,0 +1,12 @@ +import numpy as np + +# list of numarray data types +integer_types: list[str] = [ + "int8", "uint8", "int16", "uint16", + "int32", "uint32", "int64", "uint64"] + +float_types: list[str] = ["float32", "float64"] + +complex_types: list[str] = ["complex64", "complex128"] + +types: list[str] = integer_types + float_types diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40d229dbd8be2fc201d2e88797c6d85d1b9eba3e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e641414d6ef8daaa0eac036e30fd636404820614 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d485d508cba5ba0e209044733bed30c9551c450 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c858bf362e241dcce8a8bafff85fcac8f16590fd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09cc5f9c1ce6024e3c357db2270ae5c9d32de373 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66f517f9fea41468c6241af96d31fe53a7e19a56 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_inputs.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_inputs.txt new file mode 100644 index 0000000000000000000000000000000000000000..af21e291faa303f4c55753673cbb2584f31c4509 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_inputs.txt @@ -0,0 +1,21 @@ +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 0 1 1 1 +1 1 0 0 0 1 1 +1 0 1 0 1 0 1 +0 0 0 1 0 0 0 +1 0 1 0 1 0 1 +1 1 0 0 0 1 1 +1 1 1 0 1 1 1 +1 0 1 1 1 0 1 +0 0 0 1 0 0 0 +1 0 0 1 0 0 1 +1 1 1 1 1 1 1 +1 0 0 1 0 0 1 +0 0 0 1 0 0 0 +1 0 1 1 1 0 1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_results.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_results.txt new file mode 100644 index 0000000000000000000000000000000000000000..de789b0f36760a1d3df0121c7be8b8b96f94ce39 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_results.txt @@ -0,0 +1,294 @@ +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +2 2 2 2 2 2 2 +3 3 3 3 3 3 3 +4 4 4 4 4 4 4 +5 5 5 5 5 5 5 +6 6 6 6 6 6 6 +7 7 7 7 7 7 7 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 2 3 4 5 6 7 +8 9 10 11 12 13 14 +15 16 17 18 19 20 21 +22 23 24 25 26 27 28 +29 30 31 32 33 34 35 +36 37 38 39 40 41 42 +43 44 45 46 47 48 49 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 2 3 4 5 6 7 +8 1 2 3 4 5 6 +9 8 1 2 3 4 5 +10 9 8 1 2 3 4 +11 10 9 8 1 2 3 +12 11 10 9 8 1 2 +13 12 11 10 9 8 1 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 2 1 2 1 2 1 +2 1 2 1 2 1 2 +1 2 1 2 1 2 1 +2 1 2 1 2 1 2 +1 2 1 2 1 2 1 +2 1 2 1 2 1 2 +1 2 1 2 1 2 1 +1 2 3 4 5 6 7 +2 3 4 5 6 7 8 +3 4 5 6 7 8 9 +4 5 6 7 8 9 10 +5 6 7 8 9 10 11 +6 7 8 9 10 11 12 +7 8 9 10 11 12 13 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 3 0 2 0 4 +0 0 0 2 0 0 0 +5 0 2 0 6 0 7 +2 2 0 0 0 7 7 +2 2 2 0 7 7 7 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +3 0 1 0 4 0 2 +0 0 0 1 0 0 0 +5 0 6 0 1 0 7 +5 5 0 0 0 1 1 +5 5 5 0 1 1 1 +1 1 1 0 2 2 2 +3 3 0 0 0 4 4 +5 0 6 0 7 0 8 +0 0 0 9 0 0 0 +10 0 11 0 12 0 13 +14 14 0 0 0 15 15 +16 16 16 0 17 17 17 +1 1 1 0 2 3 3 +1 1 0 0 0 3 3 +1 0 4 0 3 0 3 +0 0 0 3 0 0 0 +3 0 3 0 5 0 6 +3 3 0 0 0 6 6 +3 3 7 0 6 6 6 +1 2 3 0 4 5 6 +7 8 0 0 0 9 10 +11 0 12 0 13 0 14 +0 0 0 15 0 0 0 +16 0 17 0 18 0 19 +20 21 0 0 0 22 23 +24 25 26 0 27 28 29 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 3 0 2 0 2 +0 0 0 2 0 0 0 +2 0 2 0 4 0 5 +2 2 0 0 0 5 5 +2 2 2 0 5 5 5 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 3 0 4 0 2 +0 0 0 5 0 0 0 +6 0 7 0 8 0 9 +6 6 0 0 0 9 9 +6 6 6 0 9 9 9 +1 2 3 0 4 5 6 +7 1 0 0 0 4 5 +8 0 1 0 9 0 4 +0 0 0 1 0 0 0 +10 0 11 0 1 0 12 +13 10 0 0 0 1 14 +15 13 10 0 16 17 1 +1 2 3 0 4 5 6 +1 2 0 0 0 5 6 +1 0 7 0 8 0 6 +0 0 0 9 0 0 0 +10 0 11 0 12 0 13 +10 14 0 0 0 15 13 +10 14 16 0 17 15 13 +1 1 1 0 1 1 1 +1 1 0 0 0 1 1 +1 0 1 0 1 0 1 +0 0 0 1 0 0 0 +1 0 1 0 1 0 1 +1 1 0 0 0 1 1 +1 1 1 0 1 1 1 +1 1 2 0 3 3 3 +1 1 0 0 0 3 3 +1 0 1 0 4 0 3 +0 0 0 1 0 0 0 +5 0 6 0 1 0 1 +5 5 0 0 0 1 1 +5 5 5 0 7 1 1 +1 2 1 0 1 3 1 +2 1 0 0 0 1 3 +1 0 1 0 1 0 1 +0 0 0 1 0 0 0 +1 0 1 0 1 0 1 +4 1 0 0 0 1 5 +1 4 1 0 1 5 1 +1 2 3 0 4 5 6 +2 3 0 0 0 6 7 +3 0 8 0 6 0 9 +0 0 0 6 0 0 0 +10 0 6 0 11 0 12 +13 6 0 0 0 12 14 +6 15 16 0 12 14 17 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 1 0 3 0 2 +0 0 0 1 0 0 0 +4 0 5 0 1 0 1 +4 4 0 0 0 1 1 +4 4 4 0 1 1 1 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +4 0 0 5 0 0 5 +5 5 5 5 5 5 5 +5 0 0 5 0 0 6 +0 0 0 7 0 0 0 +8 0 7 7 7 0 9 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +4 0 0 4 0 0 5 +4 4 4 4 4 4 4 +6 0 0 4 0 0 4 +0 0 0 7 0 0 0 +8 0 7 7 7 0 9 +1 0 2 2 2 0 3 +0 0 0 4 0 0 0 +5 0 0 6 0 0 7 +8 8 8 8 8 8 8 +9 0 0 10 0 0 11 +0 0 0 12 0 0 0 +13 0 14 14 14 0 15 +1 0 2 3 3 0 4 +0 0 0 3 0 0 0 +5 0 0 3 0 0 6 +5 5 3 3 3 6 6 +5 0 0 3 0 0 6 +0 0 0 3 0 0 0 +7 0 3 3 8 0 9 +1 0 2 3 4 0 5 +0 0 0 6 0 0 0 +7 0 0 8 0 0 9 +10 11 12 13 14 15 16 +17 0 0 18 0 0 19 +0 0 0 20 0 0 0 +21 0 22 23 24 0 25 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 +1 0 2 3 4 0 5 +0 0 0 2 0 0 0 +6 0 0 7 0 0 8 +9 6 10 11 7 12 13 +14 0 0 10 0 0 12 +0 0 0 15 0 0 0 +16 0 17 18 15 0 19 +1 0 2 3 4 0 5 +0 0 0 3 0 0 0 +6 0 0 3 0 0 7 +6 8 9 3 10 11 7 +6 0 0 3 0 0 7 +0 0 0 3 0 0 0 +12 0 13 3 14 0 15 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 +1 0 2 2 3 0 4 +0 0 0 2 0 0 0 +5 0 0 2 0 0 6 +5 5 2 2 2 6 6 +5 0 0 2 0 0 6 +0 0 0 2 0 0 0 +7 0 8 2 2 0 9 +1 0 2 3 2 0 4 +0 0 0 2 0 0 0 +5 0 0 6 0 0 7 +8 5 6 9 6 7 10 +5 0 0 6 0 0 7 +0 0 0 11 0 0 0 +12 0 11 13 11 0 14 +1 0 2 3 4 0 5 +0 0 0 4 0 0 0 +6 0 0 7 0 0 8 +9 10 7 11 12 8 13 +10 0 0 12 0 0 14 +0 0 0 15 0 0 0 +16 0 15 17 18 0 19 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_strels.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_strels.txt new file mode 100644 index 0000000000000000000000000000000000000000..b66c71605c8195f12b6e850659838e954d35a043 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/data/label_strels.txt @@ -0,0 +1,42 @@ +0 0 1 +1 1 1 +1 0 0 +1 0 0 +1 1 1 +0 0 1 +0 0 0 +1 1 1 +0 0 0 +0 1 1 +0 1 0 +1 1 0 +0 0 0 +0 0 0 +0 0 0 +0 1 1 +1 1 1 +1 1 0 +0 1 0 +1 1 1 +0 1 0 +1 0 0 +0 1 0 +0 0 1 +0 1 0 +0 1 0 +0 1 0 +1 1 1 +1 1 1 +1 1 1 +1 1 0 +0 1 0 +0 1 1 +1 0 1 +0 1 0 +1 0 1 +0 0 1 +0 1 0 +1 0 0 +1 1 0 +1 1 1 +0 1 1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_c_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_c_api.py new file mode 100644 index 0000000000000000000000000000000000000000..e54e6cb0282e469eb69260592adab6799034c926 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_c_api.py @@ -0,0 +1,102 @@ +import numpy as np +from scipy._lib._array_api import xp_assert_close + +from scipy import ndimage +from scipy.ndimage import _ctest +from scipy.ndimage import _cytest +from scipy._lib._ccallback import LowLevelCallable + +FILTER1D_FUNCTIONS = [ + lambda filter_size: _ctest.filter1d(filter_size), + lambda filter_size: _cytest.filter1d(filter_size, with_signature=False), + lambda filter_size: LowLevelCallable( + _cytest.filter1d(filter_size, with_signature=True) + ), + lambda filter_size: LowLevelCallable.from_cython( + _cytest, "_filter1d", + _cytest.filter1d_capsule(filter_size), + ), +] + +FILTER2D_FUNCTIONS = [ + lambda weights: _ctest.filter2d(weights), + lambda weights: _cytest.filter2d(weights, with_signature=False), + lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)), + lambda weights: LowLevelCallable.from_cython(_cytest, + "_filter2d", + _cytest.filter2d_capsule(weights),), +] + +TRANSFORM_FUNCTIONS = [ + lambda shift: _ctest.transform(shift), + lambda shift: _cytest.transform(shift, with_signature=False), + lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)), + lambda shift: LowLevelCallable.from_cython(_cytest, + "_transform", + _cytest.transform_capsule(shift),), +] + + +def test_generic_filter(): + def filter2d(footprint_elements, weights): + return (weights*footprint_elements).sum() + + def check(j): + func = FILTER2D_FUNCTIONS[j] + + im = np.ones((20, 20)) + im[:10,:10] = 0 + footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) + footprint_size = np.count_nonzero(footprint) + weights = np.ones(footprint_size)/footprint_size + + res = ndimage.generic_filter(im, func(weights), + footprint=footprint) + std = ndimage.generic_filter(im, filter2d, footprint=footprint, + extra_arguments=(weights,)) + xp_assert_close(res, std, err_msg=f"#{j} failed") + + for j, func in enumerate(FILTER2D_FUNCTIONS): + check(j) + + +def test_generic_filter1d(): + def filter1d(input_line, output_line, filter_size): + for i in range(output_line.size): + output_line[i] = 0 + for j in range(filter_size): + output_line[i] += input_line[i+j] + output_line /= filter_size + + def check(j): + func = FILTER1D_FUNCTIONS[j] + + im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1)) + filter_size = 3 + + res = ndimage.generic_filter1d(im, func(filter_size), + filter_size) + std = ndimage.generic_filter1d(im, filter1d, filter_size, + extra_arguments=(filter_size,)) + xp_assert_close(res, std, err_msg=f"#{j} failed") + + for j, func in enumerate(FILTER1D_FUNCTIONS): + check(j) + + +def test_geometric_transform(): + def transform(output_coordinates, shift): + return output_coordinates[0] - shift, output_coordinates[1] - shift + + def check(j): + func = TRANSFORM_FUNCTIONS[j] + + im = np.arange(12).reshape(4, 3).astype(np.float64) + shift = 0.5 + + res = ndimage.geometric_transform(im, func(shift)) + std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,)) + xp_assert_close(res, std, err_msg=f"#{j} failed") + + for j, func in enumerate(TRANSFORM_FUNCTIONS): + check(j) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_datatypes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_datatypes.py new file mode 100644 index 0000000000000000000000000000000000000000..dbbf76d598054d9836d156d9578d4192594f33b5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_datatypes.py @@ -0,0 +1,67 @@ +""" Testing data types for ndimage calls +""" +import numpy as np + +from scipy._lib._array_api import assert_array_almost_equal +import pytest + +from scipy import ndimage + + +def test_map_coordinates_dts(): + # check that ndimage accepts different data types for interpolation + data = np.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + shifted_data = np.array([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + idx = np.indices(data.shape) + dts = (np.uint8, np.uint16, np.uint32, np.uint64, + np.int8, np.int16, np.int32, np.int64, + np.intp, np.uintp, np.float32, np.float64) + for order in range(0, 6): + for data_dt in dts: + these_data = data.astype(data_dt) + for coord_dt in dts: + # affine mapping + mat = np.eye(2, dtype=coord_dt) + off = np.zeros((2,), dtype=coord_dt) + out = ndimage.affine_transform(these_data, mat, off) + assert_array_almost_equal(these_data, out) + # map coordinates + coords_m1 = idx.astype(coord_dt) - 1 + coords_p10 = idx.astype(coord_dt) + 10 + out = ndimage.map_coordinates(these_data, coords_m1, order=order) + assert_array_almost_equal(out, shifted_data) + # check constant fill works + out = ndimage.map_coordinates(these_data, coords_p10, order=order) + assert_array_almost_equal(out, np.zeros((3,4))) + # check shift and zoom + out = ndimage.shift(these_data, 1) + assert_array_almost_equal(out, shifted_data) + out = ndimage.zoom(these_data, 1) + assert_array_almost_equal(these_data, out) + + +@pytest.mark.xfail(True, reason="Broken on many platforms") +def test_uint64_max(): + # Test interpolation respects uint64 max. Reported to fail at least on + # win32 (due to the 32 bit visual C compiler using signed int64 when + # converting between uint64 to double) and Debian on s390x. + # Interpolation is always done in double precision floating point, so + # we use the largest uint64 value for which int(float(big)) still fits + # in a uint64. + # This test was last enabled on macOS only, and there it started failing + # on arm64 as well (see gh-19117). + big = 2**64 - 1025 + arr = np.array([big, big, big], dtype=np.uint64) + # Tests geometric transform (map_coordinates, affine_transform) + inds = np.indices(arr.shape) - 0.1 + x = ndimage.map_coordinates(arr, inds) + assert x[1] == int(float(big)) + assert x[2] == int(float(big)) + # Tests zoom / shift + x = ndimage.shift(arr, 0.1) + assert x[1] == int(float(big)) + assert x[2] == int(float(big)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_filters.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..2732bc8a5359ffa54d40ee5cebb6a8c2479b2f13 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_filters.py @@ -0,0 +1,3143 @@ +''' Some tests for filters ''' +import functools +import itertools +import re +import contextlib +import warnings + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal +from hypothesis import strategies as st +from hypothesis import given +import hypothesis.extra.numpy as npst +from pytest import raises as assert_raises +from scipy import ndimage +from scipy._lib._array_api import ( + assert_almost_equal, + assert_array_almost_equal, + xp_assert_close, + xp_assert_equal, + make_xp_test_case, + make_xp_pytest_param, +) +from scipy._lib._array_api import (is_cupy, is_torch, is_dask, is_jax, array_namespace, + is_array_api_strict, xp_copy) +from scipy.ndimage._filters import _gaussian_kernel1d + +from . import types, float_types, complex_types + + +skip_xp_backends = pytest.mark.skip_xp_backends +xfail_xp_backends = pytest.mark.xfail_xp_backends + +uses_output_dtype = skip_xp_backends( + np_only=True, exceptions=["cupy"], + reason="output=dtype is numpy-specific" +) + + +def uses_output_array(f): + return skip_xp_backends("dask.array", reason="output=array requires buffer view")( + skip_xp_backends("jax.numpy", reason="output=array requires buffer view")(f)) + + + +def sumsq(a, b, xp=None): + xp = array_namespace(a, b) if xp is None else xp + return xp.sqrt(xp.sum((a - b)**2)) + + +def _complex_correlate(xp, array, kernel, real_dtype, convolve=False, + mode="reflect", cval=0, ): + """Utility to perform a reference complex-valued convolutions. + + When convolve==False, correlation is performed instead + """ + array = xp.asarray(array) + kernel = xp.asarray(kernel) + complex_array = xp.isdtype(array.dtype, 'complex floating') + complex_kernel = xp.isdtype(kernel.dtype, 'complex floating') + if array.ndim == 1: + func = ndimage.convolve1d if convolve else ndimage.correlate1d + else: + func = ndimage.convolve if convolve else ndimage.correlate + if not convolve: + kernel = xp.conj(kernel) + if complex_array and complex_kernel: + # use: real(cval) for array.real component + # imag(cval) for array.imag component + re_cval = cval.real if isinstance(cval, complex) else xp.real(cval) + im_cval = cval.imag if isinstance(cval, complex) else xp.imag(cval) + + output = ( + func(xp.real(array), xp.real(kernel), output=real_dtype, + mode=mode, cval=re_cval) - + func(xp.imag(array), xp.imag(kernel), output=real_dtype, + mode=mode, cval=im_cval) + + 1j * func(xp.imag(array), xp.real(kernel), output=real_dtype, + mode=mode, cval=im_cval) + + 1j * func(xp.real(array), xp.imag(kernel), output=real_dtype, + mode=mode, cval=re_cval) + ) + elif complex_array: + re_cval = xp.real(cval) + re_cval = re_cval.item() if isinstance(re_cval, xp.ndarray) else re_cval + im_cval = xp.imag(cval) + im_cval = im_cval.item() if isinstance(im_cval, xp.ndarray) else im_cval + + output = ( + func(xp.real(array), kernel, output=real_dtype, mode=mode, + cval=re_cval) + + 1j * func(xp.imag(array), kernel, output=real_dtype, mode=mode, + cval=im_cval) + ) + elif complex_kernel: + # real array so cval is real too + output = ( + func(array, xp.real(kernel), output=real_dtype, mode=mode, cval=cval) + + 1j * func(array, xp.imag(kernel), output=real_dtype, mode=mode, + cval=cval) + ) + return output + + +def _cases_axes_tuple_length_mismatch(): + # Generate combinations of filter function, valid kwargs, and + # keyword-value pairs for which the value will become with mismatched + # (invalid) size + filter_func = ndimage.gaussian_filter + kwargs = dict(radius=3, mode='constant', sigma=1.0, order=0) + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + filter_funcs = [ndimage.uniform_filter, ndimage.minimum_filter, + ndimage.maximum_filter] + kwargs = dict(size=3, mode='constant', origin=0) + for filter_func in filter_funcs: + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + filter_funcs = [ndimage.correlate, ndimage.convolve] + # sequence of mode not supported for correlate or convolve + kwargs = dict(origin=0) + for filter_func in filter_funcs: + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + +@make_xp_test_case(ndimage.correlate, ndimage.correlate1d, + ndimage.convolve, ndimage.convolve1d) +class TestNdimageFilters: + def _validate_complex(self, xp, array, kernel, type2, mode='reflect', + cval=0, check_warnings=True): + # utility for validating complex-valued correlations + real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype + expected = _complex_correlate( + xp, array, kernel, real_dtype, convolve=False, mode=mode, cval=cval + ) + + if array.ndim == 1: + correlate = functools.partial(ndimage.correlate1d, axis=-1, + mode=mode, cval=cval) + convolve = functools.partial(ndimage.convolve1d, axis=-1, + mode=mode, cval=cval) + else: + correlate = functools.partial(ndimage.correlate, mode=mode, + cval=cval) + convolve = functools.partial(ndimage.convolve, mode=mode, + cval=cval) + + # test correlate output dtype + output = correlate(array, kernel, output=type2) + assert_array_almost_equal(expected, output) + assert output.dtype.type == type2 + + # test correlate with pre-allocated output + output = xp.zeros_like(array, dtype=type2) + correlate(array, kernel, output=output) + assert_array_almost_equal(expected, output) + + # test convolve output dtype + output = convolve(array, kernel, output=type2) + expected = _complex_correlate( + xp, array, kernel, real_dtype, convolve=True, mode=mode, cval=cval, + ) + assert_array_almost_equal(expected, output) + assert output.dtype.type == type2 + + # convolve with pre-allocated output + convolve(array, kernel, output=output) + assert_array_almost_equal(expected, output) + assert output.dtype.type == type2 + + if check_warnings: + # warns if the output is not a complex dtype + with pytest.warns(UserWarning, + match="promoting specified output dtype to " + "complex"): + correlate(array, kernel, output=real_dtype) + + with pytest.warns(UserWarning, + match="promoting specified output dtype to " + "complex"): + convolve(array, kernel, output=real_dtype) + + # raises if output array is provided, but is not complex-valued + output_real = xp.zeros_like(array, dtype=real_dtype) + with assert_raises(RuntimeError): + correlate(array, kernel, output=output_real) + + with assert_raises(RuntimeError): + convolve(array, kernel, output=output_real) + + def test_correlate01(self, xp): + array = xp.asarray([1, 2]) + weights = xp.asarray([2]) + expected = xp.asarray([2, 4]) + + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + @xfail_xp_backends('cupy', reason="Differs by a factor of two?") + @uses_output_array + def test_correlate01_overlap(self, xp): + array = xp.reshape(xp.arange(256), (16, 16)) + weights = xp.asarray([2]) + expected = 2 * array + + ndimage.correlate1d(array, weights, output=array) + assert_array_almost_equal(array, expected) + + def test_correlate02(self, xp): + array = xp.asarray([1, 2, 3]) + kernel = xp.asarray([1]) + + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate03(self, xp): + array = xp.asarray([1]) + weights = xp.asarray([1, 1]) + expected = xp.asarray([2]) + + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + def test_correlate04(self, xp): + array = xp.asarray([1, 2]) + tcor = xp.asarray([2, 3]) + tcov = xp.asarray([3, 4]) + weights = xp.asarray([1, 1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate05(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([2, 3, 5]) + tcov = xp.asarray([3, 5, 6]) + kernel = xp.asarray([1, 1]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(tcov, output) + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(tcov, output) + + def test_correlate06(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([9, 14, 17]) + tcov = xp.asarray([7, 10, 15]) + weights = xp.asarray([1, 2, 3]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate07(self, xp): + array = xp.asarray([1, 2, 3]) + expected = xp.asarray([5, 8, 11]) + weights = xp.asarray([1, 2, 1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + def test_correlate08(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([1, 2, 5]) + tcov = xp.asarray([3, 6, 7]) + weights = xp.asarray([1, 2, -1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate09(self, xp): + array = xp.asarray([]) + kernel = xp.asarray([1, 1]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate10(self, xp): + array = xp.asarray([[]]) + kernel = xp.asarray([[1, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate11(self, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6]]) + kernel = xp.asarray([[1, 1], + [1, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(xp.asarray([[12, 16, 18], [18, 22, 24]]), output) + + def test_correlate12(self, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6]]) + kernel = xp.asarray([[1, 0], + [0, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_kernel', types) + def test_correlate13(self, dtype_array, dtype_kernel, xp): + dtype_array = getattr(xp, dtype_array) + dtype_kernel = getattr(xp, dtype_kernel) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, output=dtype_kernel) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype.type == dtype_kernel + + output = ndimage.convolve(array, kernel, + output=dtype_kernel) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype.type == dtype_kernel + + @uses_output_array + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate14(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = xp.zeros(array.shape, dtype=dtype_output) + ndimage.correlate(array, kernel, output=output) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype == dtype_output + + ndimage.convolve(array, kernel, output=output) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype == dtype_output + + @uses_output_dtype + @pytest.mark.parametrize('dtype_array', types) + def test_correlate15(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype.type == xp.float32 + + @uses_output_dtype + @pytest.mark.parametrize('dtype_array', types) + def test_correlate16(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[0.5, 0], + [0, 0.5]]) + array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[1, 1.5, 2.5], [2.5, 3, 4]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[3, 4, 4.5], [4.5, 5.5, 6]]), output) + assert output.dtype.type == xp.float32 + + def test_correlate17(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([3, 5, 6]) + tcov = xp.asarray([2, 3, 5]) + kernel = xp.asarray([1, 1]) + output = ndimage.correlate(array, kernel, origin=-1) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve(array, kernel, origin=-1) + assert_array_almost_equal(tcov, output) + output = ndimage.correlate1d(array, kernel, origin=-1) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve1d(array, kernel, origin=-1) + assert_array_almost_equal(tcov, output) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_array', types) + def test_correlate18(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, + output=xp.float32, + mode='nearest', origin=-1) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, + output=xp.float32, + mode='nearest', origin=-1) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype.type == xp.float32 + + def test_correlate_mode_sequence(self, xp): + kernel = xp.ones((2, 2)) + array = xp.ones((3, 3), dtype=xp.float64) + with assert_raises(RuntimeError): + ndimage.correlate(array, kernel, mode=['nearest', 'reflect']) + with assert_raises(RuntimeError): + ndimage.convolve(array, kernel, mode=['nearest', 'reflect']) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_array', types) + def test_correlate19(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, + output=xp.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[5, 6, 8], [8, 9, 11]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, + output=xp.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[3, 5, 6], [6, 8, 9]]), output) + assert output.dtype.type == xp.float32 + + @uses_output_array + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate20(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, output=output) + assert_array_almost_equal(output, expected) + + def test_correlate21(self, xp): + array = xp.asarray([[1, 2, 3], + [2, 4, 6]]) + expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) + weights = xp.asarray([1, 2, 1]) + output = ndimage.correlate1d(array, weights, axis=0) + assert_array_almost_equal(output, expected) + output = ndimage.convolve1d(array, weights, axis=0) + assert_array_almost_equal(output, expected) + + @uses_output_array + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate22(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + expected = xp.asarray([[6, 12, 18], [6, 12, 18]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='wrap', output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, + mode='wrap', output=output) + assert_array_almost_equal(output, expected) + + @uses_output_array + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate23(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output) + assert_array_almost_equal(output, expected) + + @uses_output_array + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate24(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + tcor = xp.asarray([[7, 14, 21], [8, 16, 24]]) + tcov = xp.asarray([[4, 8, 12], [5, 10, 15]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output, origin=-1) + assert_array_almost_equal(output, tcor) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output, origin=-1) + assert_array_almost_equal(output, tcov) + + @uses_output_array + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate25(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + tcor = xp.asarray([[4, 8, 12], [5, 10, 15]]) + tcov = xp.asarray([[7, 14, 21], [8, 16, 24]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output, origin=1) + assert_array_almost_equal(output, tcor) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output, origin=1) + assert_array_almost_equal(output, tcov) + + def test_correlate26(self, xp): + # test fix for gh-11661 (mirror extension of a length 1 signal) + y = ndimage.convolve1d(xp.ones(1), xp.ones(5), mode='mirror') + xp_assert_equal(y, xp.asarray([5.])) + + y = ndimage.correlate1d(xp.ones(1), xp.ones(5), mode='mirror') + xp_assert_equal(y, xp.asarray([5.])) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_kernel(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype_kernel) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + @pytest.mark.parametrize('mode', ['grid-constant', 'constant']) + def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel, + dtype_output, mode, xp, + num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + if is_cupy(xp) and mode == 'grid-constant': + pytest.xfail('cupy/cupy#8404') + + # test use of non-zero cval with complex inputs + # also verifies that mode 'grid-constant' does not segfault + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype_kernel) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, mode=mode, + cval=5.0, + check_warnings=num_parallel_threads == 1) + + @xfail_xp_backends('cupy', reason="cupy/cupy#8405") + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + def test_correlate_complex_kernel_invalid_cval(self, dtype_input, + dtype_kernel, xp): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + + # cannot give complex cval with a real image + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype_kernel) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_input) + for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d, + ndimage.correlate1d]: + with pytest.raises((ValueError, TypeError)): + func(array, kernel, mode='constant', cval=5.0 + 1.0j, + output=xp.complex64) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel) + array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel, + dtype_output, xp, + num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel) + array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5.0, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1]], dtype=dtype_kernel) + array = xp.asarray([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @xfail_xp_backends("cupy", reason="cupy/cupy#8405") + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel, + dtype_output, xp, + num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5 - 3j, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'") + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input_and_kernel(self, dtype, dtype_output, xp, + num_parallel_threads): + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype) + array = xp.asarray([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @xfail_xp_backends("cupy", reason="cupy/cupy#8405") + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input_and_kernel_cval(self, dtype, + dtype_output, xp, + num_parallel_threads): + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'") + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output, xp, + num_parallel_threads): + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @uses_output_dtype + @xfail_xp_backends("cupy", reason="cupy/cupy#8405") + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_and_kernel_cval(self, dtype, + dtype_output, xp, + num_parallel_threads): + + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j, + check_warnings=num_parallel_threads == 1) + + def test_gauss01(self, xp): + input = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=xp.float32) + output = ndimage.gaussian_filter(input, 0) + assert_array_almost_equal(output, input) + + def test_gauss02(self, xp): + input = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=xp.float32) + output = ndimage.gaussian_filter(input, 1.0) + assert input.dtype == output.dtype + assert input.shape == output.shape + + @xfail_xp_backends("cupy", reason="cupy/cupy#8403") + def test_gauss03(self, xp): + # single precision data + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + output = ndimage.gaussian_filter(input, [1.0, 1.0]) + + assert input.dtype == output.dtype + assert input.shape == output.shape + + # input.sum() is 49995000.0. With single precision floats, we can't + # expect more than 8 digits of accuracy, so use decimal=0 in this test. + o_sum = xp.sum(output, dtype=xp.float64) + i_sum = xp.sum(input, dtype=xp.float64) + assert_almost_equal(o_sum, i_sum, decimal=0) + assert sumsq(input, output) > 1.0 + + @uses_output_dtype + def test_gauss04(self, xp): + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + otype = xp.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) + assert output.dtype.type == xp.float64 + assert input.shape == output.shape + assert sumsq(input, output) > 1.0 + + @uses_output_dtype + def test_gauss05(self, xp): + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + otype = xp.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], + order=1, output=otype) + assert output.dtype.type == xp.float64 + assert input.shape == output.shape + assert sumsq(input, output) > 1.0 + + @uses_output_dtype + def test_gauss06(self, xp): + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + otype = xp.float64 + output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) + output2 = ndimage.gaussian_filter(input, 1.0, output=otype) + assert_array_almost_equal(output1, output2) + + @uses_output_array + def test_gauss_memory_overlap(self, xp): + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + output1 = ndimage.gaussian_filter(input, 1.0) + ndimage.gaussian_filter(input, 1.0, output=input) + assert_array_almost_equal(output1, input) + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'), + [(ndimage.gaussian_filter, (), 0, 1.0), + (ndimage.uniform_filter, (), 1, 3), + (ndimage.minimum_filter, (), 1, 3), + (ndimage.maximum_filter, (), 1, 3), + (ndimage.median_filter, (), 1, 3), + (ndimage.rank_filter, (1,), 1, 3), + (ndimage.percentile_filter, (40,), 1, 3)]) + @pytest.mark.parametrize( + 'axes', + tuple(itertools.combinations(range(-3, 3), 1)) + + tuple(itertools.combinations(range(-3, 3), 2)) + + ((0, 1, 2),)) + def test_filter_axes(self, filter_func, extra_args, size0, size, axes, xp): + # Note: `size` is called `sigma` in `gaussian_filter` + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + if len(set(ax % array.ndim for ax in axes)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, *extra_args, size, axes=axes) + return + output = filter_func(array, *extra_args, size, axes=axes) + + # result should be equivalent to sigma=0.0/size=1 on unfiltered axes + axes = xp.asarray(axes) + all_sizes = tuple(size if ax in (axes % array.ndim) else size0 + for ax in range(array.ndim)) + expected = filter_func(array, *extra_args, all_sizes) + xp_assert_close(output, expected) + + @skip_xp_backends("cupy", + reason="these filters do not yet have axes support") + @pytest.mark.parametrize(('filter_func', 'kwargs'), + [(ndimage.laplace, {}), + (ndimage.gaussian_gradient_magnitude, + {"sigma": 1.0}), + (ndimage.gaussian_laplace, {"sigma": 0.5})]) + def test_derivative_filter_axes(self, xp, filter_func, kwargs): + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + # duplicate axes raises an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, axes=(1, 1), **kwargs) + + # compare results to manually looping over the non-filtered axes + output = filter_func(array, axes=(1, 2), **kwargs) + expected = xp.empty_like(output) + expected = [] + for i in range(array.shape[0]): + expected.append(filter_func(array[i, ...], **kwargs)) + expected = xp.stack(expected, axis=0) + xp_assert_close(output, expected) + + output = filter_func(array, axes=(0, -1), **kwargs) + expected = [] + for i in range(array.shape[1]): + expected.append(filter_func(array[:, i, :], **kwargs)) + expected = xp.stack(expected, axis=1) + xp_assert_close(output, expected) + + output = filter_func(array, axes=(1), **kwargs) + expected = [] + for i in range(array.shape[0]): + exp_inner = [] + for j in range(array.shape[2]): + exp_inner.append(filter_func(array[i, :, j], **kwargs)) + expected.append(xp.stack(exp_inner, axis=-1)) + expected = xp.stack(expected, axis=0) + xp_assert_close(output, expected) + + @skip_xp_backends("cupy", + reason="generic_filter does not yet have axes support") + @pytest.mark.parametrize( + 'axes', + tuple(itertools.combinations(range(-3, 3), 1)) + + tuple(itertools.combinations(range(-3, 3), 2)) + + ((0, 1, 2),)) + def test_generic_filter_axes(self, xp, axes): + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + size = 3 + if len(set(ax % array.ndim for ax in axes)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + ndimage.generic_filter(array, np.amax, size=size, axes=axes) + return + + # choose np.amax as the function so we can compare to maximum_filter + output = ndimage.generic_filter(array, np.amax, size=size, axes=axes) + expected = ndimage.maximum_filter(array, size=size, axes=axes) + xp_assert_close(output, expected) + + @skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize('func', [ndimage.correlate, ndimage.convolve]) + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64, np.complex64, np.complex128] + ) + @pytest.mark.parametrize( + 'axes', tuple(itertools.combinations(range(-3, 3), 2)) + ) + @pytest.mark.parametrize('origin', [(0, 0), (-1, 1)]) + def test_correlate_convolve_axes(self, xp, func, dtype, axes, origin): + array = xp.asarray(np.arange(6 * 8 * 12, dtype=dtype).reshape(6, 8, 12)) + weights = xp.arange(3 * 5) + weights = xp.reshape(weights, (3, 5)) + axes = tuple(ax % array.ndim for ax in axes) + if len(tuple(set(axes))) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError): + func(array, weights=weights, axes=axes, origin=origin) + return + output = func(array, weights=weights, axes=axes, origin=origin) + + missing_axis = tuple(set(range(3)) - set(axes))[0] + # module 'torch' has no attribute 'expand_dims' so use reshape instead + # weights_3d = xp.expand_dims(weights, axis=missing_axis) + shape_3d = ( + weights.shape[:missing_axis] + (1,) + weights.shape[missing_axis:] + ) + weights_3d = xp.reshape(weights, shape_3d) + origin_3d = [0, 0, 0] + for i, ax in enumerate(axes): + origin_3d[ax] = origin[i] + expected = func(array, weights=weights_3d, origin=origin_3d) + xp_assert_close(output, expected) + + kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2], + mode=['reflect', 'nearest', 'constant']) + kwargs_other = dict(origin=(-1, 0, 1), + mode=['reflect', 'nearest', 'constant']) + kwargs_rank = dict(origin=(-1, 0, 1)) + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize("filter_func, size0, size, kwargs", + [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss), + (ndimage.uniform_filter, 1, 3, kwargs_other), + (ndimage.maximum_filter, 1, 3, kwargs_other), + (ndimage.minimum_filter, 1, 3, kwargs_other), + (ndimage.median_filter, 1, 3, kwargs_rank), + (ndimage.rank_filter, 1, 3, kwargs_rank), + (ndimage.percentile_filter, 1, 3, kwargs_rank)]) + @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2)) + def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp): + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + kwargs = {key: np.array(val) for key, val in kwargs.items()} + axes = np.array(axes) + n_axes = axes.size + + if filter_func == ndimage.rank_filter: + args = (2,) # (rank,) + elif filter_func == ndimage.percentile_filter: + args = (30,) # (percentile,) + else: + args = () + + # form kwargs that specify only the axes in `axes` + reduced_kwargs = {key: val[axes] for key, val in kwargs.items()} + if len(set(axes % array.ndim)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, *args, [size]*n_axes, axes=axes, + **reduced_kwargs) + return + + output = filter_func(array, *args, [size]*n_axes, axes=axes, + **reduced_kwargs) + + # result should be equivalent to sigma=0.0/size=1 on unfiltered axes + size_3d = np.full(array.ndim, fill_value=size0) + size_3d[axes] = size + size_3d = [size_3d[i] for i in range(size_3d.shape[0])] + if 'origin' in kwargs: + # origin should be zero on the axis that has size 0 + origin = np.asarray([0, 0, 0]) + origin[axes] = reduced_kwargs['origin'] + origin = xp.asarray(origin) + kwargs['origin'] = origin + expected = filter_func(array, *args, size_3d, **kwargs) + xp_assert_close(output, expected) + + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize("filter_func, kwargs", + [(ndimage.convolve, {}), + (ndimage.correlate, {}), + (ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, {"rank": 1}), + (ndimage.percentile_filter, {"percentile": 30})]) + def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp): + axes = (-2, -1) + origins = (0, 1) + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + # weights with ndim matching len(axes) + footprint = np.ones((3, 5), dtype=bool) + footprint[0, 1] = 0 # make non-separable + footprint = xp.asarray(footprint) + + if filter_func in (ndimage.convolve, ndimage.correlate): + kwargs["weights"] = footprint + else: + kwargs["footprint"] = footprint + kwargs["axes"] = axes + + output = filter_func(array, origin=origins, **kwargs) + + output0 = filter_func(array, origin=0, **kwargs) + + # output has origin shift on last axis relative to output0, so + # expect shifted arrays to be equal. + if filter_func == ndimage.convolve: + # shift is in the opposite direction for convolve because it + # flips the weights array and negates the origin values. + xp_assert_equal( + output[:, :, :-origins[1]], output0[:, :, origins[1]:]) + else: + xp_assert_equal( + output[:, :, origins[1]:], output0[:, :, :-origins[1]]) + + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize( + 'filter_func, args', + [(ndimage.convolve, (np.ones((3, 3, 3)),)), # args = (weights,) + (ndimage.correlate,(np.ones((3, 3, 3)),)), # args = (weights,) + (ndimage.gaussian_filter, (1.0,)), # args = (sigma,) + (ndimage.uniform_filter, (3,)), # args = (size,) + (ndimage.minimum_filter, (3,)), # args = (size,) + (ndimage.maximum_filter, (3,)), # args = (size,) + (ndimage.median_filter, (3,)), # args = (size,) + (ndimage.rank_filter, (2, 3)), # args = (rank, size) + (ndimage.percentile_filter, (30, 3))]) # args = (percentile, size) + @pytest.mark.parametrize( + 'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)] + ) + def test_filter_invalid_axes(self, filter_func, args, axes, xp): + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + args = [ + xp.asarray(arg) if isinstance(arg, np.ndarray) else arg + for arg in args + ] + if any(isinstance(ax, float) for ax in axes): + error_class = TypeError + match = "cannot be interpreted as an integer" + else: + error_class = ValueError + match = "out of range" + with pytest.raises(error_class, match=match): + filter_func(array, *args, axes=axes) + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.convolve, {}), + (ndimage.correlate, {}), + (ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, dict(rank=3)), + (ndimage.percentile_filter, dict(percentile=30))]) + @pytest.mark.parametrize( + 'axes', [(0, ), (1, 2), (0, 1, 2)] + ) + @pytest.mark.parametrize('separable_footprint', [False, True]) + def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes, + separable_footprint, xp): + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + # create a footprint with one too many dimensions + footprint = np.ones((3,) * (len(axes) + 1)) + if not separable_footprint: + footprint[(0,) * footprint.ndim] = 0 + footprint = xp.asarray(footprint) + if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter] + and separable_footprint): + match = "sequence argument must have length equal to input rank" + elif filter_func in [ndimage.convolve, ndimage.correlate]: + match = re.escape(f"weights.ndim ({footprint.ndim}) must match " + f"len(axes) ({len(axes)})") + else: + match = re.escape(f"footprint.ndim ({footprint.ndim}) must match " + f"len(axes) ({len(axes)})") + if filter_func in [ndimage.convolve, ndimage.correlate]: + kwargs["weights"] = footprint + else: + kwargs["footprint"] = footprint + with pytest.raises(RuntimeError, match=match): + filter_func(array, axes=axes, **kwargs) + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize('n_mismatch', [1, 3]) + @pytest.mark.parametrize('filter_func, kwargs, key, val', + _cases_axes_tuple_length_mismatch()) + def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func, + kwargs, key, val, xp): + # Test for the intended RuntimeError when a kwargs has an invalid size + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + axes = (0, 1) + kwargs = dict(**kwargs, axes=axes) + kwargs[key] = (val,) * n_mismatch + if filter_func in [ndimage.convolve, ndimage.correlate]: + kwargs["weights"] = xp.ones((5,) * len(axes)) + err_msg = "sequence argument must have length equal to input rank" + with pytest.raises(RuntimeError, match=err_msg): + filter_func(array, **kwargs) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt01(self, dtype, xp): + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1) + output = ndimage.prewitt(array, 0) + assert_array_almost_equal(t, output) + + @uses_output_array + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt02(self, dtype, xp): + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.prewitt(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt03(self, dtype, xp): + dtype = getattr(xp, dtype) + if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]: + pytest.xfail("uint UB? XXX") + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1) + t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 0) + output = ndimage.prewitt(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt04(self, dtype, xp): + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.prewitt(array, -1) + output = ndimage.prewitt(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel01(self, dtype, xp): + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1) + output = ndimage.sobel(array, 0) + assert_array_almost_equal(t, output) + + @uses_output_array + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel02(self, dtype, xp): + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.sobel(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel03(self, dtype, xp): + if is_cupy(xp) and dtype in ["uint32", "uint64"]: + pytest.xfail("uint UB? XXX") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1) + t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 0) + output = xp.zeros(array.shape, dtype=dtype) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel04(self, dtype, xp): + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.sobel(array, -1) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_laplace01(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0) + tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1) + output = ndimage.laplace(array) + assert_array_almost_equal(tmp1 + tmp2, output) + + @uses_output_array + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_laplace02(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0) + tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.laplace(array, output=output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_laplace01(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) + output = ndimage.gaussian_laplace(array, 1.0) + assert_array_almost_equal(tmp1 + tmp2, output) + + @uses_output_array + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_laplace02(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.gaussian_laplace(array, 1.0, output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @uses_output_array + @pytest.mark.parametrize('dtype', types + complex_types) + def test_generic_laplace01(self, dtype, xp): + def derivative2(input, axis, output, mode, cval, a, b): + sigma = np.asarray([a, b / 2.0]) + order = [0] * input.ndim + order[axis] = 2 + return ndimage.gaussian_filter(input, sigma, order, + output, mode, cval) + + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = xp.zeros(array.shape, dtype=dtype) + tmp = ndimage.generic_laplace(array, derivative2, + extra_arguments=(1.0,), + extra_keywords={'b': 2.0}) + ndimage.gaussian_laplace(array, 1.0, output) + assert_array_almost_equal(tmp, output) + + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_gradient_magnitude01(self, dtype, xp): + is_int_dtype = dtype == "int32" + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) + output = ndimage.gaussian_gradient_magnitude(array, 1.0) + expected = tmp1 * tmp1 + tmp2 * tmp2 + + expected_float = xp.astype(expected, xp.float64) if is_int_dtype else expected + expected = xp.astype(xp.sqrt(expected_float), dtype) + xp_assert_close(output, expected, rtol=1e-6, atol=1e-6) + + @uses_output_array + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_gradient_magnitude02(self, dtype, xp): + is_int_dtype = dtype == 'int32' + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.gaussian_gradient_magnitude(array, 1.0, output) + expected = tmp1 * tmp1 + tmp2 * tmp2 + + fl_expected = xp.astype(expected, xp.float64) if is_int_dtype else expected + + expected = xp.astype(xp.sqrt(fl_expected), dtype) + xp_assert_close(output, expected, rtol=1e-6, atol=1e-6) + + def test_generic_gradient_magnitude01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=xp.float64) + + def derivative(input, axis, output, mode, cval, a, b): + sigma = [a, b / 2.0] + order = [0] * input.ndim + order[axis] = 1 + return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) + + tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0) + tmp2 = ndimage.generic_gradient_magnitude( + array, derivative, extra_arguments=(1.0,), + extra_keywords={'b': 2.0}) + assert_array_almost_equal(tmp1, tmp2) + + def test_uniform01(self, xp): + array = xp.asarray([2, 4, 6]) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal(xp.asarray([3, 5, 6]), output) + + def test_uniform01_complex(self, xp): + array = xp.asarray([2 + 1j, 4 + 2j, 6 + 3j], dtype=xp.complex128) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal(xp.real(output), xp.asarray([3., 5, 6])) + assert_array_almost_equal(xp.imag(output), xp.asarray([1.5, 2.5, 3])) + + def test_uniform02(self, xp): + array = xp.asarray([1, 2, 3]) + filter_shape = [0] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + def test_uniform03(self, xp): + array = xp.asarray([1, 2, 3]) + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + def test_uniform04(self, xp): + array = xp.asarray([2, 4, 6]) + filter_shape = [2] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([2, 3, 5]), output) + + def test_uniform05(self, xp): + array = xp.asarray([]) + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([]), output) + + @uses_output_dtype + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_uniform06(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + filter_shape = [2, 2] + array = xp.asarray([[4, 8, 12], + [16, 20, 24]], dtype=dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output) + assert output.dtype.type == dtype_output + + @uses_output_dtype + @pytest.mark.parametrize('dtype_array', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_uniform06_complex(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + filter_shape = [2, 2] + array = xp.asarray([[4, 8 + 5j, 12], + [16, 20, 24]], dtype=dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output.real) + assert output.dtype.type == dtype_output + + def test_minimum_filter01(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output) + + def test_minimum_filter02(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output) + + def test_minimum_filter03(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([3, 2, 2, 1, 1]), output) + + def test_minimum_filter04(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([2, 2, 1, 1, 1]), output) + + def test_minimum_filter05(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = xp.asarray([2, 3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]]), output) + + @uses_output_array + def test_minimum_filter05_overlap(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = xp.asarray([2, 3]) + ndimage.minimum_filter(array, filter_shape, output=array) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]]), array) + + def test_minimum_filter06(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]]), output) + # separable footprint should allow mode sequence + output2 = ndimage.minimum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + assert_array_almost_equal(output2, output) + + def test_minimum_filter07(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]]), output) + with assert_raises(RuntimeError): + ndimage.minimum_filter(array, footprint=footprint, + mode=['reflect', 'constant']) + + def test_minimum_filter08(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.minimum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal(xp.asarray([[3, 1, 3, 1, 1], + [5, 3, 3, 1, 1], + [3, 3, 1, 1, 1]]), output) + + def test_minimum_filter09(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.minimum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[2, 3, 1, 3, 1], + [5, 5, 3, 3, 1], + [5, 3, 3, 1, 1]]), output) + + def test_maximum_filter01(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([1, 2, 3, 4, 5]), output) + + def test_maximum_filter02(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([2, 3, 4, 5, 5]), output) + + def test_maximum_filter03(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([3, 3, 5, 5, 4]), output) + + def test_maximum_filter04(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([3, 5, 5, 5, 4]), output) + + def test_maximum_filter05(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = xp.asarray([2, 3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], + [7, 9, 9, 9, 5], + [8, 9, 9, 9, 7]]), output) + + def test_maximum_filter06(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], + [7, 9, 9, 9, 5], + [8, 9, 9, 9, 7]]), output) + # separable footprint should allow mode sequence + output2 = ndimage.maximum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + assert_array_almost_equal(output2, output) + + def test_maximum_filter07(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], + [7, 7, 9, 9, 5], + [7, 9, 8, 9, 7]]), output) + # non-separable footprint should not allow mode sequence + with assert_raises(RuntimeError): + ndimage.maximum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + + def test_maximum_filter08(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.maximum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal(xp.asarray([[7, 9, 9, 5, 5], + [9, 8, 9, 7, 5], + [8, 8, 7, 7, 7]]), output) + + def test_maximum_filter09(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.maximum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]]), output) + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") + @pytest.mark.parametrize( + 'axes', tuple(itertools.combinations(range(-3, 3), 2)) + ) + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, dict(rank=3)), + (ndimage.percentile_filter, dict(percentile=60))] + ) + def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp): + array = xp.arange(6 * 8 * 12, dtype=xp.float32) + array = xp.reshape(array, (6, 8, 12)) + # use 2D triangular footprint because it is non-separable + footprint = xp.asarray(np.tri(5)) + axes = np.asarray(axes) + + if len(set(axes % array.ndim)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError): + filter_func(array, footprint=footprint, axes=axes, **kwargs) + return + output = filter_func(array, footprint=footprint, axes=axes, **kwargs) + + missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0] + + footprint_3d = xp.expand_dims(footprint, axis=missing_axis) + expected = filter_func(array, footprint=footprint_3d, **kwargs) + xp_assert_close(output, expected) + + def test_rank01(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=2) + xp_assert_equal(array, output) + output = ndimage.percentile_filter(array, 100, size=2) + xp_assert_equal(array, output) + output = ndimage.median_filter(array, 2) + xp_assert_equal(array, output) + + def test_rank02(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=[3]) + xp_assert_equal(array, output) + output = ndimage.percentile_filter(array, 50, size=3) + xp_assert_equal(array, output) + output = ndimage.median_filter(array, (3,)) + xp_assert_equal(array, output) + + def test_rank03(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + output = ndimage.rank_filter(array, 1, size=[2]) + xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output) + output = ndimage.percentile_filter(array, 100, size=2) + xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output) + + def test_rank04(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + expected = xp.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, 1, size=3) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 50, size=3) + xp_assert_equal(expected, output) + output = ndimage.median_filter(array, size=3) + xp_assert_equal(expected, output) + + def test_rank05(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + expected = xp.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, -2, size=3) + xp_assert_equal(expected, output) + + def test_rank06(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[2, 2, 1, 1, 1], + [3, 3, 2, 1, 1], + [5, 5, 3, 3, 1]] + expected = xp.asarray(expected) + output = ndimage.rank_filter(array, 1, size=[2, 3]) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 17, size=(2, 3)) + xp_assert_equal(expected, output) + + @xfail_xp_backends("cupy", reason="cupy/cupy#8406") + @uses_output_array + def test_rank06_overlap(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + + array_copy = xp.asarray(array, copy=True) + expected = [[2, 2, 1, 1, 1], + [3, 3, 2, 1, 1], + [5, 5, 3, 3, 1]] + expected = xp.asarray(expected) + ndimage.rank_filter(array, 1, size=[2, 3], output=array) + xp_assert_equal(expected, array) + + ndimage.percentile_filter(array_copy, 17, size=(2, 3), + output=array_copy) + xp_assert_equal(expected, array_copy) + + def test_rank07(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[3, 5, 5, 5, 4], + [5, 5, 7, 5, 4], + [6, 8, 8, 7, 5]] + expected = xp.asarray(expected) + output = ndimage.rank_filter(array, -2, size=[2, 3]) + xp_assert_equal(expected, output) + + def test_rank08(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[3, 3, 2, 4, 4], + [5, 5, 5, 4, 4], + [5, 6, 7, 5, 5]] + expected = xp.asarray(expected) + output = ndimage.percentile_filter(array, 50.0, size=(2, 3)) + xp_assert_equal(expected, output) + output = ndimage.rank_filter(array, 3, size=(2, 3)) + xp_assert_equal(expected, output) + output = ndimage.median_filter(array, size=(2, 3)) + xp_assert_equal(expected, output) + + # non-separable: does not allow mode sequence + with assert_raises(RuntimeError): + ndimage.percentile_filter(array, 50.0, size=(2, 3), + mode=['reflect', 'constant']) + with assert_raises(RuntimeError): + ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2) + with assert_raises(RuntimeError): + ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2) + + @pytest.mark.parametrize('dtype', types) + def test_rank09(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + expected = xp.asarray(expected) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 35, footprint=footprint) + assert_array_almost_equal(expected, output) + + def test_rank10(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + expected = [[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]] + expected = xp.asarray(expected) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.rank_filter(array, 0, footprint=footprint) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 0.0, footprint=footprint) + xp_assert_equal(expected, output) + + def test_rank11(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + expected = [[3, 5, 5, 5, 4], + [7, 7, 9, 9, 5], + [7, 9, 8, 9, 7]] + expected = xp.asarray(expected) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.rank_filter(array, -1, footprint=footprint) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 100.0, footprint=footprint) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank12(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 50.0, + footprint=footprint) + xp_assert_equal(expected, output) + output = ndimage.median_filter(array, footprint=footprint) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank13(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[5, 2, 5, 1, 1], + [5, 8, 3, 5, 5], + [6, 6, 5, 5, 5]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=-1) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank14(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[3, 5, 2, 5, 1], + [5, 5, 8, 3, 5], + [5, 6, 6, 5, 5]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=[-1, 0]) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank15(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[2, 3, 1, 4, 1], + [5, 3, 7, 1, 1], + [5, 5, 3, 3, 3]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 0, footprint=footprint, + origin=[-1, 0]) + xp_assert_equal(expected, output) + + # NumPy-only because test is for list input + def test_rank16(self): + # test that lists are accepted and interpreted as numpy arrays + array = [3, 2, 5, 1, 4] + # expected values are: median(3, 2, 5) = 3, median(2, 5, 1) = 2, etc + expected = np.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, -2, size=3) + xp_assert_equal(expected, output) + + def test_rank17(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + if not hasattr(array, 'flags'): + return + array.flags.writeable = False + expected = xp.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, -2, size=3) + xp_assert_equal(expected, output) + + def test_rank18(self, xp): + # module 'array_api_strict' has no attribute 'float16' + tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64', + 'uint8', 'uint16', 'uint32', 'uint64'] + for dtype_str in tested_dtypes: + dtype = getattr(xp, dtype_str) + x = xp.asarray([3, 2, 5, 1, 4], dtype=dtype) + y = ndimage.rank_filter(x, -2, size=3) + assert y.dtype == x.dtype + + def test_rank19(self, xp): + # module 'array_api_strict' has no attribute 'float16' + tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64', + 'uint8', 'uint16', 'uint32', 'uint64'] + for dtype_str in tested_dtypes: + dtype = getattr(xp, dtype_str) + x = xp.asarray([[3, 2, 5, 1, 4], [3, 2, 5, 1, 4]], dtype=dtype) + y = ndimage.rank_filter(x, -2, size=3) + assert y.dtype == x.dtype + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason="off-by-ones on alt backends") + @xfail_xp_backends("cupy", reason="does not support extra_arguments") + @pytest.mark.parametrize('dtype', types) + def test_generic_filter1d01(self, dtype, xp): + weights = xp.asarray([1.1, 2.2, 3.3]) + + def _filter_func(input, output, fltr, total): + fltr = fltr / total + for ii in range(input.shape[0] - 2): + output[ii] = input[ii] * fltr[0] + output[ii] += input[ii + 1] * fltr[1] + output[ii] += input[ii + 2] * fltr[2] + + a = np.arange(12, dtype=dtype).reshape(3, 4) + a = xp.asarray(a) + dtype = getattr(xp, dtype) + + r1 = ndimage.correlate1d(a, weights / xp.sum(weights), 0, origin=-1) + r2 = ndimage.generic_filter1d( + a, _filter_func, 3, axis=0, origin=-1, + extra_arguments=(weights,), + extra_keywords={'total': xp.sum(weights)}) + assert_array_almost_equal(r1, r2) + + @xfail_xp_backends("cupy", reason="does not support extra_arguments") + @pytest.mark.parametrize('dtype', types) + def test_generic_filter01(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype_str = dtype + dtype = getattr(xp, dtype_str) + + filter_ = xp.asarray([[1.0, 2.0], [3.0, 4.0]]) + footprint = xp.asarray([[1.0, 0.0], [0.0, 1.0]]) + cf = xp.asarray([1., 4.]) + + def _filter_func(buffer, weights, total=1.0): + weights = np.asarray(cf) / np.asarray(total) + return np.sum(buffer * weights) + + a = np.arange(12, dtype=dtype_str).reshape(3, 4) + a = xp.asarray(a) + r1 = ndimage.correlate(a, filter_ * footprint) + if dtype_str in float_types: + r1 /= 5 + else: + r1 //= 5 + r2 = ndimage.generic_filter( + a, _filter_func, footprint=footprint, extra_arguments=(cf,), + extra_keywords={'total': xp.sum(cf)}) + assert_array_almost_equal(r1, r2) + + # generic_filter doesn't allow mode sequence + with assert_raises(RuntimeError): + r2 = ndimage.generic_filter( + a, _filter_func, mode=['reflect', 'reflect'], + footprint=footprint, extra_arguments=(cf,), + extra_keywords={'total': xp.sum(cf)}) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 2]), + ('wrap', [3, 1, 2]), + ('reflect', [1, 1, 2]), + ('mirror', [2, 1, 2]), + ('constant', [0, 1, 2])] + ) + def test_extend01(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([1, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 1]), + ('wrap', [3, 1, 2]), + ('reflect', [3, 3, 2]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend02(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([1, 0, 0, 0, 0, 0, 0, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [2, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 3, 3]), + ('mirror', [2, 3, 2]), + ('constant', [2, 3, 0])] + ) + def test_extend03(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend04(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), + ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]), + ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), + ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]), + ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])] + ) + def test_extend05(self, mode, expected_value, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = xp.asarray([[1, 0], [0, 0]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), + ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]), + ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), + ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]), + ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])] + ) + def test_extend06(self, mode, expected_value, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = xp.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend07(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[3], [3], [3]]), + ('wrap', [[2], [3], [1]]), + ('reflect', [[2], [1], [1]]), + ('mirror', [[1], [2], [3]]), + ('constant', [[0], [0], [0]])] + ) + def test_extend08(self, mode, expected_value, xp): + array = xp.asarray([[1], [2], [3]]) + weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend09(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[3], [3], [3]]), + ('wrap', [[2], [3], [1]]), + ('reflect', [[2], [1], [1]]), + ('mirror', [[1], [2], [3]]), + ('constant', [[0], [0], [0]])] + ) + def test_extend10(self, mode, expected_value, xp): + array = xp.asarray([[1], [2], [3]]) + weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + +@xfail_xp_backends("cupy", reason="TypeError") +@make_xp_test_case(ndimage.generic_filter) +def test_ticket_701(xp): + # Test generic filter sizes + arr = xp.asarray(np.arange(4).reshape(2, 2)) + def func(x): + return np.min(x) # NB: np.min not xp.min for callables + res = ndimage.generic_filter(arr, func, size=(1, 1)) + # The following raises an error unless ticket 701 is fixed + res2 = ndimage.generic_filter(arr, func, size=1) + xp_assert_equal(res, res2) + + +def test_gh_5430(): + # At least one of these raises an error unless gh-5430 is + # fixed. In py2k an int is implemented using a C long, so + # which one fails depends on your system. In py3k there is only + # one arbitrary precision integer type, so both should fail. + sigma = np.int32(1) + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert out == [sigma] + sigma = np.int64(1) + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert out == [sigma] + # This worked before; make sure it still works + sigma = 1 + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert out == [sigma] + # This worked before; make sure it still works + sigma = [1, 1] + out = ndimage._ni_support._normalize_sequence(sigma, 2) + assert out == sigma + # Also include the OPs original example to make sure we fixed the issue + x = np.random.normal(size=(256, 256)) + perlin = np.zeros_like(x) + for i in 2**np.arange(6): + perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2 + # This also fixes gh-4106, show that the OPs example now runs. + x = np.int64(21) + ndimage._ni_support._normalize_sequence(x, 0) + + +@skip_xp_backends("cupy", reason="tests a private scipy utility") +def test_gaussian_kernel1d(xp): + radius = 10 + sigma = 2 + sigma2 = sigma * sigma + x = np.arange(-radius, radius + 1, dtype=np.float64) + x = xp.asarray(x) + phi_x = xp.exp(-0.5 * x * x / sigma2) + phi_x /= xp.sum(phi_x) + xp_assert_close(phi_x, + xp.asarray(_gaussian_kernel1d(sigma, 0, radius))) + xp_assert_close(-phi_x * x / sigma2, + xp.asarray(_gaussian_kernel1d(sigma, 1, radius))) + xp_assert_close(phi_x * (x * x / sigma2 - 1) / sigma2, + xp.asarray(_gaussian_kernel1d(sigma, 2, radius))) + xp_assert_close(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2), + xp.asarray(_gaussian_kernel1d(sigma, 3, radius))) + + +@make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_filter1d) +def test_orders_gauss(xp): + # Check order inputs to Gaussians + arr = xp.zeros((1,)) + xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=0), xp.asarray([0.])) + xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=3), xp.asarray([0.])) + assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1) + xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0), + xp.asarray([0.])) + xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3), + xp.asarray([0.])) + assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1) + + +@xfail_xp_backends("cupy", reason="TypeError") +@make_xp_test_case( + ndimage.generic_filter, + ndimage.generic_filter1d, + ndimage.percentile_filter, +) +def test_valid_origins1(xp): + """Regression test for #1311.""" + + def func(x): + return xp.mean(x) + + data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64) + assert_raises(ValueError, ndimage.generic_filter, data, func, size=3, + origin=2) + assert_raises(ValueError, ndimage.generic_filter1d, data, func, + filter_size=3, origin=2) + assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3, + origin=2) + + +@xfail_xp_backends("cupy", reason="TypeError") +@pytest.mark.parametrize( + "filter_func", + [ + make_xp_pytest_param(ndimage.uniform_filter), + make_xp_pytest_param(ndimage.minimum_filter), + make_xp_pytest_param(ndimage.maximum_filter), + make_xp_pytest_param(ndimage.maximum_filter1d), + make_xp_pytest_param(ndimage.median_filter), + make_xp_pytest_param(ndimage.minimum_filter1d), + ], +) +def test_valid_origins2(xp, filter_func): + """Regression test for #1311.""" + data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64) + + # This should work, since for size == 3, the valid range for origin is + # -1 to 1. + list(filter_func(data, 3, origin=-1)) + list(filter_func(data, 3, origin=1)) + # Just check this raises an error instead of silently accepting or + # segfaulting. + assert_raises(ValueError, filter_func, data, 3, origin=2) + + +@make_xp_test_case( + ndimage.correlate1d, + ndimage.correlate, + ndimage.convolve1d, + ndimage.convolve, +) +def test_bad_convolve_and_correlate_origins(xp): + """Regression test for gh-822.""" + # Before gh-822 was fixed, these would generate seg. faults or + # other crashes on many system. + assert_raises(ValueError, ndimage.correlate1d, + [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2) + assert_raises(ValueError, ndimage.correlate, + [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2]) + assert_raises(ValueError, ndimage.correlate, + xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, 1]) + + assert_raises(ValueError, ndimage.convolve1d, + xp.arange(10), xp.ones(3), origin=-2) + assert_raises(ValueError, ndimage.convolve, + xp.arange(10), xp.ones(3), origin=[-2]) + assert_raises(ValueError, ndimage.convolve, + xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, -2]) + + +@pytest.mark.parametrize( + "filter_func,args,kwargs", + [ + make_xp_pytest_param(ndimage.gaussian_filter, [1], {}), + make_xp_pytest_param(ndimage.prewitt, [], {}), + make_xp_pytest_param(ndimage.sobel, [], {}), + make_xp_pytest_param(ndimage.laplace, [], {}), + make_xp_pytest_param(ndimage.gaussian_laplace, [1], {}), + make_xp_pytest_param(ndimage.maximum_filter, [], {"size": 5}), + make_xp_pytest_param(ndimage.minimum_filter, [], {"size": 5}), + make_xp_pytest_param(ndimage.gaussian_gradient_magnitude, [1], {}), + make_xp_pytest_param(ndimage.uniform_filter, [5], {}), + ], +) +def test_multiple_modes(xp, filter_func, args, kwargs): + # Test that the filters with multiple mode capabilities for different + # dimensions give the same result as applying a single mode. + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + mode1 = 'reflect' + mode2 = ['reflect', 'reflect'] + + xp_assert_equal(filter_func(arr, *args, mode=mode1, **kwargs), + filter_func(arr, *args, mode=mode2, **kwargs)) + + +@make_xp_test_case( + ndimage.gaussian_filter1d, ndimage.gaussian_filter, + ndimage.uniform_filter1d, ndimage.uniform_filter, + ndimage.maximum_filter1d, ndimage.maximum_filter, + ndimage.minimum_filter1d, ndimage.minimum_filter, +) +def test_multiple_modes_sequentially(xp): + # Test that the filters with multiple mode capabilities for different + # dimensions give the same result as applying the filters with + # different modes sequentially + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + modes = ['reflect', 'wrap'] + + expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0]) + expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1]) + xp_assert_equal(expected, + ndimage.gaussian_filter(arr, 1, mode=modes)) + + expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0]) + expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1]) + xp_assert_equal(expected, + ndimage.uniform_filter(arr, 5, mode=modes)) + + expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0]) + expected = ndimage.maximum_filter1d(expected, size=5, axis=1, + mode=modes[1]) + xp_assert_equal(expected, + ndimage.maximum_filter(arr, size=5, mode=modes)) + + expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0]) + expected = ndimage.minimum_filter1d(expected, size=5, axis=1, + mode=modes[1]) + xp_assert_equal(expected, + ndimage.minimum_filter(arr, size=5, mode=modes)) + + +@make_xp_test_case(ndimage.prewitt) +def test_multiple_modes_prewitt(xp): + # Test prewitt filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[1., -3., 2.], + [1., -2., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + xp_assert_equal(expected, + ndimage.prewitt(arr, mode=modes)) + + +@make_xp_test_case(ndimage.sobel) +def test_multiple_modes_sobel(xp): + # Test sobel filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[1., -4., 3.], + [2., -3., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + xp_assert_equal(expected, + ndimage.sobel(arr, mode=modes)) + + +@make_xp_test_case(ndimage.laplace) +def test_multiple_modes_laplace(xp): + # Test laplace filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[-2., 2., 1.], + [-2., -3., 2.], + [1., 1., 0.]]) + + modes = ['reflect', 'wrap'] + + xp_assert_equal(expected, + ndimage.laplace(arr, mode=modes)) + + +@make_xp_test_case(ndimage.gaussian_laplace) +def test_multiple_modes_gaussian_laplace(xp): + # Test gaussian_laplace filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[-0.28438687, 0.01559809, 0.19773499], + [-0.36630503, -0.20069774, 0.07483620], + [0.15849176, 0.18495566, 0.21934094]]) + + modes = ['reflect', 'wrap'] + + assert_almost_equal(expected, + ndimage.gaussian_laplace(arr, 1, mode=modes)) + + +@make_xp_test_case(ndimage.gaussian_gradient_magnitude) +def test_multiple_modes_gaussian_gradient_magnitude(xp): + # Test gaussian_gradient_magnitude filter for multiple + # extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[0.04928965, 0.09745625, 0.06405368], + [0.23056905, 0.14025305, 0.04550846], + [0.19894369, 0.14950060, 0.06796850]]) + + modes = ['reflect', 'wrap'] + + calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes) + + assert_almost_equal(expected, calculated) + + +@make_xp_test_case(ndimage.uniform_filter) +def test_multiple_modes_uniform(xp): + # Test uniform filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[0.32, 0.40, 0.48], + [0.20, 0.28, 0.32], + [0.28, 0.32, 0.40]]) + + modes = ['reflect', 'wrap'] + + assert_almost_equal(expected, + ndimage.uniform_filter(arr, 5, mode=modes)) + + +def _count_nonzero(arr): + # XXX: a simplified count_nonzero replacement; replace once + # https://github.com/data-apis/array-api/pull/803/ is in + + # this assumes arr.dtype == xp.bool + xp = array_namespace(arr) + return xp.sum(xp.astype(arr, xp.int8)) + + +@make_xp_test_case( + ndimage.gaussian_filter, ndimage.gaussian_filter1d, + ndimage.gaussian_laplace, ndimage.gaussian_gradient_magnitude, +) +def test_gaussian_truncate(xp): + # Test that Gaussian filters can be truncated at different widths. + # These tests only check that the result has the expected number + # of nonzero elements. + arr = np.zeros((100, 100), dtype=np.float64) + arr[50, 50] = 1 + arr = xp.asarray(arr) + num_nonzeros_2 = _count_nonzero(ndimage.gaussian_filter(arr, 5, truncate=2) > 0) + assert num_nonzeros_2 == 21**2 + + num_nonzeros_5 = _count_nonzero( + ndimage.gaussian_filter(arr, 5, truncate=5) > 0 + ) + assert num_nonzeros_5 == 51**2 + + # Test truncate when sigma is a sequence. + f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5) + fpos = f > 0 + n0 = _count_nonzero(xp.any(fpos, axis=0)) + assert n0 == 19 + n1 = _count_nonzero(xp.any(fpos, axis=1)) + assert n1 == 5 + + # Test gaussian_filter1d. + x = np.zeros(51) + x[25] = 1 + x = xp.asarray(x) + f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5) + n = _count_nonzero(f > 0) + assert n == 15 + + # Test gaussian_laplace + y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5) + nonzero_indices = xp.nonzero(y != 0)[0] + + n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1 + assert n == 15 + + # Test gaussian_gradient_magnitude + y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5) + nonzero_indices = xp.nonzero(y != 0)[0] + n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1 + assert n == 15 + + +@xfail_xp_backends("cupy", reason="cupy/cupy#8402") +@make_xp_test_case(ndimage.gaussian_filter1d, ndimage.gaussian_filter) +def test_gaussian_radius(xp): + # Test that Gaussian filters with radius argument produce the same + # results as the filters with corresponding truncate argument. + # radius = int(truncate * sigma + 0.5) + # Test gaussian_filter1d + x = np.zeros(7) + x[3] = 1 + x = xp.asarray(x) + f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5) + f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3) + xp_assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a number. + a = np.zeros((9, 9)) + a[4, 4] = 1 + a = xp.asarray(a) + f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5) + f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2) + xp_assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a sequence. + a = np.zeros((50, 50)) + a[25, 25] = 1 + a = xp.asarray(a) + f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5) + f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9]) + xp_assert_equal(f1, f2) + + +@xfail_xp_backends("cupy", reason="cupy/cupy#8402") +@make_xp_test_case(ndimage.gaussian_filter1d) +def test_gaussian_radius_invalid(xp): + # radius must be a nonnegative integer + with assert_raises(ValueError): + ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=-1) + with assert_raises(ValueError): + ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=1.1) + + +@uses_output_array +class TestThreading: + def check_func_thread(self, n, fun, args, out): + from threading import Thread + thrds = [Thread(target=fun, args=args, kwargs={'output': out[x, ...]}) + for x in range(n)] + [t.start() for t in thrds] + [t.join() for t in thrds] + + def check_func_serial(self, n, fun, args, out): + for i in range(n): + fun(*args, output=out[i, ...]) + + @xfail_xp_backends("cupy", + reason="XXX thread exception; cannot repro outside of pytest") + @make_xp_test_case(ndimage.correlate1d) + def test_correlate1d(self, xp): + d = np.random.randn(5000) + os = np.empty((4, d.size)) + ot = np.empty_like(os) + d = xp.asarray(d) + os = xp.asarray(os) + ot = xp.asarray(ot) + k = xp.arange(5) + self.check_func_serial(4, ndimage.correlate1d, (d, k), os) + self.check_func_thread(4, ndimage.correlate1d, (d, k), ot) + xp_assert_equal(os, ot) + + @xfail_xp_backends("cupy", + reason="XXX thread exception; cannot repro outside of pytest") + @make_xp_test_case(ndimage.correlate) + def test_correlate(self, xp): + d = xp.asarray(np.random.randn(500, 500)) + k = xp.asarray(np.random.randn(10, 10)) + os = xp.empty([4] + list(d.shape)) + ot = xp.empty_like(os) + self.check_func_serial(4, ndimage.correlate, (d, k), os) + self.check_func_thread(4, ndimage.correlate, (d, k), ot) + xp_assert_equal(os, ot) + + @xfail_xp_backends("cupy", + reason="XXX thread exception; cannot repro outside of pytest") + @make_xp_test_case(ndimage.median_filter) + def test_median_filter(self, xp): + d = xp.asarray(np.random.randn(500, 500)) + os = xp.empty([4] + list(d.shape)) + ot = xp.empty_like(os) + self.check_func_serial(4, ndimage.median_filter, (d, 3), os) + self.check_func_thread(4, ndimage.median_filter, (d, 3), ot) + xp_assert_equal(os, ot) + + @xfail_xp_backends("cupy", + reason="XXX thread exception; cannot repro outside of pytest") + @make_xp_test_case(ndimage.uniform_filter1d) + def test_uniform_filter1d(self, xp): + d = np.random.randn(5000) + os = np.empty((4, d.size)) + ot = np.empty_like(os) + d = xp.asarray(d) + os = xp.asarray(os) + ot = xp.asarray(ot) + self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os) + self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot) + xp_assert_equal(os, ot) + + @xfail_xp_backends("cupy", + reason="XXX thread exception; cannot repro outside of pytest") + @make_xp_test_case(ndimage.maximum_filter, ndimage.minimum_filter) + def test_minmax_filter(self, xp): + d = xp.asarray(np.random.randn(500, 500)) + os = xp.empty([4] + list(d.shape)) + ot = xp.empty_like(os) + self.check_func_serial(4, ndimage.maximum_filter, (d, 3), os) + self.check_func_thread(4, ndimage.maximum_filter, (d, 3), ot) + xp_assert_equal(os, ot) + self.check_func_serial(4, ndimage.minimum_filter, (d, 3), os) + self.check_func_thread(4, ndimage.minimum_filter, (d, 3), ot) + xp_assert_equal(os, ot) + +@make_xp_test_case(ndimage.maximum_filter1d, ndimage.minimum_filter1d) +def test_minmaximum_filter1d(xp): + # Regression gh-3898 + in_ = xp.arange(10) + out = ndimage.minimum_filter1d(in_, 1) + xp_assert_equal(in_, out) + out = ndimage.maximum_filter1d(in_, 1) + xp_assert_equal(in_, out) + # Test reflect + out = ndimage.minimum_filter1d(in_, 5, mode='reflect') + xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='reflect') + xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out) + # Test constant + out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1) + xp_assert_equal(xp.asarray([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10) + xp_assert_equal(xp.asarray([10, 10, 4, 5, 6, 7, 8, 9, 10, 10]), out) + # Test nearest + out = ndimage.minimum_filter1d(in_, 5, mode='nearest') + xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='nearest') + xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out) + # Test wrap + out = ndimage.minimum_filter1d(in_, 5, mode='wrap') + xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 0, 0]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='wrap') + xp_assert_equal(xp.asarray([9, 9, 4, 5, 6, 7, 8, 9, 9, 9]), out) + + +@xfail_xp_backends("cupy", reason="cupy/cupy#8401") +@make_xp_test_case(ndimage.uniform_filter1d) +def test_uniform_filter1d_roundoff_errors(xp): + # gh-6930 + in_ = np.repeat([0, 1, 0], [9, 9, 9]) + in_ = xp.asarray(in_) + + for filter_size in range(3, 10): + out = ndimage.uniform_filter1d(in_, filter_size) + xp_assert_equal(xp.sum(out), xp.asarray(10 - filter_size), check_0d=False) + + +@make_xp_test_case(ndimage.maximum_filter) +def test_footprint_all_zeros(xp): + # regression test for gh-6876: footprint of all zeros segfaults + arr = xp.asarray(np.random.randint(0, 100, (100, 100))) + kernel = xp.asarray(np.zeros((3, 3), dtype=bool)) + with assert_raises(ValueError): + ndimage.maximum_filter(arr, footprint=kernel) + + +@xfail_xp_backends("cupy", reason="does not raise") +@skip_xp_backends("array_api_strict", reason="no float16") +@skip_xp_backends("dask.array", reason="no float16") +@make_xp_test_case(ndimage.gaussian_filter) +def test_gaussian_filter_float16(xp): + # gh-8207 + data = xp.asarray([1], dtype=xp.float16) + sigma = 1.0 + with assert_raises(RuntimeError): + ndimage.gaussian_filter(data, sigma) + + +@xfail_xp_backends("cupy", reason="does not raise") +@make_xp_test_case(ndimage.rank_filter) +def test_rank_filter_noninteger_rank(xp): + # regression test for issue 9388: ValueError for + # non integer rank when performing rank_filter + arr = xp.asarray(np.random.random((10, 20, 30))) + footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool)) + assert_raises(TypeError, ndimage.rank_filter, arr, 0.5, + footprint=footprint) + + +@make_xp_test_case(ndimage.rank_filter) +def test_size_footprint_both_set(xp): + # test for input validation, expect user warning when + # size and footprint is set + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", + "ignoring size because footprint is set", UserWarning) + arr = xp.asarray(np.random.random((10, 20, 30))) + footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool)) + ndimage.rank_filter( + arr, 5, size=2, footprint=footprint + ) + + +# NumPy-only because 'byteorder is numpy-specific' +def test_byte_order_median(): + """Regression test for #413: median_filter does not handle bytes orders.""" + a = np.arange(9, dtype='1 makes sense too + (3, + np.array([0.25266576, 0.30958242, 0.27894721, 0.27894721, 0.27894721, 0.30445588, + 0.31442572, 0.30445588, 0.18015438, 0.14831921, 0.18015438, 0.25754605, + 0.32910465, 0.25754605, 0.17736568, 0.17736568, 0.09089549, 0.22183391, + 0.25266576, 0.30958242]), + ), + (15, + np.array([0.27894721, 0.25266576, 0.25266576, 0.25266576, 0.27894721, 0.27894721, + 0.27894721, 0.27894721, 0.25754605, 0.25754605, 0.22183391, 0.22183391, + 0.25266576, 0.25266576, 0.22183391, 0.22183391, 0.25266576, 0.25266576, + 0.25754605, 0.25754605]), + ), +]) +def test_gh_22250(filter_size, exp): + rng = np.random.default_rng(42) + image = np.zeros((20,)) + noisy_image = image + 0.4 * rng.random(image.shape) + result = ndimage.median_filter(noisy_image, size=filter_size, mode='wrap') + assert_allclose(result, exp) + + +def test_gh_22333(): + x = np.array([272, 58, 67, 163, 463, 608, 87, 108, 1378]) + expected = [58, 67, 87, 108, 163, 108, 108, 108, 87] + actual = ndimage.median_filter(x, size=9, mode='constant') + assert_array_equal(actual, expected) + + +@pytest.mark.filterwarnings("ignore:The given NumPy array is not writable:UserWarning") +@make_xp_test_case(ndimage.vectorized_filter) +class TestVectorizedFilter: + @pytest.mark.parametrize("axes, size", + [(None, (3, 4, 5)), ((0, 2), (3, 4)), ((-1,), (5,))]) + @pytest.mark.parametrize("origin", [-1, 0, 1]) + @pytest.mark.parametrize("mode", + ['reflect', 'nearest', 'mirror', 'wrap', 'constant']) + @pytest.mark.parametrize("use_output", [False, True]) + def test_against_generic_filter(self, axes, size, origin, mode, use_output, xp): + rng = np.random.default_rng(435982456983456987356) + + if use_output and (is_dask(xp) or is_jax(xp)): + pytest.skip("Requires mutable arrays.") + + input = rng.random(size=(11, 12, 13)) + input_copy = input.copy() # check that it is not modified + output = xp.zeros(input.shape) if use_output else None + + kwargs = dict(axes=axes, size=size, origin=origin, mode=mode) + ref = ndimage.generic_filter(input, np.mean, **kwargs) + kwargs['output'] = output + res = ndimage.vectorized_filter(xp.asarray(input.tolist()), + xp.mean, **kwargs) + xp_assert_close(res, xp.asarray(ref.tolist()), atol=1e-15) + if use_output: + xp_assert_equal(output, res) + + if not (is_array_api_strict(xp) or is_dask(xp)): + # currently requires support for [..., mask] indexing + kwargs.pop('size') + kwargs.pop('output') + kwargs['footprint'] = rng.random(size=size or input.shape) > 0.5 + ref = ndimage.generic_filter(input, np.mean, **kwargs) + kwargs['footprint'] = xp.asarray(kwargs['footprint']) + kwargs['output'] = output + res = ndimage.vectorized_filter(xp.asarray(input.tolist()), + xp.mean, **kwargs) + xp_assert_close(res, xp.asarray(ref.tolist()), atol=1e-15) + if use_output: + xp_assert_equal(output, res) + + xp_assert_equal(xp.asarray(input), xp.asarray(input_copy)) + + @pytest.mark.parametrize("dtype", + ["uint8", "uint16", "uint32", "uint64", + "int8", "int16", "int32", "int64", + "float32", "float64", "complex64", "complex128"]) + @pytest.mark.parametrize("batch_memory", [1, 16*3, np.inf]) + @pytest.mark.parametrize("use_footprint", [False, True]) + def test_dtype_batch_memory(self, dtype, batch_memory, use_footprint, xp): + rng = np.random.default_rng(435982456983456987356) + w = 3 + + if is_jax(xp) and not (batch_memory == 1): + pytest.skip("Requires mutable array.") + if is_torch(xp) and dtype in {'uint16', 'uint32', 'uint64'}: + pytest.skip("Needs uint support.") + + dtype = getattr(xp, dtype) + + if use_footprint: + if (is_dask(xp) or is_array_api_strict(xp)): + pytest.skip("Requires [..., mask] indexing.") + footprint = xp.asarray([True, False, True]) + kwargs = dict(footprint=footprint, batch_memory=batch_memory) + else: + footprint = xp.asarray([True, True, True]) + kwargs = dict(size=w, batch_memory=batch_memory) + + # The intent here is to exercise all the code paths involved in `batch_memory` + # and `output` handling. To test the limited-memory case, `batch_memory=16*3` + # is chosen to be just large enough for a *single* window of `complex128` to + # fit, and `n` is large enough that a whole sliding window view of `uint8`s + # *won't* fit. + n = 16*3 + 1 + input = rng.integers(0, 42, size=(n,)) + input = input + input*1j if xp.isdtype(dtype, 'complex floating') else input + input_padded = xp.asarray(np.pad(input, [(1, 1)], mode='symmetric'), + dtype=dtype) + input = xp.asarray(input, dtype=dtype) + + ref = [xp.sum(input_padded[i: i + w][footprint]) for i in range(n)] + sum_dtype = xp.sum(input_padded).dtype + + message = "`batch_memory` is insufficient for minimum chunk size." + context = (pytest.raises(ValueError, match=message) + if batch_memory == 1 else contextlib.nullcontext()) + with context: + res = ndimage.vectorized_filter(input, xp.sum, **kwargs) + xp_assert_close(res, xp.astype(xp.stack(ref), sum_dtype)) + assert res.dtype == sum_dtype + + output = xp.empty_like(input) + res = ndimage.vectorized_filter( + input, + lambda x, *args, **kw: xp.astype( + xp.sum(x, *args, **kw), x.dtype, copy=False + ), + output=output, + **kwargs + ) + xp_assert_close(res, xp.astype(xp.stack(ref), dtype)) + assert res.dtype == dtype + + def test_mode_valid(self, xp): + rng = np.random.default_rng(435982456983456987356) + input = rng.random(size=(10, 11)) + input_xp = xp.asarray(input) + input_xp_copy = xp_copy(input_xp) # check that it is not modified + size = (3, 5) + + res = ndimage.vectorized_filter(input_xp, xp.mean, size=size, mode='valid') + + view = np.lib.stride_tricks.sliding_window_view(input, size) + ref = np.mean(view, axis=(-2, -1)) + + xp_assert_close(res, xp.asarray(ref)) + assert res.shape == tuple(input.shape - np.asarray(size) + 1) + xp_assert_equal(input_xp, input_xp_copy) + + def test_input_validation(self, xp): + input = xp.ones((10, 10)) + function = xp.mean + size = 2 + footprint = xp.ones((2, 2)) + + message = "`function` must be a callable." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, "eggplant", size=size) + + message = "Either `size` or `footprint` must be provided." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function) + + message = "Either `size` or `footprint` may be provided, not both." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, footprint=footprint) + + message = "All elements of `size` must be positive integers." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=(1, -1)) + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=0) + + message = "The length of `axes` may not exceed " + axes = (0, 1, 2) + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=(1, 2), axes=axes) + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, footprint=xp.ones((2, 2)), + axes=axes) + + message = "`axes` must be compatible with the dimensionality..." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=(1,)) + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=(2,), axes=(0,1)) + + message = "All elements of `origin` must be integers" + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, origin=(1, 1.5)) + + message = "`origin` must be an integer or tuple of integers with length..." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, origin=(1, 2, 3)) + + message = "`mode` must be one of..." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, mode='coconut') + + message = "`mode='valid'` is incompatible with use of `origin`." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, + mode='valid', origin=1) + + message = "Use of `cval` is compatible only with `mode='constant'`." + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, mode='valid', cval=1) + + other_messages = "|Unsupported|The array_api_strict|new|Value 'a duck'" + message = "`cval` must include only numbers." + other_messages + with pytest.raises((ValueError, TypeError), match=message): + ndimage.vectorized_filter(input, function, size=size, + mode='constant', cval='a duck') + + message = "`batch_memory` must be positive number." + other_messages + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, batch_memory=0) + with pytest.raises(ValueError, match=message): + ndimage.vectorized_filter(input, function, size=size, batch_memory=(1, 2)) + with pytest.raises((ValueError, TypeError), match=message): + ndimage.vectorized_filter(input, function, size=size, batch_memory="a duck") + + @pytest.mark.parametrize('shape', [(0,), (1, 0), (0, 1, 0)]) + def test_zero_size(self, shape, xp): + input = xp.empty(shape) + res = ndimage.vectorized_filter(input, xp.mean, size=1) + xp_assert_equal(res, input) + + @pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning") + def test_edge_cases(self, xp): + rng = np.random.default_rng(4835982345234982) + function = xp.mean + + # 0-D input + input = xp.asarray(1.) + res = ndimage.vectorized_filter(input, function, size=()) + xp_assert_equal(res, xp.asarray(function(input, axis=()))) + + if not (is_array_api_strict(xp) or is_dask(xp)): + res = ndimage.vectorized_filter(input, function, footprint=True) + xp_assert_equal(res, xp.asarray(function(input[True], axis=()))) + + res = ndimage.vectorized_filter(input, function, footprint=False) + xp_assert_equal(res, xp.asarray(function(input[False], axis=()))) + + # 1x1 window + input = xp.asarray(rng.random((5, 5))) + res = ndimage.vectorized_filter(input, function, size=1) + xp_assert_equal(res, input) + + # window is bigger than input shouldn't be a problem + res = ndimage.vectorized_filter(input, function, size=21) + ref = ndimage.vectorized_filter(input, function, size=21) + xp_assert_close(res, ref) + + def test_gh23046_feature(self, xp): + # The intent of gh-23046 was to always allow `size` to be a scalar. + rng = np.random.default_rng(45982734597824) + img = xp.asarray(rng.random((5, 5))) + + ref = ndimage.vectorized_filter(img, xp.mean, size=2) + res = ndimage.vectorized_filter(img, xp.mean, size=2, axes=(0, 1)) + xp_assert_close(res, ref) + + ref = ndimage.vectorized_filter(img, xp.mean, size=(2,), axes=(0,)) + res = ndimage.vectorized_filter(img, xp.mean, size=2, axes=0) + xp_assert_close(res, ref) + + def test_gh23046_fix(self, xp): + # While investigating the feasibility of gh-23046, I noticed a bug when the + # length of an `axes` tuple equals the dimensionality of the image. + rng = np.random.default_rng(45982734597824) + img = xp.asarray(rng.random((5, 5))) + size = (2, 3) + ref = ndimage.vectorized_filter(img.T, xp.mean, size=size).T + res = ndimage.vectorized_filter(img, xp.mean, size=size, axes=(1, 0)) + xp_assert_close(res, ref) + + ref = ndimage.vectorized_filter(img, xp.mean, size=size, mode='constant') + res = ndimage.vectorized_filter(img, xp.mean, size=size[::-1], axes=(1, 0), + mode='constant') + xp_assert_close(res, ref) + + +@given(x=npst.arrays(dtype=np.float64, + shape=st.integers(min_value=1, max_value=1000)), + size=st.integers(min_value=1, max_value=50), + mode=st.sampled_from(["constant", "mirror", "wrap", "reflect", + "nearest"]), + ) +def test_gh_22586_crash_property(x, size, mode): + # property-based test for median_filter resilience to hard crashing + ndimage.median_filter(x, size=size, mode=mode) + + +@pytest.mark.parametrize('samples, mode, size, expected', [ + ([1, 2], "reflect", 5, [2, 1]), + ([2], "reflect", 5, [2]), # original failure from gh-23075 + ([2], "nearest", 5, [2]), + ([2], "wrap", 5, [2]), + ([2], "mirror", 5, [2]), + ([2], "constant", 5, [0]), + ([2], "reflect", 1, [2]), + ([2], "nearest", 1, [2]), + ([2], "wrap", 1, [2]), + ([2], "mirror", 1, [2]), + ([2], "constant", 1, [2]), + ([2], "reflect", 100, [2]), + ([2], "nearest", 100, [2]), + ([2], "wrap", 100, [2]), + ([2], "mirror", 100, [2]), + ([2], "constant", 100, [0]), +]) +def test_gh_23075(samples, mode, size, expected): + # results verified against SciPy 1.14.1, before the median_filter + # overhaul + sample_array = np.asarray(samples, dtype=np.float32) + expected = np.asarray(expected, dtype=np.float32) + filtered_samples = ndimage.median_filter(sample_array, size=size, mode=mode) + xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True) + + +@pytest.mark.parametrize('samples, size, cval, expected', [ + ([2], 5, 17.7, [17.7]), + ([2], 1, 0, [2]), + ([2], 100, 1.4, [1.4]), + ([9], 137, -7807.7, [-7807.7]), +]) +def test_gh_23075_constant(samples, size, cval, expected): + # results verified against SciPy 1.14.1, before the median_filter + # overhaul + sample_array = np.asarray(samples, dtype=np.single) + expected = np.asarray(expected, dtype=np.single) + filtered_samples = ndimage.median_filter(sample_array, + size=size, + mode="constant", + cval=cval) + xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True) + + +def test_median_filter_lim2(): + sample_array = np.ones(8) + expected = np.ones(8) + filtered_samples = ndimage.median_filter(sample_array, size=19, mode="reflect") + xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_fourier.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..bc750a685e88c74cc25bb979f999ba499ce6695f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_fourier.py @@ -0,0 +1,197 @@ +import math +import numpy as np + +from scipy._lib._array_api import ( + xp_assert_equal, + assert_array_almost_equal, + assert_almost_equal, + is_cupy, + make_xp_test_case, + make_xp_pytest_param, +) + +import pytest + +from scipy import ndimage + +skip_xp_backends = pytest.mark.skip_xp_backends + + +class TestNdimageFourier: + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)]) + @make_xp_test_case(ndimage.fourier_gaussian) + def test_fourier_gaussian_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.rfft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)]) + @make_xp_test_case(ndimage.fourier_gaussian) + def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.fft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)]) + @make_xp_test_case(ndimage.fourier_uniform) + def test_fourier_uniform_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.rfft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)]) + @make_xp_test_case(ndimage.fourier_uniform) + def test_fourier_uniform_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.fft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)]) + @make_xp_test_case(ndimage.fourier_shift) + def test_fourier_shift_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape) + expected = xp.asarray(expected) + + a = fft.rfft(expected, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_shift(a, [1, 1], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)]) + @make_xp_test_case(ndimage.fourier_shift) + def test_fourier_shift_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape) + expected = xp.asarray(expected) + + a = fft.fft(expected, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_shift(a, [1, 1], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec) + assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)]) + @make_xp_test_case(ndimage.fourier_ellipsoid) + def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.rfft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)]) + @make_xp_test_case(ndimage.fourier_ellipsoid) + def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.fft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @make_xp_test_case(ndimage.fourier_ellipsoid) + def test_fourier_ellipsoid_unimplemented_ndim(self, xp): + # arrays with ndim > 3 raise NotImplementedError + x = xp.ones((4, 6, 8, 10), dtype=xp.complex128) + with pytest.raises(NotImplementedError): + ndimage.fourier_ellipsoid(x, 3) + + @make_xp_test_case(ndimage.fourier_ellipsoid) + def test_fourier_ellipsoid_1d_complex(self, xp): + # expected result of 1d ellipsoid is the same as for fourier_uniform + for shape in [(32, ), (31, )]: + for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]): + x = xp.ones(shape, dtype=type_) + a = ndimage.fourier_ellipsoid(x, 5, -1, 0) + b = ndimage.fourier_uniform(x, 5, -1, 0) + assert_array_almost_equal(a, b, decimal=dec) + + @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)]) + @pytest.mark.parametrize('dtype', ["float32", "float64", + "complex64", "complex128"]) + @pytest.mark.parametrize('test_func', + [make_xp_pytest_param(ndimage.fourier_ellipsoid), + make_xp_pytest_param(ndimage.fourier_gaussian), + make_xp_pytest_param(ndimage.fourier_uniform)]) + def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp): + if ( + is_cupy(xp) + and test_func.__name__ == "fourier_ellipsoid" + and math.prod(shape) == 0 + ): + pytest.xfail("CuPy's fourier_ellipsoid does not accept size==0 arrays") + dtype = getattr(xp, dtype) + a = xp.ones(shape, dtype=dtype) + b = test_func(a, 3) + xp_assert_equal(a, b) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_interpolation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..9949476ad2be2d2615f71d8eb3757c6ce2b2d740 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_interpolation.py @@ -0,0 +1,1499 @@ +import sys +import warnings + +import numpy as np +from scipy._lib._array_api import ( + _asarray, assert_array_almost_equal, + is_jax, np_compat, + xp_assert_equal, xp_assert_close, + make_xp_test_case, +) + +import pytest +from pytest import raises as assert_raises +import scipy.ndimage as ndimage + +from . import types + +skip_xp_backends = pytest.mark.skip_xp_backends +xfail_xp_backends = pytest.mark.xfail_xp_backends +# lazy_xp_modules = [ndimage] + + +eps = 1e-12 + +ndimage_to_numpy_mode = { + 'mirror': 'reflect', + 'reflect': 'symmetric', + 'grid-mirror': 'symmetric', + 'grid-wrap': 'wrap', + 'nearest': 'edge', + 'grid-constant': 'constant', +} + + +class TestBoundaries: + + @make_xp_test_case(ndimage.geometric_transform) + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]), + ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]), + ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]), + ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]), + ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]), + ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]), + ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])] + ) + def test_boundaries(self, mode, expected_value, xp): + def shift(x): + return (x[0] + 0.5,) + + data = xp.asarray([1, 2, 3, 4.]) + xp_assert_equal( + ndimage.geometric_transform(data, shift, cval=-1, mode=mode, + output_shape=(7,), order=1), + xp.asarray(expected_value)) + + @make_xp_test_case(ndimage.geometric_transform) + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 2, 3]), + ('wrap', [3, 1, 2, 3]), + ('grid-wrap', [4, 1, 2, 3]), + ('mirror', [2, 1, 2, 3]), + ('reflect', [1, 1, 2, 3]), + ('constant', [-1, 1, 2, 3]), + ('grid-constant', [-1, 1, 2, 3])] + ) + def test_boundaries2(self, mode, expected_value, xp): + def shift(x): + return (x[0] - 0.9,) + + data = xp.asarray([1, 2, 3, 4]) + xp_assert_equal( + ndimage.geometric_transform(data, shift, cval=-1, mode=mode, + output_shape=(4,)), + xp.asarray(expected_value)) + + @make_xp_test_case(ndimage.map_coordinates) + @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror', + 'grid-wrap', 'grid-constant', + 'nearest']) + @pytest.mark.parametrize('order', range(6)) + def test_boundary_spline_accuracy(self, mode, order, xp): + """Tests based on examples from gh-2640""" + if (is_jax(xp) and + (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest'] + or order > 1) + ): + pytest.xfail("Jax does not support grid- modes or order > 1") + + np_data = np.arange(-6, 7, dtype=np.float64) + data = xp.asarray(np_data) + x = xp.asarray(np.linspace(-8, 15, num=1000)) + y = ndimage.map_coordinates(data, x[xp.newaxis, ...], order=order, mode=mode) + + # compute expected value using explicit padding via np.pad + npad = 32 + pad_mode = ndimage_to_numpy_mode.get(mode) + padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode)) + coords = xp.asarray(npad + x)[xp.newaxis, ...] + expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode) + + atol = 1e-5 if mode == 'grid-constant' else 1e-12 + xp_assert_close(y, expected, rtol=1e-7, atol=atol) + + +@make_xp_test_case(ndimage.spline_filter) +@pytest.mark.parametrize('order', range(2, 6)) +@pytest.mark.parametrize('dtype', types) +class TestSpline: + + def test_spline01(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.spline_filter(data, order=order) + assert out == xp.asarray(1, dtype=out.dtype) + + def test_spline02(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([1], dtype=dtype) + out = ndimage.spline_filter(data, order=order) + assert_array_almost_equal(out, xp.asarray([1])) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='output=dtype is numpy-specific') + def test_spline03(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.spline_filter(data, order, output=dtype) + assert out == xp.asarray(1, dtype=out.dtype) + + def test_spline04(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([4], dtype=dtype) + out = ndimage.spline_filter(data, order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1])) + + def test_spline05(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([4, 4], dtype=dtype) + out = ndimage.spline_filter(data, order=order) + expected = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]]) + assert_array_almost_equal(out, expected) + + +@make_xp_test_case(ndimage.geometric_transform) +@pytest.mark.parametrize('order', range(0, 6)) +class TestGeometricTransform: + + def test_geometric_transform01(self, order, xp): + data = xp.asarray([1]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype)) + + def test_geometric_transform02(self, order, xp): + data = xp.ones([4]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype)) + + def test_geometric_transform03(self, order, xp): + data = xp.ones([4]) + + def mapping(x): + return (x[0] - 1,) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype)) + + def test_geometric_transform04(self, order, xp): + data = xp.asarray([4, 1, 3, 2]) + + def mapping(x): + return (x[0] - 1,) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype)) + + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_geometric_transform05(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = xp.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + + if xp.isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + + def mapping(x): + return (x[0], x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, expected) + + def test_geometric_transform06(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0], x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + expected = xp.asarray([[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform07(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1]) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + expected = xp.asarray([[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform08(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform10(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1] - 1) + + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.geometric_transform(filtered, mapping, data.shape, + order=order, prefilter=False) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform13(self, order, xp): + data = xp.ones([2], dtype=xp.float64) + + def mapping(x): + return (x[0] // 2,) + + out = ndimage.geometric_transform(data, mapping, [4], order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype)) + + def test_geometric_transform14(self, order, xp): + data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4]) + + def mapping(x): + return (2 * x[0],) + + out = ndimage.geometric_transform(data, mapping, [4], order=order) + assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype)) + + def test_geometric_transform15(self, order, xp): + data = xp.asarray([1, 2, 3, 4]) + + def mapping(x): + return (x[0] / 2,) + + out = ndimage.geometric_transform(data, mapping, [8], order=order) + assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4])) + + def test_geometric_transform16(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9.0, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x): + return (x[0], x[1] * 2) + + out = ndimage.geometric_transform(data, mapping, (3, 2), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]])) + + def test_geometric_transform17(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x): + return (x[0] * 2, x[1]) + + out = ndimage.geometric_transform(data, mapping, (1, 4), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]])) + + def test_geometric_transform18(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x): + return (x[0] * 2, x[1] * 2) + + out = ndimage.geometric_transform(data, mapping, (1, 2), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 3]])) + + def test_geometric_transform19(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x): + return (x[0], x[1] / 2) + + out = ndimage.geometric_transform(data, mapping, (3, 8), + order=order) + assert_array_almost_equal(out[..., ::2], data) + + def test_geometric_transform20(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x): + return (x[0] / 2, x[1]) + + out = ndimage.geometric_transform(data, mapping, (6, 4), + order=order) + assert_array_almost_equal(out[::2, ...], data) + + def test_geometric_transform21(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x): + return (x[0] / 2, x[1] / 2) + + out = ndimage.geometric_transform(data, mapping, (6, 8), + order=order) + assert_array_almost_equal(out[::2, ::2], data) + + def test_geometric_transform22(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data, dtype=xp.float64) + + def mapping1(x): + return (x[0] / 2, x[1] / 2) + + def mapping2(x): + return (x[0] * 2, x[1] * 2) + + out = ndimage.geometric_transform(data, mapping1, + (6, 8), order=order) + out = ndimage.geometric_transform(out, mapping2, + (3, 4), order=order) + assert_array_almost_equal(out, data) + + def test_geometric_transform23(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x): + return (1, x[0] * 2) + + out = ndimage.geometric_transform(data, mapping, (2,), order=order) + assert_array_almost_equal(out, xp.asarray([5, 7])) + + def test_geometric_transform24(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + + def mapping(x, a, b): + return (a, x[0] * b) + + out = ndimage.geometric_transform( + data, mapping, (2,), order=order, extra_arguments=(1,), + extra_keywords={'b': 2}) + assert_array_almost_equal(out, xp.asarray([5, 7])) + + +@make_xp_test_case(ndimage.geometric_transform) +class TestGeometricTransformExtra: + + def test_geometric_transform_grid_constant_order1(self, xp): + + # verify interpolation outside the original bounds + x = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=xp.float64) + + def mapping(x): + return (x[0] - 0.5), (x[1] - 0.5) + + expected_result = xp.asarray([[0.25, 0.75, 1.25], + [1.25, 3.00, 4.00]]) + assert_array_almost_equal( + ndimage.geometric_transform(x, mapping, mode='grid-constant', + order=1), + expected_result, + ) + + @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest', + 'mirror', 'reflect']) + @pytest.mark.parametrize('order', range(6)) + def test_geometric_transform_vs_padded(self, order, mode, xp): + + def mapping(x): + return (x[0] - 0.4), (x[1] + 2.3) + + # Manually pad and then extract center after the transform to get the + # expected result. + x = np.arange(144, dtype=float).reshape(12, 12) + npad = 24 + pad_mode = ndimage_to_numpy_mode.get(mode) + x_padded = np.pad(x, npad, mode=pad_mode) + + x = xp.asarray(x) + x_padded = xp.asarray(x_padded) + + center_slice = tuple([slice(npad, -npad)] * x.ndim) + expected_result = ndimage.geometric_transform( + x_padded, mapping, mode=mode, order=order)[center_slice] + + xp_assert_close( + ndimage.geometric_transform(x, mapping, mode=mode, + order=order), + expected_result, + rtol=1e-7, + ) + + @skip_xp_backends(np_only=True, reason='endianness is numpy-specific') + def test_geometric_transform_endianness_with_output_parameter(self, xp): + # geometric transform given output ndarray or dtype with + # non-native endianness. see issue #4127 + data = np.asarray([1]) + + def mapping(x): + return x + + for out in [data.dtype, data.dtype.newbyteorder(), + np.empty_like(data), + np.empty_like(data).astype(data.dtype.newbyteorder())]: + returned = ndimage.geometric_transform(data, mapping, data.shape, + output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, [1]) + + @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific') + def test_geometric_transform_with_string_output(self, xp): + data = xp.asarray([1]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, output='f') + assert out.dtype is np.dtype('f') + assert_array_almost_equal(out, [1]) + + +@make_xp_test_case(ndimage.map_coordinates) +class TestMapCoordinates: + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [np.float64, np.complex128]) + def test_map_coordinates01(self, order, dtype, xp): + if is_jax(xp) and order > 1: + pytest.xfail("jax map_coordinates requires order <= 1") + + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + if xp.isdtype(data.dtype, 'complex floating'): + data = data - 1j * data + expected = expected - 1j * expected + + idx = np.indices(data.shape) + idx -= 1 + idx = xp.asarray(idx) + + out = ndimage.map_coordinates(data, idx, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_map_coordinates02(self, order, xp): + if is_jax(xp): + if order > 1: + pytest.xfail("jax map_coordinates requires order <= 1") + if order == 1: + pytest.xfail("output differs. jax bug?") + + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + idx = np.indices(data.shape, np.float64) + idx -= 0.5 + idx = xp.asarray(idx) + + out1 = ndimage.shift(data, 0.5, order=order) + out2 = ndimage.map_coordinates(data, idx, order=order) + assert_array_almost_equal(out1, out2) + + @skip_xp_backends("jax.numpy", reason="`order` is required in jax") + def test_map_coordinates03(self, xp): + data = _asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]], order='F', xp=xp) + idx = np.indices(data.shape) - 1 + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data, idx) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + assert_array_almost_equal(out, expected) + assert_array_almost_equal(out, ndimage.shift(data, (1, 1))) + + idx = np.indices(data[::2, ...].shape) - 1 + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data[::2, ...], idx) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3]])) + assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1))) + + idx = np.indices(data[:, ::2].shape) - 1 + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data[:, ::2], idx) + assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]])) + assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1))) + + @skip_xp_backends(np_only=True) + def test_map_coordinates_endianness_with_output_parameter(self, xp): + # output parameter given as array or dtype with either endianness + # see issue #4127 + # NB: NumPy-only + + data = np.asarray([[1, 2], [7, 6]]) + expected = np.asarray([[0, 0], [0, 1]]) + idx = np.indices(data.shape) + idx -= 1 + for out in [ + data.dtype, + data.dtype.newbyteorder(), + np.empty_like(expected), + np.empty_like(expected).astype(expected.dtype.newbyteorder()) + ]: + returned = ndimage.map_coordinates(data, idx, output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, expected) + + @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific') + def test_map_coordinates_with_string_output(self, xp): + data = xp.asarray([[1]]) + idx = np.indices(data.shape) + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data, idx, output='f') + assert out.dtype is np.dtype('f') + assert_array_almost_equal(out, xp.asarray([[1]])) + + @pytest.mark.skip_xp_backends(cpu_only=True) + @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8, + reason='do not run on 32 bit or windows ' + '(no sparse memory)') + def test_map_coordinates_large_data(self, xp): + # check crash on large data + try: + n = 30000 + # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n)) + a = np.empty(n**2, dtype=np.float32).reshape(n, n) + # fill the part we might read + a[n - 3:, n - 3:] = 0 + ndimage.map_coordinates( + xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1 + ) + except MemoryError as e: + raise pytest.skip('Not enough memory available') from e + + +@make_xp_test_case(ndimage.affine_transform) +class TestAffineTransform: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform01(self, order, xp): + data = xp.asarray([1]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order) + assert_array_almost_equal(out, xp.asarray([1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform02(self, order, xp): + data = xp.ones([4]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform03(self, order, xp): + data = xp.ones([4]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform04(self, order, xp): + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order) + assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3])) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_affine_transform05(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = xp.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + if xp.isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [0, -1], order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform06(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [0, -1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform07(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [-1, 0], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform08(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [-1, -1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform09(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]), + [-1, -1], order=order, + prefilter=False) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform10(self, order, xp): + data = xp.ones([2], dtype=xp.float64) + out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,), + order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform11(self, order, xp): + data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4]) + out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order) + assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform12(self, order, xp): + data = xp.asarray([1, 2, 3, 4]) + out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order) + assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform13(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9.0, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform14(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform15(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 3]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform16(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0, + (3, 8), order=order) + assert_array_almost_equal(out[..., ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform17(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0, + (6, 4), order=order) + assert_array_almost_equal(out[::2, ...], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform18(self, order, xp): + data = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]]) + out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0, + (6, 8), order=order) + assert_array_almost_equal(out[::2, ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform19(self, order, xp): + data = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], dtype=xp.float64) + out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0, + (6, 8), order=order) + out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0, + (3, 4), order=order) + assert_array_almost_equal(out, data) + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394") + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform20(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,), + order=order) + assert_array_almost_equal(out, xp.asarray([1, 3])) + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394") + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform21(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,), + order=order) + assert_array_almost_equal(out, xp.asarray([1, 9])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform22(self, order, xp): + # shift and offset interaction; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,), + order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 2])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform23(self, order, xp): + # shift and offset interaction; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,), + order=order) + assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform24(self, order, xp): + # consistency between diagonal and non-diagonal case; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + 'The behavior of affine_transform with a 1-D array .* has changed', + UserWarning) + out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order) + out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order) + assert_array_almost_equal(out1, out2) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform25(self, order, xp): + # consistency between diagonal and non-diagonal case; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed', UserWarning) + out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order) + out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order) + assert_array_almost_equal(out1, out2) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform26(self, order, xp): + # test homogeneous coordinates + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + tform_original = xp.eye(2) + offset_original = -xp.ones((2, 1)) + + tform_h1 = xp.concat((tform_original, offset_original), axis=1) # hstack + tform_h2 = xp.concat((tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0) # vstack + + offs = [float(x) for x in xp.reshape(offset_original, (-1,))] + + out1 = ndimage.affine_transform(filtered, tform_original, + offs, + order=order, prefilter=False) + out2 = ndimage.affine_transform(filtered, tform_h1, order=order, + prefilter=False) + out3 = ndimage.affine_transform(filtered, tform_h2, order=order, + prefilter=False) + for out in [out1, out2, out3]: + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @xfail_xp_backends("cupy", reason="does not raise") + def test_affine_transform27(self, xp): + # test valid homogeneous transformation matrix + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + tform_h1 = xp.concat((xp.eye(2), -xp.ones((2, 1))) , axis=1) # vstack + tform_h2 = xp.concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0) # hstack + + assert_raises(ValueError, ndimage.affine_transform, data, tform_h2) + + @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific') + def test_affine_transform_1d_endianness_with_output_parameter(self, xp): + # 1d affine transform given output ndarray or dtype with + # either endianness. see issue #7388 + data = xp.ones((2, 2)) + for out in [xp.empty_like(data), + xp.empty_like(data).astype(data.dtype.newbyteorder()), + data.dtype, data.dtype.newbyteorder()]: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", + 'The behavior of affine_transform with a 1-D array ' + '.* has changed', UserWarning) + matrix = xp.asarray([1, 1]) + returned = ndimage.affine_transform(data, matrix, output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]])) + + @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific') + def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp): + # affine transform given output ndarray or dtype with either endianness + # see issue #4127 + # NB: byteorder is numpy-specific + data = np.asarray([1]) + for out in [data.dtype, data.dtype.newbyteorder(), + np.empty_like(data), + np.empty_like(data).astype(data.dtype.newbyteorder())]: + returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, np.asarray([1])) + + @skip_xp_backends(np_only=True, + reason='`out` of a different size is numpy-specific' + ) + def test_affine_transform_output_shape(self, xp): + # don't require output_shape when out of a different size is given + data = xp.arange(8, dtype=xp.float64) + out = xp.ones((16,)) + + ndimage.affine_transform(data, xp.asarray([[1]]), output=out) + assert_array_almost_equal(out[:8], data) + + # mismatched output shape raises an error + with pytest.raises(RuntimeError): + ndimage.affine_transform( + data, [[1]], output=out, output_shape=(12,)) + + @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific') + def test_affine_transform_with_string_output(self, xp): + data = xp.asarray([1]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f') + assert out.dtype is np.dtype('f') + assert_array_almost_equal(out, xp.asarray([1])) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp): + # For mode 'grid-wrap', integer shifts should match np.roll + x = np.asarray([[0, 1], + [2, 3]]) + affine = np.zeros((2, 3)) + affine[:2, :2] = np.eye(2) + affine[:, 2] = np.asarray(shift) + + expected = np.roll(x, shift, axis=(0, 1)) + + x = xp.asarray(x) + affine = xp.asarray(affine) + expected = xp.asarray(expected) + + assert_array_almost_equal( + ndimage.affine_transform(x, affine, mode='grid-wrap', order=order), + expected + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform_shift_reflect(self, order, xp): + # shift by x.shape results in reflection + x = np.asarray([[0, 1, 2], + [3, 4, 5]]) + expected = x[::-1, ::-1].copy() # strides >0 for torch + x = xp.asarray(x) + expected = xp.asarray(expected) + + affine = np.zeros([2, 3]) + affine[:2, :2] = np.eye(2) + affine[:, 2] = np.asarray(x.shape) + affine = xp.asarray(affine) + + assert_array_almost_equal( + ndimage.affine_transform(x, affine, mode='reflect', order=order), + expected, + ) + + +@make_xp_test_case(ndimage.shift) +class TestShift: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift01(self, order, xp): + data = xp.asarray([1]) + out = ndimage.shift(data, [1], order=order) + assert_array_almost_equal(out, xp.asarray([0])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift02(self, order, xp): + data = xp.ones([4]) + out = ndimage.shift(data, [1], order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift03(self, order, xp): + data = xp.ones([4]) + out = ndimage.shift(data, -1, order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift04(self, order, xp): + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.shift(data, 1, order=order) + assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3])) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_shift05(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = xp.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + if xp.isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + out = ndimage.shift(data, [0, 1], order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('mode', ['constant', 'grid-constant']) + @pytest.mark.parametrize('dtype', ['float64', 'complex128']) + def test_shift_with_nonzero_cval(self, order, mode, dtype, xp): + data = np.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + + expected = np.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + + if np_compat.isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + cval = 5.0 + expected[:, 0] = cval # specific to shift of [0, 1] used below + + data = xp.asarray(data) + expected = xp.asarray(expected) + out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift06(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [0, 1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift07(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [1, 0], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift08(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [1, 1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift09(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_grid_wrap(self, shift, order, xp): + # For mode 'grid-wrap', integer shifts should match np.roll + x = np.asarray([[0, 1], + [2, 3]]) + expected = np.roll(x, shift, axis=(0,1)) + + x = xp.asarray(x) + expected = xp.asarray(expected) + + assert_array_almost_equal( + ndimage.shift(x, shift, mode='grid-wrap', order=order), + expected + ) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_grid_constant1(self, shift, order, xp): + # For integer shifts, 'constant' and 'grid-constant' should be equal + x = xp.reshape(xp.arange(20), (5, 4)) + assert_array_almost_equal( + ndimage.shift(x, shift, mode='grid-constant', order=order), + ndimage.shift(x, shift, mode='constant', order=order), + ) + + def test_shift_grid_constant_order1(self, xp): + x = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=xp.float64) + expected_result = xp.asarray([[0.25, 0.75, 1.25], + [1.25, 3.00, 4.00]]) + assert_array_almost_equal( + ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1), + expected_result, + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_reflect(self, order, xp): + # shift by x.shape results in reflection + x = np.asarray([[0, 1, 2], + [3, 4, 5]]) + expected = x[::-1, ::-1].copy() # strides > 0 for torch + + x = xp.asarray(x) + expected = xp.asarray(expected) + assert_array_almost_equal( + ndimage.shift(x, x.shape, mode='reflect', order=order), + expected, + ) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('prefilter', [False, True]) + def test_shift_nearest_boundary(self, order, prefilter, xp): + # verify that shifting at least order // 2 beyond the end of the array + # gives a value equal to the edge value. + x = xp.arange(16) + kwargs = dict(mode='nearest', order=order, prefilter=prefilter) + assert_array_almost_equal( + ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0], + ) + assert_array_almost_equal( + ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1], + ) + + @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest', + 'mirror', 'reflect']) + @pytest.mark.parametrize('order', range(6)) + def test_shift_vs_padded(self, order, mode, xp): + x_np = np.arange(144, dtype=float).reshape(12, 12) + shift = (0.4, -2.3) + + # manually pad and then extract center to get expected result + npad = 32 + pad_mode = ndimage_to_numpy_mode.get(mode) + x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode)) + x = xp.asarray(x_np) + + center_slice = tuple([slice(npad, -npad)] * x.ndim) + expected_result = ndimage.shift( + x_padded, shift, mode=mode, order=order)[center_slice] + + xp_assert_close( + ndimage.shift(x, shift, mode=mode, order=order), + expected_result, + rtol=1e-7, + ) + + +@make_xp_test_case(ndimage.zoom) +class TestZoom: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_zoom1(self, order, xp): + for z in [2, [2, 2]]: + arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5)) + arr = ndimage.zoom(arr, z, order=order) + assert arr.shape == (10, 10) + assert xp.all(arr[-1, :] != 0) + assert xp.all(arr[-1, :] >= (20 - eps)) + assert xp.all(arr[0, :] <= (5 + eps)) + assert xp.all(arr >= (0 - eps)) + assert xp.all(arr <= (24 + eps)) + + def test_zoom2(self, xp): + arr = xp.reshape(xp.arange(12), (3, 4)) + out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5) + xp_assert_equal(out, arr) + + def test_zoom3(self, xp): + arr = xp.asarray([[1, 2]]) + out1 = ndimage.zoom(arr, (2, 1)) + out2 = ndimage.zoom(arr, (1, 2)) + + assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]])) + assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]])) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_zoom_affine01(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], dtype=dtype) + if xp.isdtype(data.dtype, 'complex floating'): + data -= 1j * data + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed', UserWarning) + out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0, + (6, 8), order=order) + assert_array_almost_equal(out[::2, ::2], data) + + def test_zoom_infinity(self, xp): + # Ticket #1419 regression test + dim = 8 + ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest') + + def test_zoom_zoomfactor_one(self, xp): + # Ticket #1122 regression test + arr = xp.zeros((1, 5, 5)) + zoom = (1.0, 2.0, 2.0) + + out = ndimage.zoom(arr, zoom, cval=7) + ref = xp.zeros((1, 10, 10)) + assert_array_almost_equal(out, ref) + + def test_zoom_output_shape_roundoff(self, xp): + arr = xp.zeros((3, 11, 25)) + zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25) + out = ndimage.zoom(arr, zoom) + assert out.shape == (4, 15, 29) + + @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)]) + @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect', + 'mirror', 'grid-wrap', 'grid-mirror', + 'grid-constant']) + def test_zoom_by_int_order0(self, zoom, mode, xp): + # order 0 zoom should be the same as replication via np.kron + # Note: This is not True for general x shapes when grid_mode is False, + # but works here for all modes because the size ratio happens to + # always be an integer when x.shape = (2, 2). + x_np = np.asarray([[0, 1], + [2, 3]], dtype=np.float64) + expected = np.kron(x_np, np.ones(zoom)) + + x = xp.asarray(x_np) + expected = xp.asarray(expected) + + assert_array_almost_equal( + ndimage.zoom(x, zoom, order=0, mode=mode), + expected + ) + + @pytest.mark.parametrize('shape', [(2, 3), (4, 4)]) + @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)]) + @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror', + 'grid-wrap', 'grid-constant']) + def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp): + # When grid_mode is True, order 0 zoom should be the same as + # replication via np.kron. The only exceptions to this are the + # non-grid modes 'constant' and 'wrap'. + x_np = np.arange(np.prod(shape), dtype=float).reshape(shape) + + x = xp.asarray(x_np) + assert_array_almost_equal( + ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True), + xp.asarray(np.kron(x_np, np.ones(zoom))) + ) + + @pytest.mark.parametrize('mode', ['constant', 'wrap']) + def test_zoom_grid_mode_warnings(self, mode, xp): + # Warn on use of non-grid modes when grid_mode is True + x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3)) + with pytest.warns(UserWarning, + match="It is recommended to use mode"): + ndimage.zoom(x, 2, mode=mode, grid_mode=True), + + @skip_xp_backends("dask.array", reason="output=array requires buffer view") + @skip_xp_backends("jax.numpy", reason="output=array requires buffer view") + def test_zoom_output_shape(self, xp): + """Ticket #643""" + x = xp.reshape(xp.arange(12), (3, 4)) + ndimage.zoom(x, 2, output=xp.zeros((6, 8))) + + def test_zoom_0d_array(self, xp): + # Ticket #21670 regression test + a = xp.arange(10.) + factor = 2 + actual = ndimage.zoom(a, np.array(factor)) + expected = ndimage.zoom(a, factor) + xp_assert_close(actual, expected) + + @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.") + def test_zoom_1_gh20999(self, xp): + # gh-20999 reported that zoom with `zoom=1` (or sequence of ones) + # introduced noise. Check that this is resolved. + x = xp.eye(3) + xp_assert_equal(ndimage.zoom(x, 1), x) + xp_assert_equal(ndimage.zoom(x, (1, 1)), x) + + @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.") + @skip_xp_backends("jax.numpy", reason="read-only backend") + @xfail_xp_backends("dask.array", reason="numpy round-trip") + def test_zoom_1_gh20999_output(self, xp): + x = xp.eye(3) + output = xp.zeros_like(x) + ndimage.zoom(x, 1, output=output) + xp_assert_equal(output, x) + + +@make_xp_test_case(ndimage.rotate) +class TestRotate: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate01(self, order, xp): + data = xp.asarray([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 0, order=order) + assert_array_almost_equal(out, data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate02(self, order, xp): + data = xp.asarray([[0, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0]], dtype=xp.float64) + expected = xp.asarray([[0, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_rotate03(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=dtype) + expected = xp.asarray([[0, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=dtype) + if xp.isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + out = ndimage.rotate(data, 90, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate04(self, order, xp): + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=xp.float64) + expected = xp.asarray([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, reshape=False, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate05(self, order, xp): + data = np.empty((4, 3, 3)) + for i in range(3): + data[:, :, i] = np.asarray([[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=np.float64) + data = xp.asarray(data) + expected = xp.asarray([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, order=order) + for i in range(3): + assert_array_almost_equal(out[:, :, i], expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate06(self, order, xp): + data = np.empty((3, 4, 3)) + for i in range(3): + data[:, :, i] = np.asarray([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=np.float64) + data = xp.asarray(data) + expected = xp.asarray([[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, order=order) + for i in range(3): + assert_array_almost_equal(out[:, :, i], expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate07(self, order, xp): + data = xp.asarray([[[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64) + data = xp.permute_dims(data, (2, 1, 0)) + expected = xp.asarray([[[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0], + [0, 0, 0]]] * 2, dtype=xp.float64) + expected = xp.permute_dims(expected, (2, 1, 0)) + out = ndimage.rotate(data, 90, axes=(0, 1), order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate08(self, order, xp): + data = xp.asarray([[[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64) + data = xp.permute_dims(data, (2, 1, 0)) # == np.transpose + expected = xp.asarray([[[0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64) + expected = xp.permute_dims(expected, (2, 1, 0)) + out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order) + assert_array_almost_equal(out, expected) + + def test_rotate09(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]] * 2, dtype=xp.float64) + with assert_raises(ValueError): + ndimage.rotate(data, 90, axes=(0, data.ndim)) + + def test_rotate10(self, xp): + data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3)) + + # The output of ndimage.rotate before refactoring + expected = xp.asarray([[[0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [6.54914793, 7.54914793, 8.54914793], + [10.84520162, 11.84520162, 12.84520162], + [0.0, 0.0, 0.0]], + [[6.19286575, 7.19286575, 8.19286575], + [13.4730712, 14.4730712, 15.4730712], + [21.0, 22.0, 23.0], + [28.5269288, 29.5269288, 30.5269288], + [35.80713425, 36.80713425, 37.80713425]], + [[0.0, 0.0, 0.0], + [31.15479838, 32.15479838, 33.15479838], + [35.45085207, 36.45085207, 37.45085207], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0]]], dtype=xp.float64) + + out = ndimage.rotate(data, angle=12, reshape=False) + #assert_array_almost_equal(out, expected) + xp_assert_close(out, expected, rtol=1e-6, atol=2e-6) + + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8400") + def test_rotate_exact_180(self, xp): + a = xp.asarray(np.tile(np.arange(5), (5, 1))) + b = ndimage.rotate(ndimage.rotate(a, 180), -180) + xp_assert_equal(a, b) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_measurements.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_measurements.py new file mode 100644 index 0000000000000000000000000000000000000000..13da9c4b9ada00b7304b1a14a1928ebf593e6100 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_measurements.py @@ -0,0 +1,1696 @@ +import os +import os.path +import warnings + +import numpy as np + +from scipy._lib._array_api import ( + is_torch, + xp_assert_equal, + xp_assert_close, + assert_array_almost_equal, + assert_almost_equal, + make_xp_test_case, +) + +import pytest +from pytest import raises as assert_raises + +import scipy.ndimage as ndimage + +from . import types + +skip_xp_backends = pytest.mark.skip_xp_backends + +IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2' + + +@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers') +class Test_measurements_stats: + """ndimage._measurements._stats() is a utility used by other functions. + + Since internal ndimage/_measurements.py code is NumPy-only, + so is this this test class. + """ + def test_a(self, xp): + x = [0, 1, 2, 6] + labels = [0, 0, 1, 1] + index = [0, 1] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums = ndimage._measurements._stats( + x, labels=labels, index=index) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + + def test_b(self, xp): + # Same data as test_a, but different labels. The label 9 exceeds the + # length of 'labels', so this test will follow a different code path. + x = [0, 1, 2, 6] + labels = [0, 0, 9, 9] + index = [0, 9] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums = ndimage._measurements._stats( + x, labels=labels, index=index) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + + def test_a_centered(self, xp): + x = [0, 1, 2, 6] + labels = [0, 0, 1, 1] + index = [0, 1] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums, centers = ndimage._measurements._stats( + x, labels=labels, index=index, centered=True) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + xp_assert_equal(centers, np.asarray([0.5, 8.0])) + + def test_b_centered(self, xp): + x = [0, 1, 2, 6] + labels = [0, 0, 9, 9] + index = [0, 9] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums, centers = ndimage._measurements._stats( + x, labels=labels, index=index, centered=True) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + xp_assert_equal(centers, np.asarray([0.5, 8.0])) + + def test_nonint_labels(self, xp): + x = [0, 1, 2, 6] + labels = [0.0, 0.0, 9.0, 9.0] + index = [0.0, 9.0] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums, centers = ndimage._measurements._stats( + x, labels=labels, index=index, centered=True) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + xp_assert_equal(centers, np.asarray([0.5, 8.0])) + + +@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers') +class Test_measurements_select: + """ndimage._measurements._select() is a utility used by other functions.""" + + def test_basic(self, xp): + x = [0, 1, 6, 2] + cases = [ + ([0, 0, 1, 1], [0, 1]), # "Small" integer labels + ([0, 0, 9, 9], [0, 9]), # A label larger than len(labels) + ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]), # Non-integer labels + ] + for labels, index in cases: + result = ndimage._measurements._select( + x, labels=labels, index=index) + assert len(result) == 0 + result = ndimage._measurements._select( + x, labels=labels, index=index, find_max=True) + assert len(result) == 1 + xp_assert_equal(result[0], [1, 6]) + result = ndimage._measurements._select( + x, labels=labels, index=index, find_min=True) + assert len(result) == 1 + xp_assert_equal(result[0], [0, 2]) + result = ndimage._measurements._select( + x, labels=labels, index=index, find_min=True, + find_min_positions=True) + assert len(result) == 2 + xp_assert_equal(result[0], [0, 2]) + xp_assert_equal(result[1], [0, 3]) + assert result[1].dtype.kind == 'i' + result = ndimage._measurements._select( + x, labels=labels, index=index, find_max=True, + find_max_positions=True) + assert len(result) == 2 + xp_assert_equal(result[0], [1, 6]) + xp_assert_equal(result[1], [1, 2]) + assert result[1].dtype.kind == 'i' + + +@make_xp_test_case(ndimage.label) +def test_label01(xp): + data = xp.ones(()) + out, n = ndimage.label(data) + assert out == 1 + assert n == 1 + + +@make_xp_test_case(ndimage.label) +def test_label02(xp): + data = xp.zeros(()) + out, n = ndimage.label(data) + assert out == 0 + assert n == 0 + + +@make_xp_test_case(ndimage.label) +def test_label03(xp): + data = xp.ones([1]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([1])) + assert n == 1 + + +@make_xp_test_case(ndimage.label) +def test_label04(xp): + data = xp.zeros([1]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([0])) + assert n == 0 + + +@make_xp_test_case(ndimage.label) +def test_label05(xp): + data = xp.ones([5]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1])) + assert n == 1 + + +@make_xp_test_case(ndimage.label) +def test_label06(xp): + data = xp.asarray([1, 0, 1, 1, 0, 1]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3])) + assert n == 3 + + +@make_xp_test_case(ndimage.label) +def test_label07(xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray( + [[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]])) + assert n == 0 + + +@make_xp_test_case(ndimage.label) +def test_label08(xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]])) + assert n == 4 + + +@make_xp_test_case(ndimage.label) +def test_label09(xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]]) + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + out, n = ndimage.label(data, struct) + assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [2, 2, 0, 0, 0, 0], + [2, 2, 0, 0, 0, 0], + [0, 0, 0, 3, 3, 0]])) + assert n == 3 + + +@make_xp_test_case(ndimage.label) +def test_label10(xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0]]) + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + out, n = ndimage.label(data, struct) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0]])) + assert n == 1 + + +@make_xp_test_case(ndimage.label) +def test_label11(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]], dtype=dtype) + out, n = ndimage.label(data) + expected = [[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + assert n == 4 + + +@skip_xp_backends(np_only=True, reason='inplace output is numpy-specific') +@make_xp_test_case(ndimage.label) +def test_label11_inplace(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]], dtype=dtype) + n = ndimage.label(data, output=data) + expected = [[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(data, expected) + assert n == 4 + + +@make_xp_test_case(ndimage.label) +def test_label12(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 0, 1, 1, 0]], dtype=dtype) + out, n = ndimage.label(data) + expected = [[0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 0, 1, 1, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + assert n == 1 + + +@make_xp_test_case(ndimage.label) +def test_label13(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1], + [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], + dtype=dtype) + out, n = ndimage.label(data) + expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1], + [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + assert n == 1 + + +@skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='output=dtype is numpy-specific') +@make_xp_test_case(ndimage.label) +def test_label_output_typed(xp): + data = xp.ones([5]) + for t in types: + dtype = getattr(xp, t) + output = xp.zeros([5], dtype=dtype) + n = ndimage.label(data, output=output) + assert_array_almost_equal(output, + xp.ones(output.shape, dtype=output.dtype)) + assert n == 1 + + +@skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='output=dtype is numpy-specific') +@make_xp_test_case(ndimage.label) +def test_label_output_dtype(xp): + data = xp.ones([5]) + for t in types: + dtype = getattr(xp, t) + output, n = ndimage.label(data, output=dtype) + assert_array_almost_equal(output, + xp.ones(output.shape, dtype=output.dtype)) + assert output.dtype == t + + +@skip_xp_backends(np_only=True, reason="in-place output is numpy-specific") +@make_xp_test_case(ndimage.label) +def test_label_output_wrong_size(xp): + data = xp.ones([5]) + for t in types: + dtype = getattr(xp, t) + output = xp.zeros([10], dtype=dtype) + assert_raises(ValueError, ndimage.label, data, output=output) + + +@make_xp_test_case(ndimage.label) +def test_label_structuring_elements(xp): + data = np.loadtxt(os.path.join(os.path.dirname( + __file__), "data", "label_inputs.txt")) + strels = np.loadtxt(os.path.join( + os.path.dirname(__file__), "data", "label_strels.txt")) + results = np.loadtxt(os.path.join( + os.path.dirname(__file__), "data", "label_results.txt")) + data = data.reshape((-1, 7, 7)) + strels = strels.reshape((-1, 3, 3)) + results = results.reshape((-1, 7, 7)) + + data = xp.asarray(data) + strels = xp.asarray(strels) + results = xp.asarray(results) + r = 0 + for i in range(data.shape[0]): + d = data[i, :, :] + for j in range(strels.shape[0]): + s = strels[j, :, :] + xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False) + r += 1 + + +@make_xp_test_case(ndimage.label, ndimage.find_objects) +def test_ticket_742(xp): + def SE(img, thresh=.7, size=4): + mask = img > thresh + rank = len(mask.shape) + struct = ndimage.generate_binary_structure(rank, rank) + struct = xp.asarray(struct) + la, co = ndimage.label(mask, + struct) + _ = ndimage.find_objects(la) + + if np.dtype(np.intp) != np.dtype('i'): + shape = (3, 1240, 1240) + a = np.random.rand(np.prod(shape)).reshape(shape) + a = xp.asarray(a) + # shouldn't crash + SE(a) + + +@make_xp_test_case(ndimage.label) +def test_gh_issue_3025(xp): + """Github issue #3025 - improper merging of labels""" + d = np.zeros((60, 320)) + d[:, :257] = 1 + d[:, 260:] = 1 + d[36, 257] = 1 + d[35, 258] = 1 + d[35, 259] = 1 + d = xp.asarray(d) + assert ndimage.label(d, xp.ones((3, 3)))[1] == 1 + + +@make_xp_test_case(ndimage.label, ndimage.find_objects) +class TestFindObjects: + def test_label_default_dtype(self, xp): + test_array = np.random.rand(10, 10) + test_array = xp.asarray(test_array) + label, no_features = ndimage.label(test_array > 0.5) + assert label.dtype in (xp.int32, xp.int64) + # Shouldn't raise an exception + ndimage.find_objects(label) + + + def test_find_objects01(self, xp): + data = xp.ones([], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [()] + + + def test_find_objects02(self, xp): + data = xp.zeros([], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [] + + + def test_find_objects03(self, xp): + data = xp.ones([1], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None),)] + + + def test_find_objects04(self, xp): + data = xp.zeros([1], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [] + + + def test_find_objects05(self, xp): + data = xp.ones([5], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [(slice(0, 5, None),)] + + + def test_find_objects06(self, xp): + data = xp.asarray([1, 0, 2, 2, 0, 3]) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None),), + (slice(2, 4, None),), + (slice(5, 6, None),)] + + + def test_find_objects07(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]]) + out = ndimage.find_objects(data) + assert out == [] + + + def test_find_objects08(self, xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]]) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None), slice(0, 1, None)), + (slice(1, 3, None), slice(2, 5, None)), + (slice(3, 5, None), slice(0, 2, None)), + (slice(5, 6, None), slice(3, 5, None))] + + + def test_find_objects09(self, xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]]) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None), slice(0, 1, None)), + (slice(1, 3, None), slice(2, 5, None)), + None, + (slice(5, 6, None), slice(3, 5, None))] + + +@make_xp_test_case(ndimage.value_indices) +def test_value_indices01(xp): + "Test dictionary keys and entries" + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]]) + vi = ndimage.value_indices(data, ignore_value=0) + true_keys = [1, 2, 4] + assert list(vi.keys()) == true_keys + + truevi = {k: xp.nonzero(data == k) for k in true_keys} + + vi = ndimage.value_indices(data, ignore_value=0) + assert vi.keys() == truevi.keys() + for key in vi.keys(): + assert len(vi[key]) == len(truevi[key]) + for v, true_v in zip(vi[key], truevi[key]): + xp_assert_equal(v, true_v) + + +@make_xp_test_case(ndimage.value_indices) +def test_value_indices02(xp): + "Test input checking" + data = xp.zeros((5, 4), dtype=xp.float32) + msg = "Parameter 'arr' must be an integer array" + with assert_raises(ValueError, match=msg): + ndimage.value_indices(data) + + +@make_xp_test_case(ndimage.value_indices) +def test_value_indices03(xp): + "Test different input array shapes, from 1-D to 4-D" + for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]: + a = np.asarray((12*[1]+12*[2]+12*[3]), dtype=np.int32) + a = np.reshape(a, shape) + + trueKeys = np.unique(a) + a = xp.asarray(a) + vi = ndimage.value_indices(a) + assert list(vi.keys()) == list(trueKeys) + for k in [int(x) for x in trueKeys]: + trueNdx = xp.nonzero(a == k) + assert len(vi[k]) == len(trueNdx) + for vik, true_vik in zip(vi[k], trueNdx): + xp_assert_equal(vik, true_vik) + + +@make_xp_test_case(ndimage.sum) +def test_sum01(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + output = ndimage.sum(input) + assert output == 0 + + +@make_xp_test_case(ndimage.sum) +def test_sum02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.zeros([0, 4], dtype=dtype) + output = ndimage.sum(input) + assert output == 0 + + +@make_xp_test_case(ndimage.sum) +def test_sum03(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.ones([], dtype=dtype) + output = ndimage.sum(input) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.sum) +def test_sum04(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 2], dtype=dtype) + output = ndimage.sum(input) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +@make_xp_test_case(ndimage.sum) +def test_sum05(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input) + assert_almost_equal(output, xp.asarray(10.0), check_0d=False) + + +@make_xp_test_case(ndimage.sum) +def test_sum06(xp): + labels = np.asarray([], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert output == 0 + + +@make_xp_test_case(ndimage.sum) +def test_sum07(xp): + labels = np.ones([0, 4], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.zeros([0, 4], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert output == 0 + + +@make_xp_test_case(ndimage.sum) +def test_sum08(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 2], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert output == 1 + + +@make_xp_test_case(ndimage.sum) +def test_sum09(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert_almost_equal(output, xp.asarray(4.0), check_0d=False) + + +@make_xp_test_case(ndimage.sum) +def test_sum10(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[1, 2], [3, 4]], dtype=bool) + + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.sum(input, labels=labels) + assert_almost_equal(output, xp.asarray(2.0), check_0d=False) + + +@make_xp_test_case(ndimage.sum) +def test_sum11(xp): + labels = xp.asarray([1, 2], dtype=xp.int8) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(6.0), check_0d=False) + + +@make_xp_test_case(ndimage.sum) +def test_sum12(xp): + labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2])) + assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0])) + + +@make_xp_test_case(ndimage.sum) +def test_sum_labels(xp): + labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2])) + output_labels = ndimage.sum_labels( + input, labels=labels, index=xp.asarray([4, 8, 2])) + + assert xp.all(output_sum == output_labels) + assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0])) + + +@make_xp_test_case(ndimage.mean) +def test_mean01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.mean(input, labels=labels) + assert_almost_equal(output, xp.asarray(2.0), check_0d=False) + + +@make_xp_test_case(ndimage.mean) +def test_mean02(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[1, 2], [3, 4]], dtype=bool) + + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.mean(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.mean) +def test_mean03(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.mean(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +@make_xp_test_case(ndimage.mean) +def test_mean04(xp): + labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8) + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.mean(input, labels=labels, + index=xp.asarray([4, 8, 2])) + # XXX: output[[0, 2]] does not work in array-api-strict; annoying + # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5])) + assert output[0] == 4.0 + assert output[2] == 2.5 + assert xp.isnan(output[1]) + + +@make_xp_test_case(ndimage.minimum) +def test_minimum01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.minimum) +def test_minimum02(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[2, 2], [2, 4]], dtype=bool) + + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.minimum(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.minimum) +def test_minimum03(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(2.0), check_0d=False) + + +@make_xp_test_case(ndimage.minimum) +def test_minimum04(xp): + labels = xp.asarray([[1, 2], [2, 3]]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum(input, labels=labels, + index=xp.asarray([2, 3, 8])) + assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0])) + + +@make_xp_test_case(ndimage.maximum) +def test_maximum01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum(input, labels=labels) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +@make_xp_test_case(ndimage.maximum) +def test_maximum02(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[2, 2], [2, 4]], dtype=bool) + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.maximum(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.maximum) +def test_maximum03(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(4.0), check_0d=False) + + +@make_xp_test_case(ndimage.maximum) +def test_maximum04(xp): + labels = xp.asarray([[1, 2], [2, 3]]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum(input, labels=labels, + index=xp.asarray([2, 3, 8])) + assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0])) + + +@make_xp_test_case(ndimage.maximum) +def test_maximum05(xp): + # Regression test for ticket #501 (Trac) + x = xp.asarray([-3, -2, -1]) + assert ndimage.maximum(x) == -1 + + +@make_xp_test_case(ndimage.median) +def test_median01(xp): + a = xp.asarray([[1, 2, 0, 1], + [5, 3, 0, 4], + [0, 0, 0, 7], + [9, 3, 0, 0]]) + labels = xp.asarray([[1, 1, 0, 2], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]]) + output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3])) + assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0])) + + +@make_xp_test_case(ndimage.median) +def test_median02(xp): + a = xp.asarray([[1, 2, 0, 1], + [5, 3, 0, 4], + [0, 0, 0, 7], + [9, 3, 0, 0]]) + output = ndimage.median(a) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.median) +def test_median03(xp): + a = xp.asarray([[1, 2, 0, 1], + [5, 3, 0, 4], + [0, 0, 0, 7], + [9, 3, 0, 0]]) + labels = xp.asarray([[1, 1, 0, 2], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]]) + output = ndimage.median(a, labels=labels) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +@make_xp_test_case(ndimage.median) +def test_median_gh12836_bool(xp): + # test boolean addition fix on example from gh-12836 + a = np.asarray([1, 1], dtype=bool) + a = xp.asarray(a) + output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1])) + assert_array_almost_equal(output, xp.asarray([1.0])) + + +@make_xp_test_case(ndimage.median) +def test_median_no_int_overflow(xp): + # test integer overflow fix on example from gh-12836 + a = xp.asarray([65, 70], dtype=xp.int8) + output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1])) + assert_array_almost_equal(output, xp.asarray([67.5])) + + +@make_xp_test_case(ndimage.variance) +def test_variance01(xp): + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning) + output = ndimage.variance(input) + assert xp.isnan(output) + + +@make_xp_test_case(ndimage.variance) +def test_variance02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1], dtype=dtype) + output = ndimage.variance(input) + assert_almost_equal(output, xp.asarray(0.0), check_0d=False) + + +@make_xp_test_case(ndimage.variance) +def test_variance03(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3], dtype=dtype) + output = ndimage.variance(input) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.variance) +def test_variance04(xp): + input = np.asarray([1, 0], dtype=bool) + input = xp.asarray(input) + output = ndimage.variance(input) + assert_almost_equal(output, xp.asarray(0.25), check_0d=False) + + +@make_xp_test_case(ndimage.variance) +def test_variance05(xp): + labels = xp.asarray([2, 2, 3]) + for type in types: + dtype = getattr(xp, type) + + input = xp.asarray([1, 3, 8], dtype=dtype) + output = ndimage.variance(input, labels, 2) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.variance) +def test_variance06(xp): + labels = xp.asarray([2, 2, 3, 3, 4]) + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype) + output = ndimage.variance(input, labels, xp.asarray([2, 3, 4])) + assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0])) + + +@make_xp_test_case(ndimage.standard_deviation) +def test_standard_deviation01(xp): + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning) + output = ndimage.standard_deviation(input) + assert xp.isnan(output) + + +@make_xp_test_case(ndimage.standard_deviation) +def test_standard_deviation02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1], dtype=dtype) + output = ndimage.standard_deviation(input) + assert_almost_equal(output, xp.asarray(0.0), check_0d=False) + + +@make_xp_test_case(ndimage.standard_deviation) +def test_standard_deviation03(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3], dtype=dtype) + output = ndimage.standard_deviation(input) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.standard_deviation) +def test_standard_deviation04(xp): + input = np.asarray([1, 0], dtype=bool) + input = xp.asarray(input) + output = ndimage.standard_deviation(input) + assert_almost_equal(output, xp.asarray(0.5), check_0d=False) + + +@make_xp_test_case(ndimage.standard_deviation) +def test_standard_deviation05(xp): + labels = xp.asarray([2, 2, 3]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3, 8], dtype=dtype) + output = ndimage.standard_deviation(input, labels, 2) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +@make_xp_test_case(ndimage.standard_deviation) +def test_standard_deviation06(xp): + labels = xp.asarray([2, 2, 3, 3, 4]) + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype) + output = ndimage.standard_deviation( + input, labels, xp.asarray([2, 3, 4]) + ) + assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0])) + + +@make_xp_test_case(ndimage.standard_deviation) +def test_standard_deviation07(xp): + labels = xp.asarray([1]) + with np.errstate(all='ignore'): + for type in types: + if is_torch(xp) and type == 'uint8': + pytest.xfail("value cannot be converted to type uint8 " + "without overflow") + dtype = getattr(xp, type) + input = xp.asarray([-0.00619519], dtype=dtype) + output = ndimage.standard_deviation(input, labels, xp.asarray([1])) + assert_array_almost_equal(output, xp.asarray([0])) + + +@make_xp_test_case(ndimage.minimum_position) +def test_minimum_position01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum_position(input, labels=labels) + assert output == (0, 0) + + +@make_xp_test_case(ndimage.minimum_position) +def test_minimum_position02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.minimum_position(input) + assert output == (1, 2) + + +@make_xp_test_case(ndimage.minimum_position) +def test_minimum_position03(xp): + input = np.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.minimum_position(input) + assert output == (1, 2) + + +@make_xp_test_case(ndimage.minimum_position) +def test_minimum_position04(xp): + input = np.asarray([[5, 4, 2, 5], + [3, 7, 1, 2], + [1, 5, 1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.minimum_position(input) + assert output == (0, 0) + + +@make_xp_test_case(ndimage.minimum_position) +def test_minimum_position05(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 2, 3]], dtype=dtype) + output = ndimage.minimum_position(input, labels) + assert output == (2, 0) + + +@make_xp_test_case(ndimage.minimum_position) +def test_minimum_position06(xp): + labels = xp.asarray([1, 2, 3, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.minimum_position(input, labels, 2) + assert output == (0, 1) + + +@make_xp_test_case(ndimage.minimum_position) +def test_minimum_position07(xp): + labels = xp.asarray([1, 2, 3, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.minimum_position(input, labels, + xp.asarray([2, 3])) + assert output[0] == (0, 1) + assert output[1] == (1, 2) + + +@make_xp_test_case(ndimage.maximum_position) +def test_maximum_position01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum_position(input, + labels=labels) + assert output == (1, 0) + + +@make_xp_test_case(ndimage.maximum_position) +def test_maximum_position02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input) + assert output == (1, 2) + + +@make_xp_test_case(ndimage.maximum_position) +def test_maximum_position03(xp): + input = np.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.maximum_position(input) + assert output == (0, 0) + + +@make_xp_test_case(ndimage.maximum_position) +def test_maximum_position04(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels) + assert output == (1, 1) + + +@make_xp_test_case(ndimage.maximum_position) +def test_maximum_position05(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels, 1) + assert output == (0, 0) + + +@make_xp_test_case(ndimage.maximum_position) +def test_maximum_position06(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels, + xp.asarray([1, 2])) + assert output[0] == (0, 0) + assert output[1] == (1, 1) + + +@make_xp_test_case(ndimage.maximum_position) +def test_maximum_position07(xp): + # Test float labels + labels = xp.asarray([1.0, 2.5, 0.0, 4.5]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels, + xp.asarray([1.0, 4.5])) + assert output[0] == (0, 0) + assert output[1] == (0, 3) + + +@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum, + ndimage.minimum_position, ndimage.maximum_position) +def test_extrema01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output1 = ndimage.extrema(input, labels=labels) + output2 = ndimage.minimum(input, labels=labels) + output3 = ndimage.maximum(input, labels=labels) + output4 = ndimage.minimum_position(input, + labels=labels) + output5 = ndimage.maximum_position(input, + labels=labels) + assert output1 == (output2, output3, output4, output5) + + +@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum, + ndimage.minimum_position, ndimage.maximum_position) +def test_extrema02(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output1 = ndimage.extrema(input, labels=labels, + index=2) + output2 = ndimage.minimum(input, labels=labels, + index=2) + output3 = ndimage.maximum(input, labels=labels, + index=2) + output4 = ndimage.minimum_position(input, + labels=labels, index=2) + output5 = ndimage.maximum_position(input, + labels=labels, index=2) + assert output1 == (output2, output3, output4, output5) + + +@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum, + ndimage.minimum_position, ndimage.maximum_position) +def test_extrema03(xp): + labels = xp.asarray([[1, 2], [2, 3]]) + for type in types: + if is_torch(xp) and type in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output1 = ndimage.extrema(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + output2 = ndimage.minimum(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + output3 = ndimage.maximum(input, labels=labels, + index=xp.asarray([2, 3, 8])) + output4 = ndimage.minimum_position(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + output5 = ndimage.maximum_position(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + assert_array_almost_equal(output1[0], output2) + assert_array_almost_equal(output1[1], output3) + assert output1[2] == output4 + assert output1[3] == output5 + + +@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum, + ndimage.minimum_position, ndimage.maximum_position) +def test_extrema04(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + if is_torch(xp) and type in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output1 = ndimage.extrema(input, labels, xp.asarray([1, 2])) + output2 = ndimage.minimum(input, labels, xp.asarray([1, 2])) + output3 = ndimage.maximum(input, labels, xp.asarray([1, 2])) + output4 = ndimage.minimum_position(input, labels, + xp.asarray([1, 2])) + output5 = ndimage.maximum_position(input, labels, + xp.asarray([1, 2])) + assert_array_almost_equal(output1[0], output2) + assert_array_almost_equal(output1[1], output3) + assert output1[2] == output4 + assert output1[3] == output5 + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass01(xp): + expected = (0.0, 0.0) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 0], [0, 0]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass02(xp): + expected = (1, 0) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[0, 0], [1, 0]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass03(xp): + expected = (0, 1) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[0, 1], [0, 0]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass04(xp): + expected = (1, 1) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[0, 0], [0, 1]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass05(xp): + expected = (0.5, 0.5) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 1], [1, 1]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass06(xp): + expected = (0.5, 0.5) + input = np.asarray([[1, 2], [3, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass07(xp): + labels = xp.asarray([1, 0]) + expected = (0.5, 0.0) + input = np.asarray([[1, 2], [3, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input, labels) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass08(xp): + labels = xp.asarray([1, 2]) + expected = (0.5, 1.0) + input = np.asarray([[5, 2], [3, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input, labels, 2) + assert output == expected + + +@make_xp_test_case(ndimage.center_of_mass) +def test_center_of_mass09(xp): + labels = xp.asarray((1, 2)) + expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64) + input = np.asarray([[1, 2], [1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2])) + xp_assert_equal(xp.asarray(output), xp.asarray(expected)) + + +@make_xp_test_case(ndimage.histogram) +def test_histogram01(xp): + expected = xp.ones(10) + input = xp.arange(10) + output = ndimage.histogram(input, 0, 10, 10) + assert_array_almost_equal(output, expected) + + +@make_xp_test_case(ndimage.histogram) +def test_histogram02(xp): + labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2]) + expected = xp.asarray([0, 2, 0, 1, 1]) + input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3]) + output = ndimage.histogram(input, 0, 4, 5, labels, 1) + assert_array_almost_equal(output, expected) + + +@skip_xp_backends(np_only=True, reason='object arrays') +@make_xp_test_case(ndimage.histogram) +def test_histogram03(xp): + labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2]) + expected1 = xp.asarray([0, 1, 0, 1, 1]) + expected2 = xp.asarray([0, 0, 0, 3, 0]) + input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3]) + + output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2)) + + assert_array_almost_equal(output[0], expected1) + assert_array_almost_equal(output[1], expected2) + +@make_xp_test_case(ndimage.mean, ndimage.variance, ndimage.standard_deviation, + ndimage.median, ndimage.minimum, ndimage.maximum) +def test_stat_funcs_2d(xp): + a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]]) + lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]]) + + mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64)) + + var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64)) + + std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2])) + assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64))) + + med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64)) + + min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False) + + max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False) + + +@skip_xp_backends("cupy", reason="no watershed_ift on CuPy") +@make_xp_test_case(ndimage.watershed_ift) +class TestWatershedIft: + + def test_watershed_ift01(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift02(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, -1, 1, 1, 1, -1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, 1, 1, 1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift03(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 2, 0, 3, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, -1, 2, -1, 3, -1, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, -1, 2, -1, 3, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift04(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 2, 0, 3, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1]], + dtype=xp.int8) + + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift05(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 3, 0, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1]], + dtype=xp.int8) + structure = xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift06(self, xp): + data = xp.asarray([[0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific") + def test_watershed_ift07(self, xp): + shape = (7, 6) + data = np.zeros(shape, dtype=np.uint8) + data = data.transpose() + data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8) + data = xp.asarray(data) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + out = xp.zeros(shape, dtype=xp.int16) + out = out.T + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + ndimage.watershed_ift(data, markers, structure=structure, + output=out) + expected = [[-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + @skip_xp_backends("cupy", reason="no watershed_ift on CuPy") + def test_watershed_ift08(self, xp): + # Test cost larger than uint8. See gh-10069. + data = xp.asarray([[256, 0], + [0, 0]], dtype=xp.uint16) + markers = xp.asarray([[1, 0], + [0, 0]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[1, 1], + [1, 1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + @skip_xp_backends("cupy", reason="no watershed_ift on CuPy") + def test_watershed_ift09(self, xp): + # Test large cost. See gh-19575 + data = xp.asarray([[xp.iinfo(xp.uint16).max, 0], + [0, 0]], dtype=xp.uint16) + markers = xp.asarray([[1, 0], + [0, 0]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[1, 1], + [1, 1]] + xp_assert_close(out, xp.asarray(expected), check_dtype=False) + + +@skip_xp_backends(np_only=True) +@pytest.mark.parametrize("dt", [np.intc, np.uintc]) +@make_xp_test_case(ndimage.value_indices) +def test_gh_19423(dt, xp): + rng = np.random.default_rng(123) + max_val = 8 + image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt) + val_idx = ndimage.value_indices(image) + assert len(val_idx.keys()) == max_val diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_morphology.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_morphology.py new file mode 100644 index 0000000000000000000000000000000000000000..61096d2f36c8d1f0ce8f00158316d020dff02a82 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_morphology.py @@ -0,0 +1,3105 @@ +import numpy as np +from scipy._lib._array_api import ( + is_cupy, is_numpy, + xp_assert_close, xp_assert_equal, assert_array_almost_equal, + make_xp_test_case, + make_xp_pytest_param, +) +import pytest +from pytest import raises as assert_raises + +from scipy import ndimage + +from . import types + +skip_xp_backends = pytest.mark.skip_xp_backends +xfail_xp_backends = pytest.mark.xfail_xp_backends + + +class TestNdimageMorphology: + + @make_xp_test_case(ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf01(self, dtype, xp): + dtype = getattr(xp, dtype) + + # brute force (bf) distance transform + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf(data, 'euclidean', + return_indices=True) + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 2, 4, 2, 1, 0, 0], + [0, 0, 1, 4, 8, 4, 1, 0, 0], + [0, 0, 1, 2, 4, 2, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out * out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 3, 2, 1, 2, 3, 3, 3], + [4, 4, 4, 4, 6, 4, 4, 4, 4], + [5, 5, 6, 6, 7, 6, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 1, 2, 4, 6, 7, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @make_xp_test_case(ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf02(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf(data, 'cityblock', + return_indices=True) + + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 2, 2, 2, 1, 0, 0], + [0, 0, 1, 2, 3, 2, 1, 0, 0], + [0, 0, 1, 2, 2, 2, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 3, 3, 1, 3, 3, 3, 3], + [4, 4, 4, 4, 7, 4, 4, 4, 4], + [5, 5, 6, 7, 7, 7, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 1, 1, 4, 7, 7, 7, 8], + [0, 1, 1, 1, 4, 7, 7, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @make_xp_test_case(ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf03(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf(data, 'chessboard', + return_indices=True) + + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 2, 1, 1, 0, 0], + [0, 0, 1, 2, 2, 2, 1, 0, 0], + [0, 0, 1, 1, 2, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 4, 2, 2, 2, 4, 3, 3], + [4, 4, 5, 6, 6, 6, 5, 4, 4], + [5, 5, 6, 6, 7, 6, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 5, 6, 6, 7, 8], + [0, 1, 1, 2, 6, 6, 7, 7, 8], + [0, 1, 1, 2, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 6, 6, 7, 7, 8], + [0, 1, 2, 4, 5, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + + @skip_xp_backends( + np_only=True, reason='inplace distances= arrays are numpy-specific' + ) + @make_xp_test_case(ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf04(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + tdt, tft = ndimage.distance_transform_bf(data, return_indices=1) + dts = [] + fts = [] + dt = xp.zeros(data.shape, dtype=xp.float64) + ndimage.distance_transform_bf(data, distances=dt) + dts.append(dt) + ft = ndimage.distance_transform_bf( + data, return_distances=False, return_indices=1) + fts.append(ft) + ft = np.indices(data.shape, dtype=xp.int32) + ndimage.distance_transform_bf( + data, return_distances=False, return_indices=True, indices=ft) + fts.append(ft) + dt, ft = ndimage.distance_transform_bf( + data, return_indices=1) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = ndimage.distance_transform_bf( + data, distances=dt, return_indices=True) + dts.append(dt) + fts.append(ft) + ft = np.indices(data.shape, dtype=xp.int32) + dt = ndimage.distance_transform_bf( + data, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = np.indices(data.shape, dtype=xp.int32) + ndimage.distance_transform_bf( + data, distances=dt, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + for dt in dts: + assert_array_almost_equal(tdt, dt) + for ft in fts: + assert_array_almost_equal(tft, ft) + + @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf') + @make_xp_test_case(ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf05(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf( + data, 'euclidean', return_indices=True, sampling=[2, 2]) + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 4, 0, 0, 0], + [0, 0, 4, 8, 16, 8, 4, 0, 0], + [0, 0, 4, 16, 32, 16, 4, 0, 0], + [0, 0, 4, 8, 16, 8, 4, 0, 0], + [0, 0, 0, 4, 4, 4, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out * out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 3, 2, 1, 2, 3, 3, 3], + [4, 4, 4, 4, 6, 4, 4, 4, 4], + [5, 5, 6, 6, 7, 6, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 1, 2, 4, 6, 7, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @make_xp_test_case(ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf06(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf( + data, 'euclidean', return_indices=True, sampling=[2, 1]) + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 4, 1, 0, 0, 0], + [0, 0, 1, 4, 8, 4, 1, 0, 0], + [0, 0, 1, 4, 9, 4, 1, 0, 0], + [0, 0, 1, 4, 8, 4, 1, 0, 0], + [0, 0, 0, 1, 4, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out * out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 2, 2, 2, 2, 2], + [3, 3, 3, 3, 2, 3, 3, 3, 3], + [4, 4, 4, 4, 4, 4, 4, 4, 4], + [5, 5, 5, 5, 6, 5, 5, 5, 5], + [6, 6, 6, 6, 7, 6, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 6, 6, 6, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 1, 1, 7, 7, 7, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @make_xp_test_case(ndimage.distance_transform_bf) + def test_distance_transform_bf07(self, xp): + # test input validation per discussion on PR #13302 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + with assert_raises(RuntimeError): + ndimage.distance_transform_bf( + data, return_distances=False, return_indices=False + ) + + @make_xp_test_case(ndimage.distance_transform_bf, + ndimage.distance_transform_cdt) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt01(self, dtype, xp): + dtype = getattr(xp, dtype) + + # chamfer type distance (cdt) transform + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_cdt( + data, 'cityblock', return_indices=True) + bf = ndimage.distance_transform_bf(data, 'cityblock') + assert_array_almost_equal(bf, out) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 1, 1, 1, 2, 2, 2], + [3, 3, 2, 1, 1, 1, 2, 3, 3], + [4, 4, 4, 4, 1, 4, 4, 4, 4], + [5, 5, 5, 5, 7, 7, 6, 5, 5], + [6, 6, 6, 6, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 1, 1, 4, 7, 7, 7, 8], + [0, 1, 1, 1, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @make_xp_test_case(ndimage.distance_transform_bf, + ndimage.distance_transform_cdt) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt02(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_cdt(data, 'chessboard', + return_indices=True) + bf = ndimage.distance_transform_bf(data, 'chessboard') + assert_array_almost_equal(bf, out) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 1, 1, 1, 2, 2, 2], + [3, 3, 2, 2, 1, 2, 2, 3, 3], + [4, 4, 3, 2, 2, 2, 3, 4, 4], + [5, 5, 4, 6, 7, 6, 4, 5, 5], + [6, 6, 6, 6, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 3, 4, 6, 7, 8], + [0, 1, 1, 2, 2, 6, 6, 7, 8], + [0, 1, 1, 1, 2, 6, 7, 7, 8], + [0, 1, 1, 2, 6, 6, 7, 7, 8], + [0, 1, 2, 2, 5, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @skip_xp_backends( + np_only=True, reason='inplace indices= arrays are numpy-specific' + ) + @make_xp_test_case(ndimage.distance_transform_cdt) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt03(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True) + dts = [] + fts = [] + dt = xp.zeros(data.shape, dtype=xp.int32) + ndimage.distance_transform_cdt(data, distances=dt) + dts.append(dt) + ft = ndimage.distance_transform_cdt( + data, return_distances=False, return_indices=True) + fts.append(ft) + ft = xp.asarray(np.indices(data.shape, dtype=np.int32)) + ndimage.distance_transform_cdt( + data, return_distances=False, return_indices=True, indices=ft) + fts.append(ft) + dt, ft = ndimage.distance_transform_cdt( + data, return_indices=True) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.int32) + ft = ndimage.distance_transform_cdt( + data, distances=dt, return_indices=True) + dts.append(dt) + fts.append(ft) + ft = xp.asarray(np.indices(data.shape, dtype=np.int32)) + dt = ndimage.distance_transform_cdt( + data, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.int32) + ft = xp.asarray(np.indices(data.shape, dtype=np.int32)) + ndimage.distance_transform_cdt(data, distances=dt, + return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + for dt in dts: + assert_array_almost_equal(tdt, dt) + for ft in fts: + assert_array_almost_equal(tft, ft) + + @skip_xp_backends( + np_only=True, reason='XXX: does not raise unless indices is a numpy array' + ) + @make_xp_test_case(ndimage.distance_transform_cdt) + def test_distance_transform_cdt04(self, xp): + # test input validation per discussion on PR #13302 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + indices_out = xp.zeros((data.ndim,) + data.shape, dtype=xp.int32) + with assert_raises(RuntimeError): + ndimage.distance_transform_bf( + data, + return_distances=True, + return_indices=False, + indices=indices_out + ) + + @xfail_xp_backends("torch", reason="int overflow") + @make_xp_test_case(ndimage.distance_transform_cdt) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt05(self, dtype, xp): + dtype = getattr(xp, dtype) + + # test custom metric type per discussion on issue #17381 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + metric_arg = xp.ones((3, 3)) + actual = ndimage.distance_transform_cdt(data, metric=metric_arg) + assert xp.sum(actual) == -21 + + @skip_xp_backends("cupy", reason="CuPy does not have distance_transform_bf") + @make_xp_test_case(ndimage.distance_transform_edt, + ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt01(self, dtype, xp): + dtype = getattr(xp, dtype) + + # euclidean distance transform (edt) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_edt(data, return_indices=True) + bf = ndimage.distance_transform_bf(data, 'euclidean') + assert_array_almost_equal(bf, out) + + # np-specific check + np_ft = np.asarray(ft) + dt = np_ft - np.indices(np_ft.shape[1:], dtype=np_ft.dtype) + dt = dt.astype(np.float64) + np.multiply(dt, dt, dt) + dt = np.add.reduce(dt, axis=0) + np.sqrt(dt, dt) + + dt = xp.asarray(dt) + assert_array_almost_equal(bf, dt) + + @skip_xp_backends( + np_only=True, reason='inplace distances= are numpy-specific' + ) + @make_xp_test_case(ndimage.distance_transform_edt, + ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt02(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + tdt, tft = ndimage.distance_transform_edt(data, return_indices=True) + dts = [] + fts = [] + + dt = xp.zeros(data.shape, dtype=xp.float64) + ndimage.distance_transform_edt(data, distances=dt) + dts.append(dt) + + ft = ndimage.distance_transform_edt( + data, return_distances=0, return_indices=True) + fts.append(ft) + + ft = np.indices(data.shape, dtype=xp.int32) + ft = xp.asarray(ft) + ndimage.distance_transform_edt( + data, return_distances=False, return_indices=True, indices=ft) + fts.append(ft) + + dt, ft = ndimage.distance_transform_edt( + data, return_indices=True) + dts.append(dt) + fts.append(ft) + + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = ndimage.distance_transform_edt( + data, distances=dt, return_indices=True) + dts.append(dt) + fts.append(ft) + + ft = np.indices(data.shape, dtype=xp.int32) + ft = xp.asarray(ft) + dt = ndimage.distance_transform_edt( + data, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = np.indices(data.shape, dtype=xp.int32) + ft = xp.asarray(ft) + ndimage.distance_transform_edt( + data, distances=dt, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + + for dt in dts: + assert_array_almost_equal(tdt, dt) + for ft in fts: + assert_array_almost_equal(tft, ft) + + @make_xp_test_case(ndimage.distance_transform_edt, + ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt03(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2]) + out = ndimage.distance_transform_edt(data, sampling=[2, 2]) + assert_array_almost_equal(out, ref) + + @make_xp_test_case(ndimage.distance_transform_edt, + ndimage.distance_transform_bf) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt4(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1]) + out = ndimage.distance_transform_edt(data, sampling=[2, 1]) + assert_array_almost_equal(out, ref) + + @xfail_xp_backends( + "cupy", reason="Only 2D and 3D distance transforms are supported in CuPy" + ) + @make_xp_test_case(ndimage.distance_transform_edt) + def test_distance_transform_edt5(self, xp): + # Ticket #954 regression test + out = ndimage.distance_transform_edt(xp.asarray(False)) + assert_array_almost_equal(out, xp.asarray([0.])) + + @xfail_xp_backends( + np_only=True, reason='XXX: does not raise unless indices is a numpy array' + ) + @make_xp_test_case(ndimage.distance_transform_edt) + def test_distance_transform_edt6(self, xp): + # test input validation per discussion on PR #13302 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + distances_out = xp.zeros(data.shape, dtype=xp.float64) + with assert_raises(RuntimeError): + ndimage.distance_transform_bf( + data, + return_indices=True, + return_distances=False, + distances=distances_out + ) + + @make_xp_test_case(ndimage.generate_binary_structure) + def test_generate_structure01(self, xp): + struct = ndimage.generate_binary_structure(0, 1) + assert struct == 1 + + @make_xp_test_case(ndimage.generate_binary_structure) + def test_generate_structure02(self, xp): + struct = ndimage.generate_binary_structure(1, 1) + assert_array_almost_equal(struct, [1, 1, 1]) + + @make_xp_test_case(ndimage.generate_binary_structure) + def test_generate_structure03(self, xp): + struct = ndimage.generate_binary_structure(2, 1) + assert_array_almost_equal(struct, [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) + + @make_xp_test_case(ndimage.generate_binary_structure) + def test_generate_structure04(self, xp): + struct = ndimage.generate_binary_structure(2, 2) + assert_array_almost_equal(struct, [[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + + @make_xp_test_case(ndimage.iterate_structure) + def test_iterate_structure01(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + out = ndimage.iterate_structure(struct, 2) + expected = np.asarray([[0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.iterate_structure) + def test_iterate_structure02(self, xp): + struct = [[0, 1], + [1, 1], + [0, 1]] + struct = xp.asarray(struct) + out = ndimage.iterate_structure(struct, 2) + expected = np.asarray([[0, 0, 1], + [0, 1, 1], + [1, 1, 1], + [0, 1, 1], + [0, 0, 1]], dtype=bool) + expected = xp.asarray(expected) + + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.iterate_structure) + def test_iterate_structure03(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + out = ndimage.iterate_structure(struct, 2, 1) + expected = [[0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + assert_array_almost_equal(out[0], expected) + assert out[1] == [2, 2] + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion01(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.binary_erosion(data) + assert out == xp.asarray(1, dtype=out.dtype) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion02(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert out == xp.asarray(1, dtype=out.dtype) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion03(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion04(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion05(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0, 1, 0])) + + + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8912") + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion05_broadcasted(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones((1, ), dtype=dtype) + data = xp.broadcast_to(data, (3, )) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0, 1, 0])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion06(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion07(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([5], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion08(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([5], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion09(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0, 0, 0, 0, 0])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion10(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 0, 0, 0, 1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion11(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion12(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) + assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion13(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1, origin=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion14(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion15(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) + assert_array_almost_equal(out, xp.asarray([1, 0, 0, 1, 1])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion16(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 1], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([[1]])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion17(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 1], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([[0]])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion18(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 3], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0]])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion19(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 3], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1]])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion20(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3, 3], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0], + [0, 1, 0], + [0, 0, 0]])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion21(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3, 3], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]])) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion22(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion23(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion24(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = xp.asarray([[0, 1], + [1, 1]]) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion25(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 0, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_erosion) + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion26(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 0, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 1, 0, 0, 1], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1, + origin=(-1, -1)) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends( + "cupy", reason="CuPy: NotImplementedError: only brute_force iteration" + ) + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion27(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, border_value=1, + iterations=2) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace out= arguments are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion28(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=2, output=out) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends( + "cupy", reason="CuPy: NotImplementedError: only brute_force iteration" + ) + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion29(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, iterations=3) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace out= arguments are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion30(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=3, output=out) + assert_array_almost_equal(out, expected) + + # test with output memory overlap + ndimage.binary_erosion(data, struct, border_value=1, + iterations=3, output=data) + assert_array_almost_equal(data, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace out= arguments are numpy-specific') + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion31(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 1], + [0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 1]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=1, output=out, origin=(-1, -1)) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion32(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, iterations=2) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion33(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + mask = [[1, 1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1]] + mask = xp.asarray(mask) + data = np.asarray([[0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 1, 0, 0, 1], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, mask=mask, iterations=-1) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion34(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + mask = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + mask = xp.asarray(mask) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, mask=mask) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace out= arguments are numpy-specific') + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion35(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + mask = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray(mask, dtype=bool) + mask = xp.asarray(mask) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + tmp = [[0, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 1], + [0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 1]] + tmp = np.asarray(tmp, dtype=bool) + tmp = xp.asarray(tmp) + expected = xp.logical_and(tmp, mask) + tmp = xp.logical_and(data, xp.logical_not(mask)) + expected = xp.logical_or(expected, tmp) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=1, output=out, + origin=(-1, -1), mask=mask) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion36(self, xp): + struct = [[0, 1, 0], + [1, 0, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + mask = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray(mask, dtype=bool) + mask = xp.asarray(mask) + tmp = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 1, 0, 0, 1], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1]] + tmp = np.asarray(tmp, dtype=bool) + tmp = xp.asarray(tmp) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + expected = xp.logical_and(tmp, mask) + tmp = xp.logical_and(data, xp.logical_not(mask)) + expected = xp.logical_or(expected, tmp) + out = ndimage.binary_erosion(data, struct, mask=mask, + border_value=1, origin=(-1, -1)) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace out= arguments are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion37(self, xp): + a = np.asarray([[1, 0, 1], + [0, 1, 0], + [1, 0, 1]], dtype=bool) + a = xp.asarray(a) + b = xp.zeros_like(a) + out = ndimage.binary_erosion(a, structure=a, output=b, iterations=0, + border_value=True, brute_force=True) + assert out is b + xp_assert_equal( + ndimage.binary_erosion(a, structure=a, iterations=0, + border_value=True), + b) + + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion38(self, xp): + data = np.asarray([[1, 0, 1], + [0, 1, 0], + [1, 0, 1]], dtype=bool) + data = xp.asarray(data) + iterations = 2.0 + with assert_raises(TypeError): + _ = ndimage.binary_erosion(data, iterations=iterations) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace out= arguments are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion39(self, xp): + iterations = np.int32(3) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=iterations, output=out) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace out= arguments are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_erosion) + def test_binary_erosion40(self, xp): + iterations = np.int64(3) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=iterations, output=out) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation01(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.binary_dilation(data) + assert out == xp.asarray(1, dtype=out.dtype) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation02(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([], dtype=dtype) + out = ndimage.binary_dilation(data) + assert out == xp.asarray(False) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation03(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype)) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation04(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation05(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation05_broadcasted(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones((1, ), dtype=dtype) + data = xp.broadcast_to(data, (3,)) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation06(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([0, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation07(self, dtype, xp): + data = np.zeros([3], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation08(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data[3] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation09(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation10(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data, origin=-1) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation11(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data, origin=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation12(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation13(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation14(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct, origin=-1) + assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation15(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct, + origin=-1, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation16(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[1]])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation17(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([1, 1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[0]])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation18(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation19(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3, 3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation20(self, dtype, xp): + data = np.zeros([3, 3], dtype=dtype) + data[1, 1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation21(self, dtype, xp): + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + data = np.zeros([3, 3], dtype=dtype) + data[1, 1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation22(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation23(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 0, 0, 0, 0, 1], + [1, 1, 0, 0, 0, 1, 0, 1], + [1, 0, 0, 1, 1, 1, 1, 1], + [1, 0, 1, 1, 1, 1, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 1, 0, 0, 1, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation24(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, origin=(1, 1)) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation25(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 0, 0, 0, 0, 1, 1], + [1, 0, 0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [0, 1, 0, 0, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation26(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + expected = [[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation27(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1], + [1, 1]] + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation28(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 1, 1], + [1, 0, 0, 1], + [1, 0, 0, 1], + [1, 1, 1, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, border_value=1) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation29(self, xp): + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct, iterations=2) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='output= arrays are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation30(self, xp): + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_dilation(data, struct, iterations=2, output=out) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation31(self, xp): + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct, iterations=3) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='output= arrays are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation32(self, xp): + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_dilation(data, struct, iterations=3, output=out) + assert_array_almost_equal(out, expected) + + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation33(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + + out = ndimage.binary_dilation(data, struct, iterations=-1, + mask=mask, border_value=0) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason='inplace output= arrays are numpy-specific') + @xfail_xp_backends("cupy", + reason="NotImplementedError: only brute_force iteration") + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation34(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.zeros(mask.shape, dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct, iterations=-1, + mask=mask, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation35(self, dtype, xp): + dtype = getattr(xp, dtype) + tmp = [[1, 1, 0, 0, 0, 0, 1, 1], + [1, 0, 0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [0, 1, 0, 0, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1]] + + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]]) + mask = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray(mask, dtype=bool) + + expected = np.logical_and(tmp, mask) + tmp = np.logical_and(data, np.logical_not(mask)) + expected = np.logical_or(expected, tmp) + + mask = xp.asarray(mask) + expected = xp.asarray(expected) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, mask=mask, + origin=(1, 1), border_value=1) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_dilation) + def test_binary_dilation36(self, xp): + # gh-21009 + data = np.zeros([], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, iterations=-1) + assert out == xp.asarray(False) + + @make_xp_test_case(ndimage.binary_propagation) + def test_binary_propagation01(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_propagation(data, struct, + mask=mask, border_value=0) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_propagation) + def test_binary_propagation02(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + struct = xp.asarray(struct) + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.zeros(mask.shape, dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_propagation(data, struct, + mask=mask, border_value=1) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_propagation) + def test_binary_propagation03(self, xp): + # gh-21009 + data = xp.asarray(np.zeros([], dtype=bool)) + expected = xp.asarray(np.zeros([], dtype=bool)) + out = ndimage.binary_propagation(data) + assert out == expected + + @make_xp_test_case(ndimage.binary_opening) + @pytest.mark.parametrize('dtype', types) + def test_binary_opening01(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_opening(data) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_opening) + @pytest.mark.parametrize('dtype', types) + def test_binary_opening02(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + expected = [[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + struct = xp.asarray(struct) + data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_opening(data, struct) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_closing) + def test_binary_closing01(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_closing(data) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + @make_xp_test_case(ndimage.binary_closing) + def test_binary_closing02(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + struct = xp.asarray(struct) + data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_closing(data, struct) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_fill_holes) + def test_binary_fill_holes01(self, xp): + expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + + out = ndimage.binary_fill_holes(data) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_fill_holes) + def test_binary_fill_holes02(self, xp): + expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_fill_holes(data) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_fill_holes) + def test_binary_fill_holes03(self, xp): + expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 1, 1], + [0, 1, 1, 1, 0, 1, 1, 1], + [0, 1, 1, 1, 0, 1, 1, 1], + [0, 0, 1, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 1, 0, 1, 1, 1], + [0, 1, 0, 1, 0, 1, 0, 1], + [0, 1, 0, 1, 0, 1, 0, 1], + [0, 0, 1, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_fill_holes(data) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(cpu_only=True) + @skip_xp_backends( + "cupy", reason="these filters do not yet have axes support in CuPy") + @skip_xp_backends( + "jax.numpy", reason="these filters are not implemented in JAX.numpy") + @pytest.mark.parametrize('border_value',[0, 1]) + @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)]) + @pytest.mark.parametrize('expand_axis', [0, 1, 2]) + @pytest.mark.parametrize( + 'func', [ + make_xp_pytest_param(ndimage.binary_erosion), + make_xp_pytest_param(ndimage.binary_dilation), + make_xp_pytest_param(ndimage.binary_opening), + make_xp_pytest_param(ndimage.binary_closing), + make_xp_pytest_param(ndimage.binary_hit_or_miss), + make_xp_pytest_param(ndimage.binary_propagation), + make_xp_pytest_param(ndimage.binary_fill_holes), + ] + ) + def test_binary_axes(self, xp, func, expand_axis, origin, border_value): + func_name = func.__name__ + struct = np.asarray([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]], bool) + struct = xp.asarray(struct) + + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 0, 1, 0], + [0, 1, 0, 1, 1, 0, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], bool) + data = xp.asarray(data) + if func_name == "binary_hit_or_miss": + kwargs = dict(origin1=origin, origin2=origin) + else: + kwargs = dict(origin=origin) + border_supported = func_name not in ["binary_hit_or_miss", + "binary_fill_holes"] + if border_supported: + kwargs['border_value'] = border_value + elif border_value != 0: + pytest.skip('border_value !=0 unsupported by this function') + + expected = func(data, struct, **kwargs) + + # replicate data and expected result along a new axis + n_reps = 5 + expected = xp.stack([expected] * n_reps, axis=expand_axis) + data = xp.stack([data] * n_reps, axis=expand_axis) + + # filter all axes except expand_axis + axes = [0, 1, 2] + axes.remove(expand_axis) + if is_numpy(xp) or is_cupy(xp): + out = xp.asarray(np.zeros(data.shape, bool)) + func(data, struct, output=out, axes=axes, **kwargs) + else: + # inplace output= is unsupported by JAX + out = func(data, struct, axes=axes, **kwargs) + xp_assert_close(out, expected) + + @make_xp_test_case(ndimage.grey_erosion) + def test_grey_erosion01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.grey_erosion(array, footprint=footprint) + assert_array_almost_equal(output, + xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]])) + + @skip_xp_backends("jax.numpy", reason="output=array requires buffer view") + @skip_xp_backends("dask.array", reason="output=array requires buffer view") + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8398") + @make_xp_test_case(ndimage.grey_erosion) + def test_grey_erosion01_overlap(self, xp): + + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + ndimage.grey_erosion(array, footprint=footprint, output=array) + assert_array_almost_equal(array, + xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]]) + ) + + @make_xp_test_case(ndimage.grey_erosion) + def test_grey_erosion02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + output = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]]) + ) + + @make_xp_test_case(ndimage.grey_erosion) + def test_grey_erosion03(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[1, 1, 0, 0, 0], + [1, 2, 0, 2, 0], + [4, 4, 2, 2, 0]]) + ) + + @make_xp_test_case(ndimage.grey_dilation) + def test_grey_dilation01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[0, 1, 1], [1, 0, 1]]) + output = ndimage.grey_dilation(array, footprint=footprint) + assert_array_almost_equal(output, + xp.asarray([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]]), + ) + + @make_xp_test_case(ndimage.grey_dilation) + def test_grey_dilation02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[0, 1, 1], [1, 0, 1]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + output = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]]), + ) + + @make_xp_test_case(ndimage.grey_dilation) + def test_grey_dilation03(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[0, 1, 1], [1, 0, 1]]) + structure = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[8, 8, 10, 10, 6], + [8, 10, 9, 10, 8], + [9, 9, 9, 8, 8]]), + ) + + @make_xp_test_case(ndimage.grey_opening) + def test_grey_opening01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + tmp = ndimage.grey_erosion(array, footprint=footprint) + expected = ndimage.grey_dilation(tmp, footprint=footprint) + output = ndimage.grey_opening(array, footprint=footprint) + assert_array_almost_equal(output, expected) + + @make_xp_test_case(ndimage.grey_opening) + def test_grey_opening02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = ndimage.grey_dilation(tmp, footprint=footprint, + structure=structure) + output = ndimage.grey_opening(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, expected) + + @make_xp_test_case(ndimage.grey_closing) + def test_grey_closing01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + tmp = ndimage.grey_dilation(array, footprint=footprint) + expected = ndimage.grey_erosion(tmp, footprint=footprint) + output = ndimage.grey_closing(array, footprint=footprint) + assert_array_almost_equal(output, expected) + + @make_xp_test_case(ndimage.grey_closing) + def test_grey_closing02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + expected = ndimage.grey_erosion(tmp, footprint=footprint, + structure=structure) + output = ndimage.grey_closing(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, expected) + + @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific') + @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion, + ndimage.morphological_gradient) + def test_morphological_gradient01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 - tmp2 + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.morphological_gradient(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(output, expected) + + @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion, + ndimage.morphological_gradient) + def test_morphological_gradient02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 - tmp2 + output = ndimage.morphological_gradient(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, expected) + + @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific') + @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion, + ndimage.morphological_laplace) + def test_morphological_laplace01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 + tmp2 - 2 * array + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.morphological_laplace(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(output, expected) + + @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion, + ndimage.morphological_laplace) + def test_morphological_laplace02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 + tmp2 - 2 * array + output = ndimage.morphological_laplace(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, expected) + + @skip_xp_backends("jax.numpy", reason="output=array requires buffer view") + @skip_xp_backends("dask.array", reason="output=array requires buffer view") + @make_xp_test_case(ndimage.grey_opening, ndimage.white_tophat) + def test_white_tophat01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_opening(array, footprint=footprint, + structure=structure) + expected = array - tmp + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.white_tophat(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(output, expected) + + @make_xp_test_case(ndimage.grey_opening, ndimage.white_tophat) + def test_white_tophat02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_opening(array, footprint=footprint, + structure=structure) + expected = array - tmp + output = ndimage.white_tophat(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, expected) + + @xfail_xp_backends('cupy', reason="cupy#8399") + @make_xp_test_case(ndimage.white_tophat) + def test_white_tophat03(self, xp): + + array = np.asarray([[1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 1]], dtype=bool) + array = xp.asarray(array) + structure = np.ones((3, 3), dtype=bool) + structure = xp.asarray(structure) + expected = np.asarray([[0, 1, 1, 0, 0, 0, 0], + [1, 0, 0, 1, 1, 1, 0], + [1, 0, 0, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 0, 1], + [0, 1, 1, 0, 1, 0, 1], + [0, 1, 1, 0, 0, 0, 1], + [0, 0, 0, 1, 1, 1, 1]], dtype=bool) + expected = xp.asarray(expected) + + output = ndimage.white_tophat(array, structure=structure) + xp_assert_equal(output, expected) + + @skip_xp_backends("jax.numpy", reason="output=array requires buffer view") + @skip_xp_backends("dask.array", reason="output=array requires buffer view") + @make_xp_test_case(ndimage.white_tophat) + def test_white_tophat04(self, xp): + array = np.eye(5, dtype=bool) + structure = np.ones((3, 3), dtype=bool) + + array = xp.asarray(array) + structure = xp.asarray(structure) + + # Check that type mismatch is properly handled + output = xp.empty_like(array, dtype=xp.float64) + ndimage.white_tophat(array, structure=structure, output=output) + + @skip_xp_backends("jax.numpy", reason="output=array requires buffer view") + @skip_xp_backends("dask.array", reason="output=array requires buffer view") + @make_xp_test_case(ndimage.grey_closing, ndimage.black_tophat) + def test_black_tophat01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_closing(array, footprint=footprint, + structure=structure) + expected = tmp - array + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.black_tophat(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(output, expected) + + @make_xp_test_case(ndimage.grey_closing, ndimage.black_tophat) + def test_black_tophat02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_closing(array, footprint=footprint, + structure=structure) + expected = tmp - array + output = ndimage.black_tophat(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, expected) + + @xfail_xp_backends('cupy', reason="cupy/cupy#8399") + @make_xp_test_case(ndimage.black_tophat) + def test_black_tophat03(self, xp): + + array = np.asarray([[1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 1]], dtype=bool) + array = xp.asarray(array) + structure = np.ones((3, 3), dtype=bool) + structure = xp.asarray(structure) + expected = np.asarray([[0, 1, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 1, 0, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 0]], dtype=bool) + expected = xp.asarray(expected) + + output = ndimage.black_tophat(array, structure=structure) + xp_assert_equal(output, expected) + + @skip_xp_backends("jax.numpy", reason="output=array requires buffer view") + @skip_xp_backends("dask.array", reason="output=array requires buffer view") + @make_xp_test_case(ndimage.black_tophat) + def test_black_tophat04(self, xp): + array = xp.asarray(np.eye(5, dtype=bool)) + structure = xp.asarray(np.ones((3, 3), dtype=bool)) + + # Check that type mismatch is properly handled + output = xp.empty_like(array, dtype=xp.float64) + ndimage.black_tophat(array, structure=structure, output=output) + + @skip_xp_backends(cpu_only=True) + @skip_xp_backends( + "cupy", reason="these filters do not yet have axes support in CuPy") + @skip_xp_backends( + "jax.numpy", reason="these filters are not implemented in JAX.numpy") + @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)]) + @pytest.mark.parametrize('expand_axis', [0, 1, 2]) + @pytest.mark.parametrize('mode', ['reflect', 'constant', 'nearest', + 'mirror', 'wrap']) + @pytest.mark.parametrize('footprint_mode', ['size', 'footprint', + 'structure']) + @pytest.mark.parametrize( + 'func', + [ + make_xp_pytest_param(ndimage.grey_erosion), + make_xp_pytest_param(ndimage.grey_dilation), + make_xp_pytest_param(ndimage.grey_opening), + make_xp_pytest_param(ndimage.grey_closing), + make_xp_pytest_param(ndimage.morphological_laplace), + make_xp_pytest_param(ndimage.morphological_gradient), + make_xp_pytest_param(ndimage.white_tophat), + make_xp_pytest_param(ndimage.black_tophat), + ] + ) + def test_grey_axes(self, xp, func, expand_axis, origin, footprint_mode, + mode): + data = xp.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 4, 0, 0, 0], + [0, 0, 2, 1, 0, 2, 0], + [0, 3, 0, 6, 5, 0, 1], + [0, 4, 5, 3, 3, 4, 0], + [0, 0, 9, 3, 0, 0, 0], + [0, 0, 0, 2, 0, 0, 0]]) + kwargs = dict(origin=origin, mode=mode) + if footprint_mode == 'size': + kwargs['size'] = (2, 3) + else: + kwargs['footprint'] = xp.asarray([[1, 0, 1], [1, 1, 0]]) + if footprint_mode == 'structure': + kwargs['structure'] = xp.ones_like(kwargs['footprint']) + + expected = func(data, **kwargs) + + # replicate data and expected result along a new axis + n_reps = 5 + expected = xp.stack([expected] * n_reps, axis=expand_axis) + data = xp.stack([data] * n_reps, axis=expand_axis) + + # filter all axes except expand_axis + axes = [0, 1, 2] + axes.remove(expand_axis) + + if is_numpy(xp) or is_cupy(xp): + out = xp.zeros(expected.shape, dtype=expected.dtype) + func(data, output=out, axes=axes, **kwargs) + else: + # inplace output= is unsupported by JAX + out = func(data, axes=axes, **kwargs) + xp_assert_close(out, expected) + + @skip_xp_backends(np_only=True, exceptions=["cupy"], + reason="inplace output= is numpy-specific") + @make_xp_test_case(ndimage.binary_hit_or_miss) + @pytest.mark.parametrize('dtype', types) + def test_hit_or_miss01(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [0, 1, 0, 1, 1], + [0, 0, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 1], + [0, 1, 1, 1, 1], + [0, 0, 0, 0, 0]], dtype=dtype) + out = xp.asarray(np.zeros(data.shape, dtype=bool)) + ndimage.binary_hit_or_miss(data, struct, output=out) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_hit_or_miss) + @pytest.mark.parametrize('dtype', types) + def test_hit_or_miss02(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0], + [1, 1, 1, 0, 0, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_hit_or_miss(data, struct) + assert_array_almost_equal(out, expected) + + @make_xp_test_case(ndimage.binary_hit_or_miss) + @pytest.mark.parametrize('dtype', types) + def test_hit_or_miss03(self, dtype, xp): + dtype = getattr(xp, dtype) + struct1 = [[0, 0, 0], + [1, 1, 1], + [0, 0, 0]] + struct2 = [[1, 1, 1], + [0, 0, 0], + [1, 1, 1]] + expected = [[0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct1 = xp.asarray(struct1) + struct2 = xp.asarray(struct2) + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 1, 0], + [0, 0, 0, 0, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_hit_or_miss(data, struct1, struct2) + assert_array_almost_equal(out, expected) + + +@make_xp_test_case(ndimage.binary_dilation, ndimage.grey_dilation) +class TestDilateFix: + + # pytest's setup_method seems to clash with the autouse `xp` fixture + # so call _setup manually from all methods + def _setup(self, xp): + # dilation related setup + self.array = xp.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 0, 0, 0, 0]], dtype=xp.uint8) + + self.sq3x3 = xp.ones((3, 3)) + dilated3x3 = ndimage.binary_dilation(self.array, structure=self.sq3x3) + + if is_numpy(xp): + self.dilated3x3 = dilated3x3.view(xp.uint8) + else: + self.dilated3x3 = xp.astype(dilated3x3, xp.uint8) + + + def test_dilation_square_structure(self, xp): + self._setup(xp) + result = ndimage.grey_dilation(self.array, structure=self.sq3x3) + # +1 accounts for difference between grey and binary dilation + assert_array_almost_equal(result, self.dilated3x3 + 1) + + def test_dilation_scalar_size(self, xp): + self._setup(xp) + result = ndimage.grey_dilation(self.array, size=3) + assert_array_almost_equal(result, self.dilated3x3) + + +@make_xp_test_case(ndimage.binary_opening, ndimage.binary_closing) +class TestBinaryOpeningClosing: + + def _setup(self, xp): + a = np.zeros((5, 5), dtype=bool) + a[1:4, 1:4] = True + a[4, 4] = True + self.array = xp.asarray(a) + self.sq3x3 = xp.ones((3, 3)) + self.opened_old = ndimage.binary_opening(self.array, self.sq3x3, + 1, None, 0) + self.closed_old = ndimage.binary_closing(self.array, self.sq3x3, + 1, None, 0) + + def test_opening_new_arguments(self, xp): + self._setup(xp) + opened_new = ndimage.binary_opening(self.array, self.sq3x3, 1, None, + 0, None, 0, False) + xp_assert_equal(opened_new, self.opened_old) + + def test_closing_new_arguments(self, xp): + self._setup(xp) + closed_new = ndimage.binary_closing(self.array, self.sq3x3, 1, None, + 0, None, 0, False) + xp_assert_equal(closed_new, self.closed_old) + + +@make_xp_test_case(ndimage.binary_erosion) +def test_binary_erosion_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_erosion, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_erosion, data, iterations=1.5) + + +@make_xp_test_case(ndimage.binary_dilation) +def test_binary_dilation_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_dilation, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_dilation, data, iterations=1.5) + + +@make_xp_test_case(ndimage.binary_opening) +def test_binary_opening_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_opening, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_opening, data, iterations=1.5) + + +@make_xp_test_case(ndimage.binary_closing) +def test_binary_closing_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_closing, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_closing, data, iterations=1.5) + + +@xfail_xp_backends( + "cupy", reason="CuPy: NotImplementedError: only brute_force iteration" +) +@make_xp_test_case(ndimage.binary_erosion) +def test_binary_closing_noninteger_brute_force_passes_when_true(xp): + # regression test for gh-9905, gh-9909: ValueError for non integer iterations + data = xp.ones([1]) + xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=1.5), + ndimage.binary_erosion(data, iterations=2, brute_force=bool(1.5)) + ) + xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=0.0), + ndimage.binary_erosion(data, iterations=2, brute_force=bool(0.0)) + ) + + +@skip_xp_backends(np_only=True, exceptions=["cupy"], + reason="inplace output= is numpy-specific") +@xfail_xp_backends("cupy", reason="NotImplementedError: only brute_force iteration") +@pytest.mark.parametrize( + 'func', + [ + make_xp_pytest_param(ndimage.binary_erosion), + make_xp_pytest_param(ndimage.binary_dilation), + make_xp_pytest_param(ndimage.binary_opening), + make_xp_pytest_param(ndimage.binary_closing), + ], +) +@pytest.mark.parametrize('iterations', [1, 5]) +@pytest.mark.parametrize('brute_force', [False, True]) +def test_binary_input_as_output(func, iterations, brute_force, xp): + rstate = np.random.RandomState(123) + data = rstate.randint(low=0, high=2, size=100).astype(bool) + data = xp.asarray(data) + + # input data is not modified + data_orig = data.copy() + expected = func(data, brute_force=brute_force, iterations=iterations) + xp_assert_equal(data, data_orig) + + # data should now contain the expected result + func(data, brute_force=brute_force, iterations=iterations, output=data) + xp_assert_equal(data, expected) + + +@skip_xp_backends(np_only=True, exceptions=["cupy"], + reason="inplace output= is numpy-specific") +@make_xp_test_case(ndimage.binary_hit_or_miss) +def test_binary_hit_or_miss_input_as_output(xp): + rstate = np.random.RandomState(123) + data = rstate.randint(low=0, high=2, size=100).astype(bool) + data = xp.asarray(data) + + # input data is not modified + data_orig = data.copy() + expected = ndimage.binary_hit_or_miss(data) + xp_assert_equal(data, data_orig) + + # data should now contain the expected result + ndimage.binary_hit_or_miss(data, output=data) + xp_assert_equal(data, expected) + + +@make_xp_test_case(ndimage.distance_transform_cdt) +def test_distance_transform_cdt_invalid_metric(xp): + msg = 'invalid metric provided' + with pytest.raises(ValueError, match=msg): + ndimage.distance_transform_cdt(xp.ones((5, 5)), + metric="garbage") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_ni_support.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_ni_support.py new file mode 100644 index 0000000000000000000000000000000000000000..95b442833edf3b4d66699837eeb658e82d00636c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_ni_support.py @@ -0,0 +1,77 @@ +import pytest + +import numpy as np +from .._ni_support import _get_output + + +@pytest.mark.parametrize( + 'dtype', + [ + # String specifiers + 'f4', 'float32', 'complex64', 'complex128', + # Type and dtype specifiers + np.float32, float, np.dtype('f4'), + # Derive from input + None, + ], +) +def test_get_output_basic(dtype): + shape = (2, 3) + + input_ = np.zeros(shape, dtype='float32') + + # For None, derive dtype from input + expected_dtype = 'float32' if dtype is None else dtype + + # Output is dtype-specifier, retrieve shape from input + result = _get_output(dtype, input_) + assert result.shape == shape + assert result.dtype == np.dtype(expected_dtype) + + # Output is dtype specifier, with explicit shape, overriding input + result = _get_output(dtype, input_, shape=(3, 2)) + assert result.shape == (3, 2) + assert result.dtype == np.dtype(expected_dtype) + + # Output is pre-allocated array, return directly + output = np.zeros(shape, dtype=dtype) + result = _get_output(output, input_) + assert result is output + + +def test_get_output_complex(): + shape = (2, 3) + + input_ = np.zeros(shape) + + # None, promote input type to complex + result = _get_output(None, input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex128') + + # Explicit type, promote type to complex + with pytest.warns(UserWarning, match='promoting specified output dtype to complex'): + result = _get_output(float, input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex128') + + # String specifier, simply verify complex output + result = _get_output('complex64', input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex64') + + +def test_get_output_error_cases(): + input_ = np.zeros((2, 3), 'float32') + + # Two separate paths can raise the same error + with pytest.raises(RuntimeError, match='output must have complex dtype'): + _get_output('float32', input_, complex_output=True) + with pytest.raises(RuntimeError, match='output must have complex dtype'): + _get_output(np.zeros((2, 3)), input_, complex_output=True) + + with pytest.raises(RuntimeError, match='output must have numeric dtype'): + _get_output('void', input_) + + with pytest.raises(RuntimeError, match='shape not correct'): + _get_output(np.zeros((3, 2)), input_) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_splines.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_splines.py new file mode 100644 index 0000000000000000000000000000000000000000..a9706211977d905c6876e4073dcaac3928ea5a17 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/ndimage/tests/test_splines.py @@ -0,0 +1,68 @@ +"""Tests for spline filtering.""" +import pytest + +import numpy as np +from scipy._lib._array_api import assert_almost_equal, make_xp_test_case + +from scipy import ndimage + + +def get_spline_knot_values(order): + """Knot values to the right of a B-spline's center.""" + knot_values = {0: [1], + 1: [1], + 2: [6, 1], + 3: [4, 1], + 4: [230, 76, 1], + 5: [66, 26, 1]} + + return knot_values[order] + + +def make_spline_knot_matrix(xp, n, order, mode='mirror'): + """Matrix to invert to find the spline coefficients.""" + knot_values = get_spline_knot_values(order) + + # NB: do computations with numpy, convert to xp as the last step only + + matrix = np.zeros((n, n)) + for diag, knot_value in enumerate(knot_values): + indices = np.arange(diag, n) + if diag == 0: + matrix[indices, indices] = knot_value + else: + matrix[indices, indices - diag] = knot_value + matrix[indices - diag, indices] = knot_value + + knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:]) + + if mode == 'mirror': + start, step = 1, 1 + elif mode == 'reflect': + start, step = 0, 1 + elif mode == 'grid-wrap': + start, step = -1, -1 + else: + raise ValueError(f'unsupported mode {mode}') + + for row in range(len(knot_values) - 1): + for idx, knot_value in enumerate(knot_values[row + 1:]): + matrix[row, start + step*idx] += knot_value + matrix[-row - 1, -start - 1 - step*idx] += knot_value + + return xp.asarray(matrix / knot_values_sum) + + +@make_xp_test_case(ndimage.spline_filter1d) +@pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5]) +@pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect']) +def test_spline_filter_vs_matrix_solution(order, mode, xp): + n = 100 + eye = xp.eye(n, dtype=xp.float64) + spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order, + mode=mode) + spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order, + mode=mode) + matrix = make_spline_knot_matrix(xp, n, order, mode=mode) + assert_almost_equal(eye, spline_filter_axis_0 @ matrix) + assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3aa97d19ce2c2253ddd34f009a94a741bfffc689 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..055693c82ccf9f807e7d9c404b12a5b193e78e29 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_models.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0c5df4a18462189bea0e5c432aef30391a3ed22 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_models.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_odrpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_odrpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4d731935c48040ee16caa0dd42d84ec8b686ca2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/_odrpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/models.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77c491652233cddce446bf9d821eab5fe3f87f28 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/models.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/odrpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/odrpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6685ed960bbb6dfe70eb1d45c8800c4db3958fec Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/__pycache__/odrpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e3d538c1a95fb34c7e98388e8650c5d69c5fb8d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5fc178fa11290cc2c24076e495a7b839261606b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/test_odr.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/test_odr.py new file mode 100644 index 0000000000000000000000000000000000000000..3437b39bba991537e496770e361fe9df680a9b7a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/odr/tests/test_odr.py @@ -0,0 +1,621 @@ +import pickle +import tempfile +import shutil +import os + +import numpy as np +from numpy import pi +from numpy.testing import (assert_array_almost_equal, + assert_equal, + assert_allclose) +import pytest +from pytest import raises as assert_raises + +from scipy.odr import (Data, Model, ODR, RealData, OdrStop, OdrWarning, + OdrError, multilinear, exponential, unilinear, + quadratic, polynomial) + + +class TestODR: + + # Bad Data for 'x' + + def test_bad_data(self): + assert_raises(ValueError, Data, 2, 1) + assert_raises(ValueError, RealData, 2, 1) + + # Empty Data for 'x' + def empty_data_func(self, B, x): + return B[0]*x + B[1] + + def test_empty_data(self): + beta0 = [0.02, 0.0] + linear = Model(self.empty_data_func) + + empty_dat = Data([], []) + with pytest.warns(OdrWarning): + ODR(empty_dat, linear, beta0=beta0) + + empty_dat = RealData([], []) + with pytest.warns(OdrWarning): + ODR(empty_dat, linear, beta0=beta0) + + # Explicit Example + + def explicit_fcn(self, B, x): + ret = B[0] + B[1] * np.power(np.exp(B[2]*x) - 1.0, 2) + return ret + + def explicit_fjd(self, B, x): + eBx = np.exp(B[2]*x) + ret = B[1] * 2.0 * (eBx-1.0) * B[2] * eBx + return ret + + def explicit_fjb(self, B, x): + eBx = np.exp(B[2]*x) + res = np.vstack([np.ones(x.shape[-1]), + np.power(eBx-1.0, 2), + B[1]*2.0*(eBx-1.0)*eBx*x]) + return res + + def test_explicit(self): + explicit_mod = Model( + self.explicit_fcn, + fjacb=self.explicit_fjb, + fjacd=self.explicit_fjd, + meta=dict(name='Sample Explicit Model', + ref='ODRPACK UG, pg. 39'), + ) + explicit_dat = Data([0.,0.,5.,7.,7.5,10.,16.,26.,30.,34.,34.5,100.], + [1265.,1263.6,1258.,1254.,1253.,1249.8,1237.,1218.,1220.6, + 1213.8,1215.5,1212.]) + explicit_odr = ODR(explicit_dat, explicit_mod, beta0=[1500.0, -50.0, -0.1], + ifixx=[0,0,1,1,1,1,1,1,1,1,1,0]) + explicit_odr.set_job(deriv=2) + explicit_odr.set_iprint(init=0, iter=0, final=0) + + out = explicit_odr.run() + assert_array_almost_equal( + out.beta, + np.array([1.2646548050648876e+03, -5.4018409956678255e+01, + -8.7849712165253724e-02]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([1.0349270280543437, 1.583997785262061, 0.0063321988657267]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[4.4949592379003039e-01, -3.7421976890364739e-01, + -8.0978217468468912e-04], + [-3.7421976890364739e-01, 1.0529686462751804e+00, + -1.9453521827942002e-03], + [-8.0978217468468912e-04, -1.9453521827942002e-03, + 1.6827336938454476e-05]]), + ) + + # Implicit Example + + def implicit_fcn(self, B, x): + return (B[2]*np.power(x[0]-B[0], 2) + + 2.0*B[3]*(x[0]-B[0])*(x[1]-B[1]) + + B[4]*np.power(x[1]-B[1], 2) - 1.0) + + def test_implicit(self): + implicit_mod = Model( + self.implicit_fcn, + implicit=1, + meta=dict(name='Sample Implicit Model', + ref='ODRPACK UG, pg. 49'), + ) + implicit_dat = Data([ + [0.5,1.2,1.6,1.86,2.12,2.36,2.44,2.36,2.06,1.74,1.34,0.9,-0.28, + -0.78,-1.36,-1.9,-2.5,-2.88,-3.18,-3.44], + [-0.12,-0.6,-1.,-1.4,-2.54,-3.36,-4.,-4.75,-5.25,-5.64,-5.97,-6.32, + -6.44,-6.44,-6.41,-6.25,-5.88,-5.5,-5.24,-4.86]], + 1, + ) + implicit_odr = ODR(implicit_dat, implicit_mod, + beta0=[-1.0, -3.0, 0.09, 0.02, 0.08]) + + out = implicit_odr.run() + assert_array_almost_equal( + out.beta, + np.array([-0.9993809167281279, -2.9310484652026476, 0.0875730502693354, + 0.0162299708984738, 0.0797537982976416]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([0.1113840353364371, 0.1097673310686467, 0.0041060738314314, + 0.0027500347539902, 0.0034962501532468]), + ) + assert_allclose( + out.cov_beta, + np.array([[2.1089274602333052e+00, -1.9437686411979040e+00, + 7.0263550868344446e-02, -4.7175267373474862e-02, + 5.2515575927380355e-02], + [-1.9437686411979040e+00, 2.0481509222414456e+00, + -6.1600515853057307e-02, 4.6268827806232933e-02, + -5.8822307501391467e-02], + [7.0263550868344446e-02, -6.1600515853057307e-02, + 2.8659542561579308e-03, -1.4628662260014491e-03, + 1.4528860663055824e-03], + [-4.7175267373474862e-02, 4.6268827806232933e-02, + -1.4628662260014491e-03, 1.2855592885514335e-03, + -1.2692942951415293e-03], + [5.2515575927380355e-02, -5.8822307501391467e-02, + 1.4528860663055824e-03, -1.2692942951415293e-03, + 2.0778813389755596e-03]]), + rtol=1e-6, atol=2e-6, + ) + + # Multi-variable Example + + def multi_fcn(self, B, x): + if (x < 0.0).any(): + raise OdrStop + theta = pi*B[3]/2. + ctheta = np.cos(theta) + stheta = np.sin(theta) + omega = np.power(2.*pi*x*np.exp(-B[2]), B[3]) + phi = np.arctan2((omega*stheta), (1.0 + omega*ctheta)) + r = (B[0] - B[1]) * np.power(np.sqrt(np.power(1.0 + omega*ctheta, 2) + + np.power(omega*stheta, 2)), -B[4]) + ret = np.vstack([B[1] + r*np.cos(B[4]*phi), + r*np.sin(B[4]*phi)]) + return ret + + def test_multi(self): + multi_mod = Model( + self.multi_fcn, + meta=dict(name='Sample Multi-Response Model', + ref='ODRPACK UG, pg. 56'), + ) + + multi_x = np.array([30.0, 50.0, 70.0, 100.0, 150.0, 200.0, 300.0, 500.0, + 700.0, 1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 10000.0, + 15000.0, 20000.0, 30000.0, 50000.0, 70000.0, 100000.0, 150000.0]) + multi_y = np.array([ + [4.22, 4.167, 4.132, 4.038, 4.019, 3.956, 3.884, 3.784, 3.713, + 3.633, 3.54, 3.433, 3.358, 3.258, 3.193, 3.128, 3.059, 2.984, + 2.934, 2.876, 2.838, 2.798, 2.759], + [0.136, 0.167, 0.188, 0.212, 0.236, 0.257, 0.276, 0.297, 0.309, + 0.311, 0.314, 0.311, 0.305, 0.289, 0.277, 0.255, 0.24, 0.218, + 0.202, 0.182, 0.168, 0.153, 0.139], + ]) + n = len(multi_x) + multi_we = np.zeros((2, 2, n), dtype=float) + multi_ifixx = np.ones(n, dtype=int) + multi_delta = np.zeros(n, dtype=float) + + multi_we[0,0,:] = 559.6 + multi_we[1,0,:] = multi_we[0,1,:] = -1634.0 + multi_we[1,1,:] = 8397.0 + + for i in range(n): + if multi_x[i] < 100.0: + multi_ifixx[i] = 0 + elif multi_x[i] <= 150.0: + pass # defaults are fine + elif multi_x[i] <= 1000.0: + multi_delta[i] = 25.0 + elif multi_x[i] <= 10000.0: + multi_delta[i] = 560.0 + elif multi_x[i] <= 100000.0: + multi_delta[i] = 9500.0 + else: + multi_delta[i] = 144000.0 + if multi_x[i] == 100.0 or multi_x[i] == 150.0: + multi_we[:,:,i] = 0.0 + + multi_dat = Data(multi_x, multi_y, wd=1e-4/np.power(multi_x, 2), + we=multi_we) + multi_odr = ODR(multi_dat, multi_mod, beta0=[4.,2.,7.,.4,.5], + delta0=multi_delta, ifixx=multi_ifixx) + multi_odr.set_job(deriv=1, del_init=1) + + out = multi_odr.run() + assert_array_almost_equal( + out.beta, + np.array([4.3799880305938963, 2.4333057577497703, 8.0028845899503978, + 0.5101147161764654, 0.5173902330489161]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([0.0130625231081944, 0.0130499785273277, 0.1167085962217757, + 0.0132642749596149, 0.0288529201353984]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[0.0064918418231375, 0.0036159705923791, 0.0438637051470406, + -0.0058700836512467, 0.011281212888768], + [0.0036159705923791, 0.0064793789429006, 0.0517610978353126, + -0.0051181304940204, 0.0130726943624117], + [0.0438637051470406, 0.0517610978353126, 0.5182263323095322, + -0.0563083340093696, 0.1269490939468611], + [-0.0058700836512467, -0.0051181304940204, -0.0563083340093696, + 0.0066939246261263, -0.0140184391377962], + [0.011281212888768, 0.0130726943624117, 0.1269490939468611, + -0.0140184391377962, 0.0316733013820852]]), + ) + + # Pearson's Data + # K. Pearson, Philosophical Magazine, 2, 559 (1901) + + def pearson_fcn(self, B, x): + return B[0] + B[1]*x + + def test_pearson(self): + p_x = np.array([0.,.9,1.8,2.6,3.3,4.4,5.2,6.1,6.5,7.4]) + p_y = np.array([5.9,5.4,4.4,4.6,3.5,3.7,2.8,2.8,2.4,1.5]) + p_sx = np.array([.03,.03,.04,.035,.07,.11,.13,.22,.74,1.]) + p_sy = np.array([1.,.74,.5,.35,.22,.22,.12,.12,.1,.04]) + + p_dat = RealData(p_x, p_y, sx=p_sx, sy=p_sy) + + # Reverse the data to test invariance of results + pr_dat = RealData(p_y, p_x, sx=p_sy, sy=p_sx) + + p_mod = Model(self.pearson_fcn, meta=dict(name='Uni-linear Fit')) + + p_odr = ODR(p_dat, p_mod, beta0=[1.,1.]) + pr_odr = ODR(pr_dat, p_mod, beta0=[1.,1.]) + + out = p_odr.run() + assert_array_almost_equal( + out.beta, + np.array([5.4767400299231674, -0.4796082367610305]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([0.3590121690702467, 0.0706291186037444]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[0.0854275622946333, -0.0161807025443155], + [-0.0161807025443155, 0.003306337993922]]), + ) + + rout = pr_odr.run() + assert_array_almost_equal( + rout.beta, + np.array([11.4192022410781231, -2.0850374506165474]), + ) + assert_array_almost_equal( + rout.sd_beta, + np.array([0.9820231665657161, 0.3070515616198911]), + ) + assert_array_almost_equal( + rout.cov_beta, + np.array([[0.6391799462548782, -0.1955657291119177], + [-0.1955657291119177, 0.0624888159223392]]), + ) + + # Lorentz Peak + # The data is taken from one of the undergraduate physics labs I performed. + + def lorentz(self, beta, x): + return (beta[0]*beta[1]*beta[2] / np.sqrt(np.power(x*x - + beta[2]*beta[2], 2.0) + np.power(beta[1]*x, 2.0))) + + def test_lorentz(self): + l_sy = np.array([.29]*18) + l_sx = np.array([.000972971,.000948268,.000707632,.000706679, + .000706074, .000703918,.000698955,.000456856, + .000455207,.000662717,.000654619,.000652694, + .000000859202,.00106589,.00106378,.00125483, .00140818,.00241839]) + + l_dat = RealData( + [3.9094, 3.85945, 3.84976, 3.84716, 3.84551, 3.83964, 3.82608, + 3.78847, 3.78163, 3.72558, 3.70274, 3.6973, 3.67373, 3.65982, + 3.6562, 3.62498, 3.55525, 3.41886], + [652, 910.5, 984, 1000, 1007.5, 1053, 1160.5, 1409.5, 1430, 1122, + 957.5, 920, 777.5, 709.5, 698, 578.5, 418.5, 275.5], + sx=l_sx, + sy=l_sy, + ) + l_mod = Model(self.lorentz, meta=dict(name='Lorentz Peak')) + l_odr = ODR(l_dat, l_mod, beta0=(1000., .1, 3.8)) + + out = l_odr.run() + assert_array_almost_equal( + out.beta, + np.array([1.4306780846149925e+03, 1.3390509034538309e-01, + 3.7798193600109009e+00]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([7.3621186811330963e-01, 3.5068899941471650e-04, + 2.4451209281408992e-04]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[2.4714409064597873e-01, -6.9067261911110836e-05, + -3.1236953270424990e-05], + [-6.9067261911110836e-05, 5.6077531517333009e-08, + 3.6133261832722601e-08], + [-3.1236953270424990e-05, 3.6133261832722601e-08, + 2.7261220025171730e-08]]), + ) + + def test_ticket_1253(self): + def linear(c, x): + return c[0]*x+c[1] + + c = [2.0, 3.0] + x = np.linspace(0, 10) + y = linear(c, x) + + model = Model(linear) + data = Data(x, y, wd=1.0, we=1.0) + job = ODR(data, model, beta0=[1.0, 1.0]) + result = job.run() + assert_equal(result.info, 2) + + # Verify fix for gh-9140 + + def test_ifixx(self): + x1 = [-2.01, -0.99, -0.001, 1.02, 1.98] + x2 = [3.98, 1.01, 0.001, 0.998, 4.01] + fix = np.vstack((np.zeros_like(x1, dtype=int), np.ones_like(x2, dtype=int))) + data = Data(np.vstack((x1, x2)), y=1, fix=fix) + model = Model(lambda beta, x: x[1, :] - beta[0] * x[0, :]**2., implicit=True) + + odr1 = ODR(data, model, beta0=np.array([1.])) + sol1 = odr1.run() + odr2 = ODR(data, model, beta0=np.array([1.]), ifixx=fix) + sol2 = odr2.run() + assert_equal(sol1.beta, sol2.beta) + + # verify bugfix for #11800 in #11802 + def test_ticket_11800(self): + # parameters + beta_true = np.array([1.0, 2.3, 1.1, -1.0, 1.3, 0.5]) + nr_measurements = 10 + + std_dev_x = 0.01 + x_error = np.array([[0.00063445, 0.00515731, 0.00162719, 0.01022866, + -0.01624845, 0.00482652, 0.00275988, -0.00714734, -0.00929201, -0.00687301], + [-0.00831623, -0.00821211, -0.00203459, 0.00938266, -0.00701829, + 0.0032169, 0.00259194, -0.00581017, -0.0030283, 0.01014164]]) + + std_dev_y = 0.05 + y_error = np.array([[0.05275304, 0.04519563, -0.07524086, 0.03575642, + 0.04745194, 0.03806645, 0.07061601, -0.00753604, -0.02592543, -0.02394929], + [0.03632366, 0.06642266, 0.08373122, 0.03988822, -0.0092536, + -0.03750469, -0.03198903, 0.01642066, 0.01293648, -0.05627085]]) + + beta_solution = np.array([ + 2.62920235756665876536e+00, -1.26608484996299608838e+02, + 1.29703572775403074502e+02, -1.88560985401185465804e+00, + 7.83834160771274923718e+01, -7.64124076838087091801e+01]) + + # model's function and Jacobians + def func(beta, x): + y0 = beta[0] + beta[1] * x[0, :] + beta[2] * x[1, :] + y1 = beta[3] + beta[4] * x[0, :] + beta[5] * x[1, :] + + return np.vstack((y0, y1)) + + def df_dbeta_odr(beta, x): + nr_meas = np.shape(x)[1] + zeros = np.zeros(nr_meas) + ones = np.ones(nr_meas) + + dy0 = np.array([ones, x[0, :], x[1, :], zeros, zeros, zeros]) + dy1 = np.array([zeros, zeros, zeros, ones, x[0, :], x[1, :]]) + + return np.stack((dy0, dy1)) + + def df_dx_odr(beta, x): + nr_meas = np.shape(x)[1] + ones = np.ones(nr_meas) + + dy0 = np.array([beta[1] * ones, beta[2] * ones]) + dy1 = np.array([beta[4] * ones, beta[5] * ones]) + return np.stack((dy0, dy1)) + + # do measurements with errors in independent and dependent variables + x0_true = np.linspace(1, 10, nr_measurements) + x1_true = np.linspace(1, 10, nr_measurements) + x_true = np.array([x0_true, x1_true]) + + y_true = func(beta_true, x_true) + + x_meas = x_true + x_error + y_meas = y_true + y_error + + # estimate model's parameters + model_f = Model(func, fjacb=df_dbeta_odr, fjacd=df_dx_odr) + + data = RealData(x_meas, y_meas, sx=std_dev_x, sy=std_dev_y) + + odr_obj = ODR(data, model_f, beta0=0.9 * beta_true, maxit=100) + #odr_obj.set_iprint(init=2, iter=0, iter_step=1, final=1) + odr_obj.set_job(deriv=3) + + odr_out = odr_obj.run() + + # check results + assert_equal(odr_out.info, 1) + assert_array_almost_equal(odr_out.beta, beta_solution) + + def test_multilinear_model(self): + x = np.linspace(0.0, 5.0) + y = 10.0 + 5.0 * x + data = Data(x, y) + odr_obj = ODR(data, multilinear) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [10.0, 5.0]) + + def test_exponential_model(self): + x = np.linspace(0.0, 5.0) + y = -10.0 + np.exp(0.5*x) + data = Data(x, y) + odr_obj = ODR(data, exponential) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [-10.0, 0.5]) + + def test_polynomial_model(self): + x = np.linspace(0.0, 5.0) + y = 1.0 + 2.0 * x + 3.0 * x ** 2 + 4.0 * x ** 3 + poly_model = polynomial(3) + data = Data(x, y) + odr_obj = ODR(data, poly_model) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0, 4.0]) + + def test_unilinear_model(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + data = Data(x, y) + odr_obj = ODR(data, unilinear) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [1.0, 2.0]) + + def test_quadratic_model(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x ** 2 + 2.0 * x + 3.0 + data = Data(x, y) + odr_obj = ODR(data, quadratic) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0]) + + def test_work_ind(self): + + def func(par, x): + b0, b1 = par + return b0 + b1 * x + + # generate some data + n_data = 4 + x = np.arange(n_data) + y = np.where(x % 2, x + 0.1, x - 0.1) + x_err = np.full(n_data, 0.1) + y_err = np.full(n_data, 0.1) + + # do the fitting + linear_model = Model(func) + real_data = RealData(x, y, sx=x_err, sy=y_err) + odr_obj = ODR(real_data, linear_model, beta0=[0.4, 0.4]) + odr_obj.set_job(fit_type=0) + out = odr_obj.run() + + sd_ind = out.work_ind['sd'] + assert_array_almost_equal(out.sd_beta, + out.work[sd_ind:sd_ind + len(out.sd_beta)]) + + @pytest.mark.skipif(True, reason="Fortran I/O prone to crashing so better " + "not to run this test, see gh-13127") + def test_output_file_overwrite(self): + """ + Verify fix for gh-1892 + """ + def func(b, x): + return b[0] + b[1] * x + + p = Model(func) + data = Data(np.arange(10), 12 * np.arange(10)) + tmp_dir = tempfile.mkdtemp() + error_file_path = os.path.join(tmp_dir, "error.dat") + report_file_path = os.path.join(tmp_dir, "report.dat") + try: + ODR(data, p, beta0=[0.1, 13], errfile=error_file_path, + rptfile=report_file_path).run() + ODR(data, p, beta0=[0.1, 13], errfile=error_file_path, + rptfile=report_file_path, overwrite=True).run() + finally: + # remove output files for clean up + shutil.rmtree(tmp_dir) + + def test_odr_model_default_meta(self): + def func(b, x): + return b[0] + b[1] * x + + p = Model(func) + p.set_meta(name='Sample Model Meta', ref='ODRPACK') + assert_equal(p.meta, {'name': 'Sample Model Meta', 'ref': 'ODRPACK'}) + + def test_work_array_del_init(self): + """ + Verify fix for gh-18739 where del_init=1 fails. + """ + def func(b, x): + return b[0] + b[1] * x + + # generate some data + n_data = 4 + x = np.arange(n_data) + y = np.where(x % 2, x + 0.1, x - 0.1) + x_err = np.full(n_data, 0.1) + y_err = np.full(n_data, 0.1) + + linear_model = Model(func) + # Try various shapes of the `we` array from various `sy` and `covy` + rd0 = RealData(x, y, sx=x_err, sy=y_err) + rd1 = RealData(x, y, sx=x_err, sy=0.1) + rd2 = RealData(x, y, sx=x_err, sy=[0.1]) + rd3 = RealData(x, y, sx=x_err, sy=np.full((1, n_data), 0.1)) + rd4 = RealData(x, y, sx=x_err, covy=[[0.01]]) + rd5 = RealData(x, y, sx=x_err, covy=np.full((1, 1, n_data), 0.01)) + for rd in [rd0, rd1, rd2, rd3, rd4, rd5]: + odr_obj = ODR(rd, linear_model, beta0=[0.4, 0.4], + delta0=np.full(n_data, -0.1)) + odr_obj.set_job(fit_type=0, del_init=1) + # Just make sure that it runs without raising an exception. + odr_obj.run() + + def test_pickling_data(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + data = Data(x, y) + + obj_pickle = pickle.dumps(data) + del data + pickle.loads(obj_pickle) + + def test_pickling_real_data(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + data = RealData(x, y) + + obj_pickle = pickle.dumps(data) + del data + pickle.loads(obj_pickle) + + def test_pickling_model(self): + obj_pickle = pickle.dumps(unilinear) + pickle.loads(obj_pickle) + + def test_pickling_odr(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + odr_obj = ODR(Data(x, y), unilinear) + + obj_pickle = pickle.dumps(odr_obj) + del odr_obj + pickle.loads(obj_pickle) + + def test_pickling_output(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + output = ODR(Data(x, y), unilinear).run + + obj_pickle = pickle.dumps(output) + del output + pickle.loads(obj_pickle) + + def test_explicit_model_with_implicit_job(self): + """ + Verify fix for gh-23763 that ODR doesn't segfault + """ + x = np.linspace(0, 10, 10) + y = 2.0 + 3.0 * x + + data = Data(x, y) + model = unilinear # this is an explicit model + + # job=1 is implicit, should raise on explicit model + with assert_raises(OdrError): + odr = ODR(data, model, job=1) + odr.run() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70120d8dd4a1ff6f28f471a2ff6e720293fde484 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..216c2676b0444674e5b5cdabe6a792a74ef02419 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_bracket.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_bracket.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4266f373f7949484c53aadda78b589e52361d4fd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_bracket.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78f4e04f7ee1215ad7a5028471726a13a3281163 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84d3cd673c6068fdeaf5016f87501f752d1bcb34 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..342791d6dcfc30d204ad3a66a5789b33c6041387 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_constraints.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_constraints.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78cfe16c3bca96d1d34574b5abe608457ebc172a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_constraints.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e06d687a57576bffeb98f3f7ab2eb92ab6a472c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11f76f4ed71f4f6a34e82020a3257dacabe48b52 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..175a9b3f6a2ad0d168ef8487ddabf84205a6bb48 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4194abc7bfee39943116145f0793604896c13a4f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0abdc238a1791967dc5f63e9c02a25ec84af235 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca91371db85b193749c51565a34dab87d7825637 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49b9865cfb1deb74d5039643748def74190bf3f1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..289d56347ec90271ae3fc9a17a61837c4a98b211 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5cba929e852bdce79e803595ff89518608f734d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9adf985304e42059650be6174e79f8662ebf64ae Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d051baa7d2de3fea308786c305eea706be79384 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2a4c6c43bd8833b98d8f648e68adeb348baf8b3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eccc30af08e18df5082a934dfc9381702b2975dd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13b314ac27a4e05bec2e23f9b73d9c2f93d474f7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_rs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_rs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbc12d7744858739631613f93cf3955562da5716 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_rs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_simplex.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_simplex.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34ae619c860ab14e1398ba72325764fc9c4746be Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_simplex.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_util.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3221e747b62455fabb52cef3ce4609ddc29f2c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_linprog_util.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_milp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_milp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81fa177375b17fe0d2384a17872a7e1d53449796 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_milp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_minimize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_minimize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d27e4ce5901df29c49cd359c6863e49916aadd5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_minimize.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4a92733add7d5a3d4bcc05c92aa4ce57453c149 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_nnls.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_nnls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ae85d7f6641af3f1138badb31ac9fdefdf41d10 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_nnls.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e46d30dea61e1e2c8f783313d4eb7301d8159d1b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_numdiff.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_numdiff.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14ea625a2bfacd79890508ef2c8a631e3fd88476 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_numdiff.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_qap.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_qap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b32d32b6e37dee7e6af4fa6a60159c149f361a6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_qap.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de53ae6c83e0c278e339a5b0487054bf28708a88 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_root.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_root.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92543fd80be6a9ee0ee8889694c78216725fe8f8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_root.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0a97dbda13fe91e68c40cbe6c0b5fe1ed74227b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_shgo.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_shgo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a18bbb4ff6633ccb32689511213d22c18d34ed8e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_shgo.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_slsqp_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_slsqp_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6522d7a1eeaddc41adb4e19f85cef99d8e5f4cc0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_slsqp_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_spectral.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_spectral.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db8e9edbb192dc5e61badc5fd6d4870007f1623d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_spectral.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_tnc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_tnc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8f2d2f69288322a6fe04fa012a811e234a96343 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_tnc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7aeb6865cae12a550e6a6a86967a7fbee886ebad Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_dogleg.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_dogleg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..445b56499bb9a17631821088fb6a8b3ee3d2e536 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_dogleg.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_exact.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_exact.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f965591a8a0b7cea5d14d392368ebdfcd4ff89d6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_exact.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8a4998f60779b299d21c2638ce0176dee18cfa6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f813e66436013d9a1d2ccd4875f686011e5b694 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_tstutils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_tstutils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4adb5c1814737e1c8ac0a95d8e4352a9ee1b32c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_tstutils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_zeros_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_zeros_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f817b31f756af11b33a2f39294ddf33cc760cb24 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/_zeros_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/cobyla.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/cobyla.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..975220b1ebd97aa26ad910e758d97e0b6cad8262 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/cobyla.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/elementwise.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/elementwise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67832648e706f70fd9dce8bc838e9b8f249bb291 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/elementwise.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/lbfgsb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/lbfgsb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09a37bfc9b05b78c237f227465e1233721c1b61a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/lbfgsb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/linesearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/linesearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87b8486db9bebaf1c2de664ed406b6f07a4d6526 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/linesearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/minpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/minpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ff4749520379ad71e26de2e788b82c70521a61 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/minpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/minpack2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/minpack2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c03939d603501e0f7f40188b4918b0e74bf0d410 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/minpack2.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/moduleTNC.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/moduleTNC.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3978e67043c23de3283a4c15779a911bf765836 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/moduleTNC.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/nonlin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/nonlin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0503fbf06c41525164ed36d9d69a8272da94116f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/nonlin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/optimize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/optimize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cede5d14550be2380d1d68153337d180f639782e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/optimize.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/slsqp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/slsqp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0eaa73118857397bd85b8a6beafcf2595e3e49b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/slsqp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/tnc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/tnc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..117be0948b7ccd6347797651f84cc20948e3ff6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/tnc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/zeros.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/zeros.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30d05260fffc71afc57737d97df592d9ae2d739a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/__pycache__/zeros.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_highspy/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_highspy/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f16455bdfb653561018494edc38cd30cef26c712 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_highspy/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_highspy/__pycache__/_highs_wrapper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_highspy/__pycache__/_highs_wrapper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..036eb90431561823141dc57274fb20913da95b01 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_highspy/__pycache__/_highs_wrapper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065fa20b7e2df3707e8ed9c41a8110a9913977d3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ff280519eb49a4077a8584eb614b3b01b284a10 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2066e3b6bed7330f81ef0d410e8228fd11bc23a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/dogbox.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/dogbox.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9604c4458d0b943144d0559bb12d021f344ebb06 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/dogbox.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/least_squares.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/least_squares.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b1596f904a594a5f30db7c363977f8a8aebf95b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/least_squares.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/lsq_linear.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/lsq_linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab809b099750c2f51c1ab4e6ae4d50058515995e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/lsq_linear.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/trf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/trf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31e5f05cfcf4211b2584c8ddce9bba83c58ab186 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/trf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2558e8ff0a1ab03c5d84ecba5a7a5cb2d5fdf0d0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cf50d6d7560f185ad059df4820778f20d2b6b9e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebc1d8251daaec6362eb610b48439a510a55fb7e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae2abfd8ca15bf704e9a1d8fad6231cd0266c6c2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/_complex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/_complex.py new file mode 100644 index 0000000000000000000000000000000000000000..b7b1e70b8d04efd7b06529f3dc6a37338922b092 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/_complex.py @@ -0,0 +1,1225 @@ +"""Base classes for low memory simplicial complex structures.""" +import copy +import logging +import itertools +import decimal +from functools import cache + +import numpy as np + +from ._vertex import (VertexCacheField, VertexCacheIndex) + + +class Complex: + """ + Base class for a simplicial complex described as a cache of vertices + together with their connections. + + Important methods: + Domain triangulation: + Complex.triangulate, Complex.split_generation + Triangulating arbitrary points (must be traingulable, + may exist outside domain): + Complex.triangulate(sample_set) + Converting another simplicial complex structure data type to the + structure used in Complex (ex. OBJ wavefront) + Complex.convert(datatype, data) + + Important objects: + HC.V: The cache of vertices and their connection + HC.H: Storage structure of all vertex groups + + Parameters + ---------- + dim : int + Spatial dimensionality of the complex R^dim + domain : list of tuples, optional + The bounds [x_l, x_u]^dim of the hyperrectangle space + ex. The default domain is the hyperrectangle [0, 1]^dim + Note: The domain must be convex, non-convex spaces can be cut + away from this domain using the non-linear + g_cons functions to define any arbitrary domain + (these domains may also be disconnected from each other) + sfield : + A scalar function defined in the associated domain f: R^dim --> R + sfield_args : tuple + Additional arguments to be passed to `sfield` + vfield : + A scalar function defined in the associated domain + f: R^dim --> R^m + (for example a gradient function of the scalar field) + vfield_args : tuple + Additional arguments to be passed to vfield + symmetry : None or list + Specify if the objective function contains symmetric variables. + The search space (and therefore performance) is decreased by up to + O(n!) times in the fully symmetric case. + + E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2 + + In this equation x_2 and x_3 are symmetric to x_1, while x_5 and + x_6 are symmetric to x_4, this can be specified to the solver as: + + symmetry = [0, # Variable 1 + 0, # symmetric to variable 1 + 0, # symmetric to variable 1 + 3, # Variable 4 + 3, # symmetric to variable 4 + 3, # symmetric to variable 4 + ] + + constraints : dict or sequence of dict, optional + Constraints definition. + Function(s) ``R**n`` in the form:: + + g(x) <= 0 applied as g : R^n -> R^m + h(x) == 0 applied as h : R^n -> R^p + + Each constraint is defined in a dictionary with fields: + + type : str + Constraint type: 'eq' for equality, 'ineq' for inequality. + fun : callable + The function defining the constraint. + jac : callable, optional + The Jacobian of `fun` (only for SLSQP). + args : sequence, optional + Extra arguments to be passed to the function and Jacobian. + + Equality constraint means that the constraint function result is to + be zero whereas inequality means that it is to be + non-negative.constraints : dict or sequence of dict, optional + Constraints definition. + Function(s) ``R**n`` in the form:: + + g(x) <= 0 applied as g : R^n -> R^m + h(x) == 0 applied as h : R^n -> R^p + + Each constraint is defined in a dictionary with fields: + + type : str + Constraint type: 'eq' for equality, 'ineq' for inequality. + fun : callable + The function defining the constraint. + jac : callable, optional + The Jacobian of `fun` (unused). + args : sequence, optional + Extra arguments to be passed to the function and Jacobian. + + Equality constraint means that the constraint function result is to + be zero whereas inequality means that it is to be non-negative. + + workers : int optional + Uses `multiprocessing.Pool `) to compute the field + functions in parallel. + """ + def __init__(self, dim, domain=None, sfield=None, sfield_args=(), + symmetry=None, constraints=None, workers=1): + self.dim = dim + + # Domains + self.domain = domain + if domain is None: + self.bounds = [(0.0, 1.0), ] * dim + else: + self.bounds = domain + self.symmetry = symmetry + # here in init to avoid if checks + + # Field functions + self.sfield = sfield + self.sfield_args = sfield_args + + # Process constraints + # Constraints + # Process constraint dict sequence: + if constraints is not None: + self.min_cons = constraints + self.g_cons = [] + self.g_args = [] + if not isinstance(constraints, tuple | list): + constraints = (constraints,) + + for cons in constraints: + if cons['type'] in ('ineq'): + self.g_cons.append(cons['fun']) + try: + self.g_args.append(cons['args']) + except KeyError: + self.g_args.append(()) + self.g_cons = tuple(self.g_cons) + self.g_args = tuple(self.g_args) + else: + self.g_cons = None + self.g_args = None + + # Homology properties + self.gen = 0 + self.perm_cycle = 0 + + # Every cell is stored in a list of its generation, + # ex. the initial cell is stored in self.H[0] + # 1st get new cells are stored in self.H[1] etc. + # When a cell is sub-generated it is removed from this list + + self.H = [] # Storage structure of vertex groups + + # Cache of all vertices + if (sfield is not None) or (self.g_cons is not None): + # Initiate a vertex cache and an associated field cache, note that + # the field case is always initiated inside the vertex cache if an + # associated field scalar field is defined: + if sfield is not None: + self.V = VertexCacheField(field=sfield, field_args=sfield_args, + g_cons=self.g_cons, + g_cons_args=self.g_args, + workers=workers) + elif self.g_cons is not None: + self.V = VertexCacheField(field=sfield, field_args=sfield_args, + g_cons=self.g_cons, + g_cons_args=self.g_args, + workers=workers) + else: + self.V = VertexCacheIndex() + + self.V_non_symm = [] # List of non-symmetric vertices + self.split_edge = cache(self._split_edge) + + def __call__(self): + return self.H + + # %% Triangulation methods + def cyclic_product(self, bounds, origin, supremum, centroid=True): + """Generate initial triangulation using cyclic product""" + # Define current hyperrectangle + vot = tuple(origin) + vut = tuple(supremum) # Hyperrectangle supremum + self.V[vot] + vo = self.V[vot] + yield vo.x + self.V[vut].connect(self.V[vot]) + yield vut + # Cyclic group approach with second x_l --- x_u operation. + + # These containers store the "lower" and "upper" vertices + # corresponding to the origin or supremum of every C2 group. + # It has the structure of `dim` times embedded lists each containing + # these vertices as the entire complex grows. Bounds[0] has to be done + # outside the loops before we have symmetric containers. + # NOTE: This means that bounds[0][1] must always exist + C0x = [[self.V[vot]]] + a_vo = copy.copy(list(origin)) + a_vo[0] = vut[0] # Update aN Origin + a_vo = self.V[tuple(a_vo)] + # self.V[vot].connect(self.V[tuple(a_vo)]) + self.V[vot].connect(a_vo) + yield a_vo.x + C1x = [[a_vo]] + # C1x = [[self.V[tuple(a_vo)]]] + ab_C = [] # Container for a + b operations + + # Loop over remaining bounds + for i, x in enumerate(bounds[1:]): + # Update lower and upper containers + C0x.append([]) + C1x.append([]) + # try to access a second bound (if not, C1 is symmetric) + try: + # Early try so that we don't have to copy the cache before + # moving on to next C1/C2: Try to add the operation of a new + # C2 product by accessing the upper bound + x[1] + # Copy lists for iteration + cC0x = [x[:] for x in C0x[:i + 1]] + cC1x = [x[:] for x in C1x[:i + 1]] + for j, (VL, VU) in enumerate(zip(cC0x, cC1x)): + for k, (vl, vu) in enumerate(zip(VL, VU)): + # Build aN vertices for each lower-upper pair in N: + a_vl = list(vl.x) + a_vu = list(vu.x) + a_vl[i + 1] = vut[i + 1] + a_vu[i + 1] = vut[i + 1] + a_vl = self.V[tuple(a_vl)] + + # Connect vertices in N to corresponding vertices + # in aN: + vl.connect(a_vl) + + yield a_vl.x + + a_vu = self.V[tuple(a_vu)] + # Connect vertices in N to corresponding vertices + # in aN: + vu.connect(a_vu) + + # Connect new vertex pair in aN: + a_vl.connect(a_vu) + + # Connect lower pair to upper (triangulation + # operation of a + b (two arbitrary operations): + vl.connect(a_vu) + ab_C.append((vl, a_vu)) + + # Update the containers + C0x[i + 1].append(vl) + C0x[i + 1].append(vu) + C1x[i + 1].append(a_vl) + C1x[i + 1].append(a_vu) + + # Update old containers + C0x[j].append(a_vl) + C1x[j].append(a_vu) + + # Yield new points + yield a_vu.x + + # Try to connect aN lower source of previous a + b + # operation with a aN vertex + ab_Cc = copy.copy(ab_C) + + for vp in ab_Cc: + b_v = list(vp[0].x) + ab_v = list(vp[1].x) + b_v[i + 1] = vut[i + 1] + ab_v[i + 1] = vut[i + 1] + b_v = self.V[tuple(b_v)] # b + vl + ab_v = self.V[tuple(ab_v)] # b + a_vl + # Note o---o is already connected + vp[0].connect(ab_v) # o-s + b_v.connect(ab_v) # s-s + + # Add new list of cross pairs + ab_C.append((vp[0], ab_v)) + ab_C.append((b_v, ab_v)) + + except IndexError: + cC0x = C0x[i] + cC1x = C1x[i] + VL, VU = cC0x, cC1x + for k, (vl, vu) in enumerate(zip(VL, VU)): + # Build aN vertices for each lower-upper pair in N: + a_vu = list(vu.x) + a_vu[i + 1] = vut[i + 1] + # Connect vertices in N to corresponding vertices + # in aN: + a_vu = self.V[tuple(a_vu)] + # Connect vertices in N to corresponding vertices + # in aN: + vu.connect(a_vu) + # Connect new vertex pair in aN: + # a_vl.connect(a_vu) + # Connect lower pair to upper (triangulation + # operation of a + b (two arbitrary operations): + vl.connect(a_vu) + ab_C.append((vl, a_vu)) + C0x[i + 1].append(vu) + C1x[i + 1].append(a_vu) + # Yield new points + a_vu.connect(self.V[vut]) + yield a_vu.x + ab_Cc = copy.copy(ab_C) + for vp in ab_Cc: + if vp[1].x[i] == vut[i]: + ab_v = list(vp[1].x) + ab_v[i + 1] = vut[i + 1] + ab_v = self.V[tuple(ab_v)] # b + a_vl + # Note o---o is already connected + vp[0].connect(ab_v) # o-s + + # Add new list of cross pairs + ab_C.append((vp[0], ab_v)) + + # Clean class trash + try: + del C0x + del cC0x + del C1x + del cC1x + del ab_C + del ab_Cc + except UnboundLocalError: + pass + + # Extra yield to ensure that the triangulation is completed + if centroid: + vo = self.V[vot] + vs = self.V[vut] + # Disconnect the origin and supremum + vo.disconnect(vs) + # Build centroid + vc = self.split_edge(vot, vut) + for v in vo.nn: + v.connect(vc) + yield vc.x + return vc.x + else: + yield vut + return vut + + def triangulate(self, n=None, symmetry=None, centroid=True, + printout=False): + """ + Triangulate the initial domain, if n is not None then a limited number + of points will be generated + + Parameters + ---------- + n : int, Number of points to be sampled. + symmetry : + + Ex. Dictionary/hashtable + f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2 + + symmetry = symmetry[0]: 0, # Variable 1 + symmetry[1]: 0, # symmetric to variable 1 + symmetry[2]: 0, # symmetric to variable 1 + symmetry[3]: 3, # Variable 4 + symmetry[4]: 3, # symmetric to variable 4 + symmetry[5]: 3, # symmetric to variable 4 + } + centroid : bool, if True add a central point to the hypercube + printout : bool, if True print out results + + NOTES: + ------ + Rather than using the combinatorial algorithm to connect vertices we + make the following observation: + + The bound pairs are similar a C2 cyclic group and the structure is + formed using the cartesian product: + + H = C2 x C2 x C2 ... x C2 (dim times) + + So construct any normal subgroup N and consider H/N first, we connect + all vertices within N (ex. N is C2 (the first dimension), then we move + to a left coset aN (an operation moving around the defined H/N group by + for example moving from the lower bound in C2 (dimension 2) to the + higher bound in C2. During this operation connection all the vertices. + Now repeat the N connections. Note that these elements can be connected + in parallel. + """ + # Inherit class arguments + if symmetry is None: + symmetry = self.symmetry + # Build origin and supremum vectors + origin = [i[0] for i in self.bounds] + self.origin = origin + supremum = [i[1] for i in self.bounds] + + self.supremum = supremum + + if symmetry is None: + cbounds = self.bounds + else: + cbounds = copy.copy(self.bounds) + for i, j in enumerate(symmetry): + if i is not j: + # pop second entry on second symmetry vars + cbounds[i] = [self.bounds[symmetry[i]][0]] + # Sole (first) entry is the sup value and there is no + # origin: + cbounds[i] = [self.bounds[symmetry[i]][1]] + if (self.bounds[symmetry[i]] is not + self.bounds[symmetry[j]]): + logging.warning(f"Variable {i} was specified as " + f"symmetric to variable {j}, however" + f", the bounds {i} =" + f" {self.bounds[symmetry[i]]} and {j}" + f" =" + f" {self.bounds[symmetry[j]]} do not " + f"match, the mismatch was ignored in " + f"the initial triangulation.") + cbounds[i] = self.bounds[symmetry[j]] + + if n is None: + # Build generator + self.cp = self.cyclic_product(cbounds, origin, supremum, centroid) + for i in self.cp: + i + + try: + self.triangulated_vectors.append((tuple(self.origin), + tuple(self.supremum))) + except (AttributeError, KeyError): + self.triangulated_vectors = [(tuple(self.origin), + tuple(self.supremum))] + + else: + # Check if generator already exists + try: + self.cp + except (AttributeError, KeyError): + self.cp = self.cyclic_product(cbounds, origin, supremum, + centroid) + + try: + while len(self.V.cache) < n: + next(self.cp) + except StopIteration: + try: + self.triangulated_vectors.append((tuple(self.origin), + tuple(self.supremum))) + except (AttributeError, KeyError): + self.triangulated_vectors = [(tuple(self.origin), + tuple(self.supremum))] + + if printout: + # for v in self.C0(): + # v.print_out() + for v in self.V.cache: + self.V[v].print_out() + + return + + def refine(self, n=1): + if n is None: + try: + self.triangulated_vectors + self.refine_all() + return + except AttributeError as ae: + if str(ae) == "'Complex' object has no attribute " \ + "'triangulated_vectors'": + self.triangulate(symmetry=self.symmetry) + return + else: + raise + + nt = len(self.V.cache) + n # Target number of total vertices + # In the outer while loop we iterate until we have added an extra `n` + # vertices to the complex: + while len(self.V.cache) < nt: # while loop 1 + try: # try 1 + # Try to access triangulated_vectors, this should only be + # defined if an initial triangulation has already been + # performed: + self.triangulated_vectors + # Try a usual iteration of the current generator, if it + # does not exist or is exhausted then produce a new generator + try: # try 2 + next(self.rls) + except (AttributeError, StopIteration, KeyError): + vp = self.triangulated_vectors[0] + self.rls = self.refine_local_space(*vp, bounds=self.bounds) + next(self.rls) + + except (AttributeError, KeyError): + # If an initial triangulation has not been completed, then + # we start/continue the initial triangulation targeting `nt` + # vertices, if nt is greater than the initial number of + # vertices then the `refine` routine will move back to try 1. + self.triangulate(nt, self.symmetry) + return + + def refine_all(self, centroids=True): + """Refine the entire domain of the current complex.""" + try: + self.triangulated_vectors + tvs = copy.copy(self.triangulated_vectors) + for i, vp in enumerate(tvs): + self.rls = self.refine_local_space(*vp, bounds=self.bounds) + for i in self.rls: + i + except AttributeError as ae: + if str(ae) == "'Complex' object has no attribute " \ + "'triangulated_vectors'": + self.triangulate(symmetry=self.symmetry, centroid=centroids) + else: + raise + + # This adds a centroid to every new sub-domain generated and defined + # by self.triangulated_vectors, in addition the vertices ! to complete + # the triangulation + return + + def refine_local_space(self, origin, supremum, bounds, centroid=1): + # Copy for later removal + origin_c = copy.copy(origin) + supremum_c = copy.copy(supremum) + + # Initiate local variables redefined in later inner `for` loop: + vl, vu, a_vu = None, None, None + + # Change the vector orientation so that it is only increasing + s_ov = list(origin) + s_origin = list(origin) + s_sv = list(supremum) + s_supremum = list(supremum) + for i, vi in enumerate(s_origin): + if s_ov[i] > s_sv[i]: + s_origin[i] = s_sv[i] + s_supremum[i] = s_ov[i] + + vot = tuple(s_origin) + vut = tuple(s_supremum) # Hyperrectangle supremum + + vo = self.V[vot] # initiate if doesn't exist yet + vs = self.V[vut] + # Start by finding the old centroid of the new space: + vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg + + # Find set of extreme vertices in current local space + sup_set = copy.copy(vco.nn) + # Cyclic group approach with second x_l --- x_u operation. + + # These containers store the "lower" and "upper" vertices + # corresponding to the origin or supremum of every C2 group. + # It has the structure of `dim` times embedded lists each containing + # these vertices as the entire complex grows. Bounds[0] has to be done + # outside the loops before we have symmetric containers. + # NOTE: This means that bounds[0][1] must always exist + + a_vl = copy.copy(list(vot)) + a_vl[0] = vut[0] # Update aN Origin + if tuple(a_vl) not in self.V.cache: + vo = self.V[vot] # initiate if doesn't exist yet + vs = self.V[vut] + # Start by finding the old centroid of the new space: + vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg + + # Find set of extreme vertices in current local space + sup_set = copy.copy(vco.nn) + a_vl = copy.copy(list(vot)) + a_vl[0] = vut[0] # Update aN Origin + a_vl = self.V[tuple(a_vl)] + else: + a_vl = self.V[tuple(a_vl)] + + c_v = self.split_edge(vo.x, a_vl.x) + c_v.connect(vco) + yield c_v.x + Cox = [[vo]] + Ccx = [[c_v]] + Cux = [[a_vl]] + ab_C = [] # Container for a + b operations + s_ab_C = [] # Container for symmetric a + b operations + + # Loop over remaining bounds + for i, x in enumerate(bounds[1:]): + # Update lower and upper containers + Cox.append([]) + Ccx.append([]) + Cux.append([]) + # try to access a second bound (if not, C1 is symmetric) + try: + t_a_vl = list(vot) + t_a_vl[i + 1] = vut[i + 1] + + # New: lists are used anyway, so copy all + # %% + # Copy lists for iteration + cCox = [x[:] for x in Cox[:i + 1]] + cCcx = [x[:] for x in Ccx[:i + 1]] + cCux = [x[:] for x in Cux[:i + 1]] + # Try to connect aN lower source of previous a + b + # operation with a aN vertex + ab_Cc = copy.copy(ab_C) # NOTE: We append ab_C in the + # (VL, VC, VU) for-loop, but we use the copy of the list in the + # ab_Cc for-loop. + s_ab_Cc = copy.copy(s_ab_C) + + # Early try so that we don't have to copy the cache before + # moving on to next C1/C2: Try to add the operation of a new + # C2 product by accessing the upper bound + if tuple(t_a_vl) not in self.V.cache: + # Raise error to continue symmetric refine + raise IndexError + t_a_vu = list(vut) + t_a_vu[i + 1] = vut[i + 1] + if tuple(t_a_vu) not in self.V.cache: + # Raise error to continue symmetric refine: + raise IndexError + + for vectors in s_ab_Cc: + # s_ab_C.append([c_vc, vl, vu, a_vu]) + bc_vc = list(vectors[0].x) + b_vl = list(vectors[1].x) + b_vu = list(vectors[2].x) + ba_vu = list(vectors[3].x) + + bc_vc[i + 1] = vut[i + 1] + b_vl[i + 1] = vut[i + 1] + b_vu[i + 1] = vut[i + 1] + ba_vu[i + 1] = vut[i + 1] + + bc_vc = self.V[tuple(bc_vc)] + bc_vc.connect(vco) # NOTE: Unneeded? + yield bc_vc + + # Split to centre, call this centre group "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(bc_vc) + d_bc_vc.connect(vectors[1]) # Connect all to centroid + d_bc_vc.connect(vectors[2]) # Connect all to centroid + d_bc_vc.connect(vectors[3]) # Connect all to centroid + yield d_bc_vc.x + b_vl = self.V[tuple(b_vl)] + bc_vc.connect(b_vl) # Connect aN cross pairs + d_bc_vc.connect(b_vl) # Connect all to centroid + + yield b_vl + b_vu = self.V[tuple(b_vu)] + bc_vc.connect(b_vu) # Connect aN cross pairs + d_bc_vc.connect(b_vu) # Connect all to centroid + + b_vl_c = self.split_edge(b_vu.x, b_vl.x) + bc_vc.connect(b_vl_c) + + yield b_vu + ba_vu = self.V[tuple(ba_vu)] + bc_vc.connect(ba_vu) # Connect aN cross pairs + d_bc_vc.connect(ba_vu) # Connect all to centroid + + # Split the a + b edge of the initial triangulation: + os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s + ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s + b_vu_c = self.split_edge(b_vu.x, ba_vu.x) + bc_vc.connect(b_vu_c) + yield os_v.x # often equal to vco, but not always + yield ss_v.x # often equal to bc_vu, but not always + yield ba_vu + # Split remaining to centre, call this centre group + # "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + yield d_bc_vc.x + d_b_vl = self.split_edge(vectors[1].x, b_vl.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vl) # Connect dN cross pairs + yield d_b_vl.x + d_b_vu = self.split_edge(vectors[2].x, b_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vu) # Connect dN cross pairs + yield d_b_vu.x + d_ba_vu = self.split_edge(vectors[3].x, ba_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs + yield d_ba_vu + + # comb = [c_vc, vl, vu, a_vl, a_vu, + # bc_vc, b_vl, b_vu, ba_vl, ba_vu] + comb = [vl, vu, a_vu, + b_vl, b_vu, ba_vu] + comb_iter = itertools.combinations(comb, 2) + for vecs in comb_iter: + self.split_edge(vecs[0].x, vecs[1].x) + # Add new list of cross pairs + ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu)) + ab_C.append((d_bc_vc, vl, b_vl, a_vu, ba_vu)) # = prev + + for vectors in ab_Cc: + bc_vc = list(vectors[0].x) + b_vl = list(vectors[1].x) + b_vu = list(vectors[2].x) + ba_vl = list(vectors[3].x) + ba_vu = list(vectors[4].x) + bc_vc[i + 1] = vut[i + 1] + b_vl[i + 1] = vut[i + 1] + b_vu[i + 1] = vut[i + 1] + ba_vl[i + 1] = vut[i + 1] + ba_vu[i + 1] = vut[i + 1] + bc_vc = self.V[tuple(bc_vc)] + bc_vc.connect(vco) # NOTE: Unneeded? + yield bc_vc + + # Split to centre, call this centre group "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(bc_vc) + d_bc_vc.connect(vectors[1]) # Connect all to centroid + d_bc_vc.connect(vectors[2]) # Connect all to centroid + d_bc_vc.connect(vectors[3]) # Connect all to centroid + d_bc_vc.connect(vectors[4]) # Connect all to centroid + yield d_bc_vc.x + b_vl = self.V[tuple(b_vl)] + bc_vc.connect(b_vl) # Connect aN cross pairs + d_bc_vc.connect(b_vl) # Connect all to centroid + yield b_vl + b_vu = self.V[tuple(b_vu)] + bc_vc.connect(b_vu) # Connect aN cross pairs + d_bc_vc.connect(b_vu) # Connect all to centroid + yield b_vu + ba_vl = self.V[tuple(ba_vl)] + bc_vc.connect(ba_vl) # Connect aN cross pairs + d_bc_vc.connect(ba_vl) # Connect all to centroid + self.split_edge(b_vu.x, ba_vl.x) + yield ba_vl + ba_vu = self.V[tuple(ba_vu)] + bc_vc.connect(ba_vu) # Connect aN cross pairs + d_bc_vc.connect(ba_vu) # Connect all to centroid + # Split the a + b edge of the initial triangulation: + os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s + ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s + yield os_v.x # often equal to vco, but not always + yield ss_v.x # often equal to bc_vu, but not always + yield ba_vu + # Split remaining to centre, call this centre group + # "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + yield d_bc_vc.x + d_b_vl = self.split_edge(vectors[1].x, b_vl.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vl) # Connect dN cross pairs + yield d_b_vl.x + d_b_vu = self.split_edge(vectors[2].x, b_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vu) # Connect dN cross pairs + yield d_b_vu.x + d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_ba_vl) # Connect dN cross pairs + yield d_ba_vl + d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs + yield d_ba_vu + c_vc, vl, vu, a_vl, a_vu = vectors + + comb = [vl, vu, a_vl, a_vu, + b_vl, b_vu, ba_vl, ba_vu] + comb_iter = itertools.combinations(comb, 2) + for vecs in comb_iter: + self.split_edge(vecs[0].x, vecs[1].x) + + # Add new list of cross pairs + ab_C.append((bc_vc, b_vl, b_vu, ba_vl, ba_vu)) + ab_C.append((d_bc_vc, d_b_vl, d_b_vu, d_ba_vl, d_ba_vu)) + ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu)) + ab_C.append((d_bc_vc, vu, b_vu, a_vl, ba_vl)) + + for j, (VL, VC, VU) in enumerate(zip(cCox, cCcx, cCux)): + for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)): + # Build aN vertices for each lower-upper C3 group in N: + a_vl = list(vl.x) + a_vu = list(vu.x) + a_vl[i + 1] = vut[i + 1] + a_vu[i + 1] = vut[i + 1] + a_vl = self.V[tuple(a_vl)] + a_vu = self.V[tuple(a_vu)] + # Note, build (a + vc) later for consistent yields + # Split the a + b edge of the initial triangulation: + c_vc = self.split_edge(vl.x, a_vu.x) + self.split_edge(vl.x, vu.x) # Equal to vc + # Build cN vertices for each lower-upper C3 group in N: + c_vc.connect(vco) + c_vc.connect(vc) + c_vc.connect(vl) # Connect c + ac operations + c_vc.connect(vu) # Connect c + ac operations + c_vc.connect(a_vl) # Connect c + ac operations + c_vc.connect(a_vu) # Connect c + ac operations + yield c_vc.x + c_vl = self.split_edge(vl.x, a_vl.x) + c_vl.connect(vco) + c_vc.connect(c_vl) # Connect cN group vertices + yield c_vl.x + # yield at end of loop: + c_vu = self.split_edge(vu.x, a_vu.x) + c_vu.connect(vco) + # Connect remaining cN group vertices + c_vc.connect(c_vu) # Connect cN group vertices + yield c_vu.x + + a_vc = self.split_edge(a_vl.x, a_vu.x) # is (a + vc) ? + a_vc.connect(vco) + a_vc.connect(c_vc) + + # Storage for connecting c + ac operations: + ab_C.append((c_vc, vl, vu, a_vl, a_vu)) + + # Update the containers + Cox[i + 1].append(vl) + Cox[i + 1].append(vc) + Cox[i + 1].append(vu) + Ccx[i + 1].append(c_vl) + Ccx[i + 1].append(c_vc) + Ccx[i + 1].append(c_vu) + Cux[i + 1].append(a_vl) + Cux[i + 1].append(a_vc) + Cux[i + 1].append(a_vu) + + # Update old containers + Cox[j].append(c_vl) # ! + Cox[j].append(a_vl) + Ccx[j].append(c_vc) # ! + Ccx[j].append(a_vc) # ! + Cux[j].append(c_vu) # ! + Cux[j].append(a_vu) + + # Yield new points + yield a_vc.x + + except IndexError: + for vectors in ab_Cc: + ba_vl = list(vectors[3].x) + ba_vu = list(vectors[4].x) + ba_vl[i + 1] = vut[i + 1] + ba_vu[i + 1] = vut[i + 1] + ba_vu = self.V[tuple(ba_vu)] + yield ba_vu + d_bc_vc = self.split_edge(vectors[1].x, ba_vu.x) # o-s + yield ba_vu + d_bc_vc.connect(vectors[1]) # Connect all to centroid + d_bc_vc.connect(vectors[2]) # Connect all to centroid + d_bc_vc.connect(vectors[3]) # Connect all to centroid + d_bc_vc.connect(vectors[4]) # Connect all to centroid + yield d_bc_vc.x + ba_vl = self.V[tuple(ba_vl)] + yield ba_vl + d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x) + d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x) + d_ba_vc = self.split_edge(d_ba_vl.x, d_ba_vu.x) + yield d_ba_vl + yield d_ba_vu + yield d_ba_vc + c_vc, vl, vu, a_vl, a_vu = vectors + comb = [vl, vu, a_vl, a_vu, + ba_vl, + ba_vu] + comb_iter = itertools.combinations(comb, 2) + for vecs in comb_iter: + self.split_edge(vecs[0].x, vecs[1].x) + + # Copy lists for iteration + cCox = Cox[i] + cCcx = Ccx[i] + cCux = Cux[i] + VL, VC, VU = cCox, cCcx, cCux + for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)): + # Build aN vertices for each lower-upper pair in N: + a_vu = list(vu.x) + a_vu[i + 1] = vut[i + 1] + + # Connect vertices in N to corresponding vertices + # in aN: + a_vu = self.V[tuple(a_vu)] + yield a_vl.x + # Split the a + b edge of the initial triangulation: + c_vc = self.split_edge(vl.x, a_vu.x) + self.split_edge(vl.x, vu.x) # Equal to vc + c_vc.connect(vco) + c_vc.connect(vc) + c_vc.connect(vl) # Connect c + ac operations + c_vc.connect(vu) # Connect c + ac operations + c_vc.connect(a_vu) # Connect c + ac operations + yield (c_vc.x) + c_vu = self.split_edge(vu.x, + a_vu.x) # yield at end of loop + c_vu.connect(vco) + # Connect remaining cN group vertices + c_vc.connect(c_vu) # Connect cN group vertices + yield (c_vu.x) + + # Update the containers + Cox[i + 1].append(vu) + Ccx[i + 1].append(c_vu) + Cux[i + 1].append(a_vu) + + # Update old containers + s_ab_C.append([c_vc, vl, vu, a_vu]) + + yield a_vu.x + + # Clean class trash + try: + del Cox + del Ccx + del Cux + del ab_C + del ab_Cc + except UnboundLocalError: + pass + + try: + self.triangulated_vectors.remove((tuple(origin_c), + tuple(supremum_c))) + except ValueError: + # Turn this into a logging warning? + pass + # Add newly triangulated vectors: + for vs in sup_set: + self.triangulated_vectors.append((tuple(vco.x), tuple(vs.x))) + + # Extra yield to ensure that the triangulation is completed + if centroid: + vcn_set = set() + c_nn_lists = [] + for vs in sup_set: + # Build centroid + c_nn = self.vpool(vco.x, vs.x) + try: + c_nn.remove(vcn_set) + except KeyError: + pass + c_nn_lists.append(c_nn) + + for c_nn in c_nn_lists: + try: + c_nn.remove(vcn_set) + except KeyError: + pass + + for vs, c_nn in zip(sup_set, c_nn_lists): + # Build centroid + vcn = self.split_edge(vco.x, vs.x) + vcn_set.add(vcn) + try: # Shouldn't be needed? + c_nn.remove(vcn_set) + except KeyError: + pass + for vnn in c_nn: + vcn.connect(vnn) + yield vcn.x + else: + pass + + yield vut + return + + def refine_star(self, v): + """Refine the star domain of a vertex `v`.""" + # Copy lists before iteration + vnn = copy.copy(v.nn) + v1nn = [] + d_v0v1_set = set() + for v1 in vnn: + v1nn.append(copy.copy(v1.nn)) + + for v1, v1nn in zip(vnn, v1nn): + vnnu = v1nn.intersection(vnn) + + d_v0v1 = self.split_edge(v.x, v1.x) + for o_d_v0v1 in d_v0v1_set: + d_v0v1.connect(o_d_v0v1) + d_v0v1_set.add(d_v0v1) + for v2 in vnnu: + d_v1v2 = self.split_edge(v1.x, v2.x) + d_v0v1.connect(d_v1v2) + return + + def _split_edge(self, v1, v2): + v1 = self.V[v1] + v2 = self.V[v2] + # Destroy original edge, if it exists: + v1.disconnect(v2) + # Compute vertex on centre of edge: + try: + vct = (v2.x_a - v1.x_a) / 2.0 + v1.x_a + except TypeError: # Allow for decimal operations + vct = (v2.x_a - v1.x_a) / decimal.Decimal(2.0) + v1.x_a + + vc = self.V[tuple(vct)] + # Connect to original 2 vertices to the new centre vertex + vc.connect(v1) + vc.connect(v2) + return vc + + def vpool(self, origin, supremum): + vot = tuple(origin) + vst = tuple(supremum) + # Initiate vertices in case they don't exist + vo = self.V[vot] + vs = self.V[vst] + + # Remove origin - supremum disconnect + + # Find the lower/upper bounds of the refinement hyperrectangle + bl = list(vot) + bu = list(vst) + for i, (voi, vsi) in enumerate(zip(vot, vst)): + if bl[i] > vsi: + bl[i] = vsi + if bu[i] < voi: + bu[i] = voi + + # NOTE: This is mostly done with sets/lists because we aren't sure + # how well the numpy arrays will scale to thousands of + # dimensions. + vn_pool = set() + vn_pool.update(vo.nn) + vn_pool.update(vs.nn) + cvn_pool = copy.copy(vn_pool) + for vn in cvn_pool: + for i, xi in enumerate(vn.x): + if bl[i] <= xi <= bu[i]: + pass + else: + try: + vn_pool.remove(vn) + except KeyError: + pass # NOTE: Not all neighbours are in initial pool + return vn_pool + + def vf_to_vv(self, vertices, simplices): + """ + Convert a vertex-face mesh to a vertex-vertex mesh used by this class + + Parameters + ---------- + vertices : list + Vertices + simplices : list + Simplices + """ + if self.dim > 1: + for s in simplices: + edges = itertools.combinations(s, self.dim) + for e in edges: + self.V[tuple(vertices[e[0]])].connect( + self.V[tuple(vertices[e[1]])]) + else: + for e in simplices: + self.V[tuple(vertices[e[0]])].connect( + self.V[tuple(vertices[e[1]])]) + return + + def connect_vertex_non_symm(self, v_x, near=None): + """ + Adds a vertex at coords v_x to the complex that is not symmetric to the + initial triangulation and sub-triangulation. + + If near is specified (for example; a star domain or collections of + cells known to contain v) then only those simplices containd in near + will be searched, this greatly speeds up the process. + + If near is not specified this method will search the entire simplicial + complex structure. + + Parameters + ---------- + v_x : tuple + Coordinates of non-symmetric vertex + near : set or list + List of vertices, these are points near v to check for + """ + if near is None: + star = self.V + else: + star = near + # Create the vertex origin + if tuple(v_x) in self.V.cache: + if self.V[v_x] in self.V_non_symm: + pass + else: + return + + self.V[v_x] + found_nn = False + S_rows = [] + for v in star: + S_rows.append(v.x) + + S_rows = np.array(S_rows) + A = np.array(S_rows) - np.array(v_x) + # Iterate through all the possible simplices of S_rows + for s_i in itertools.combinations(range(S_rows.shape[0]), + r=self.dim + 1): + # Check if connected, else s_i is not a simplex + valid_simplex = True + for i in itertools.combinations(s_i, r=2): + # Every combination of vertices must be connected, we check of + # the current iteration of all combinations of s_i are + # connected we break the loop if it is not. + if ((self.V[tuple(S_rows[i[1]])] not in + self.V[tuple(S_rows[i[0]])].nn) + and (self.V[tuple(S_rows[i[0]])] not in + self.V[tuple(S_rows[i[1]])].nn)): + valid_simplex = False + break + + S = S_rows[tuple([s_i])] + if valid_simplex: + if self.deg_simplex(S, proj=None): + valid_simplex = False + + # If s_i is a valid simplex we can test if v_x is inside si + if valid_simplex: + # Find the A_j0 value from the precalculated values + A_j0 = A[tuple([s_i])] + if self.in_simplex(S, v_x, A_j0): + found_nn = True + # breaks the main for loop, s_i is the target simplex: + break + + # Connect the simplex to point + if found_nn: + for i in s_i: + self.V[v_x].connect(self.V[tuple(S_rows[i])]) + # Attached the simplex to storage for all non-symmetric vertices + self.V_non_symm.append(self.V[v_x]) + # this bool value indicates a successful connection if True: + return found_nn + + def in_simplex(self, S, v_x, A_j0=None): + """Check if a vector v_x is in simplex `S`. + + Parameters + ---------- + S : array_like + Array containing simplex entries of vertices as rows + v_x : + A candidate vertex + A_j0 : array, optional, + Allows for A_j0 to be pre-calculated + + Returns + ------- + res : boolean + True if `v_x` is in `S` + """ + A_11 = np.delete(S, 0, 0) - S[0] + + sign_det_A_11 = np.sign(np.linalg.det(A_11)) + if sign_det_A_11 == 0: + # NOTE: We keep the variable A_11, but we loop through A_jj + # ind= + # while sign_det_A_11 == 0: + # A_11 = np.delete(S, ind, 0) - S[ind] + # sign_det_A_11 = np.sign(np.linalg.det(A_11)) + + sign_det_A_11 = -1 # TODO: Choose another det of j instead? + # TODO: Unlikely to work in many cases + + if A_j0 is None: + A_j0 = S - v_x + + for d in range(self.dim + 1): + det_A_jj = (-1)**d * sign_det_A_11 + # TODO: Note that scipy might be faster to add as an optional + # dependency + sign_det_A_j0 = np.sign(np.linalg.det(np.delete(A_j0, d, + 0))) + # TODO: Note if sign_det_A_j0 == then the point is coplanar to the + # current simplex facet, so perhaps return True and attach? + if det_A_jj == sign_det_A_j0: + continue + else: + return False + + return True + + def deg_simplex(self, S, proj=None): + """Test a simplex S for degeneracy (linear dependence in R^dim). + + Parameters + ---------- + S : np.array + Simplex with rows as vertex vectors + proj : array, optional, + If the projection S[1:] - S[0] is already + computed it can be added as an optional argument. + """ + # Strategy: we test all combination of faces, if any of the + # determinants are zero then the vectors lie on the same face and is + # therefore linearly dependent in the space of R^dim + if proj is None: + proj = S[1:] - S[0] + + # TODO: Is checking the projection of one vertex against faces of other + # vertices sufficient? Or do we need to check more vertices in + # dimensions higher than 2? + # TODO: Literature seems to suggest using proj.T, but why is this + # needed? + if np.linalg.det(proj) == 0.0: # TODO: Replace with tolerance? + return True # Simplex is degenerate + else: + return False # Simplex is not degenerate diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/_vertex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/_vertex.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7f14f255edfaa10a554320c947474a182d58b8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_shgo_lib/_vertex.py @@ -0,0 +1,460 @@ +import collections +from abc import ABC, abstractmethod + +import numpy as np + +from scipy._lib._util import MapWrapper + + +class VertexBase(ABC): + """ + Base class for a vertex. + """ + def __init__(self, x, nn=None, index=None): + """ + Initiation of a vertex object. + + Parameters + ---------- + x : tuple or vector + The geometric location (domain). + nn : list, optional + Nearest neighbour list. + index : int, optional + Index of vertex. + """ + self.x = x + self.hash = hash(self.x) # Save precomputed hash + + if nn is not None: + self.nn = set(nn) # can use .indexupdate to add a new list + else: + self.nn = set() + + self.index = index + + def __hash__(self): + return self.hash + + def __getattr__(self, item): + if item not in ['x_a']: + raise AttributeError(f"{type(self)} object has no attribute " + f"'{item}'") + if item == 'x_a': + self.x_a = np.array(self.x) + return self.x_a + + @abstractmethod + def connect(self, v): + raise NotImplementedError("This method is only implemented with an " + "associated child of the base class.") + + @abstractmethod + def disconnect(self, v): + raise NotImplementedError("This method is only implemented with an " + "associated child of the base class.") + + def star(self): + """Returns the star domain ``st(v)`` of the vertex. + + Parameters + ---------- + v : + The vertex ``v`` in ``st(v)`` + + Returns + ------- + st : set + A set containing all the vertices in ``st(v)`` + """ + self.st = self.nn + self.st.add(self) + return self.st + + +class VertexScalarField(VertexBase): + """ + Add homology properties of a scalar field f: R^n --> R associated with + the geometry built from the VertexBase class + """ + + def __init__(self, x, field=None, nn=None, index=None, field_args=(), + g_cons=None, g_cons_args=()): + """ + Parameters + ---------- + x : tuple, + vector of vertex coordinates + field : callable, optional + a scalar field f: R^n --> R associated with the geometry + nn : list, optional + list of nearest neighbours + index : int, optional + index of the vertex + field_args : tuple, optional + additional arguments to be passed to field + g_cons : callable, optional + constraints on the vertex + g_cons_args : tuple, optional + additional arguments to be passed to g_cons + + """ + super().__init__(x, nn=nn, index=index) + + # Note Vertex is only initiated once for all x so only + # evaluated once + # self.feasible = None + + # self.f is externally defined by the cache to allow parallel + # processing + # None type that will break arithmetic operations unless defined + # self.f = None + + self.check_min = True + self.check_max = True + + def connect(self, v): + """Connects self to another vertex object v. + + Parameters + ---------- + v : VertexBase or VertexScalarField object + """ + if v is not self and v not in self.nn: + self.nn.add(v) + v.nn.add(self) + + # Flags for checking homology properties: + self.check_min = True + self.check_max = True + v.check_min = True + v.check_max = True + + def disconnect(self, v): + if v in self.nn: + self.nn.remove(v) + v.nn.remove(self) + + # Flags for checking homology properties: + self.check_min = True + self.check_max = True + v.check_min = True + v.check_max = True + + def minimiser(self): + """Check whether this vertex is strictly less than all its + neighbours""" + if self.check_min: + self._min = all(self.f < v.f for v in self.nn) + self.check_min = False + + return self._min + + def maximiser(self): + """ + Check whether this vertex is strictly greater than all its + neighbours. + """ + if self.check_max: + self._max = all(self.f > v.f for v in self.nn) + self.check_max = False + + return self._max + + +class VertexVectorField(VertexBase): + """ + Add homology properties of a scalar field f: R^n --> R^m associated with + the geometry built from the VertexBase class. + """ + + def __init__(self, x, sfield=None, vfield=None, field_args=(), + vfield_args=(), g_cons=None, + g_cons_args=(), nn=None, index=None): + super().__init__(x, nn=nn, index=index) + + raise NotImplementedError("This class is still a work in progress") + + +class VertexCacheBase: + """Base class for a vertex cache for a simplicial complex.""" + def __init__(self): + + self.cache = collections.OrderedDict() + self.nfev = 0 # Feasible points + self.index = -1 + + def __iter__(self): + for v in self.cache: + yield self.cache[v] + return + + def size(self): + """Returns the size of the vertex cache.""" + return self.index + 1 + + def print_out(self): + headlen = len(f"Vertex cache of size: {len(self.cache)}:") + print('=' * headlen) + print(f"Vertex cache of size: {len(self.cache)}:") + print('=' * headlen) + for v in self.cache: + self.cache[v].print_out() + + +class VertexCube(VertexBase): + """Vertex class to be used for a pure simplicial complex with no associated + differential geometry (single level domain that exists in R^n)""" + def __init__(self, x, nn=None, index=None): + super().__init__(x, nn=nn, index=index) + + def connect(self, v): + if v is not self and v not in self.nn: + self.nn.add(v) + v.nn.add(self) + + def disconnect(self, v): + if v in self.nn: + self.nn.remove(v) + v.nn.remove(self) + + +class VertexCacheIndex(VertexCacheBase): + def __init__(self): + """ + Class for a vertex cache for a simplicial complex without an associated + field. Useful only for building and visualising a domain complex. + + Parameters + ---------- + """ + super().__init__() + self.Vertex = VertexCube + + def __getitem__(self, x, nn=None): + try: + return self.cache[x] + except KeyError: + self.index += 1 + xval = self.Vertex(x, index=self.index) + # logging.info("New generated vertex at x = {}".format(x)) + # NOTE: Surprisingly high performance increase if logging + # is commented out + self.cache[x] = xval + return self.cache[x] + + +class VertexCacheField(VertexCacheBase): + def __init__(self, field=None, field_args=(), g_cons=None, g_cons_args=(), + workers=1): + """ + Class for a vertex cache for a simplicial complex with an associated + field. + + Parameters + ---------- + field : callable + Scalar or vector field callable. + field_args : tuple, optional + Any additional fixed parameters needed to completely specify the + field function + g_cons : dict or sequence of dict, optional + Constraints definition. + Function(s) ``R**n`` in the form:: + g_cons_args : tuple, optional + Any additional fixed parameters needed to completely specify the + constraint functions + workers : int optional + Uses `multiprocessing.Pool `) to compute the field + functions in parallel. + + """ + super().__init__() + self.index = -1 + self.Vertex = VertexScalarField + self.field = field + self.field_args = field_args + self.wfield = FieldWrapper(field, field_args) # if workers is not 1 + + self.g_cons = g_cons + self.g_cons_args = g_cons_args + self.wgcons = ConstraintWrapper(g_cons, g_cons_args) + self.gpool = set() # A set of tuples to process for feasibility + + # Field processing objects + self.fpool = set() # A set of tuples to process for scalar function + self.sfc_lock = False # True if self.fpool is non-Empty + + self.workers = workers + self._mapwrapper = MapWrapper(workers) + + if workers == 1: + self.process_gpool = self.proc_gpool + if g_cons is None: + self.process_fpool = self.proc_fpool_nog + else: + self.process_fpool = self.proc_fpool_g + else: + self.process_gpool = self.pproc_gpool + if g_cons is None: + self.process_fpool = self.pproc_fpool_nog + else: + self.process_fpool = self.pproc_fpool_g + + def __getitem__(self, x, nn=None): + try: + return self.cache[x] + except KeyError: + self.index += 1 + xval = self.Vertex(x, field=self.field, nn=nn, index=self.index, + field_args=self.field_args, + g_cons=self.g_cons, + g_cons_args=self.g_cons_args) + + self.cache[x] = xval # Define in cache + self.gpool.add(xval) # Add to pool for processing feasibility + self.fpool.add(xval) # Add to pool for processing field values + return self.cache[x] + + def __getstate__(self): + self_dict = self.__dict__.copy() + del self_dict['pool'] + return self_dict + + def process_pools(self): + if self.g_cons is not None: + self.process_gpool() + self.process_fpool() + self.proc_minimisers() + + def feasibility_check(self, v): + v.feasible = True + for g, args in zip(self.g_cons, self.g_cons_args): + # constraint may return more than 1 value. + if np.any(g(v.x_a, *args) < 0.0): + v.f = np.inf + v.feasible = False + break + + def compute_sfield(self, v): + """Compute the scalar field values of a vertex object `v`. + + Parameters + ---------- + v : VertexBase or VertexScalarField object + """ + try: + v.f = self.field(v.x_a, *self.field_args) + self.nfev += 1 + except AttributeError: + v.f = np.inf + # logging.warning(f"Field function not found at x = {self.x_a}") + if np.isnan(v.f): + v.f = np.inf + + def proc_gpool(self): + """Process all constraints.""" + if self.g_cons is not None: + for v in self.gpool: + self.feasibility_check(v) + # Clean the pool + self.gpool = set() + + def pproc_gpool(self): + """Process all constraints in parallel.""" + gpool_l = [] + for v in self.gpool: + gpool_l.append(v.x_a) + + G = self._mapwrapper(self.wgcons.gcons, gpool_l) + for v, g in zip(self.gpool, G): + v.feasible = g # set vertex object attribute v.feasible = g (bool) + + def proc_fpool_g(self): + """Process all field functions with constraints supplied.""" + for v in self.fpool: + if v.feasible: + self.compute_sfield(v) + # Clean the pool + self.fpool = set() + + def proc_fpool_nog(self): + """Process all field functions with no constraints supplied.""" + for v in self.fpool: + self.compute_sfield(v) + # Clean the pool + self.fpool = set() + + def pproc_fpool_g(self): + """ + Process all field functions with constraints supplied in parallel. + """ + self.wfield.func + fpool_l = [] + for v in self.fpool: + if v.feasible: + fpool_l.append(v.x_a) + else: + v.f = np.inf + F = self._mapwrapper(self.wfield.func, fpool_l) + for va, f in zip(fpool_l, F): + vt = tuple(va) + self[vt].f = f # set vertex object attribute v.f = f + self.nfev += 1 + # Clean the pool + self.fpool = set() + + def pproc_fpool_nog(self): + """ + Process all field functions with no constraints supplied in parallel. + """ + self.wfield.func + fpool_l = [] + for v in self.fpool: + fpool_l.append(v.x_a) + F = self._mapwrapper(self.wfield.func, fpool_l) + for va, f in zip(fpool_l, F): + vt = tuple(va) + self[vt].f = f # set vertex object attribute v.f = f + self.nfev += 1 + # Clean the pool + self.fpool = set() + + def proc_minimisers(self): + """Check for minimisers.""" + for v in self: + v.minimiser() + v.maximiser() + + +class ConstraintWrapper: + """Object to wrap constraints to pass to `multiprocessing.Pool`.""" + def __init__(self, g_cons, g_cons_args): + self.g_cons = g_cons + self.g_cons_args = g_cons_args + + def gcons(self, v_x_a): + vfeasible = True + for g, args in zip(self.g_cons, self.g_cons_args): + # constraint may return more than 1 value. + if np.any(g(v_x_a, *args) < 0.0): + vfeasible = False + break + return vfeasible + + +class FieldWrapper: + """Object to wrap field to pass to `multiprocessing.Pool`.""" + def __init__(self, field, field_args): + self.field = field + self.field_args = field_args + + def func(self, v_x_a): + try: + v_f = self.field(v_x_a, *self.field_args) + except Exception: + v_f = np.inf + if np.isnan(v_f): + v_f = np.inf + + return v_f diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c6c05fb595d7aaaf263518545ef5313485e431 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/__init__.py @@ -0,0 +1,12 @@ +from ._trlib import TRLIBQuadraticSubproblem + +__all__ = ['TRLIBQuadraticSubproblem', 'get_trlib_quadratic_subproblem'] + + +def get_trlib_quadratic_subproblem(tol_rel_i=-2.0, tol_rel_b=-3.0, disp=False): + def subproblem_factory(x, fun, jac, hess, hessp): + return TRLIBQuadraticSubproblem(x, fun, jac, hess, hessp, + tol_rel_i=tol_rel_i, + tol_rel_b=tol_rel_b, + disp=disp) + return subproblem_factory diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81afa5b64611347387388bf8b805804113a3b7dc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/_trlib.cp311-win_amd64.dll.a b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/_trlib.cp311-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..c61526c6950645354e2b6e3ee48f2a0bf8e2831a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trlib/_trlib.cp311-win_amd64.dll.a differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..267a975a0a9134cd416cdeae27b231f49e15fd7e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__init__.py @@ -0,0 +1,6 @@ +"""This module contains the equality constrained SQP solver.""" + + +from .minimize_trustregion_constr import _minimize_trustregion_constr + +__all__ = ['_minimize_trustregion_constr'] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b66264d72f6bd9e9d1ccf8e1acf40f0e6bbd500 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9359c03d53610e21893fbac59a01ab7e498711ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fd2307423349b6a20c3fe05c26721f4bf31b832 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/minimize_trustregion_constr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/minimize_trustregion_constr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee4398fb30a86b1c6c76a5de3b031a5c9d7a9bf8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/minimize_trustregion_constr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3dcb13560a98e986245f26e6e2b512cc7829117 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/qp_subproblem.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/qp_subproblem.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adaa7682b8285d924e44a1eb2918a48375f6558c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/qp_subproblem.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/report.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/report.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a360a20c476d17c8d9e5dad6606cf2cdea018b83 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/report.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/tr_interior_point.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/tr_interior_point.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a791041147f902dcce4a2d348ea42fec43876ebb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/__pycache__/tr_interior_point.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..deda6c6fa01dc5c970ef26726c101c83e5936483 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py @@ -0,0 +1,390 @@ +import numpy as np +import scipy.sparse as sps + + +class CanonicalConstraint: + """Canonical constraint to use with trust-constr algorithm. + + It represents the set of constraints of the form:: + + f_eq(x) = 0 + f_ineq(x) <= 0 + + where ``f_eq`` and ``f_ineq`` are evaluated by a single function, see + below. + + The class is supposed to be instantiated by factory methods, which + should prepare the parameters listed below. + + Parameters + ---------- + n_eq, n_ineq : int + Number of equality and inequality constraints respectively. + fun : callable + Function defining the constraints. The signature is + ``fun(x) -> c_eq, c_ineq``, where ``c_eq`` is ndarray with `n_eq` + components and ``c_ineq`` is ndarray with `n_ineq` components. + jac : callable + Function to evaluate the Jacobian of the constraint. The signature + is ``jac(x) -> J_eq, J_ineq``, where ``J_eq`` and ``J_ineq`` are + either ndarray of csr_array of shapes (n_eq, n) and (n_ineq, n), + respectively. + hess : callable + Function to evaluate the Hessian of the constraints multiplied + by Lagrange multipliers, that is + ``dot(f_eq, v_eq) + dot(f_ineq, v_ineq)``. The signature is + ``hess(x, v_eq, v_ineq) -> H``, where ``H`` has an implied + shape (n, n) and provide a matrix-vector product operation + ``H.dot(p)``. + keep_feasible : ndarray, shape (n_ineq,) + Mask indicating which inequality constraints should be kept feasible. + """ + def __init__(self, n_eq, n_ineq, fun, jac, hess, keep_feasible): + self.n_eq = n_eq + self.n_ineq = n_ineq + self.fun = fun + self.jac = jac + self.hess = hess + self.keep_feasible = keep_feasible + + @classmethod + def from_PreparedConstraint(cls, constraint): + """Create an instance from `PreparedConstrained` object.""" + lb, ub = constraint.bounds + cfun = constraint.fun + keep_feasible = constraint.keep_feasible + + if np.all(lb == -np.inf) and np.all(ub == np.inf): + return cls.empty(cfun.n) + + if np.all(lb == -np.inf) and np.all(ub == np.inf): + return cls.empty(cfun.n) + elif np.all(lb == ub): + return cls._equal_to_canonical(cfun, lb) + elif np.all(lb == -np.inf): + return cls._less_to_canonical(cfun, ub, keep_feasible) + elif np.all(ub == np.inf): + return cls._greater_to_canonical(cfun, lb, keep_feasible) + else: + return cls._interval_to_canonical(cfun, lb, ub, keep_feasible) + + @classmethod + def empty(cls, n): + """Create an "empty" instance. + + This "empty" instance is required to allow working with unconstrained + problems as if they have some constraints. + """ + empty_fun = np.empty(0) + empty_jac = np.empty((0, n)) + empty_hess = sps.csr_array((n, n)) + + def fun(x): + return empty_fun, empty_fun + + def jac(x): + return empty_jac, empty_jac + + def hess(x, v_eq, v_ineq): + return empty_hess + + return cls(0, 0, fun, jac, hess, np.empty(0, dtype=np.bool_)) + + @classmethod + def concatenate(cls, canonical_constraints, sparse_jacobian): + """Concatenate multiple `CanonicalConstraint` into one. + + `sparse_jacobian` (bool) determines the Jacobian format of the + concatenated constraint. Note that items in `canonical_constraints` + must have their Jacobians in the same format. + """ + def fun(x): + if canonical_constraints: + eq_all, ineq_all = zip( + *[c.fun(x) for c in canonical_constraints]) + else: + eq_all, ineq_all = [], [] + + return np.hstack(eq_all), np.hstack(ineq_all) + + if sparse_jacobian: + vstack = sps.vstack + else: + vstack = np.vstack + + def jac(x): + if canonical_constraints: + eq_all, ineq_all = zip( + *[c.jac(x) for c in canonical_constraints]) + else: + eq_all, ineq_all = [], [] + + return vstack(eq_all), vstack(ineq_all) + + def hess(x, v_eq, v_ineq): + hess_all = [] + index_eq = 0 + index_ineq = 0 + for c in canonical_constraints: + vc_eq = v_eq[index_eq:index_eq + c.n_eq] + vc_ineq = v_ineq[index_ineq:index_ineq + c.n_ineq] + hess_all.append(c.hess(x, vc_eq, vc_ineq)) + index_eq += c.n_eq + index_ineq += c.n_ineq + + def matvec(p): + result = np.zeros_like(p, dtype=float) + for h in hess_all: + result += h.dot(p) + return result + + n = x.shape[0] + return sps.linalg.LinearOperator((n, n), matvec, dtype=float) + + n_eq = sum(c.n_eq for c in canonical_constraints) + n_ineq = sum(c.n_ineq for c in canonical_constraints) + keep_feasible = np.hstack([c.keep_feasible for c in + canonical_constraints]) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _equal_to_canonical(cls, cfun, value): + empty_fun = np.empty(0) + n = cfun.n + + n_eq = value.shape[0] + n_ineq = 0 + keep_feasible = np.empty(0, dtype=bool) + + if cfun.sparse_jacobian: + empty_jac = sps.csr_array((0, n)) + else: + empty_jac = np.empty((0, n)) + + def fun(x): + return cfun.fun(x) - value, empty_fun + + def jac(x): + return cfun.jac(x), empty_jac + + def hess(x, v_eq, v_ineq): + return cfun.hess(x, v_eq) + + empty_fun = np.empty(0) + n = cfun.n + if cfun.sparse_jacobian: + empty_jac = sps.csr_array((0, n)) + else: + empty_jac = np.empty((0, n)) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _less_to_canonical(cls, cfun, ub, keep_feasible): + empty_fun = np.empty(0) + n = cfun.n + if cfun.sparse_jacobian: + empty_jac = sps.csr_array((0, n)) + else: + empty_jac = np.empty((0, n)) + + finite_ub = ub < np.inf + n_eq = 0 + n_ineq = np.sum(finite_ub) + + if np.all(finite_ub): + def fun(x): + return empty_fun, cfun.fun(x) - ub + + def jac(x): + return empty_jac, cfun.jac(x) + + def hess(x, v_eq, v_ineq): + return cfun.hess(x, v_ineq) + else: + finite_ub = np.nonzero(finite_ub)[0] + keep_feasible = keep_feasible[finite_ub] + ub = ub[finite_ub] + + def fun(x): + return empty_fun, cfun.fun(x)[finite_ub] - ub + + def jac(x): + return empty_jac, cfun.jac(x)[finite_ub] + + def hess(x, v_eq, v_ineq): + v = np.zeros(cfun.m) + v[finite_ub] = v_ineq + return cfun.hess(x, v) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _greater_to_canonical(cls, cfun, lb, keep_feasible): + empty_fun = np.empty(0) + n = cfun.n + if cfun.sparse_jacobian: + empty_jac = sps.csr_array((0, n)) + else: + empty_jac = np.empty((0, n)) + + finite_lb = lb > -np.inf + n_eq = 0 + n_ineq = np.sum(finite_lb) + + if np.all(finite_lb): + def fun(x): + return empty_fun, lb - cfun.fun(x) + + def jac(x): + return empty_jac, -cfun.jac(x) + + def hess(x, v_eq, v_ineq): + return cfun.hess(x, -v_ineq) + else: + finite_lb = np.nonzero(finite_lb)[0] + keep_feasible = keep_feasible[finite_lb] + lb = lb[finite_lb] + + def fun(x): + return empty_fun, lb - cfun.fun(x)[finite_lb] + + def jac(x): + return empty_jac, -cfun.jac(x)[finite_lb] + + def hess(x, v_eq, v_ineq): + v = np.zeros(cfun.m) + v[finite_lb] = -v_ineq + return cfun.hess(x, v) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _interval_to_canonical(cls, cfun, lb, ub, keep_feasible): + lb_inf = lb == -np.inf + ub_inf = ub == np.inf + equal = lb == ub + less = lb_inf & ~ub_inf + greater = ub_inf & ~lb_inf + interval = ~equal & ~lb_inf & ~ub_inf + + equal = np.nonzero(equal)[0] + less = np.nonzero(less)[0] + greater = np.nonzero(greater)[0] + interval = np.nonzero(interval)[0] + n_less = less.shape[0] + n_greater = greater.shape[0] + n_interval = interval.shape[0] + n_ineq = n_less + n_greater + 2 * n_interval + n_eq = equal.shape[0] + + keep_feasible = np.hstack((keep_feasible[less], + keep_feasible[greater], + keep_feasible[interval], + keep_feasible[interval])) + + def fun(x): + f = cfun.fun(x) + eq = f[equal] - lb[equal] + le = f[less] - ub[less] + ge = lb[greater] - f[greater] + il = f[interval] - ub[interval] + ig = lb[interval] - f[interval] + return eq, np.hstack((le, ge, il, ig)) + + def jac(x): + J = cfun.jac(x) + eq = J[equal] + le = J[less] + ge = -J[greater] + il = J[interval] + ig = -il + if sps.issparse(J): + ineq = sps.vstack((le, ge, il, ig)) + else: + ineq = np.vstack((le, ge, il, ig)) + return eq, ineq + + def hess(x, v_eq, v_ineq): + n_start = 0 + v_l = v_ineq[n_start:n_start + n_less] + n_start += n_less + v_g = v_ineq[n_start:n_start + n_greater] + n_start += n_greater + v_il = v_ineq[n_start:n_start + n_interval] + n_start += n_interval + v_ig = v_ineq[n_start:n_start + n_interval] + + v = np.zeros_like(lb) + v[equal] = v_eq + v[less] = v_l + v[greater] = -v_g + v[interval] = v_il - v_ig + + return cfun.hess(x, v) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + +def initial_constraints_as_canonical(n, prepared_constraints, sparse_jacobian): + """Convert initial values of the constraints to the canonical format. + + The purpose to avoid one additional call to the constraints at the initial + point. It takes saved values in `PreparedConstraint`, modifies and + concatenates them to the canonical constraint format. + """ + c_eq = [] + c_ineq = [] + J_eq = [] + J_ineq = [] + + for c in prepared_constraints: + f = c.fun.f + J = c.fun.J + lb, ub = c.bounds + if np.all(lb == ub): + c_eq.append(f - lb) + J_eq.append(J) + elif np.all(lb == -np.inf): + finite_ub = ub < np.inf + c_ineq.append(f[finite_ub] - ub[finite_ub]) + J_ineq.append(J[finite_ub]) + elif np.all(ub == np.inf): + finite_lb = lb > -np.inf + c_ineq.append(lb[finite_lb] - f[finite_lb]) + J_ineq.append(-J[finite_lb]) + else: + lb_inf = lb == -np.inf + ub_inf = ub == np.inf + equal = lb == ub + less = lb_inf & ~ub_inf + greater = ub_inf & ~lb_inf + interval = ~equal & ~lb_inf & ~ub_inf + + c_eq.append(f[equal] - lb[equal]) + c_ineq.append(f[less] - ub[less]) + c_ineq.append(lb[greater] - f[greater]) + c_ineq.append(f[interval] - ub[interval]) + c_ineq.append(lb[interval] - f[interval]) + + J_eq.append(J[equal]) + J_ineq.append(J[less]) + J_ineq.append(-J[greater]) + J_ineq.append(J[interval]) + J_ineq.append(-J[interval]) + + c_eq = np.hstack(c_eq) if c_eq else np.empty(0) + c_ineq = np.hstack(c_ineq) if c_ineq else np.empty(0) + + if sparse_jacobian: + vstack = sps.vstack + empty = sps.csr_array((0, n)) + else: + vstack = np.vstack + empty = np.empty((0, n)) + + J_eq = vstack(J_eq) if J_eq else empty + J_ineq = vstack(J_ineq) if J_ineq else empty + + return c_eq, c_ineq, J_eq, J_ineq diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py new file mode 100644 index 0000000000000000000000000000000000000000..ecf3bb89c852a4e574ec66bff19a56f58f60f6b4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py @@ -0,0 +1,231 @@ +"""Byrd-Omojokun Trust-Region SQP method.""" + +from scipy.sparse import eye_array as speye +from .projections import projections +from .qp_subproblem import modified_dogleg, projected_cg, box_intersections +import numpy as np +from numpy.linalg import norm + +__all__ = ['equality_constrained_sqp'] + + +def default_scaling(x): + n, = np.shape(x) + return speye(n) + + +def equality_constrained_sqp(fun_and_constr, grad_and_jac, lagr_hess, + x0, fun0, grad0, constr0, + jac0, stop_criteria, + state, + initial_penalty, + initial_trust_radius, + factorization_method, + trust_lb=None, + trust_ub=None, + scaling=default_scaling): + """Solve nonlinear equality-constrained problem using trust-region SQP. + + Solve optimization problem: + + minimize fun(x) + subject to: constr(x) = 0 + + using Byrd-Omojokun Trust-Region SQP method described in [1]_. Several + implementation details are based on [2]_ and [3]_, p. 549. + + References + ---------- + .. [1] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. "On the + implementation of an algorithm for large-scale equality + constrained optimization." SIAM Journal on + Optimization 8.3 (1998): 682-706. + .. [2] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. + "An interior point algorithm for large-scale nonlinear + programming." SIAM Journal on Optimization 9.4 (1999): 877-900. + .. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). + """ + PENALTY_FACTOR = 0.3 # Rho from formula (3.51), reference [2]_, p.891. + LARGE_REDUCTION_RATIO = 0.9 + INTERMEDIARY_REDUCTION_RATIO = 0.3 + SUFFICIENT_REDUCTION_RATIO = 1e-8 # Eta from reference [2]_, p.892. + TRUST_ENLARGEMENT_FACTOR_L = 7.0 + TRUST_ENLARGEMENT_FACTOR_S = 2.0 + MAX_TRUST_REDUCTION = 0.5 + MIN_TRUST_REDUCTION = 0.1 + SOC_THRESHOLD = 0.1 + TR_FACTOR = 0.8 # Zeta from formula (3.21), reference [2]_, p.885. + BOX_FACTOR = 0.5 + + n, = np.shape(x0) # Number of parameters + + # Set default lower and upper bounds. + if trust_lb is None: + trust_lb = np.full(n, -np.inf) + if trust_ub is None: + trust_ub = np.full(n, np.inf) + + # Initial values + x = np.copy(x0) + trust_radius = initial_trust_radius + penalty = initial_penalty + # Compute Values + f = fun0 + c = grad0 + b = constr0 + A = jac0 + S = scaling(x) + # Get projections + try: + Z, LS, Y = projections(A, factorization_method) + except ValueError as e: + if str(e) == "expected square matrix": + # can be the case if there are more equality + # constraints than independent variables + raise ValueError( + "The 'expected square matrix' error can occur if there are" + " more equality constraints than independent variables." + " Consider how your constraints are set up, or use" + " factorization_method='SVDFactorization'." + ) from e + else: + raise e + + # Compute least-square lagrange multipliers + v = -LS.dot(c) + # Compute Hessian + H = lagr_hess(x, v) + + # Update state parameters + optimality = norm(c + A.T.dot(v), np.inf) + constr_violation = norm(b, np.inf) if len(b) > 0 else 0 + cg_info = {'niter': 0, 'stop_cond': 0, + 'hits_boundary': False} + + last_iteration_failed = False + while not stop_criteria(state, x, last_iteration_failed, + optimality, constr_violation, + trust_radius, penalty, cg_info): + # Normal Step - `dn` + # minimize 1/2*||A dn + b||^2 + # subject to: + # ||dn|| <= TR_FACTOR * trust_radius + # BOX_FACTOR * lb <= dn <= BOX_FACTOR * ub. + dn = modified_dogleg(A, Y, b, + TR_FACTOR*trust_radius, + BOX_FACTOR*trust_lb, + BOX_FACTOR*trust_ub) + + # Tangential Step - `dt` + # Solve the QP problem: + # minimize 1/2 dt.T H dt + dt.T (H dn + c) + # subject to: + # A dt = 0 + # ||dt|| <= sqrt(trust_radius**2 - ||dn||**2) + # lb - dn <= dt <= ub - dn + c_t = H.dot(dn) + c + b_t = np.zeros_like(b) + trust_radius_t = np.sqrt(trust_radius**2 - np.linalg.norm(dn)**2) + lb_t = trust_lb - dn + ub_t = trust_ub - dn + dt, cg_info = projected_cg(H, c_t, Z, Y, b_t, + trust_radius_t, + lb_t, ub_t) + + # Compute update (normal + tangential steps). + d = dn + dt + + # Compute second order model: 1/2 d H d + c.T d + f. + quadratic_model = 1/2*(H.dot(d)).dot(d) + c.T.dot(d) + # Compute linearized constraint: l = A d + b. + linearized_constr = A.dot(d)+b + # Compute new penalty parameter according to formula (3.52), + # reference [2]_, p.891. + vpred = norm(b) - norm(linearized_constr) + # Guarantee `vpred` always positive, + # regardless of roundoff errors. + vpred = max(1e-16, vpred) + previous_penalty = penalty + if quadratic_model > 0: + new_penalty = quadratic_model / ((1-PENALTY_FACTOR)*vpred) + penalty = max(penalty, new_penalty) + # Compute predicted reduction according to formula (3.52), + # reference [2]_, p.891. + predicted_reduction = -quadratic_model + penalty*vpred + + # Compute merit function at current point + merit_function = f + penalty*norm(b) + # Evaluate function and constraints at trial point + x_next = x + S.dot(d) + f_next, b_next = fun_and_constr(x_next) + # Compute merit function at trial point + merit_function_next = f_next + penalty*norm(b_next) + # Compute actual reduction according to formula (3.54), + # reference [2]_, p.892. + actual_reduction = merit_function - merit_function_next + # Compute reduction ratio + reduction_ratio = actual_reduction / predicted_reduction + + # Second order correction (SOC), reference [2]_, p.892. + if reduction_ratio < SUFFICIENT_REDUCTION_RATIO and \ + norm(dn) <= SOC_THRESHOLD * norm(dt): + # Compute second order correction + y = -Y.dot(b_next) + # Make sure increment is inside box constraints + _, t, intersect = box_intersections(d, y, trust_lb, trust_ub) + # Compute tentative point + x_soc = x + S.dot(d + t*y) + f_soc, b_soc = fun_and_constr(x_soc) + # Recompute actual reduction + merit_function_soc = f_soc + penalty*norm(b_soc) + actual_reduction_soc = merit_function - merit_function_soc + # Recompute reduction ratio + reduction_ratio_soc = actual_reduction_soc / predicted_reduction + if intersect and reduction_ratio_soc >= SUFFICIENT_REDUCTION_RATIO: + x_next = x_soc + f_next = f_soc + b_next = b_soc + reduction_ratio = reduction_ratio_soc + + # Readjust trust region step, formula (3.55), reference [2]_, p.892. + if reduction_ratio >= LARGE_REDUCTION_RATIO: + trust_radius = max(TRUST_ENLARGEMENT_FACTOR_L * norm(d), + trust_radius) + elif reduction_ratio >= INTERMEDIARY_REDUCTION_RATIO: + trust_radius = max(TRUST_ENLARGEMENT_FACTOR_S * norm(d), + trust_radius) + # Reduce trust region step, according to reference [3]_, p.696. + elif reduction_ratio < SUFFICIENT_REDUCTION_RATIO: + trust_reduction = ((1-SUFFICIENT_REDUCTION_RATIO) / + (1-reduction_ratio)) + new_trust_radius = trust_reduction * norm(d) + if new_trust_radius >= MAX_TRUST_REDUCTION * trust_radius: + trust_radius *= MAX_TRUST_REDUCTION + elif new_trust_radius >= MIN_TRUST_REDUCTION * trust_radius: + trust_radius = new_trust_radius + else: + trust_radius *= MIN_TRUST_REDUCTION + + # Update iteration + if reduction_ratio >= SUFFICIENT_REDUCTION_RATIO: + x = x_next + f, b = f_next, b_next + c, A = grad_and_jac(x) + S = scaling(x) + # Get projections + Z, LS, Y = projections(A, factorization_method) + # Compute least-square lagrange multipliers + v = -LS.dot(c) + # Compute Hessian + H = lagr_hess(x, v) + # Set Flag + last_iteration_failed = False + # Optimality values + optimality = norm(c + A.T.dot(v), np.inf) + constr_violation = norm(b, np.inf) if len(b) > 0 else 0 + else: + penalty = previous_penalty + last_iteration_failed = True + + return x, state diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py new file mode 100644 index 0000000000000000000000000000000000000000..69aa380991cf9bf2955ade9c8a9f0c83525553e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py @@ -0,0 +1,586 @@ +import time +import numpy as np +from scipy.sparse.linalg import LinearOperator +from .._differentiable_functions import VectorFunction +from .._constraints import ( + NonlinearConstraint, LinearConstraint, PreparedConstraint, Bounds, strict_bounds) +from .._hessian_update_strategy import BFGS +from .._optimize import OptimizeResult +from .._differentiable_functions import ScalarFunction +from .equality_constrained_sqp import equality_constrained_sqp +from .canonical_constraint import (CanonicalConstraint, + initial_constraints_as_canonical) +from .tr_interior_point import tr_interior_point +from .report import BasicReport, SQPReport, IPReport + + +TERMINATION_MESSAGES = { + 0: "The maximum number of function evaluations is exceeded.", + 1: "`gtol` termination condition is satisfied.", + 2: "`xtol` termination condition is satisfied.", + 3: "`callback` raised `StopIteration`.", + 4: "Constraint violation exceeds 'gtol'" +} + + +class HessianLinearOperator: + """Build LinearOperator from hessp""" + def __init__(self, hessp, n): + self.hessp = hessp + self.n = n + + def __call__(self, x, *args): + def matvec(p): + return self.hessp(x, p, *args) + + return LinearOperator((self.n, self.n), matvec=matvec) + + +class LagrangianHessian: + """The Hessian of the Lagrangian as LinearOperator. + + The Lagrangian is computed as the objective function plus all the + constraints multiplied with some numbers (Lagrange multipliers). + """ + def __init__(self, n, objective_hess, constraints_hess): + self.n = n + self.objective_hess = objective_hess + self.constraints_hess = constraints_hess + + def __call__(self, x, v_eq, v_ineq=None): + if v_ineq is None: + v_ineq = np.empty(0) + H_objective = self.objective_hess(x) + H_constraints = self.constraints_hess(x, v_eq, v_ineq) + + def matvec(p): + return H_objective.dot(p) + H_constraints.dot(p) + + return LinearOperator((self.n, self.n), matvec) + + +def update_state_sqp(state, x, last_iteration_failed, objective, prepared_constraints, + start_time, tr_radius, constr_penalty, cg_info): + state.nit += 1 + state.nfev = objective.nfev + state.njev = objective.ngev + state.nhev = objective.nhev + state.constr_nfev = [c.fun.nfev if isinstance(c.fun, VectorFunction) else 0 + for c in prepared_constraints] + state.constr_njev = [c.fun.njev if isinstance(c.fun, VectorFunction) else 0 + for c in prepared_constraints] + state.constr_nhev = [c.fun.nhev if isinstance(c.fun, VectorFunction) else 0 + for c in prepared_constraints] + + if not last_iteration_failed: + state.x = x + state.fun = objective.f + state.grad = objective.g + state.v = [c.fun.v for c in prepared_constraints] + state.constr = [c.fun.f for c in prepared_constraints] + state.jac = [c.fun.J for c in prepared_constraints] + # Compute Lagrangian Gradient + state.lagrangian_grad = np.copy(state.grad) + for c in prepared_constraints: + state.lagrangian_grad += c.fun.J.T.dot(c.fun.v) + state.optimality = np.linalg.norm(state.lagrangian_grad, np.inf) + # Compute maximum constraint violation + state.constr_violation = 0 + for i in range(len(prepared_constraints)): + lb, ub = prepared_constraints[i].bounds + c = state.constr[i] + state.constr_violation = np.max([state.constr_violation, + np.max(lb - c), + np.max(c - ub)]) + + state.execution_time = time.time() - start_time + state.tr_radius = tr_radius + state.constr_penalty = constr_penalty + state.cg_niter += cg_info["niter"] + state.cg_stop_cond = cg_info["stop_cond"] + + return state + + +def update_state_ip(state, x, last_iteration_failed, objective, + prepared_constraints, start_time, + tr_radius, constr_penalty, cg_info, + barrier_parameter, barrier_tolerance): + state = update_state_sqp(state, x, last_iteration_failed, objective, + prepared_constraints, start_time, tr_radius, + constr_penalty, cg_info) + state.barrier_parameter = barrier_parameter + state.barrier_tolerance = barrier_tolerance + return state + + +def _minimize_trustregion_constr(fun, x0, args, grad, + hess, hessp, bounds, constraints, + xtol=1e-8, gtol=1e-8, + barrier_tol=1e-8, + sparse_jacobian=None, + callback=None, maxiter=1000, + verbose=0, finite_diff_rel_step=None, + initial_constr_penalty=1.0, initial_tr_radius=1.0, + initial_barrier_parameter=0.1, + initial_barrier_tolerance=0.1, + factorization_method=None, + disp=False, + workers=None): + """Minimize a scalar function subject to constraints. + + Parameters + ---------- + gtol : float, optional + Tolerance for termination by the norm of the Lagrangian gradient. + The algorithm will terminate when both the infinity norm (i.e., max + abs value) of the Lagrangian gradient and the constraint violation + are smaller than ``gtol``. Default is 1e-8. + xtol : float, optional + Tolerance for termination by the change of the independent variable. + The algorithm will terminate when ``tr_radius < xtol``, where + ``tr_radius`` is the radius of the trust region used in the algorithm. + Default is 1e-8. + barrier_tol : float, optional + Threshold on the barrier parameter for the algorithm termination. + When inequality constraints are present, the algorithm will terminate + only when the barrier parameter is less than `barrier_tol`. + Default is 1e-8. + sparse_jacobian : {bool, None}, optional + Determines how to represent Jacobians of the constraints. If bool, + then Jacobians of all the constraints will be converted to the + corresponding format. If None (default), then Jacobians won't be + converted, but the algorithm can proceed only if they all have the + same format. + initial_tr_radius: float, optional + Initial trust radius. The trust radius gives the maximum distance + between solution points in consecutive iterations. It reflects the + trust the algorithm puts in the local approximation of the optimization + problem. For an accurate local approximation the trust-region should be + large and for an approximation valid only close to the current point it + should be a small one. The trust radius is automatically updated throughout + the optimization process, with ``initial_tr_radius`` being its initial value. + Default is 1 (recommended in [1]_, p. 19). + initial_constr_penalty : float, optional + Initial constraints penalty parameter. The penalty parameter is used for + balancing the requirements of decreasing the objective function + and satisfying the constraints. It is used for defining the merit function: + ``merit_function(x) = fun(x) + constr_penalty * constr_norm_l2(x)``, + where ``constr_norm_l2(x)`` is the l2 norm of a vector containing all + the constraints. The merit function is used for accepting or rejecting + trial points and ``constr_penalty`` weights the two conflicting goals + of reducing objective function and constraints. The penalty is automatically + updated throughout the optimization process, with + ``initial_constr_penalty`` being its initial value. Default is 1 + (recommended in [1]_, p 19). + initial_barrier_parameter, initial_barrier_tolerance: float, optional + Initial barrier parameter and initial tolerance for the barrier subproblem. + Both are used only when inequality constraints are present. For dealing with + optimization problems ``min_x f(x)`` subject to inequality constraints + ``c(x) <= 0`` the algorithm introduces slack variables, solving the problem + ``min_(x,s) f(x) + barrier_parameter*sum(ln(s))`` subject to the equality + constraints ``c(x) + s = 0`` instead of the original problem. This subproblem + is solved for decreasing values of ``barrier_parameter`` and with decreasing + tolerances for the termination, starting with ``initial_barrier_parameter`` + for the barrier parameter and ``initial_barrier_tolerance`` for the + barrier tolerance. Default is 0.1 for both values (recommended in [1]_ p. 19). + Also note that ``barrier_parameter`` and ``barrier_tolerance`` are updated + with the same prefactor. + factorization_method : string or None, optional + Method to factorize the Jacobian of the constraints. Use None (default) + for the auto selection or one of: + + - 'NormalEquation' (requires scikit-sparse) + - 'AugmentedSystem' + - 'QRFactorization' + - 'SVDFactorization' + + The methods 'NormalEquation' and 'AugmentedSystem' can be used only + with sparse constraints. The projections required by the algorithm + will be computed using, respectively, the normal equation and the + augmented system approaches explained in [1]_. 'NormalEquation' + computes the Cholesky factorization of ``A A.T`` and 'AugmentedSystem' + performs the LU factorization of an augmented system. They usually + provide similar results. 'AugmentedSystem' is used by default for + sparse matrices. + + The methods 'QRFactorization' and 'SVDFactorization' can be used + only with dense constraints. They compute the required projections + using, respectively, QR and SVD factorizations. The 'SVDFactorization' + method can cope with Jacobian matrices with deficient row rank and will + be used whenever other factorization methods fail (which may imply the + conversion of sparse matrices to a dense format when required). + By default, 'QRFactorization' is used for dense matrices. + finite_diff_rel_step : None or array_like, optional + Relative step size for the finite difference approximation. + maxiter : int, optional + Maximum number of algorithm iterations. Default is 1000. + verbose : {0, 1, 2, 3}, optional + Level of algorithm's verbosity: + + * 0 (default) : work silently. + * 1 : display a termination report. + * 2 : display progress during iterations. + * 3 : display progress during iterations (more complete report). + + disp : bool, optional + If True (default), then `verbose` will be set to 1 if it was 0. + workers : int, map-like callable, optional + A map-like callable, such as `multiprocessing.Pool.map` for evaluating + any numerical differentiation in parallel. + This evaluation is carried out as ``workers(fun, iterable)``. + + .. versionadded:: 1.16.0 + + Returns + ------- + `OptimizeResult` with the fields documented below. Note the following: + + 1. All values corresponding to the constraints are ordered as they + were passed to the solver. And values corresponding to `bounds` + constraints are put *after* other constraints. + 2. All numbers of function, Jacobian or Hessian evaluations correspond + to numbers of actual Python function calls. It means, for example, + that if a Jacobian is estimated by finite differences, then the + number of Jacobian evaluations will be zero and the number of + function evaluations will be incremented by all calls during the + finite difference estimation. + + x : ndarray, shape (n,) + Solution found. + optimality : float + Infinity norm of the Lagrangian gradient at the solution. + constr_violation : float + Maximum constraint violation at the solution. + fun : float + Objective function at the solution. + grad : ndarray, shape (n,) + Gradient of the objective function at the solution. + lagrangian_grad : ndarray, shape (n,) + Gradient of the Lagrangian function at the solution. + nit : int + Total number of iterations. + nfev : integer + Number of the objective function evaluations. + njev : integer + Number of the objective function gradient evaluations. + nhev : integer + Number of the objective function Hessian evaluations. + cg_niter : int + Total number of the conjugate gradient method iterations. + method : {'equality_constrained_sqp', 'tr_interior_point'} + Optimization method used. + constr : list of ndarray + List of constraint values at the solution. + jac : list of {ndarray, sparse array} + List of the Jacobian matrices of the constraints at the solution. + v : list of ndarray + List of the Lagrange multipliers for the constraints at the solution. + For an inequality constraint a positive multiplier means that the upper + bound is active, a negative multiplier means that the lower bound is + active and if a multiplier is zero it means the constraint is not + active. + constr_nfev : list of int + Number of constraint evaluations for each of the constraints. + constr_njev : list of int + Number of Jacobian matrix evaluations for each of the constraints. + constr_nhev : list of int + Number of Hessian evaluations for each of the constraints. + tr_radius : float + Radius of the trust region at the last iteration. + constr_penalty : float + Penalty parameter at the last iteration, see `initial_constr_penalty`. + barrier_tolerance : float + Tolerance for the barrier subproblem at the last iteration. + Only for problems with inequality constraints. + barrier_parameter : float + Barrier parameter at the last iteration. Only for problems + with inequality constraints. + execution_time : float + Total execution time. + message : str + Termination message. + status : {0, 1, 2, 3, 4} + Termination status: + + * 0 : The maximum number of function evaluations is exceeded. + * 1 : `gtol` termination condition is satisfied. + * 2 : `xtol` termination condition is satisfied. + * 3 : `callback` raised `StopIteration`. + * 4 : Constraint violation exceeds 'gtol'. + + .. versionchanged:: 1.15.0 + If the constraint violation exceeds `gtol`, then ``result.success`` + will now be False. + + cg_stop_cond : int + Reason for CG subproblem termination at the last iteration: + + * 0 : CG subproblem not evaluated. + * 1 : Iteration limit was reached. + * 2 : Reached the trust-region boundary. + * 3 : Negative curvature detected. + * 4 : Tolerance was satisfied. + + References + ---------- + .. [1] Conn, A. R., Gould, N. I., & Toint, P. L. + Trust region methods. 2000. Siam. pp. 19. + """ + x0 = np.atleast_1d(x0).astype(float) + n_vars = np.size(x0) + if hess is None: + if callable(hessp): + hess = HessianLinearOperator(hessp, n_vars) + else: + hess = BFGS() + if disp and verbose == 0: + verbose = 1 + + if bounds is not None: + modified_lb = np.nextafter(bounds.lb, -np.inf, where=bounds.lb > -np.inf, + out=None) + modified_ub = np.nextafter(bounds.ub, np.inf, where=bounds.ub < np.inf, + out=None) + modified_lb = np.where(np.isfinite(bounds.lb), modified_lb, bounds.lb) + modified_ub = np.where(np.isfinite(bounds.ub), modified_ub, bounds.ub) + bounds = Bounds(modified_lb, modified_ub, keep_feasible=bounds.keep_feasible) + finite_diff_bounds = strict_bounds(bounds.lb, bounds.ub, + bounds.keep_feasible, n_vars) + else: + finite_diff_bounds = (-np.inf, np.inf) + + # Define Objective Function + objective = ScalarFunction(fun, x0, args, grad, hess, + finite_diff_rel_step, finite_diff_bounds, + workers=workers) + + # Put constraints in list format when needed. + if isinstance(constraints, (NonlinearConstraint | LinearConstraint)): + constraints = [constraints] + + # Prepare constraints. + prepared_constraints = [ + PreparedConstraint(c, x0, sparse_jacobian, finite_diff_bounds) + for c in constraints] + + # Check that all constraints are either sparse or dense. + n_sparse = sum(c.fun.sparse_jacobian for c in prepared_constraints) + if 0 < n_sparse < len(prepared_constraints): + raise ValueError("All constraints must have the same kind of the " + "Jacobian --- either all sparse or all dense. " + "You can set the sparsity globally by setting " + "`sparse_jacobian` to either True of False.") + if prepared_constraints: + sparse_jacobian = n_sparse > 0 + + if bounds is not None: + if sparse_jacobian is None: + sparse_jacobian = True + prepared_constraints.append(PreparedConstraint(bounds, x0, + sparse_jacobian)) + + # Concatenate initial constraints to the canonical form. + c_eq0, c_ineq0, J_eq0, J_ineq0 = initial_constraints_as_canonical( + n_vars, prepared_constraints, sparse_jacobian) + + # Prepare all canonical constraints and concatenate it into one. + canonical_all = [CanonicalConstraint.from_PreparedConstraint(c) + for c in prepared_constraints] + + if len(canonical_all) == 0: + canonical = CanonicalConstraint.empty(n_vars) + elif len(canonical_all) == 1: + canonical = canonical_all[0] + else: + canonical = CanonicalConstraint.concatenate(canonical_all, + sparse_jacobian) + + # Generate the Hessian of the Lagrangian. + lagrangian_hess = LagrangianHessian(n_vars, objective.hess, canonical.hess) + + # Choose appropriate method + if canonical.n_ineq == 0: + method = 'equality_constrained_sqp' + else: + method = 'tr_interior_point' + + # Construct OptimizeResult + state = OptimizeResult( + nit=0, nfev=0, njev=0, nhev=0, + cg_niter=0, cg_stop_cond=0, + fun=objective.f, grad=objective.g, + lagrangian_grad=np.copy(objective.g), + constr=[c.fun.f for c in prepared_constraints], + jac=[c.fun.J for c in prepared_constraints], + constr_nfev=[0 for c in prepared_constraints], + constr_njev=[0 for c in prepared_constraints], + constr_nhev=[0 for c in prepared_constraints], + v=[c.fun.v for c in prepared_constraints], + method=method) + + # Start counting + start_time = time.time() + + # Define stop criteria + if method == 'equality_constrained_sqp': + def stop_criteria(state, x, last_iteration_failed, + optimality, constr_violation, + tr_radius, constr_penalty, cg_info): + state = update_state_sqp(state, x, last_iteration_failed, + objective, prepared_constraints, + start_time, tr_radius, constr_penalty, + cg_info) + if verbose == 2: + BasicReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation) + elif verbose > 2: + SQPReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation, + state.constr_penalty, + state.cg_stop_cond) + state.status = None + state.niter = state.nit # Alias for callback (backward-compatibility) + if callback is not None: + callback_stop = False + try: + callback_stop = callback(state) + except StopIteration: + callback_stop = True + if callback_stop: + state.status = 3 + return True + if state.optimality < gtol and state.constr_violation < gtol: + state.status = 1 + elif state.tr_radius < xtol: + state.status = 2 + elif state.nit >= maxiter: + state.status = 0 + return state.status in (0, 1, 2, 3) + elif method == 'tr_interior_point': + def stop_criteria(state, x, last_iteration_failed, tr_radius, + constr_penalty, cg_info, barrier_parameter, + barrier_tolerance): + state = update_state_ip(state, x, last_iteration_failed, + objective, prepared_constraints, + start_time, tr_radius, constr_penalty, + cg_info, barrier_parameter, barrier_tolerance) + if verbose == 2: + BasicReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation) + elif verbose > 2: + IPReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation, + state.constr_penalty, + state.barrier_parameter, + state.cg_stop_cond) + state.status = None + state.niter = state.nit # Alias for callback (backward compatibility) + if callback is not None: + callback_stop = False + try: + callback_stop = callback(state) + except StopIteration: + callback_stop = True + if callback_stop: + state.status = 3 + return True + if state.optimality < gtol and state.constr_violation < gtol: + state.status = 1 + elif (state.tr_radius < xtol + and state.barrier_parameter < barrier_tol): + state.status = 2 + elif state.nit >= maxiter: + state.status = 0 + return state.status in (0, 1, 2, 3) + + if verbose == 2: + BasicReport.print_header() + elif verbose > 2: + if method == 'equality_constrained_sqp': + SQPReport.print_header() + elif method == 'tr_interior_point': + IPReport.print_header() + + # Call inferior function to do the optimization + if method == 'equality_constrained_sqp': + def fun_and_constr(x): + f = objective.fun(x) + c_eq, _ = canonical.fun(x) + return f, c_eq + + def grad_and_jac(x): + g = objective.grad(x) + J_eq, _ = canonical.jac(x) + return g, J_eq + + _, result = equality_constrained_sqp( + fun_and_constr, grad_and_jac, lagrangian_hess, + x0, objective.f, objective.g, + c_eq0, J_eq0, + stop_criteria, state, + initial_constr_penalty, initial_tr_radius, + factorization_method) + + elif method == 'tr_interior_point': + _, result = tr_interior_point( + objective.fun, objective.grad, lagrangian_hess, + n_vars, canonical.n_ineq, canonical.n_eq, + canonical.fun, canonical.jac, + x0, objective.f, objective.g, + c_ineq0, J_ineq0, c_eq0, J_eq0, + stop_criteria, + canonical.keep_feasible, + xtol, state, initial_barrier_parameter, + initial_barrier_tolerance, + initial_constr_penalty, initial_tr_radius, + factorization_method, finite_diff_bounds) + + # Status 4 occurs when minimize is successful but constraints are not satisfied. + if result.status in (1, 2) and state.constr_violation > gtol: + result.status = 4 + + # Status 3 occurs when the callback function requests termination, + # this is assumed to not be a success. + result.success = True if result.status in (1, 2) else False + result.message = TERMINATION_MESSAGES[result.status] + + # Alias (for backward compatibility with 1.1.0) + result.niter = result.nit + + if verbose == 2: + BasicReport.print_footer() + elif verbose > 2: + if method == 'equality_constrained_sqp': + SQPReport.print_footer() + elif method == 'tr_interior_point': + IPReport.print_footer() + if verbose >= 1: + print(result.message) + print(f"Number of iterations: {result.nit}, " + f"function evaluations: {result.nfev}, " + f"CG iterations: {result.cg_niter}, " + f"optimality: {result.optimality:.2e}, " + f"constraint violation: {result.constr_violation:.2e}, " + f"execution time: {result.execution_time:4.2} s.") + return result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/projections.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/projections.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8fdd7c8b98c9314e5a9c1c15d0d942c0861ec3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/projections.py @@ -0,0 +1,411 @@ +"""Basic linear factorizations needed by the solver.""" + +from scipy.sparse import block_array, csc_array, eye_array, issparse +from scipy.sparse.linalg import LinearOperator +import scipy.linalg +import scipy.sparse.linalg +try: + from sksparse.cholmod import cholesky_AAt, CholmodTypeConversionWarning + sksparse_available = True +except ImportError: + import warnings + sksparse_available = False +import numpy as np +from warnings import warn, catch_warnings + +__all__ = [ + 'orthogonality', + 'projections', +] + + +def orthogonality(A, g): + """Measure orthogonality between a vector and the null space of a matrix. + + Compute a measure of orthogonality between the null space + of the (possibly sparse) matrix ``A`` and a given vector ``g``. + + The formula is a simplified (and cheaper) version of formula (3.13) + from [1]_. + ``orth = norm(A g, ord=2)/(norm(A, ord='fro')*norm(g, ord=2))``. + + References + ---------- + .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal. + "On the solution of equality constrained quadratic + programming problems arising in optimization." + SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395. + """ + # Compute vector norms + norm_g = np.linalg.norm(g) + # Compute Froebnius norm of the matrix A + if issparse(A): + norm_A = scipy.sparse.linalg.norm(A, ord='fro') + else: + norm_A = np.linalg.norm(A, ord='fro') + + # Check if norms are zero + if norm_g == 0 or norm_A == 0: + return 0 + + norm_A_g = np.linalg.norm(A.dot(g)) + # Orthogonality measure + orth = norm_A_g / (norm_A*norm_g) + return orth + + +def normal_equation_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A using ``NormalEquation`` approach. + """ + # Cholesky factorization + # TODO: revert this once the warning bug fix in sksparse is merged/released + # Add suppression of spurious warning bug from sksparse with csc_array gh-22089 + # factor = cholesky_AAt(A) + with catch_warnings(action='ignore', category=CholmodTypeConversionWarning): + factor = cholesky_AAt(A) + + # z = x - A.T inv(A A.T) A x + def null_space(x): + v = factor(A.dot(x)) + z = x - A.T.dot(v) + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.1. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # z_next = z - A.T inv(A A.T) A z + v = factor(A.dot(z)) + z = z - A.T.dot(v) + k += 1 + + return z + + # z = inv(A A.T) A x + def least_squares(x): + return factor(A.dot(x)) + + # z = A.T inv(A A.T) x + def row_space(x): + return A.T.dot(factor(x)) + + return null_space, least_squares, row_space + + +def augmented_system_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A - ``AugmentedSystem``.""" + # Form augmented system + K = block_array([[eye_array(n), A.T], [A, None]], format="csc") + # LU factorization + # TODO: Use a symmetric indefinite factorization + # to solve the system twice as fast (because + # of the symmetry). + try: + solve = scipy.sparse.linalg.factorized(K) + except RuntimeError: + warn("Singular Jacobian matrix. Using dense SVD decomposition to " + "perform the factorizations.", + stacklevel=3) + return svd_factorization_projections(A.toarray(), + m, n, orth_tol, + max_refin, tol) + + # z = x - A.T inv(A A.T) A x + # is computed solving the extended system: + # [I A.T] * [ z ] = [x] + # [A O ] [aux] [0] + def null_space(x): + # v = [x] + # [0] + v = np.hstack([x, np.zeros(m)]) + # lu_sol = [ z ] + # [aux] + lu_sol = solve(v) + z = lu_sol[:n] + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.2. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # new_v = [x] - [I A.T] * [ z ] + # [0] [A O ] [aux] + new_v = v - K.dot(lu_sol) + # [I A.T] * [delta z ] = new_v + # [A O ] [delta aux] + lu_update = solve(new_v) + # [ z ] += [delta z ] + # [aux] [delta aux] + lu_sol += lu_update + z = lu_sol[:n] + k += 1 + + # return z = x - A.T inv(A A.T) A x + return z + + # z = inv(A A.T) A x + # is computed solving the extended system: + # [I A.T] * [aux] = [x] + # [A O ] [ z ] [0] + def least_squares(x): + # v = [x] + # [0] + v = np.hstack([x, np.zeros(m)]) + # lu_sol = [aux] + # [ z ] + lu_sol = solve(v) + # return z = inv(A A.T) A x + return lu_sol[n:m+n] + + # z = A.T inv(A A.T) x + # is computed solving the extended system: + # [I A.T] * [ z ] = [0] + # [A O ] [aux] [x] + def row_space(x): + # v = [0] + # [x] + v = np.hstack([np.zeros(n), x]) + # lu_sol = [ z ] + # [aux] + lu_sol = solve(v) + # return z = A.T inv(A A.T) x + return lu_sol[:n] + + return null_space, least_squares, row_space + + +def qr_factorization_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A using ``QRFactorization`` approach. + """ + # QRFactorization + Q, R, P = scipy.linalg.qr(A.T, pivoting=True, mode='economic') + + if np.linalg.norm(R[-1, :], np.inf) < tol: + warn('Singular Jacobian matrix. Using SVD decomposition to ' + + 'perform the factorizations.', + stacklevel=3) + return svd_factorization_projections(A, m, n, + orth_tol, + max_refin, + tol) + + # z = x - A.T inv(A A.T) A x + def null_space(x): + # v = P inv(R) Q.T x + aux1 = Q.T.dot(x) + aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False) + v = np.zeros(m) + v[P] = aux2 + z = x - A.T.dot(v) + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.1. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # v = P inv(R) Q.T x + aux1 = Q.T.dot(z) + aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False) + v[P] = aux2 + # z_next = z - A.T v + z = z - A.T.dot(v) + k += 1 + + return z + + # z = inv(A A.T) A x + def least_squares(x): + # z = P inv(R) Q.T x + aux1 = Q.T.dot(x) + aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False) + z = np.zeros(m) + z[P] = aux2 + return z + + # z = A.T inv(A A.T) x + def row_space(x): + # z = Q inv(R.T) P.T x + aux1 = x[P] + aux2 = scipy.linalg.solve_triangular(R, aux1, + lower=False, + trans='T') + z = Q.dot(aux2) + return z + + return null_space, least_squares, row_space + + +def svd_factorization_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A using ``SVDFactorization`` approach. + """ + # SVD Factorization + U, s, Vt = scipy.linalg.svd(A, full_matrices=False) + + # Remove dimensions related with very small singular values + U = U[:, s > tol] + Vt = Vt[s > tol, :] + s = s[s > tol] + + # z = x - A.T inv(A A.T) A x + def null_space(x): + # v = U 1/s V.T x = inv(A A.T) A x + aux1 = Vt.dot(x) + aux2 = 1/s*aux1 + v = U.dot(aux2) + z = x - A.T.dot(v) + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.1. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # v = U 1/s V.T x = inv(A A.T) A x + aux1 = Vt.dot(z) + aux2 = 1/s*aux1 + v = U.dot(aux2) + # z_next = z - A.T v + z = z - A.T.dot(v) + k += 1 + + return z + + # z = inv(A A.T) A x + def least_squares(x): + # z = U 1/s V.T x = inv(A A.T) A x + aux1 = Vt.dot(x) + aux2 = 1/s*aux1 + z = U.dot(aux2) + return z + + # z = A.T inv(A A.T) x + def row_space(x): + # z = V 1/s U.T x + aux1 = U.T.dot(x) + aux2 = 1/s*aux1 + z = Vt.T.dot(aux2) + return z + + return null_space, least_squares, row_space + + +def projections(A, method=None, orth_tol=1e-12, max_refin=3, tol=1e-15): + """Return three linear operators related with a given matrix A. + + Parameters + ---------- + A : sparse array (or ndarray), shape (m, n) + Matrix ``A`` used in the projection. + method : string, optional + Method used for compute the given linear + operators. Should be one of: + + - 'NormalEquation': The operators + will be computed using the + so-called normal equation approach + explained in [1]_. In order to do + so the Cholesky factorization of + ``(A A.T)`` is computed. Exclusive + for sparse matrices. + - 'AugmentedSystem': The operators + will be computed using the + so-called augmented system approach + explained in [1]_. Exclusive + for sparse matrices. + - 'QRFactorization': Compute projections + using QR factorization. Exclusive for + dense matrices. + - 'SVDFactorization': Compute projections + using SVD factorization. Exclusive for + dense matrices. + + orth_tol : float, optional + Tolerance for iterative refinements. + max_refin : int, optional + Maximum number of iterative refinements. + tol : float, optional + Tolerance for singular values. + + Returns + ------- + Z : LinearOperator, shape (n, n) + Null-space operator. For a given vector ``x``, + the null space operator is equivalent to apply + a projection matrix ``P = I - A.T inv(A A.T) A`` + to the vector. It can be shown that this is + equivalent to project ``x`` into the null space + of A. + LS : LinearOperator, shape (m, n) + Least-squares operator. For a given vector ``x``, + the least-squares operator is equivalent to apply a + pseudoinverse matrix ``pinv(A.T) = inv(A A.T) A`` + to the vector. It can be shown that this vector + ``pinv(A.T) x`` is the least_square solution to + ``A.T y = x``. + Y : LinearOperator, shape (n, m) + Row-space operator. For a given vector ``x``, + the row-space operator is equivalent to apply a + projection matrix ``Q = A.T inv(A A.T)`` + to the vector. It can be shown that this + vector ``y = Q x`` the minimum norm solution + of ``A y = x``. + + Notes + ----- + Uses iterative refinements described in [1] + during the computation of ``Z`` in order to + cope with the possibility of large roundoff errors. + + References + ---------- + .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal. + "On the solution of equality constrained quadratic + programming problems arising in optimization." + SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395. + """ + m, n = np.shape(A) + + # The factorization of an empty matrix + # only works for the sparse representation. + if m*n == 0: + A = csc_array(A) + + # Check Argument + if issparse(A): + if method is None: + method = "AugmentedSystem" + if method not in ("NormalEquation", "AugmentedSystem"): + raise ValueError("Method not allowed for sparse array.") + if method == "NormalEquation" and not sksparse_available: + warnings.warn("Only accepts 'NormalEquation' option when " + "scikit-sparse is available. Using " + "'AugmentedSystem' option instead.", + ImportWarning, stacklevel=3) + method = 'AugmentedSystem' + else: + if method is None: + method = "QRFactorization" + if method not in ("QRFactorization", "SVDFactorization"): + raise ValueError("Method not allowed for dense array.") + + if method == 'NormalEquation': + null_space, least_squares, row_space \ + = normal_equation_projections(A, m, n, orth_tol, max_refin, tol) + elif method == 'AugmentedSystem': + null_space, least_squares, row_space \ + = augmented_system_projections(A, m, n, orth_tol, max_refin, tol) + elif method == "QRFactorization": + null_space, least_squares, row_space \ + = qr_factorization_projections(A, m, n, orth_tol, max_refin, tol) + elif method == "SVDFactorization": + null_space, least_squares, row_space \ + = svd_factorization_projections(A, m, n, orth_tol, max_refin, tol) + + Z = LinearOperator((n, n), null_space) + LS = LinearOperator((m, n), least_squares) + Y = LinearOperator((n, m), row_space) + + return Z, LS, Y diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py new file mode 100644 index 0000000000000000000000000000000000000000..978a41536336e85d81f767f0d8c8adb30795913e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py @@ -0,0 +1,637 @@ +"""Equality-constrained quadratic programming solvers.""" + +from scipy.sparse import linalg, block_array +from math import copysign +import numpy as np +from numpy.linalg import norm + +__all__ = [ + 'eqp_kktfact', + 'sphere_intersections', + 'box_intersections', + 'box_sphere_intersections', + 'inside_box_boundaries', + 'modified_dogleg', + 'projected_cg' +] + + +# For comparison with the projected CG +def eqp_kktfact(H, c, A, b): + """Solve equality-constrained quadratic programming (EQP) problem. + + Solve ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` + using direct factorization of the KKT system. + + Parameters + ---------- + H : sparse array, shape (n, n) + Hessian matrix of the EQP problem. + c : array_like, shape (n,) + Gradient of the quadratic objective function. + A : sparse array + Jacobian matrix of the EQP problem. + b : array_like, shape (m,) + Right-hand side of the constraint equation. + + Returns + ------- + x : array_like, shape (n,) + Solution of the KKT problem. + lagrange_multipliers : ndarray, shape (m,) + Lagrange multipliers of the KKT problem. + """ + n, = np.shape(c) # Number of parameters + m, = np.shape(b) # Number of constraints + + # Karush-Kuhn-Tucker matrix of coefficients. + # Defined as in Nocedal/Wright "Numerical + # Optimization" p.452 in Eq. (16.4). + kkt_matrix = block_array([[H, A.T], [A, None]], format="csc") + # Vector of coefficients. + kkt_vec = np.hstack([-c, -b]) + + # TODO: Use a symmetric indefinite factorization + # to solve the system twice as fast (because + # of the symmetry). + lu = linalg.splu(kkt_matrix) + kkt_sol = lu.solve(kkt_vec) + x = kkt_sol[:n] + lagrange_multipliers = -kkt_sol[n:n+m] + + return x, lagrange_multipliers + + +def sphere_intersections(z, d, trust_radius, + entire_line=False): + """Find the intersection between segment (or line) and spherical constraints. + + Find the intersection between the segment (or line) defined by the + parametric equation ``x(t) = z + t*d`` and the ball + ``||x|| <= trust_radius``. + + Parameters + ---------- + z : array_like, shape (n,) + Initial point. + d : array_like, shape (n,) + Direction. + trust_radius : float + Ball radius. + entire_line : bool, optional + When ``True``, the function returns the intersection between the line + ``x(t) = z + t*d`` (``t`` can assume any value) and the ball + ``||x|| <= trust_radius``. When ``False``, the function returns the intersection + between the segment ``x(t) = z + t*d``, ``0 <= t <= 1``, and the ball. + + Returns + ------- + ta, tb : float + The line/segment ``x(t) = z + t*d`` is inside the ball for + for ``ta <= t <= tb``. + intersect : bool + When ``True``, there is a intersection between the line/segment + and the sphere. On the other hand, when ``False``, there is no + intersection. + """ + # Special case when d=0 + if norm(d) == 0: + return 0, 0, False + # Check for inf trust_radius + if np.isinf(trust_radius): + if entire_line: + ta = -np.inf + tb = np.inf + else: + ta = 0 + tb = 1 + intersect = True + return ta, tb, intersect + + a = np.dot(d, d) + b = 2 * np.dot(z, d) + c = np.dot(z, z) - trust_radius**2 + discriminant = b*b - 4*a*c + if discriminant < 0: + intersect = False + return 0, 0, intersect + sqrt_discriminant = np.sqrt(discriminant) + + # The following calculation is mathematically + # equivalent to: + # ta = (-b - sqrt_discriminant) / (2*a) + # tb = (-b + sqrt_discriminant) / (2*a) + # but produce smaller round off errors. + # Look at Matrix Computation p.97 + # for a better justification. + aux = b + copysign(sqrt_discriminant, b) + ta = -aux / (2*a) + tb = -2*c / aux + ta, tb = sorted([ta, tb]) + + if entire_line: + intersect = True + else: + # Checks to see if intersection happens + # within vectors length. + if tb < 0 or ta > 1: + intersect = False + ta = 0 + tb = 0 + else: + intersect = True + # Restrict intersection interval + # between 0 and 1. + ta = max(0, ta) + tb = min(1, tb) + + return ta, tb, intersect + + +def box_intersections(z, d, lb, ub, + entire_line=False): + """Find the intersection between segment (or line) and box constraints. + + Find the intersection between the segment (or line) defined by the + parametric equation ``x(t) = z + t*d`` and the rectangular box + ``lb <= x <= ub``. + + Parameters + ---------- + z : array_like, shape (n,) + Initial point. + d : array_like, shape (n,) + Direction. + lb : array_like, shape (n,) + Lower bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + ub : array_like, shape (n, ) + Upper bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + entire_line : bool, optional + When ``True``, the function returns the intersection between the line + ``x(t) = z + t*d`` (``t`` can assume any value) and the rectangular + box. When ``False``, the function returns the intersection between the segment + ``x(t) = z + t*d``, ``0 <= t <= 1``, and the rectangular box. + + Returns + ------- + ta, tb : float + The line/segment ``x(t) = z + t*d`` is inside the box for + for ``ta <= t <= tb``. + intersect : bool + When ``True``, there is a intersection between the line (or segment) + and the rectangular box. On the other hand, when ``False``, there is no + intersection. + """ + # Make sure it is a numpy array + z = np.asarray(z) + d = np.asarray(d) + lb = np.asarray(lb) + ub = np.asarray(ub) + # Special case when d=0 + if norm(d) == 0: + return 0, 0, False + + # Get values for which d==0 + zero_d = (d == 0) + # If the boundaries are not satisfied for some coordinate + # for which "d" is zero, there is no box-line intersection. + if (z[zero_d] < lb[zero_d]).any() or (z[zero_d] > ub[zero_d]).any(): + intersect = False + return 0, 0, intersect + # Remove values for which d is zero + not_zero_d = np.logical_not(zero_d) + z = z[not_zero_d] + d = d[not_zero_d] + lb = lb[not_zero_d] + ub = ub[not_zero_d] + + # Find a series of intervals (t_lb[i], t_ub[i]). + t_lb = (lb-z) / d + t_ub = (ub-z) / d + # Get the intersection of all those intervals. + ta = max(np.minimum(t_lb, t_ub)) + tb = min(np.maximum(t_lb, t_ub)) + + # Check if intersection is feasible + if ta <= tb: + intersect = True + else: + intersect = False + # Checks to see if intersection happens within vectors length. + if not entire_line: + if tb < 0 or ta > 1: + intersect = False + ta = 0 + tb = 0 + else: + # Restrict intersection interval between 0 and 1. + ta = max(0, ta) + tb = min(1, tb) + + return ta, tb, intersect + + +def box_sphere_intersections(z, d, lb, ub, trust_radius, + entire_line=False, + extra_info=False): + """Find the intersection between segment (or line) and box/sphere constraints. + + Find the intersection between the segment (or line) defined by the + parametric equation ``x(t) = z + t*d``, the rectangular box + ``lb <= x <= ub`` and the ball ``||x|| <= trust_radius``. + + Parameters + ---------- + z : array_like, shape (n,) + Initial point. + d : array_like, shape (n,) + Direction. + lb : array_like, shape (n,) + Lower bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + ub : array_like, shape (n, ) + Upper bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + trust_radius : float + Ball radius. + entire_line : bool, optional + When ``True``, the function returns the intersection between the line + ``x(t) = z + t*d`` (``t`` can assume any value) and the constraints. + When ``False``, the function returns the intersection between the segment + ``x(t) = z + t*d``, ``0 <= t <= 1`` and the constraints. + extra_info : bool, optional + When ``True``, the function returns ``intersect_sphere`` and ``intersect_box``. + + Returns + ------- + ta, tb : float + The line/segment ``x(t) = z + t*d`` is inside the rectangular box and + inside the ball for ``ta <= t <= tb``. + intersect : bool + When ``True``, there is a intersection between the line (or segment) + and both constraints. On the other hand, when ``False``, there is no + intersection. + sphere_info : dict, optional + Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]`` + for which the line intercepts the ball. And a boolean value indicating + whether the sphere is intersected by the line. + box_info : dict, optional + Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]`` + for which the line intercepts the box. And a boolean value indicating + whether the box is intersected by the line. + """ + ta_b, tb_b, intersect_b = box_intersections(z, d, lb, ub, + entire_line) + ta_s, tb_s, intersect_s = sphere_intersections(z, d, + trust_radius, + entire_line) + ta = np.maximum(ta_b, ta_s) + tb = np.minimum(tb_b, tb_s) + if intersect_b and intersect_s and ta <= tb: + intersect = True + else: + intersect = False + + if extra_info: + sphere_info = {'ta': ta_s, 'tb': tb_s, 'intersect': intersect_s} + box_info = {'ta': ta_b, 'tb': tb_b, 'intersect': intersect_b} + return ta, tb, intersect, sphere_info, box_info + else: + return ta, tb, intersect + + +def inside_box_boundaries(x, lb, ub): + """Check if lb <= x <= ub.""" + return (lb <= x).all() and (x <= ub).all() + + +def reinforce_box_boundaries(x, lb, ub): + """Return clipped value of x""" + return np.minimum(np.maximum(x, lb), ub) + + +def modified_dogleg(A, Y, b, trust_radius, lb, ub): + """Approximately minimize ``1/2*|| A x + b ||^2`` inside trust-region. + + Approximately solve the problem of minimizing ``1/2*|| A x + b ||^2`` + subject to ``||x|| < Delta`` and ``lb <= x <= ub`` using a modification + of the classical dogleg approach. + + Parameters + ---------- + A : LinearOperator (or sparse array or ndarray), shape (m, n) + Matrix ``A`` in the minimization problem. It should have + dimension ``(m, n)`` such that ``m < n``. + Y : LinearOperator (or sparse array or ndarray), shape (n, m) + LinearOperator that apply the projection matrix + ``Q = A.T inv(A A.T)`` to the vector. The obtained vector + ``y = Q x`` being the minimum norm solution of ``A y = x``. + b : array_like, shape (m,) + Vector ``b``in the minimization problem. + trust_radius: float + Trust radius to be considered. Delimits a sphere boundary + to the problem. + lb : array_like, shape (n,) + Lower bounds to each one of the components of ``x``. + It is expected that ``lb <= 0``, otherwise the algorithm + may fail. If ``lb[i] = -Inf``, the lower + bound for the ith component is just ignored. + ub : array_like, shape (n, ) + Upper bounds to each one of the components of ``x``. + It is expected that ``ub >= 0``, otherwise the algorithm + may fail. If ``ub[i] = Inf``, the upper bound for the ith + component is just ignored. + + Returns + ------- + x : array_like, shape (n,) + Solution to the problem. + + Notes + ----- + Based on implementations described in pp. 885-886 from [1]_. + + References + ---------- + .. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. + "An interior point algorithm for large-scale nonlinear + programming." SIAM Journal on Optimization 9.4 (1999): 877-900. + """ + # Compute minimum norm minimizer of 1/2*|| A x + b ||^2. + newton_point = -Y.dot(b) + # Check for interior point + if inside_box_boundaries(newton_point, lb, ub) \ + and norm(newton_point) <= trust_radius: + x = newton_point + return x + + # Compute gradient vector ``g = A.T b`` + g = A.T.dot(b) + # Compute Cauchy point + # `cauchy_point = g.T g / (g.T A.T A g)``. + A_g = A.dot(g) + cauchy_point = -np.dot(g, g) / np.dot(A_g, A_g) * g + # Origin + origin_point = np.zeros_like(cauchy_point) + + # Check the segment between cauchy_point and newton_point + # for a possible solution. + z = cauchy_point + p = newton_point - cauchy_point + _, alpha, intersect = box_sphere_intersections(z, p, lb, ub, + trust_radius) + if intersect: + x1 = z + alpha*p + else: + # Check the segment between the origin and cauchy_point + # for a possible solution. + z = origin_point + p = cauchy_point + _, alpha, _ = box_sphere_intersections(z, p, lb, ub, + trust_radius) + x1 = z + alpha*p + + # Check the segment between origin and newton_point + # for a possible solution. + z = origin_point + p = newton_point + _, alpha, _ = box_sphere_intersections(z, p, lb, ub, + trust_radius) + x2 = z + alpha*p + + # Return the best solution among x1 and x2. + if norm(A.dot(x1) + b) < norm(A.dot(x2) + b): + return x1 + else: + return x2 + + +def projected_cg(H, c, Z, Y, b, trust_radius=np.inf, + lb=None, ub=None, tol=None, + max_iter=None, max_infeasible_iter=None, + return_all=False): + """Solve EQP problem with projected CG method. + + Solve equality-constrained quadratic programming problem + ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` and, + possibly, to trust region constraints ``||x|| < trust_radius`` + and box constraints ``lb <= x <= ub``. + + Parameters + ---------- + H : LinearOperator (or sparse array or ndarray), shape (n, n) + Operator for computing ``H v``. + c : array_like, shape (n,) + Gradient of the quadratic objective function. + Z : LinearOperator (or sparse array or ndarray), shape (n, n) + Operator for projecting ``x`` into the null space of A. + Y : LinearOperator, sparse array, ndarray, shape (n, m) + Operator that, for a given a vector ``b``, compute smallest + norm solution of ``A x + b = 0``. + b : array_like, shape (m,) + Right-hand side of the constraint equation. + trust_radius : float, optional + Trust radius to be considered. By default, uses ``trust_radius=inf``, + which means no trust radius at all. + lb : array_like, shape (n,), optional + Lower bounds to each one of the components of ``x``. + If ``lb[i] = -Inf`` the lower bound for the i-th + component is just ignored (default). + ub : array_like, shape (n, ), optional + Upper bounds to each one of the components of ``x``. + If ``ub[i] = Inf`` the upper bound for the i-th + component is just ignored (default). + tol : float, optional + Tolerance used to interrupt the algorithm. + max_iter : int, optional + Maximum algorithm iterations. Where ``max_inter <= n-m``. + By default, uses ``max_iter = n-m``. + max_infeasible_iter : int, optional + Maximum infeasible (regarding box constraints) iterations the + algorithm is allowed to take. + By default, uses ``max_infeasible_iter = n-m``. + return_all : bool, optional + When ``true``, return the list of all vectors through the iterations. + + Returns + ------- + x : array_like, shape (n,) + Solution of the EQP problem. + info : Dict + Dictionary containing the following: + + - niter : Number of iterations. + - stop_cond : Reason for algorithm termination: + 1. Iteration limit was reached; + 2. Reached the trust-region boundary; + 3. Negative curvature detected; + 4. Tolerance was satisfied. + - allvecs : List containing all intermediary vectors (optional). + - hits_boundary : True if the proposed step is on the boundary + of the trust region. + + Notes + ----- + Implementation of Algorithm 6.2 on [1]_. + + In the absence of spherical and box constraints, for sufficient + iterations, the method returns a truly optimal result. + In the presence of those constraints, the value returned is only + a inexpensive approximation of the optimal value. + + References + ---------- + .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal. + "On the solution of equality constrained quadratic + programming problems arising in optimization." + SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395. + """ + CLOSE_TO_ZERO = 1e-25 + + n, = np.shape(c) # Number of parameters + m, = np.shape(b) # Number of constraints + + # Initial Values + x = Y.dot(-b) + r = Z.dot(H.dot(x) + c) + g = Z.dot(r) + p = -g + + # Store ``x`` value + if return_all: + allvecs = [x] + # Values for the first iteration + H_p = H.dot(p) + rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389) + + # If x > trust-region the problem does not have a solution. + tr_distance = trust_radius - norm(x) + if tr_distance < 0: + raise ValueError("Trust region problem does not have a solution.") + # If x == trust_radius, then x is the solution + # to the optimization problem, since x is the + # minimum norm solution to Ax=b. + elif tr_distance < CLOSE_TO_ZERO: + info = {'niter': 0, 'stop_cond': 2, 'hits_boundary': True} + if return_all: + allvecs.append(x) + info['allvecs'] = allvecs + return x, info + + # Set default tolerance + if tol is None: + tol = max(min(0.01 * np.sqrt(rt_g), 0.1 * rt_g), CLOSE_TO_ZERO) + # Set default lower and upper bounds + if lb is None: + lb = np.full(n, -np.inf) + if ub is None: + ub = np.full(n, np.inf) + # Set maximum iterations + if max_iter is None: + max_iter = n-m + max_iter = min(max_iter, n-m) + # Set maximum infeasible iterations + if max_infeasible_iter is None: + max_infeasible_iter = n-m + + hits_boundary = False + stop_cond = 1 + counter = 0 + last_feasible_x = np.zeros_like(x) + k = 0 + for i in range(max_iter): + # Stop criteria - Tolerance : r.T g < tol + if rt_g < tol: + stop_cond = 4 + break + k += 1 + # Compute curvature + pt_H_p = H_p.dot(p) + # Stop criteria - Negative curvature + if pt_H_p <= 0: + if np.isinf(trust_radius): + raise ValueError("Negative curvature not allowed " + "for unrestricted problems.") + else: + # Find intersection with constraints + _, alpha, intersect = box_sphere_intersections( + x, p, lb, ub, trust_radius, entire_line=True) + # Update solution + if intersect: + x = x + alpha*p + # Reinforce variables are inside box constraints. + # This is only necessary because of roundoff errors. + x = reinforce_box_boundaries(x, lb, ub) + # Attribute information + stop_cond = 3 + hits_boundary = True + break + + # Get next step + alpha = rt_g / pt_H_p + x_next = x + alpha*p + + # Stop criteria - Hits boundary + if np.linalg.norm(x_next) >= trust_radius: + # Find intersection with box constraints + _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub, + trust_radius) + # Update solution + if intersect: + x = x + theta*alpha*p + # Reinforce variables are inside box constraints. + # This is only necessary because of roundoff errors. + x = reinforce_box_boundaries(x, lb, ub) + # Attribute information + stop_cond = 2 + hits_boundary = True + break + + # Check if ``x`` is inside the box and start counter if it is not. + if inside_box_boundaries(x_next, lb, ub): + counter = 0 + else: + counter += 1 + # Whenever outside box constraints keep looking for intersections. + if counter > 0: + _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub, + trust_radius) + if intersect: + last_feasible_x = x + theta*alpha*p + # Reinforce variables are inside box constraints. + # This is only necessary because of roundoff errors. + last_feasible_x = reinforce_box_boundaries(last_feasible_x, + lb, ub) + counter = 0 + # Stop after too many infeasible (regarding box constraints) iteration. + if counter > max_infeasible_iter: + break + # Store ``x_next`` value + if return_all: + allvecs.append(x_next) + + # Update residual + r_next = r + alpha*H_p + # Project residual g+ = Z r+ + g_next = Z.dot(r_next) + # Compute conjugate direction step d + rt_g_next = norm(g_next)**2 # g.T g = r.T g (ref [1]_ p.1389) + beta = rt_g_next / rt_g + p = - g_next + beta*p + # Prepare for next iteration + x = x_next + g = g_next + r = g_next + rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389) + H_p = H.dot(p) + + if not inside_box_boundaries(x, lb, ub): + x = last_feasible_x + hits_boundary = True + info = {'niter': k, 'stop_cond': stop_cond, + 'hits_boundary': hits_boundary} + if return_all: + info['allvecs'] = allvecs + return x, info diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/report.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/report.py new file mode 100644 index 0000000000000000000000000000000000000000..2d55e0ba1d82e579cd30bba8b63736c045b9474c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/report.py @@ -0,0 +1,49 @@ +"""Progress report printers.""" + +class ReportBase: + COLUMN_NAMES: list[str] = NotImplemented + COLUMN_WIDTHS: list[int] = NotImplemented + ITERATION_FORMATS: list[str] = NotImplemented + + @classmethod + def print_header(cls): + fmt = ("|" + + "|".join([f"{{:^{x}}}" for x in cls.COLUMN_WIDTHS]) + + "|") + separators = ['-' * x for x in cls.COLUMN_WIDTHS] + print(fmt.format(*cls.COLUMN_NAMES)) + print(fmt.format(*separators)) + + @classmethod + def print_iteration(cls, *args): + iteration_format = [f"{{:{x}}}" for x in cls.ITERATION_FORMATS] + fmt = "|" + "|".join(iteration_format) + "|" + print(fmt.format(*args)) + + @classmethod + def print_footer(cls): + print() + + +class BasicReport(ReportBase): + COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", + "opt", "c viol"] + COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10] + ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", + "^10.2e", "^10.2e", "^10.2e"] + + +class SQPReport(ReportBase): + COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", + "opt", "c viol", "penalty", "CG stop"] + COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 7] + ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e", + "^10.2e", "^10.2e", "^7"] + + +class IPReport(ReportBase): + COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", + "opt", "c viol", "penalty", "barrier param", "CG stop"] + COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 13, 7] + ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e", + "^10.2e", "^10.2e", "^13.2e", "^7"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eab75e005a6b3657222d0b751fd7a8b60e9e6ccf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_canonical_constraint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_canonical_constraint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccf2d9ebf24af02160f277699df10303a15ae339 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_canonical_constraint.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_nested_minimize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_nested_minimize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b9992cc628811b468047eab90fa124362e3c73e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_nested_minimize.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0ed38734dae9a05b0b7ca76f576c4081e686d72 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_qp_subproblem.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_qp_subproblem.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c046b90e85b4ba0dc32ae4185fa75b4dd0078ebc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_qp_subproblem.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b1f86617dbd8d9719c43311ac825f8ba3ebba48 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..c42e000ab845d5583b200aa4ff2d312baf063c4b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py @@ -0,0 +1,296 @@ +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +from scipy.optimize._constraints import (NonlinearConstraint, Bounds, + PreparedConstraint) +from scipy.optimize._trustregion_constr.canonical_constraint \ + import CanonicalConstraint, initial_constraints_as_canonical + + +def create_quadratic_function(n, m, rng): + a = rng.rand(m) + A = rng.rand(m, n) + H = rng.rand(m, n, n) + HT = np.transpose(H, (1, 2, 0)) + + def fun(x): + return a + A.dot(x) + 0.5 * H.dot(x).dot(x) + + def jac(x): + return A + H.dot(x) + + def hess(x, v): + return HT.dot(v) + + return fun, jac, hess + + +def test_bounds_cases(): + # Test 1: no constraints. + user_constraint = Bounds(-np.inf, np.inf) + x0 = np.array([-1, 2]) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 0) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, []) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, np.empty((0, 2))) + assert_array_equal(J_ineq, np.empty((0, 2))) + + assert_array_equal(c.keep_feasible, []) + + # Test 2: infinite lower bound. + user_constraint = Bounds(-np.inf, [0, np.inf, 1], [False, True, True]) + x0 = np.array([-1, -2, -3], dtype=float) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 2) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, [-1, -4]) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, np.empty((0, 3))) + assert_array_equal(J_ineq, np.array([[1, 0, 0], [0, 0, 1]])) + + assert_array_equal(c.keep_feasible, [False, True]) + + # Test 3: infinite upper bound. + user_constraint = Bounds([0, 1, -np.inf], np.inf, [True, False, True]) + x0 = np.array([1, 2, 3], dtype=float) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 2) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, [-1, -1]) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, np.empty((0, 3))) + assert_array_equal(J_ineq, np.array([[-1, 0, 0], [0, -1, 0]])) + + assert_array_equal(c.keep_feasible, [True, False]) + + # Test 4: interval constraint. + user_constraint = Bounds([-1, -np.inf, 2, 3], [1, np.inf, 10, 3], + [False, True, True, True]) + x0 = np.array([0, 10, 8, 5]) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 1) + assert_equal(c.n_ineq, 4) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, [2]) + assert_array_equal(c_ineq, [-1, -2, -1, -6]) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, [[0, 0, 0, 1]]) + assert_array_equal(J_ineq, [[1, 0, 0, 0], + [0, 0, 1, 0], + [-1, 0, 0, 0], + [0, 0, -1, 0]]) + + assert_array_equal(c.keep_feasible, [False, True, False, True]) + + +def test_nonlinear_constraint(): + n = 3 + m = 5 + rng = np.random.RandomState(0) + x0 = rng.rand(n) + + fun, jac, hess = create_quadratic_function(n, m, rng) + f = fun(x0) + J = jac(x0) + + lb = [-10, 3, -np.inf, -np.inf, -5] + ub = [10, 3, np.inf, 3, np.inf] + user_constraint = NonlinearConstraint( + fun, lb, ub, jac, hess, [True, False, False, True, False]) + + for sparse_jacobian in [False, True]: + prepared_constraint = PreparedConstraint(user_constraint, x0, + sparse_jacobian) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_array_equal(c.n_eq, 1) + assert_array_equal(c.n_ineq, 4) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, [f[1] - lb[1]]) + assert_array_equal(c_ineq, [f[3] - ub[3], lb[4] - f[4], + f[0] - ub[0], lb[0] - f[0]]) + + J_eq, J_ineq = c.jac(x0) + if sparse_jacobian: + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, J[1, None]) + assert_array_equal(J_ineq, np.vstack((J[3], -J[4], J[0], -J[0]))) + + v_eq = rng.rand(c.n_eq) + v_ineq = rng.rand(c.n_ineq) + v = np.zeros(m) + v[1] = v_eq[0] + v[3] = v_ineq[0] + v[4] = -v_ineq[1] + v[0] = v_ineq[2] - v_ineq[3] + assert_array_equal(c.hess(x0, v_eq, v_ineq), hess(x0, v)) + + assert_array_equal(c.keep_feasible, [True, False, True, True]) + + +def test_concatenation(): + rng = np.random.RandomState(0) + n = 4 + x0 = rng.rand(n) + + f1 = x0 + J1 = np.eye(n) + lb1 = [-1, -np.inf, -2, 3] + ub1 = [1, np.inf, np.inf, 3] + bounds = Bounds(lb1, ub1, [False, False, True, False]) + + fun, jac, hess = create_quadratic_function(n, 5, rng) + f2 = fun(x0) + J2 = jac(x0) + lb2 = [-10, 3, -np.inf, -np.inf, -5] + ub2 = [10, 3, np.inf, 5, np.inf] + nonlinear = NonlinearConstraint( + fun, lb2, ub2, jac, hess, [True, False, False, True, False]) + + for sparse_jacobian in [False, True]: + bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian) + nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian) + + c1 = CanonicalConstraint.from_PreparedConstraint(bounds_prepared) + c2 = CanonicalConstraint.from_PreparedConstraint(nonlinear_prepared) + c = CanonicalConstraint.concatenate([c1, c2], sparse_jacobian) + + assert_equal(c.n_eq, 2) + assert_equal(c.n_ineq, 7) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]]) + assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0], + lb1[0] - f1[0], f2[3] - ub2[3], + lb2[4] - f2[4], f2[0] - ub2[0], + lb2[0] - f2[0]]) + + J_eq, J_ineq = c.jac(x0) + if sparse_jacobian: + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, np.vstack((J1[3], J2[1]))) + assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3], + -J2[4], J2[0], -J2[0]))) + + v_eq = rng.rand(c.n_eq) + v_ineq = rng.rand(c.n_ineq) + v = np.zeros(5) + v[1] = v_eq[1] + v[3] = v_ineq[3] + v[4] = -v_ineq[4] + v[0] = v_ineq[5] - v_ineq[6] + H = c.hess(x0, v_eq, v_ineq).dot(np.eye(n)) + assert_array_equal(H, hess(x0, v)) + + assert_array_equal(c.keep_feasible, + [True, False, False, True, False, True, True]) + + +def test_empty(): + x = np.array([1, 2, 3]) + c = CanonicalConstraint.empty(3) + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 0) + + c_eq, c_ineq = c.fun(x) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, []) + + J_eq, J_ineq = c.jac(x) + assert_array_equal(J_eq, np.empty((0, 3))) + assert_array_equal(J_ineq, np.empty((0, 3))) + + H = c.hess(x, None, None).toarray() + assert_array_equal(H, np.zeros((3, 3))) + + +def test_initial_constraints_as_canonical(): + # rng is only used to generate the coefficients of the quadratic + # function that is used by the nonlinear constraint. + rng = np.random.RandomState(0) + + x0 = np.array([0.5, 0.4, 0.3, 0.2]) + n = len(x0) + + lb1 = [-1, -np.inf, -2, 3] + ub1 = [1, np.inf, np.inf, 3] + bounds = Bounds(lb1, ub1, [False, False, True, False]) + + fun, jac, hess = create_quadratic_function(n, 5, rng) + lb2 = [-10, 3, -np.inf, -np.inf, -5] + ub2 = [10, 3, np.inf, 5, np.inf] + nonlinear = NonlinearConstraint( + fun, lb2, ub2, jac, hess, [True, False, False, True, False]) + + for sparse_jacobian in [False, True]: + bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian) + nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian) + + f1 = bounds_prepared.fun.f + J1 = bounds_prepared.fun.J + f2 = nonlinear_prepared.fun.f + J2 = nonlinear_prepared.fun.J + + c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical( + n, [bounds_prepared, nonlinear_prepared], sparse_jacobian) + + assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]]) + assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0], + lb1[0] - f1[0], f2[3] - ub2[3], + lb2[4] - f2[4], f2[0] - ub2[0], + lb2[0] - f2[0]]) + + if sparse_jacobian: + J1 = J1.toarray() + J2 = J2.toarray() + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, np.vstack((J1[3], J2[1]))) + assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3], + -J2[4], J2[0], -J2[0]))) + + +def test_initial_constraints_as_canonical_empty(): + n = 3 + for sparse_jacobian in [False, True]: + c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical( + n, [], sparse_jacobian) + + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, []) + + if sparse_jacobian: + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, np.empty((0, n))) + assert_array_equal(J_ineq, np.empty((0, n))) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py new file mode 100644 index 0000000000000000000000000000000000000000..762cb851a78c9fb0d2283817676831f80a50322f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py @@ -0,0 +1,39 @@ +import pytest +import numpy as np +from scipy.optimize import minimize, NonlinearConstraint, rosen, rosen_der + + +# Ignore this warning about inefficient use of Hessians +# The bug only shows up with the default HUS +@pytest.mark.filterwarnings( + "ignore:delta_grad == 0.0. Check if the approximated function is linear." +) +def test_gh21193(): + # Test that nested minimization does not share Hessian objects + def identity(x): + return x[0] + def identity_jac(x): + a = np.zeros(len(x)) + a[0] = 1 + return a + constraint1 = NonlinearConstraint(identity, 0, 0, identity_jac) + constraint2 = NonlinearConstraint(identity, 0, 0, identity_jac) + + # The default HUS for each should be distinct + assert constraint1.hess is not constraint2.hess + + _ = minimize( + lambda x: minimize( + rosen, + x[1:], + jac=rosen_der, + constraints=constraint1, + method="trust-constr", + options={'maxiter': 2}, + ).fun, + [1, 0, 0], + constraints=constraint2, + method="trust-constr", + options={'maxiter': 2}, + ) + # This test doesn't check that the output is correct, just that it doesn't crash diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py new file mode 100644 index 0000000000000000000000000000000000000000..460fc70cd23faa383668804dee305a4c82271f19 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py @@ -0,0 +1,214 @@ +import numpy as np +import scipy.linalg +from scipy.sparse import csc_array +from scipy.optimize._trustregion_constr.projections \ + import projections, orthogonality +from numpy.testing import (TestCase, assert_array_almost_equal, + assert_equal, assert_allclose) + +try: + from sksparse.cholmod import cholesky_AAt # noqa: F401 + sksparse_available = True + available_sparse_methods = ("NormalEquation", "AugmentedSystem") +except ImportError: + sksparse_available = False + available_sparse_methods = ("AugmentedSystem",) +available_dense_methods = ('QRFactorization', 'SVDFactorization') + + +class TestProjections(TestCase): + + def test_nullspace_and_least_squares_sparse(self): + A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + At_dense = A_dense.T + A = csc_array(A_dense) + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1.12, 10, 0, 0, 100000, 6, 0.7, 8]) + + for method in available_sparse_methods: + Z, LS, _ = projections(A, method) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + assert_array_almost_equal(A.dot(x), 0) + # Test orthogonality + assert_array_almost_equal(orthogonality(A, x), 0) + # Test if x is the least square solution + x = LS.matvec(z) + x2 = scipy.linalg.lstsq(At_dense, z)[0] + assert_array_almost_equal(x, x2) + + def test_iterative_refinements_sparse(self): + A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + A = csc_array(A_dense) + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1.12, 10, 0, 0, 100000, 6, 0.7, 8], + [1, 0, 0, 0, 0, 1, 2, 3+1e-10]) + + for method in available_sparse_methods: + Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=100) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + atol = 1e-13 * abs(x).max() + assert_allclose(A.dot(x), 0, atol=atol) + # Test orthogonality + assert_allclose(orthogonality(A, x), 0, atol=1e-13) + + def test_rowspace_sparse(self): + A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + A = csc_array(A_dense) + test_points = ([1, 2, 3], + [1, 10, 3], + [1.12, 10, 0]) + + for method in available_sparse_methods: + _, _, Y = projections(A, method) + for z in test_points: + # Test if x is solution of A x = z + x = Y.matvec(z) + assert_array_almost_equal(A.dot(x), z) + # Test if x is in the return row space of A + A_ext = np.vstack((A_dense, x)) + assert_equal(np.linalg.matrix_rank(A_dense), + np.linalg.matrix_rank(A_ext)) + + def test_nullspace_and_least_squares_dense(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + At = A.T + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1.12, 10, 0, 0, 100000, 6, 0.7, 8]) + + for method in available_dense_methods: + Z, LS, _ = projections(A, method) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + assert_array_almost_equal(A.dot(x), 0) + # Test orthogonality + assert_array_almost_equal(orthogonality(A, x), 0) + # Test if x is the least square solution + x = LS.matvec(z) + x2 = scipy.linalg.lstsq(At, z)[0] + assert_array_almost_equal(x, x2) + + def test_compare_dense_and_sparse(self): + D = np.diag(range(1, 101)) + A = np.hstack([D, D, D, D]) + A_sparse = csc_array(A) + rng = np.random.default_rng(123) + + Z, LS, Y = projections(A) + Z_sparse, LS_sparse, Y_sparse = projections(A_sparse) + for k in range(20): + z = rng.standard_normal(size=(400,)) + assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z)) + assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z)) + x = rng.standard_normal(size=(100,)) + assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x)) + + def test_compare_dense_and_sparse2(self): + D1 = np.diag([-1.7, 1, 0.5]) + D2 = np.diag([1, -0.6, -0.3]) + D3 = np.diag([-0.3, -1.5, 2]) + A = np.hstack([D1, D2, D3]) + A_sparse = csc_array(A) + rng = np.random.default_rng(123) + + Z, LS, Y = projections(A) + Z_sparse, LS_sparse, Y_sparse = projections(A_sparse) + for k in range(1): + z = rng.standard_normal(size=(9,)) + assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z)) + assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z)) + x = rng.standard_normal(size=(3,)) + assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x)) + + def test_iterative_refinements_dense(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1, 0, 0, 0, 0, 1, 2, 3+1e-10]) + + for method in available_dense_methods: + Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=10) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + assert_allclose(A.dot(x), 0, rtol=0, atol=2.5e-14) + # Test orthogonality + assert_allclose(orthogonality(A, x), 0, rtol=0, atol=5e-16) + + def test_rowspace_dense(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + test_points = ([1, 2, 3], + [1, 10, 3], + [1.12, 10, 0]) + + for method in available_dense_methods: + _, _, Y = projections(A, method) + for z in test_points: + # Test if x is solution of A x = z + x = Y.matvec(z) + assert_array_almost_equal(A.dot(x), z) + # Test if x is in the return row space of A + A_ext = np.vstack((A, x)) + assert_equal(np.linalg.matrix_rank(A), + np.linalg.matrix_rank(A_ext)) + + +class TestOrthogonality(TestCase): + + def test_dense_matrix(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + test_vectors = ([-1.98931144, -1.56363389, + -0.84115584, 2.2864762, + 5.599141, 0.09286976, + 1.37040802, -0.28145812], + [697.92794044, -4091.65114008, + -3327.42316335, 836.86906951, + 99434.98929065, -1285.37653682, + -4109.21503806, 2935.29289083]) + test_expected_orth = (0, 0) + + for i in range(len(test_vectors)): + x = test_vectors[i] + orth = test_expected_orth[i] + assert_array_almost_equal(orthogonality(A, x), orth) + + def test_sparse_matrix(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + A = csc_array(A) + test_vectors = ([-1.98931144, -1.56363389, + -0.84115584, 2.2864762, + 5.599141, 0.09286976, + 1.37040802, -0.28145812], + [697.92794044, -4091.65114008, + -3327.42316335, 836.86906951, + 99434.98929065, -1285.37653682, + -4109.21503806, 2935.29289083]) + test_expected_orth = (0, 0) + + for i in range(len(test_vectors)): + x = test_vectors[i] + orth = test_expected_orth[i] + assert_array_almost_equal(orthogonality(A, x), orth) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py new file mode 100644 index 0000000000000000000000000000000000000000..430e5f1cc36ec1511c44c507a183cf6efe2931e9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py @@ -0,0 +1,645 @@ +import numpy as np +from scipy.sparse import csc_array +from scipy.optimize._trustregion_constr.qp_subproblem \ + import (eqp_kktfact, + projected_cg, + box_intersections, + sphere_intersections, + box_sphere_intersections, + modified_dogleg) +from scipy.optimize._trustregion_constr.projections \ + import projections +from numpy.testing import TestCase, assert_array_almost_equal, assert_equal +import pytest + + +class TestEQPDirectFactorization(TestCase): + + # From Example 16.2 Nocedal/Wright "Numerical + # Optimization" p.452. + def test_nocedal_example(self): + H = csc_array([[6, 2, 1], + [2, 5, 2], + [1, 2, 4]]) + A = csc_array([[1, 0, 1], + [0, 1, 1]]) + c = np.array([-8, -3, -3]) + b = -np.array([3, 0]) + x, lagrange_multipliers = eqp_kktfact(H, c, A, b) + assert_array_almost_equal(x, [2, -1, 1]) + assert_array_almost_equal(lagrange_multipliers, [3, -2]) + + +class TestSphericalBoundariesIntersections(TestCase): + + def test_2d_sphere_constraints(self): + # Interior initial point + ta, tb, intersect = sphere_intersections([0, 0], + [1, 0], 0.5) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and circle + ta, tb, intersect = sphere_intersections([2, 0], + [0, 1], 1) + assert_equal(intersect, False) + + # Outside initial point pointing toward outside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 1) + assert_equal(intersect, False) + + # Outside initial point pointing toward inside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [-1, 0], 1.5) + assert_array_almost_equal([ta, tb], [0.5, 1]) + assert_equal(intersect, True) + + # Initial point on the boundary + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 2) + assert_array_almost_equal([ta, tb], [0, 0]) + assert_equal(intersect, True) + + def test_2d_sphere_constraints_line_intersections(self): + # Interior initial point + ta, tb, intersect = sphere_intersections([0, 0], + [1, 0], 0.5, + entire_line=True) + assert_array_almost_equal([ta, tb], [-0.5, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and circle + ta, tb, intersect = sphere_intersections([2, 0], + [0, 1], 1, + entire_line=True) + assert_equal(intersect, False) + + # Outside initial point pointing toward outside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 1, + entire_line=True) + assert_array_almost_equal([ta, tb], [-3, -1]) + assert_equal(intersect, True) + + # Outside initial point pointing toward inside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [-1, 0], 1.5, + entire_line=True) + assert_array_almost_equal([ta, tb], [0.5, 3.5]) + assert_equal(intersect, True) + + # Initial point on the boundary + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 2, + entire_line=True) + assert_array_almost_equal([ta, tb], [-4, 0]) + assert_equal(intersect, True) + + +class TestBoxBoundariesIntersections(TestCase): + + def test_2d_box_constraints(self): + # Box constraint in the direction of vector d + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, 1], [3, 3]) + assert_array_almost_equal([ta, tb], [0.5, 1]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, -3], [3, -1]) + assert_equal(intersect, False) + + # Some constraints are absent (set to +/- inf) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-np.inf, 1], + [np.inf, np.inf]) + assert_array_almost_equal([ta, tb], [0.5, 1]) + assert_equal(intersect, True) + + # Intersect on the face of the box + ta, tb, intersect = box_intersections([1, 0], [0, 1], + [1, 1], [3, 3]) + assert_array_almost_equal([ta, tb], [1, 1]) + assert_equal(intersect, True) + + # Interior initial point + ta, tb, intersect = box_intersections([0, 0], [4, 4], + [-2, -3], [3, 2]) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and box constraints + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -3], [-1, -1]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, 3], [-1, 1]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -np.inf], + [-1, np.inf]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0, 0], [1, 100], + [1, 1], [3, 3]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0.99, 0], [0, 2], + [1, 1], [3, 3]) + assert_equal(intersect, False) + + # Initial point on the boundary + ta, tb, intersect = box_intersections([2, 2], [0, 1], + [-2, -2], [2, 2]) + assert_array_almost_equal([ta, tb], [0, 0]) + assert_equal(intersect, True) + + def test_2d_box_constraints_entire_line(self): + # Box constraint in the direction of vector d + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, 1], [3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [0.5, 1.5]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, -3], [3, -1], + entire_line=True) + assert_array_almost_equal([ta, tb], [-1.5, -0.5]) + assert_equal(intersect, True) + + # Some constraints are absent (set to +/- inf) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-np.inf, 1], + [np.inf, np.inf], + entire_line=True) + assert_array_almost_equal([ta, tb], [0.5, np.inf]) + assert_equal(intersect, True) + + # Intersect on the face of the box + ta, tb, intersect = box_intersections([1, 0], [0, 1], + [1, 1], [3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [1, 3]) + assert_equal(intersect, True) + + # Interior initial point + ta, tb, intersect = box_intersections([0, 0], [4, 4], + [-2, -3], [3, 2], + entire_line=True) + assert_array_almost_equal([ta, tb], [-0.5, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and box constraints + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -3], [-1, -1], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, 3], [-1, 1], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -np.inf], + [-1, np.inf], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0, 0], [1, 100], + [1, 1], [3, 3], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0.99, 0], [0, 2], + [1, 1], [3, 3], + entire_line=True) + assert_equal(intersect, False) + + # Initial point on the boundary + ta, tb, intersect = box_intersections([2, 2], [0, 1], + [-2, -2], [2, 2], + entire_line=True) + assert_array_almost_equal([ta, tb], [-4, 0]) + assert_equal(intersect, True) + + def test_3d_box_constraints(self): + # Simple case + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1], + [1, 1, 1], [3, 3, 3]) + assert_array_almost_equal([ta, tb], [1, 1]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1], + [1, 1, 1], [3, 3, 3]) + assert_equal(intersect, False) + + # Interior point + ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1], + [1, 1, 1], [3, 3, 3]) + assert_array_almost_equal([ta, tb], [0, 1]) + assert_equal(intersect, True) + + def test_3d_box_constraints_entire_line(self): + # Simple case + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1], + [1, 1, 1], [3, 3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [1, 3]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1], + [1, 1, 1], [3, 3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [-3, -1]) + assert_equal(intersect, True) + + # Interior point + ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1], + [1, 1, 1], [3, 3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [-1, 1]) + assert_equal(intersect, True) + + +class TestBoxSphereBoundariesIntersections(TestCase): + + def test_2d_box_constraints(self): + # Both constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2], + [-1, -2], [1, 2], 2, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # None of the constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1], + [-1, -3], [1, 3], 10, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 1]) + assert_equal(intersect, True) + + # Box constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 10, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # Spherical constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 0.25]) + assert_equal(intersect, True) + + # Infeasible problems + ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=False) + assert_equal(intersect, False) + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [2, 4], [2, 4], 2, + entire_line=False) + assert_equal(intersect, False) + + def test_2d_box_constraints_entire_line(self): + # Both constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2], + [-1, -2], [1, 2], 2, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # None of the constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1], + [-1, -3], [1, 3], 10, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 2]) + assert_equal(intersect, True) + + # Box constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 10, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # Spherical constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 0.25]) + assert_equal(intersect, True) + + # Infeasible problems + ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [2, 4], [2, 4], 2, + entire_line=True) + assert_equal(intersect, False) + + +class TestModifiedDogleg(TestCase): + + def test_cauchypoint_equalsto_newtonpoint(self): + A = np.array([[1, 8]]) + b = np.array([-16]) + _, _, Y = projections(A) + newton_point = np.array([0.24615385, 1.96923077]) + + # Newton point inside boundaries + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [np.inf, np.inf]) + assert_array_almost_equal(x, newton_point) + + # Spherical constraint active + x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf], [np.inf, np.inf]) + assert_array_almost_equal(x, newton_point/np.linalg.norm(newton_point)) + + # Box constraints active + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [0.1, np.inf]) + assert_array_almost_equal(x, (newton_point/newton_point[0]) * 0.1) + + def test_3d_example(self): + A = np.array([[1, 8, 1], + [4, 2, 2]]) + b = np.array([-16, 2]) + Z, LS, Y = projections(A) + + newton_point = np.array([-1.37090909, 2.23272727, -0.49090909]) + cauchy_point = np.array([0.11165723, 1.73068711, 0.16748585]) + origin = np.zeros_like(newton_point) + + # newton_point inside boundaries + x = modified_dogleg(A, Y, b, 3, [-np.inf, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + assert_array_almost_equal(x, newton_point) + + # line between cauchy_point and newton_point contains best point + # (spherical constraint is active). + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + z = cauchy_point + d = newton_point-cauchy_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.40807330)) + assert_array_almost_equal(np.linalg.norm(x), 2) + + # line between cauchy_point and newton_point contains best point + # (box constraint is active). + x = modified_dogleg(A, Y, b, 5, [-1, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + z = cauchy_point + d = newton_point-cauchy_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.7498195)) + assert_array_almost_equal(x[0], -1) + + # line between origin and cauchy_point contains best point + # (spherical constraint is active). + x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + z = origin + d = cauchy_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.573936265)) + assert_array_almost_equal(np.linalg.norm(x), 1) + + # line between origin and newton_point contains best point + # (box constraint is active). + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf], + [np.inf, 1, np.inf]) + z = origin + d = newton_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.4478827364)) + assert_array_almost_equal(x[1], 1) + + +class TestProjectCG(TestCase): + + # From Example 16.2 Nocedal/Wright "Numerical + # Optimization" p.452. + def test_nocedal_example(self): + H = csc_array([[6, 2, 1], + [2, 5, 2], + [1, 2, 4]]) + A = csc_array([[1, 0, 1], + [0, 1, 1]]) + c = np.array([-8, -3, -3]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b) + assert_equal(info["stop_cond"], 4) + assert_equal(info["hits_boundary"], False) + assert_array_almost_equal(x, [2, -1, 1]) + + def test_compare_with_direct_fact(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, tol=0) + x_kkt, _ = eqp_kktfact(H, c, A, b) + assert_equal(info["stop_cond"], 1) + assert_equal(info["hits_boundary"], False) + assert_array_almost_equal(x, x_kkt) + + def test_trust_region_infeasible(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 1 + Z, _, Y = projections(A) + with pytest.raises(ValueError): + projected_cg(H, c, Z, Y, b, trust_radius=trust_radius) + + def test_trust_region_barely_feasible(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 2.32379000772445021283 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(np.linalg.norm(x), trust_radius) + assert_array_almost_equal(x, -Y.dot(b)) + + def test_hits_boundary(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 3 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(np.linalg.norm(x), trust_radius) + + def test_negative_curvature_unconstrained(self): + H = csc_array([[1, 2, 1, 3], + [2, 0, 2, 4], + [1, 2, 0, 2], + [3, 4, 2, 0]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 0, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + with pytest.raises(ValueError): + projected_cg(H, c, Z, Y, b, tol=0) + + def test_negative_curvature(self): + H = csc_array([[1, 2, 1, 3], + [2, 0, 2, 4], + [1, 2, 0, 2], + [3, 4, 2, 0]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 0, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + trust_radius = 1000 + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 3) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(np.linalg.norm(x), trust_radius) + + # The box constraints are inactive at the solution but + # are active during the iterations. + def test_inactive_box_constraints(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + lb=[0.5, -np.inf, + -np.inf, -np.inf], + return_all=True) + x_kkt, _ = eqp_kktfact(H, c, A, b) + assert_equal(info["stop_cond"], 1) + assert_equal(info["hits_boundary"], False) + assert_array_almost_equal(x, x_kkt) + + # The box constraints active and the termination is + # by maximum iterations (infeasible interaction). + def test_active_box_constraints_maximum_iterations_reached(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + lb=[0.8, -np.inf, + -np.inf, -np.inf], + return_all=True) + assert_equal(info["stop_cond"], 1) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(A.dot(x), -b) + assert_array_almost_equal(x[0], 0.8) + + # The box constraints are active and the termination is + # because it hits boundary (without infeasible interaction). + def test_active_box_constraints_hits_boundaries(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 3 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + ub=[np.inf, np.inf, 1.6, np.inf], + trust_radius=trust_radius, + return_all=True) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(x[2], 1.6) + + # The box constraints are active and the termination is + # because it hits boundary (infeasible interaction). + def test_active_box_constraints_hits_boundaries_infeasible_iter(self): + H = csc_array([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 4 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + ub=[np.inf, 0.1, np.inf, np.inf], + trust_radius=trust_radius, + return_all=True) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(x[1], 0.1) + + # The box constraints are active and the termination is + # because it hits boundary (no infeasible interaction). + def test_active_box_constraints_negative_curvature(self): + H = csc_array([[1, 2, 1, 3], + [2, 0, 2, 4], + [1, 2, 0, 2], + [3, 4, 2, 0]]) + A = csc_array([[1, 0, 1, 0], + [0, 1, 0, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + trust_radius = 1000 + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + ub=[np.inf, np.inf, 100, np.inf], + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 3) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(x[2], 100) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f79c9b03860c9c323b7f27cb75980dd42fdb926d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py @@ -0,0 +1,34 @@ +import pytest +import numpy as np +from scipy.optimize import minimize, Bounds + +def test_gh10880(): + # checks that verbose reporting works with trust-constr for + # bound-constrained problems + bnds = Bounds(1, 2) + opts = {'maxiter': 1000, 'verbose': 2} + minimize(lambda x: x**2, x0=2., method='trust-constr', + bounds=bnds, options=opts) + + opts = {'maxiter': 1000, 'verbose': 3} + minimize(lambda x: x**2, x0=2., method='trust-constr', + bounds=bnds, options=opts) + +@pytest.mark.xslow +def test_gh12922(): + # checks that verbose reporting works with trust-constr for + # general constraints + def objective(x): + return np.array([(np.sum((x+1)**4))]) + + cons = {'type': 'ineq', 'fun': lambda x: -x[0]**2} + n = 25 + x0 = np.linspace(-5, 5, n) + + opts = {'maxiter': 1000, 'verbose': 2} + minimize(objective, x0=x0, method='trust-constr', + constraints=cons, options=opts) + + opts = {'maxiter': 1000, 'verbose': 3} + minimize(objective, x0=x0, method='trust-constr', + constraints=cons, options=opts) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py new file mode 100644 index 0000000000000000000000000000000000000000..e6f0d189135ea72c84791da94e65c4b38c0a903e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py @@ -0,0 +1,361 @@ +"""Trust-region interior point method. + +References +---------- +.. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. + "An interior point algorithm for large-scale nonlinear + programming." SIAM Journal on Optimization 9.4 (1999): 877-900. +.. [2] Byrd, Richard H., Guanghui Liu, and Jorge Nocedal. + "On the local behavior of an interior point method for + nonlinear programming." Numerical analysis 1997 (1997): 37-56. +.. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). +""" + +import scipy.sparse as sps +import numpy as np +from .equality_constrained_sqp import equality_constrained_sqp +from scipy.sparse.linalg import LinearOperator + +__all__ = ['tr_interior_point'] + + +class BarrierSubproblem: + """ + Barrier optimization problem: + minimize fun(x) - barrier_parameter*sum(log(s)) + subject to: constr_eq(x) = 0 + constr_ineq(x) + s = 0 + """ + + def __init__(self, x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, + constr, jac, barrier_parameter, tolerance, + enforce_feasibility, global_stop_criteria, + xtol, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0, + jac_eq0, finite_diff_bounds): + # Store parameters + self.n_vars = n_vars + self.x0 = x0 + self.s0 = s0 + self.fun = fun + self.grad = grad + self.lagr_hess = lagr_hess + self.constr = constr + self.jac = jac + self.barrier_parameter = barrier_parameter + self.tolerance = tolerance + self.n_eq = n_eq + self.n_ineq = n_ineq + self.enforce_feasibility = enforce_feasibility + self.global_stop_criteria = global_stop_criteria + self.xtol = xtol + self.fun0 = self._compute_function(fun0, constr_ineq0, s0) + self.grad0 = self._compute_gradient(grad0) + self.constr0 = self._compute_constr(constr_ineq0, constr_eq0, s0) + self.jac0 = self._compute_jacobian(jac_eq0, jac_ineq0, s0) + self.terminate = False + self.lb = finite_diff_bounds[0] + self.ub = finite_diff_bounds[1] + + def update(self, barrier_parameter, tolerance): + self.barrier_parameter = barrier_parameter + self.tolerance = tolerance + + def get_slack(self, z): + return z[self.n_vars:self.n_vars+self.n_ineq] + + def get_variables(self, z): + return z[:self.n_vars] + + def function_and_constraints(self, z): + """Returns barrier function and constraints at given point. + + For z = [x, s], returns barrier function: + function(z) = fun(x) - barrier_parameter*sum(log(s)) + and barrier constraints: + constraints(z) = [ constr_eq(x) ] + [ constr_ineq(x) + s ] + + """ + # Get variables and slack variables + x = self.get_variables(z) + s = self.get_slack(z) + + # Compute function and constraints, + # making sure x is within any strict bounds + if np.any((x < self.lb) | (x > self.ub)): + # If x is out of the strict bounds, set f = inf, + # and just set both equality and inequality + # constraints to 0 since we can't evaluate + # them separately. + f = np.inf + c_eq = np.full(self.n_eq, 0.) + c_ineq = np.full(self.n_ineq, 0.) + else: + f = self.fun(x) + c_eq, c_ineq = self.constr(x) + + # Return objective function and constraints + return (self._compute_function(f, c_ineq, s), + self._compute_constr(c_ineq, c_eq, s)) + + def _compute_function(self, f, c_ineq, s): + # Use technique from Nocedal and Wright book, ref [3]_, p.576, + # to guarantee constraints from `enforce_feasibility` + # stay feasible along iterations. + s[self.enforce_feasibility] = -c_ineq[self.enforce_feasibility] + log_s = [np.log(s_i) if s_i > 0 else -np.inf for s_i in s] + # Compute barrier objective function + return f - self.barrier_parameter*np.sum(log_s) + + def _compute_constr(self, c_ineq, c_eq, s): + # Compute barrier constraint + return np.hstack((c_eq, + c_ineq + s)) + + def scaling(self, z): + """Returns scaling vector. + Given by: + scaling = [ones(n_vars), s] + """ + s = self.get_slack(z) + diag_elements = np.hstack((np.ones(self.n_vars), s)) + + # Diagonal matrix + def matvec(vec): + return diag_elements*vec + return LinearOperator((self.n_vars+self.n_ineq, + self.n_vars+self.n_ineq), + matvec) + + def gradient_and_jacobian(self, z): + """Returns scaled gradient. + + Return scaled gradient: + gradient = [ grad(x) ] + [ -barrier_parameter*ones(n_ineq) ] + and scaled Jacobian matrix: + jacobian = [ jac_eq(x) 0 ] + [ jac_ineq(x) S ] + Both of them scaled by the previously defined scaling factor. + """ + # Get variables and slack variables + x = self.get_variables(z) + s = self.get_slack(z) + # Compute first derivatives + g = self.grad(x) + J_eq, J_ineq = self.jac(x) + # Return gradient and Jacobian + return (self._compute_gradient(g), + self._compute_jacobian(J_eq, J_ineq, s)) + + def _compute_gradient(self, g): + return np.hstack((g, -self.barrier_parameter*np.ones(self.n_ineq))) + + def _compute_jacobian(self, J_eq, J_ineq, s): + if self.n_ineq == 0: + return J_eq + else: + if sps.issparse(J_eq) or sps.issparse(J_ineq): + # It is expected that J_eq and J_ineq + # are already `csr_array` because of + # the way ``BoxConstraint``, ``NonlinearConstraint`` + # and ``LinearConstraint`` are defined. + J_eq = sps.csr_array(J_eq) + J_ineq = sps.csr_array(J_ineq) + return self._assemble_sparse_jacobian(J_eq, J_ineq, s) + else: + S = np.diag(s) + zeros = np.zeros((self.n_eq, self.n_ineq)) + # Convert to matrix + if sps.issparse(J_ineq): + J_ineq = J_ineq.toarray() + if sps.issparse(J_eq): + J_eq = J_eq.toarray() + # Concatenate matrices + return np.block([[J_eq, zeros], + [J_ineq, S]]) + + def _assemble_sparse_jacobian(self, J_eq, J_ineq, s): + """Assemble sparse Jacobian given its components. + + Given ``J_eq``, ``J_ineq`` and ``s`` returns: + jacobian = [ J_eq, 0 ] + [ J_ineq, diag(s) ] + + It is equivalent to: + sps.bmat([[ J_eq, None ], + [ J_ineq, diag(s) ]], "csr") + but significantly more efficient for this + given structure. + """ + n_vars, n_ineq, n_eq = self.n_vars, self.n_ineq, self.n_eq + J_aux = sps.vstack([J_eq, J_ineq], "csr") + indptr, indices, data = J_aux.indptr, J_aux.indices, J_aux.data + new_indptr = indptr + np.hstack((np.zeros(n_eq, dtype=int), + np.arange(n_ineq+1, dtype=int))) + size = indices.size+n_ineq + new_indices = np.empty(size) + new_data = np.empty(size) + mask = np.full(size, False, bool) + mask[new_indptr[-n_ineq:]-1] = True + new_indices[mask] = n_vars+np.arange(n_ineq) + new_indices[~mask] = indices + new_data[mask] = s + new_data[~mask] = data + J = sps.csr_array((new_data, new_indices, new_indptr), + (n_eq + n_ineq, n_vars + n_ineq)) + return J + + def lagrangian_hessian_x(self, z, v): + """Returns Lagrangian Hessian (in relation to `x`) -> Hx""" + x = self.get_variables(z) + # Get lagrange multipliers related to nonlinear equality constraints + v_eq = v[:self.n_eq] + # Get lagrange multipliers related to nonlinear ineq. constraints + v_ineq = v[self.n_eq:self.n_eq+self.n_ineq] + lagr_hess = self.lagr_hess + return lagr_hess(x, v_eq, v_ineq) + + def lagrangian_hessian_s(self, z, v): + """Returns scaled Lagrangian Hessian (in relation to`s`) -> S Hs S""" + s = self.get_slack(z) + # Using the primal formulation: + # S Hs S = diag(s)*diag(barrier_parameter/s**2)*diag(s). + # Reference [1]_ p. 882, formula (3.1) + primal = self.barrier_parameter + # Using the primal-dual formulation + # S Hs S = diag(s)*diag(v/s)*diag(s) + # Reference [1]_ p. 883, formula (3.11) + primal_dual = v[-self.n_ineq:]*s + # Uses the primal-dual formulation for + # positives values of v_ineq, and primal + # formulation for the remaining ones. + return np.where(v[-self.n_ineq:] > 0, primal_dual, primal) + + def lagrangian_hessian(self, z, v): + """Returns scaled Lagrangian Hessian""" + # Compute Hessian in relation to x and s + Hx = self.lagrangian_hessian_x(z, v) + if self.n_ineq > 0: + S_Hs_S = self.lagrangian_hessian_s(z, v) + + # The scaled Lagragian Hessian is: + # [ Hx 0 ] + # [ 0 S Hs S ] + def matvec(vec): + vec_x = self.get_variables(vec) + vec_s = self.get_slack(vec) + if self.n_ineq > 0: + return np.hstack((Hx.dot(vec_x), S_Hs_S*vec_s)) + else: + return Hx.dot(vec_x) + return LinearOperator((self.n_vars+self.n_ineq, + self.n_vars+self.n_ineq), + matvec) + + def stop_criteria(self, state, z, last_iteration_failed, + optimality, constr_violation, + trust_radius, penalty, cg_info): + """Stop criteria to the barrier problem. + The criteria here proposed is similar to formula (2.3) + from [1]_, p.879. + """ + x = self.get_variables(z) + if self.global_stop_criteria(state, x, + last_iteration_failed, + trust_radius, penalty, + cg_info, + self.barrier_parameter, + self.tolerance): + self.terminate = True + return True + else: + g_cond = (optimality < self.tolerance and + constr_violation < self.tolerance) + x_cond = trust_radius < self.xtol + return g_cond or x_cond + + +def tr_interior_point(fun, grad, lagr_hess, n_vars, n_ineq, n_eq, + constr, jac, x0, fun0, grad0, + constr_ineq0, jac_ineq0, constr_eq0, + jac_eq0, stop_criteria, + enforce_feasibility, xtol, state, + initial_barrier_parameter, + initial_tolerance, + initial_penalty, + initial_trust_radius, + factorization_method, + finite_diff_bounds): + """Trust-region interior points method. + + Solve problem: + minimize fun(x) + subject to: constr_ineq(x) <= 0 + constr_eq(x) = 0 + using trust-region interior point method described in [1]_. + """ + # BOUNDARY_PARAMETER controls the decrease on the slack + # variables. Represents ``tau`` from [1]_ p.885, formula (3.18). + BOUNDARY_PARAMETER = 0.995 + # BARRIER_DECAY_RATIO controls the decay of the barrier parameter + # and of the subproblem tolerance. Represents ``theta`` from [1]_ p.879. + BARRIER_DECAY_RATIO = 0.2 + # TRUST_ENLARGEMENT controls the enlargement on trust radius + # after each iteration + TRUST_ENLARGEMENT = 5 + + # Default enforce_feasibility + if enforce_feasibility is None: + enforce_feasibility = np.zeros(n_ineq, bool) + # Initial Values + barrier_parameter = initial_barrier_parameter + tolerance = initial_tolerance + trust_radius = initial_trust_radius + # Define initial value for the slack variables + s0 = np.maximum(-1.5*constr_ineq0, np.ones(n_ineq)) + # Define barrier subproblem + subprob = BarrierSubproblem( + x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac, + barrier_parameter, tolerance, enforce_feasibility, + stop_criteria, xtol, fun0, grad0, constr_ineq0, jac_ineq0, + constr_eq0, jac_eq0, finite_diff_bounds) + # Define initial parameter for the first iteration. + z = np.hstack((x0, s0)) + fun0_subprob, constr0_subprob = subprob.fun0, subprob.constr0 + grad0_subprob, jac0_subprob = subprob.grad0, subprob.jac0 + # Define trust region bounds + trust_lb = np.hstack((np.full(subprob.n_vars, -np.inf), + np.full(subprob.n_ineq, -BOUNDARY_PARAMETER))) + trust_ub = np.full(subprob.n_vars+subprob.n_ineq, np.inf) + + # Solves a sequence of barrier problems + while True: + # Solve SQP subproblem + z, state = equality_constrained_sqp( + subprob.function_and_constraints, + subprob.gradient_and_jacobian, + subprob.lagrangian_hessian, + z, fun0_subprob, grad0_subprob, + constr0_subprob, jac0_subprob, subprob.stop_criteria, + state, initial_penalty, trust_radius, + factorization_method, trust_lb, trust_ub, subprob.scaling) + if subprob.terminate: + break + # Update parameters + trust_radius = max(initial_trust_radius, + TRUST_ENLARGEMENT*state.tr_radius) + # TODO: Use more advanced strategies from [2]_ + # to update this parameters. + barrier_parameter *= BARRIER_DECAY_RATIO + tolerance *= BARRIER_DECAY_RATIO + # Update Barrier Problem + subprob.update(barrier_parameter, tolerance) + # Compute initial values for next iteration + fun0_subprob, constr0_subprob = subprob.function_and_constraints(z) + grad0_subprob, jac0_subprob = subprob.gradient_and_jacobian(z) + + # Get x and s + x = subprob.get_variables(z) + return x, state diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/cython_optimize/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/cython_optimize/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..470d18ece71cfb60cc20297f85d32b32d1919b98 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/cython_optimize/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44d5221621b8e5fc95beae6e0c5686e008c1bc2d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__basinhopping.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__basinhopping.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d78c6d635ef20134409ce0144e1345a467c8d759 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__basinhopping.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__dual_annealing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__dual_annealing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbb239b5103c04cd95c1466a3b564d4a4b0e9032 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__dual_annealing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__linprog_clean_inputs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__linprog_clean_inputs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e3354e89071e99de243cbdc8c93d92a77442c78 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__linprog_clean_inputs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81736ee088f885272605492d43b83f3aec6e39d5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__remove_redundancy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__remove_redundancy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b8cab8d5455b47638c5b27d503dcc76119846c6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__remove_redundancy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__root.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__root.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f95e2e2fdbc40a49aa1e29b7a63b279e60172451 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__root.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__shgo.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__shgo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40330b7e44ac757920cd766678909bf38221cd12 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__shgo.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__spectral.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__spectral.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ef7b16b046b4595f001833eec0cf839499c01f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test__spectral.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_bracket.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_bracket.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc0de0ce6d81a8b7820066190294ce6cdf33a06c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_bracket.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29afb82158d75e8576beea925034726970d1a0f6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cobyla.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cobyla.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26d5227334824f43604d232977e31fc8399ffefc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cobyla.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cobyqa.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cobyqa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fe3e963cf3c6957da03de89ded9586979e6e924 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cobyqa.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_constraint_conversion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_constraint_conversion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfd9c7e406674388329e8037997e80fc0329b532 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_constraint_conversion.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_constraints.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_constraints.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d42e18f866435502110913fcc0fc702a3b4d6cfc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_constraints.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..118128e16d1c390e4c4cd9fbddc4deb42e311165 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b2dea3c7850adb81e763eb5db2217186f6357ad Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_direct.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_direct.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a05e8830ca095f8eb02787790346f3c93f15816 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_direct.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_extending.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_extending.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acb9bcbb13a46f626eb338ee214adf91a7e9b946 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_extending.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_hessian_update_strategy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_hessian_update_strategy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89956b53d3176ddc0f4e4ca3c8a588e5967d8fb4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_hessian_update_strategy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a68c65e8f320f000a26b73b4b042c09f923c5e2d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_hessinv.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_hessinv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbc6f774f5bea6cfb4c1bf13c3dee61385b1d8ff Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_hessinv.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_setulb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_setulb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a651a37b1711028ea78ad0b29af286562ece904 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lbfgsb_setulb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_least_squares.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_least_squares.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e4f4089ed0976323153f5c2e2d178a232462b28 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_least_squares.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f05a3195ebce3d7b6a5facf51710bac5f3dc5fe5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_linesearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_linesearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f46a3e00308bc510b3d5723b2c07723a04f19535 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_linesearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff5024b247f0a6c14c86a12463f8038b3e070648 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lsq_linear.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lsq_linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa462f4e4c9289c772f3fc6965162ffa47f18965 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_lsq_linear.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_milp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_milp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceda07c2a7b2fb2ed09097932157c02244723aaa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_milp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8db4e5514ebd1332ebd2194cf30776639c6c41c5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_minpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_minpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e50c7169995dbf0c0cf39c3021a62aedf192aeb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_minpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_nnls.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_nnls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..329e5b037e1f8f8ea374284403b9564368b6ee4e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_nnls.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_nonlin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_nonlin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60f6eb5148d5b79f5e17424a995524f8625c84de Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_nonlin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_quadratic_assignment.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_quadratic_assignment.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..311749de05eb4a0b1335dc1090f569d217c32d6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_quadratic_assignment.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_regression.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_regression.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b3dd1598b6193e978beb6349c6ab1b69d9cbf59 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_regression.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_slsqp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_slsqp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1bb51c77d6240763d9f6ed2510222cca7c1ef1c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_slsqp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_tnc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_tnc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0d5863415342b04cf5573bbea50ef66f9a255c1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_tnc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec8302a3089b14703aad69bc90a5c0dd794d5c07 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_exact.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_exact.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..571bb2a1fa162ff8b76229593371fc394a15cc18 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_exact.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_krylov.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_krylov.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06088b72e15781b73f00b3d443e3cbdd19fa369c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_trustregion_krylov.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_zeros.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_zeros.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea590fe0ef6e62f465e77400ddb5ff3e554fe8a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/__pycache__/test_zeros.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx new file mode 100644 index 0000000000000000000000000000000000000000..1690170711835df0ee7a578a6ac3ecba536a9af6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +#cython: language_level=3 +#cython: boundscheck=False +#cython: wraparound=False +""" +Taken from docstring for scipy.optimize.cython_optimize module. +""" + +from scipy.optimize.cython_optimize cimport brentq + +# import math from Cython +from libc cimport math + +myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments +XLO, XHI = 0.5, 1.0 # lower and upper search boundaries +XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters + +# user-defined struct for extra parameters +ctypedef struct test_params: + double C0 + double C1 + + +# user-defined callback +cdef double f(double x, void *args) noexcept: + cdef test_params *myargs = args + return myargs.C0 - math.exp(-(x - myargs.C1)) + + +# Cython wrapper function +cdef double brentq_wrapper_example(dict args, double xa, double xb, + double xtol, double rtol, int mitr): + # Cython automatically casts dictionary to struct + cdef test_params myargs = args + return brentq( + f, xa, xb, &myargs, xtol, rtol, mitr, NULL) + + +# Python function +def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL, + mitr=MITR): + '''Calls Cython wrapper from Python.''' + return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/_cython_examples/meson.build b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/_cython_examples/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..0f6767f16dd6003f82e2bb7666193662ec9b8ddc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/scipy/optimize/tests/_cython_examples/meson.build @@ -0,0 +1,32 @@ +project('random-build-examples', 'c', 'cpp', 'cython') + +fs = import('fs') + +py3 = import('python').find_installation(pure: false) + +cy = meson.get_compiler('cython') + +if not cy.version().version_compare('>=3.0.8') + error('tests requires Cython >= 3.0.8') +endif + +cython_args = [] +if cy.version().version_compare('>=3.1.0') + cython_args += ['-Xfreethreading_compatible=True'] +endif + +py3.extension_module( + 'extending', + 'extending.pyx', + cython_args: cython_args, + install: false, +) + +extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx') +py3.extension_module( + 'extending_cpp', + extending_cpp, + cython_args: cython_args, + install: false, + override_options : ['cython_language=cpp'] +)